artifacts
__all__ = ['ActionArtifact', 'AudioArtifact', 'BaseArtifact', 'BlobArtifact', 'UrlArtifact', 'BooleanArtifact', 'ErrorArtifact', 'GenericArtifact', 'ImageArtifact', 'ImageUrlArtifact', 'InfoArtifact', 'JsonArtifact', 'ListArtifact', 'ModelArtifact', 'TextArtifact']
module-attribute
Bases:
BaseArtifact
Attributes
Name | Type | Description |
---|---|---|
value | ToolAction | The Action to take. Currently only supports ToolAction. |
Source Code in griptape/artifacts/action_artifact.py
@define() class ActionArtifact(BaseArtifact): """Represents the LLM taking an action to use a Tool. Attributes: value: The Action to take. Currently only supports ToolAction. """ value: ToolAction = field(metadata={"serializable": True}) def to_text(self) -> str: return str(self.value)
value = field(metadata={'serializable': True})
class-attribute instance-attribute
to_text()
Source Code in griptape/artifacts/action_artifact.py
def to_text(self) -> str: return str(self.value)
AudioArtifact
Bases:
BlobArtifact
Attributes
Name | Type | Description |
---|---|---|
format | str | The audio format, e.g. "wav" or "mp3". |
Source Code in griptape/artifacts/audio_artifact.py
@define class AudioArtifact(BlobArtifact): """Stores audio data. Attributes: format: The audio format, e.g. "wav" or "mp3". """ format: str = field(kw_only=True, metadata={"serializable": True}) def __attrs_post_init__(self) -> None: # Generating the name string requires attributes set by child classes. # This waits until all attributes are available before generating a name. if self.name == self.id: self.name = self.make_name() @property def mime_type(self) -> str: return f"audio/{self.format}" def to_bytes(self, **kwargs) -> bytes: return self.value def to_text(self) -> str: return f"Audio, format: {self.format}, size: {len(self.value)} bytes" def make_name(self) -> str: entropy = "".join(random.choices(string.ascii_lowercase + string.digits, k=4)) fmt_time = time.strftime("%y%m%d%H%M%S", time.localtime()) return f"audio_artifact_{fmt_time}_{entropy}.{self.format}"
format = field(kw_only=True, metadata={'serializable': True})
class-attribute instance-attributemime_type
property
attrs_post_init()
Source Code in griptape/artifacts/audio_artifact.py
def __attrs_post_init__(self) -> None: # Generating the name string requires attributes set by child classes. # This waits until all attributes are available before generating a name. if self.name == self.id: self.name = self.make_name()
make_name()
Source Code in griptape/artifacts/audio_artifact.py
def make_name(self) -> str: entropy = "".join(random.choices(string.ascii_lowercase + string.digits, k=4)) fmt_time = time.strftime("%y%m%d%H%M%S", time.localtime()) return f"audio_artifact_{fmt_time}_{entropy}.{self.format}"
to_bytes(**kwargs)
Source Code in griptape/artifacts/audio_artifact.py
def to_bytes(self, **kwargs) -> bytes: return self.value
to_text()
Source Code in griptape/artifacts/audio_artifact.py
def to_text(self) -> str: return f"Audio, format: {self.format}, size: {len(self.value)} bytes"
BaseArtifact
Bases:
SerializableMixin
, ABC
Attributes
Name | Type | Description |
---|---|---|
id | str | The unique identifier of the Artifact. Defaults to a random UUID. |
reference | Optional[Reference] | The optional Reference to the Artifact. |
meta | dict[str, Any] | The metadata associated with the Artifact. Defaults to an empty dictionary. |
name | str | The name of the Artifact. Defaults to the id. |
value | Any | The value of the Artifact. |
encoding | str | The encoding to use when encoding/decoding the value. |
encoding_error_handler | str | The error on_event to use when encoding/decoding the value. |
Source Code in griptape/artifacts/base_artifact.py
@define class BaseArtifact(SerializableMixin, ABC): """Serves as the base class for all Artifacts. Artifacts are used to encapsulate data and enhance it with metadata. Attributes: id: The unique identifier of the Artifact. Defaults to a random UUID. reference: The optional Reference to the Artifact. meta: The metadata associated with the Artifact. Defaults to an empty dictionary. name: The name of the Artifact. Defaults to the id. value: The value of the Artifact. encoding: The encoding to use when encoding/decoding the value. encoding_error_handler: The error on_event to use when encoding/decoding the value. """ id: str = field(default=Factory(lambda: uuid.uuid4().hex), kw_only=True, metadata={"serializable": True}) reference: Optional[Reference] = field(default=None, kw_only=True, metadata={"serializable": True}) meta: dict[str, Any] = field(factory=dict, kw_only=True, metadata={"serializable": True}) name: str = field( default=Factory(lambda self: self.id, takes_self=True), kw_only=True, metadata={"serializable": True}, ) value: Any = field() encoding_error_handler: str = field(default="strict", kw_only=True) encoding: str = field(default="utf-8", kw_only=True) def __str__(self) -> str: return self.to_text() def __bool__(self) -> bool: return bool(self.value) def __len__(self) -> int: return len(self.value) def to_bytes(self, **kwargs) -> bytes: return self.to_text().encode(encoding=self.encoding, errors=self.encoding_error_handler) @abstractmethod def to_text(self) -> str: ...
encoding = field(default='utf-8', kw_only=True)
class-attribute instance-attributeencoding_error_handler = field(default='strict', kw_only=True)
class-attribute instance-attributeid = field(default=Factory(lambda: uuid.uuid4().hex), kw_only=True, metadata={'serializable': True})
class-attribute instance-attributemeta = field(factory=dict, kw_only=True, metadata={'serializable': True})
class-attribute instance-attributename = field(default=Factory(lambda self: self.id, takes_self=True), kw_only=True, metadata={'serializable': True})
class-attribute instance-attributereference = field(default=None, kw_only=True, metadata={'serializable': True})
class-attribute instance-attributevalue = field()
class-attribute instance-attribute
bool()
Source Code in griptape/artifacts/base_artifact.py
def __bool__(self) -> bool: return bool(self.value)
len()
Source Code in griptape/artifacts/base_artifact.py
def __len__(self) -> int: return len(self.value)
str()
Source Code in griptape/artifacts/base_artifact.py
def __str__(self) -> str: return self.to_text()
to_bytes(**kwargs)
Source Code in griptape/artifacts/base_artifact.py
def to_bytes(self, **kwargs) -> bytes: return self.to_text().encode(encoding=self.encoding, errors=self.encoding_error_handler)
to_text()abstractmethod
Source Code in griptape/artifacts/base_artifact.py
@abstractmethod def to_text(self) -> str: ...
BlobArtifact
Bases:
BaseArtifact
Attributes
Name | Type | Description |
---|---|---|
value | bytes | The binary data. |
Source Code in griptape/artifacts/blob_artifact.py
@define class BlobArtifact(BaseArtifact): """Stores arbitrary binary data. Attributes: value: The binary data. """ value: bytes = field( converter=lambda value: value if isinstance(value, bytes) else str(value).encode(), metadata={"serializable": True}, ) @property def base64(self) -> str: return base64.b64encode(self.value).decode(self.encoding) @property def mime_type(self) -> str: return "application/octet-stream" def to_bytes(self, **kwargs) -> bytes: return self.value def to_text(self) -> str: return self.value.decode(encoding=self.encoding, errors=self.encoding_error_handler)
base64
propertymime_type
propertyvalue = field(converter=lambda value: value if isinstance(value, bytes) else str(value).encode(), metadata={'serializable': True})
class-attribute instance-attribute
to_bytes(**kwargs)
Source Code in griptape/artifacts/blob_artifact.py
def to_bytes(self, **kwargs) -> bytes: return self.value
to_text()
Source Code in griptape/artifacts/blob_artifact.py
def to_text(self) -> str: return self.value.decode(encoding=self.encoding, errors=self.encoding_error_handler)
BooleanArtifact
Bases:
BaseArtifact
Attributes
Name | Type | Description |
---|---|---|
value | bool | The boolean value. |
Source Code in griptape/artifacts/boolean_artifact.py
@define class BooleanArtifact(BaseArtifact): """Stores a boolean value. Attributes: value: The boolean value. """ value: bool = field(converter=bool, metadata={"serializable": True}) @classmethod def parse_bool(cls, value: Union[str, bool]) -> BooleanArtifact: """Convert a string literal or bool to a BooleanArtifact. The string must be either "true" or "false".""" if value is not None: if isinstance(value, str): if value.lower() == "true": return BooleanArtifact(value=True) if value.lower() == "false": return BooleanArtifact(value=False) elif isinstance(value, bool): return BooleanArtifact(value) raise ValueError(f"Cannot convert '{value}' to BooleanArtifact") def __add__(self, other: BaseArtifact) -> BooleanArtifact: raise ValueError("Cannot add BooleanArtifact with other artifacts") def __eq__(self, value: object) -> bool: return self.value == value def to_text(self) -> str: return str(self.value).lower()
value = field(converter=bool, metadata={'serializable': True})
class-attribute instance-attribute
add(other)
Source Code in griptape/artifacts/boolean_artifact.py
def __add__(self, other: BaseArtifact) -> BooleanArtifact: raise ValueError("Cannot add BooleanArtifact with other artifacts")
eq(value)
Source Code in griptape/artifacts/boolean_artifact.py
def __eq__(self, value: object) -> bool: return self.value == value
parse_bool(value)classmethod
Source Code in griptape/artifacts/boolean_artifact.py
@classmethod def parse_bool(cls, value: Union[str, bool]) -> BooleanArtifact: """Convert a string literal or bool to a BooleanArtifact. The string must be either "true" or "false".""" if value is not None: if isinstance(value, str): if value.lower() == "true": return BooleanArtifact(value=True) if value.lower() == "false": return BooleanArtifact(value=False) elif isinstance(value, bool): return BooleanArtifact(value) raise ValueError(f"Cannot convert '{value}' to BooleanArtifact")
to_text()
Source Code in griptape/artifacts/boolean_artifact.py
def to_text(self) -> str: return str(self.value).lower()
ErrorArtifact
Bases:
BaseArtifact
Attributes
Name | Type | Description |
---|---|---|
value | str | The error message. |
exception | Optional[Exception] | The exception that caused the error. Defaults to None. |
Source Code in griptape/artifacts/error_artifact.py
@define class ErrorArtifact(BaseArtifact): """Represents an error that may want to be conveyed to the LLM. Attributes: value: The error message. exception: The exception that caused the error. Defaults to None. """ value: str = field(converter=str, metadata={"serializable": True}) exception: Optional[Exception] = field(default=None, kw_only=True, metadata={"serializable": False}) def to_text(self) -> str: return self.value
exception = field(default=None, kw_only=True, metadata={'serializable': False})
class-attribute instance-attributevalue = field(converter=str, metadata={'serializable': True})
class-attribute instance-attribute
to_text()
Source Code in griptape/artifacts/error_artifact.py
def to_text(self) -> str: return self.value
GenericArtifact
Bases:
BaseArtifact
, Generic[T]
Attributes
Source Code in griptape/artifacts/generic_artifact.py
@define class GenericArtifact(BaseArtifact, Generic[T]): """Serves as an escape hatch for artifacts that don't fit into any other category. Attributes: value: The value of the Artifact. """ value: T = field(metadata={"serializable": True}) def to_text(self) -> str: return str(self.value)
value = field(metadata={'serializable': True})
class-attribute instance-attribute
to_text()
Source Code in griptape/artifacts/generic_artifact.py
def to_text(self) -> str: return str(self.value)
ImageArtifact
Bases:
BlobArtifact
Attributes
Name | Type | Description |
---|---|---|
format | str | The format of the image data. Used when building the MIME type. |
width | int | The width of the image. |
height | int | The height of the image |
Source Code in griptape/artifacts/image_artifact.py
@define class ImageArtifact(BlobArtifact): """Stores image data. Attributes: format: The format of the image data. Used when building the MIME type. width: The width of the image. height: The height of the image """ format: str = field(kw_only=True, metadata={"serializable": True}) width: int = field(kw_only=True, metadata={"serializable": True}) height: int = field(kw_only=True, metadata={"serializable": True}) def __attrs_post_init__(self) -> None: # Generating the name string requires attributes set by child classes. # This waits until all attributes are available before generating a name. if self.name == self.id: self.name = self.make_name() @property def mime_type(self) -> str: return f"image/{self.format}" def to_bytes(self, **kwargs) -> bytes: return self.value def to_text(self) -> str: return f"Image, format: {self.format}, size: {len(self.value)} bytes" def make_name(self) -> str: entropy = "".join(random.choices(string.ascii_lowercase + string.digits, k=4)) fmt_time = time.strftime("%y%m%d%H%M%S", time.localtime()) return f"image_artifact_{fmt_time}_{entropy}.{self.format}"
format = field(kw_only=True, metadata={'serializable': True})
class-attribute instance-attributeheight = field(kw_only=True, metadata={'serializable': True})
class-attribute instance-attributemime_type
propertywidth = field(kw_only=True, metadata={'serializable': True})
class-attribute instance-attribute
attrs_post_init()
Source Code in griptape/artifacts/image_artifact.py
def __attrs_post_init__(self) -> None: # Generating the name string requires attributes set by child classes. # This waits until all attributes are available before generating a name. if self.name == self.id: self.name = self.make_name()
make_name()
Source Code in griptape/artifacts/image_artifact.py
def make_name(self) -> str: entropy = "".join(random.choices(string.ascii_lowercase + string.digits, k=4)) fmt_time = time.strftime("%y%m%d%H%M%S", time.localtime()) return f"image_artifact_{fmt_time}_{entropy}.{self.format}"
to_bytes(**kwargs)
Source Code in griptape/artifacts/image_artifact.py
def to_bytes(self, **kwargs) -> bytes: return self.value
to_text()
Source Code in griptape/artifacts/image_artifact.py
def to_text(self) -> str: return f"Image, format: {self.format}, size: {len(self.value)} bytes"
ImageUrlArtifact
Bases:
UrlArtifact
Attributes
Name | Type | Description |
---|---|---|
value | str | The url. |
Source Code in griptape/artifacts/image_url_artifact.py
class ImageUrlArtifact(UrlArtifact): """Stores a url to an image. Attributes: value: The url. """
InfoArtifact
Bases:
BaseArtifact
Attributes
Name | Type | Description |
---|---|---|
value | str | The info to convey. |
Source Code in griptape/artifacts/info_artifact.py
@define class InfoArtifact(BaseArtifact): """Represents helpful info that can be conveyed to the LLM. For example, "No results found" or "Please try again.". Attributes: value: The info to convey. """ value: str = field(converter=str, metadata={"serializable": True}) def to_text(self) -> str: return self.value
value = field(converter=str, metadata={'serializable': True})
class-attribute instance-attribute
to_text()
Source Code in griptape/artifacts/info_artifact.py
def to_text(self) -> str: return self.value
JsonArtifact
Bases:
BaseArtifact
Attributes
Name | Type | Description |
---|---|---|
value | Json | The JSON data. Values will automatically be converted to a JSON-compatible format. |
Source Code in griptape/artifacts/json_artifact.py
@define class JsonArtifact(BaseArtifact): """Stores JSON data. Attributes: value: The JSON data. Values will automatically be converted to a JSON-compatible format. """ value: Json = field(converter=lambda value: JsonArtifact.value_to_json(value), metadata={"serializable": True}) @classmethod def value_to_json(cls, value: Any) -> Json: if isinstance(value, str): return json.loads(value) return json.loads(json.dumps(value)) def to_text(self) -> str: return json.dumps(self.value)
value = field(converter=lambda value: JsonArtifact.value_to_json(value), metadata={'serializable': True})
class-attribute instance-attribute
to_text()
Source Code in griptape/artifacts/json_artifact.py
def to_text(self) -> str: return json.dumps(self.value)
value_to_json(value)classmethod
Source Code in griptape/artifacts/json_artifact.py
@classmethod def value_to_json(cls, value: Any) -> Json: if isinstance(value, str): return json.loads(value) return json.loads(json.dumps(value))
ListArtifact
Bases:
BaseArtifact
, Generic[T_co]
Source Code in griptape/artifacts/list_artifact.py
@define class ListArtifact(BaseArtifact, Generic[T_co]): value: Sequence[T_co] = field(factory=list, metadata={"serializable": True}) item_separator: str = field(default="\n\n", kw_only=True, metadata={"serializable": True}) validate_uniform_types: bool = field(default=False, kw_only=True, metadata={"serializable": True}) @value.validator # pyright: ignore[reportAttributeAccessIssue] def validate_value(self, _: Attribute, value: list[T_co]) -> None: if self.validate_uniform_types and len(value) > 0: first_type = type(value[0]) if not all(isinstance(v, first_type) for v in value): raise ValueError("list elements in 'value' are not the same type") @property def child_type(self) -> Optional[type]: if self.value: return type(self.value[0]) return None def __getitem__(self, key: int) -> T_co: return self.value[key] def __bool__(self) -> bool: return len(self) > 0 def __add__(self, other: BaseArtifact) -> ListArtifact[T_co]: return ListArtifact(self.value + other.value) def __iter__(self) -> Iterator[T_co]: return iter(self.value) def to_text(self) -> str: return self.item_separator.join([v.to_text() for v in self.value]) def is_type(self, target_type: type) -> bool: if self.value: return isinstance(self.value[0], target_type) return False def has_items(self) -> bool: return len(self) > 0
child_type
propertyitem_separator = field(default='\n\n', kw_only=True, metadata={'serializable': True})
class-attribute instance-attributevalidate_uniform_types = field(default=False, kw_only=True, metadata={'serializable': True})
class-attribute instance-attributevalue = field(factory=list, metadata={'serializable': True})
class-attribute instance-attribute
add(other)
Source Code in griptape/artifacts/list_artifact.py
def __add__(self, other: BaseArtifact) -> ListArtifact[T_co]: return ListArtifact(self.value + other.value)
bool()
Source Code in griptape/artifacts/list_artifact.py
def __bool__(self) -> bool: return len(self) > 0
getitem(key)
Source Code in griptape/artifacts/list_artifact.py
def __getitem__(self, key: int) -> T_co: return self.value[key]
iter()
Source Code in griptape/artifacts/list_artifact.py
def __iter__(self) -> Iterator[T_co]: return iter(self.value)
has_items()
Source Code in griptape/artifacts/list_artifact.py
def has_items(self) -> bool: return len(self) > 0
is_type(target_type)
Source Code in griptape/artifacts/list_artifact.py
def is_type(self, target_type: type) -> bool: if self.value: return isinstance(self.value[0], target_type) return False
to_text()
Source Code in griptape/artifacts/list_artifact.py
def to_text(self) -> str: return self.item_separator.join([v.to_text() for v in self.value])
validatevalue(, value)
Source Code in griptape/artifacts/list_artifact.py
@value.validator # pyright: ignore[reportAttributeAccessIssue] def validate_value(self, _: Attribute, value: list[T_co]) -> None: if self.validate_uniform_types and len(value) > 0: first_type = type(value[0]) if not all(isinstance(v, first_type) for v in value): raise ValueError("list elements in 'value' are not the same type")
ModelArtifact
Bases:
GenericArtifact[BaseModel]
Attributes
Name | Type | Description |
---|---|---|
value | BaseModel | The pydantic model to store. |
Source Code in griptape/artifacts/model_artifact.py
@define class ModelArtifact(GenericArtifact[BaseModel]): """Stores Pydantic models as Artifacts. Required since Pydantic models require a custom serialization method. Attributes: value: The pydantic model to store. """ # We must explicitly define the type rather than rely on the parent T since # generic type information is lost at runtime. value: BaseModel = field(metadata={"serializable": True}) def to_text(self) -> str: return self.value.model_dump_json()
value = field(metadata={'serializable': True})
class-attribute instance-attribute
to_text()
Source Code in griptape/artifacts/model_artifact.py
def to_text(self) -> str: return self.value.model_dump_json()
TextArtifact
Bases:
BaseArtifact
Source Code in griptape/artifacts/text_artifact.py
@define class TextArtifact(BaseArtifact): value: str = field(converter=str, metadata={"serializable": True}) embedding: Optional[list[float]] = field(default=None, kw_only=True) def __add__(self, other: BaseArtifact) -> TextArtifact: return TextArtifact(self.value + other.value) def __bool__(self) -> bool: return bool(self.value.strip()) def to_text(self) -> str: return self.value def generate_embedding(self, driver: BaseEmbeddingDriver) -> list[float]: embedding = driver.embed(str(self.value)) if self.embedding is None: self.embedding = [] self.embedding.clear() self.embedding.extend(embedding) return self.embedding def token_count(self, tokenizer: BaseTokenizer) -> int: return tokenizer.count_tokens(str(self.value))
embedding = field(default=None, kw_only=True)
class-attribute instance-attributevalue = field(converter=str, metadata={'serializable': True})
class-attribute instance-attribute
add(other)
Source Code in griptape/artifacts/text_artifact.py
def __add__(self, other: BaseArtifact) -> TextArtifact: return TextArtifact(self.value + other.value)
bool()
Source Code in griptape/artifacts/text_artifact.py
def __bool__(self) -> bool: return bool(self.value.strip())
generate_embedding(driver)
Source Code in griptape/artifacts/text_artifact.py
def generate_embedding(self, driver: BaseEmbeddingDriver) -> list[float]: embedding = driver.embed(str(self.value)) if self.embedding is None: self.embedding = [] self.embedding.clear() self.embedding.extend(embedding) return self.embedding
to_text()
Source Code in griptape/artifacts/text_artifact.py
def to_text(self) -> str: return self.value
token_count(tokenizer)
Source Code in griptape/artifacts/text_artifact.py
def token_count(self, tokenizer: BaseTokenizer) -> int: return tokenizer.count_tokens(str(self.value))
UrlArtifact
Bases:
BaseArtifact
Attributes
Name | Type | Description |
---|---|---|
value | str | The url. |
Source Code in griptape/artifacts/url_artifact.py
@define class UrlArtifact(BaseArtifact): """Stores a url. Attributes: value: The url. """ value: str = field(metadata={"serializable": True}) def to_bytes(self, *, headers: dict | None = None, **kwargs: dict) -> bytes: """Fetches the content of the URL and returns it as bytes. Args: headers: Optional headers to include in the request. **kwargs: Additional keyword arguments, not used. Returns: bytes: The content of the URL as bytes. """ response = requests.get(self.value, headers=headers) response.raise_for_status() return response.content def to_text(self) -> str: """Returns the URL as is.""" return self.value
value = field(metadata={'serializable': True})
class-attribute instance-attribute
to_bytes(*, headers=None, **kwargs)
Fetches the content of the URL and returns it as bytes.
Parameters
Name | Type | Description | Default |
---|---|---|---|
headers | dict | None | Optional headers to include in the request. | None |
**kwargs | dict | Additional keyword arguments, not used. | {} |
Returns
Name | Type | Description |
---|---|---|
bytes | bytes | The content of the URL as bytes. |
Source Code in griptape/artifacts/url_artifact.py
def to_bytes(self, *, headers: dict | None = None, **kwargs: dict) -> bytes: """Fetches the content of the URL and returns it as bytes. Args: headers: Optional headers to include in the request. **kwargs: Additional keyword arguments, not used. Returns: bytes: The content of the URL as bytes. """ response = requests.get(self.value, headers=headers) response.raise_for_status() return response.content
to_text()
Source Code in griptape/artifacts/url_artifact.py
def to_text(self) -> str: """Returns the URL as is.""" return self.value
Could this page be better? Report a problem or suggest an addition!