Skip to content

artifacts

__all__ = ['BaseArtifact', 'ErrorArtifact', 'InfoArtifact', 'TextArtifact', 'JsonArtifact', 'BlobArtifact', 'BooleanArtifact', 'ListArtifact', 'ImageArtifact', 'AudioArtifact', 'ActionArtifact', 'GenericArtifact'] module-attribute

ActionArtifact

Bases: BaseArtifact

Represents the LLM taking an action to use a Tool.

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: ToolAction = 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

Stores audio data.

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})

    @property
    def mime_type(self) -> str:
        return f"audio/{self.format}"

    def to_bytes(self) -> bytes:
        return self.value

    def to_text(self) -> str:
        return f"Audio, format: {self.format}, size: {len(self.value)} bytes"

format: str = field(kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute

mime_type: str property

to_bytes()

Source code in griptape/artifacts/audio_artifact.py
def to_bytes(self) -> 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

Serves as the base class for all Artifacts.

Artifacts are used to encapsulate data and enhance it with metadata.

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 handler 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 handler 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) -> bytes:
        return self.to_text().encode(encoding=self.encoding, errors=self.encoding_error_handler)

    @abstractmethod
    def to_text(self) -> str: ...

encoding: str = field(default='utf-8', kw_only=True) class-attribute instance-attribute

encoding_error_handler: str = field(default='strict', kw_only=True) class-attribute instance-attribute

id: str = field(default=Factory(lambda: uuid.uuid4().hex), kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute

meta: dict[str, Any] = field(factory=dict, kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute

name: str = field(default=Factory(lambda self: self.id, takes_self=True), kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute

reference: Optional[Reference] = field(default=None, kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute

value: Any = 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()

Source code in griptape/artifacts/base_artifact.py
def to_bytes(self) -> 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

Stores arbitrary binary data.

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) -> bytes:
        return self.value

    def to_text(self) -> str:
        return self.value.decode(encoding=self.encoding, errors=self.encoding_error_handler)

base64: str property

mime_type: str property

value: bytes = field(converter=lambda value: value if isinstance(value, bytes) else str(value).encode(), metadata={'serializable': True}) class-attribute instance-attribute

to_bytes()

Source code in griptape/artifacts/blob_artifact.py
def to_bytes(self) -> 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

Stores a boolean value.

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)
                elif 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: bool = 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

Convert a string literal or bool to a BooleanArtifact. The string must be either "true" or "false".

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)
            elif 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

Represents an error that may want to be conveyed to the LLM.

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: Optional[Exception] = field(default=None, kw_only=True, metadata={'serializable': False}) class-attribute instance-attribute

value: str = 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

Serves as an escape hatch for artifacts that don't fit into any other category.

Attributes:

Name Type Description
value Any

The value of the Artifact.

Source code in griptape/artifacts/generic_artifact.py
@define
class GenericArtifact(BaseArtifact):
    """Serves as an escape hatch for artifacts that don't fit into any other category.

    Attributes:
        value: The value of the Artifact.
    """

    value: Any = field(metadata={"serializable": True})

    def to_text(self) -> str:
        return str(self.value)

value: Any = 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

Stores image data.

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})

    @property
    def mime_type(self) -> str:
        return f"image/{self.format}"

    def to_bytes(self) -> bytes:
        return self.value

    def to_text(self) -> str:
        return f"Image, format: {self.format}, size: {len(self.value)} bytes"

format: str = field(kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute

height: int = field(kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute

mime_type: str property

width: int = field(kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute

to_bytes()

Source code in griptape/artifacts/image_artifact.py
def to_bytes(self) -> 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"

InfoArtifact

Bases: BaseArtifact

Represents helpful info that can be conveyed to the LLM.

For example, "No results found" or "Please try again.".

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: str = 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

Stores JSON data.

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)
        else:
            return json.loads(json.dumps(value))

    def to_text(self) -> str:
        return json.dumps(self.value)

value: Json = 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)
    else:
        return json.loads(json.dumps(value))

ListArtifact

Bases: BaseArtifact, Generic[T]

Source code in griptape/artifacts/list_artifact.py
@define
class ListArtifact(BaseArtifact, Generic[T]):
    value: Sequence[T] = 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]) -> 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])
        else:
            return None

    def __getitem__(self, key: int) -> T:
        return self.value[key]

    def __bool__(self) -> bool:
        return len(self) > 0

    def __add__(self, other: BaseArtifact) -> ListArtifact[T]:
        return ListArtifact(self.value + other.value)

    def __iter__(self) -> Iterator[T]:
        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)
        else:
            return False

    def has_items(self) -> bool:
        return len(self) > 0

child_type: Optional[type] property

item_separator: str = field(default='\n\n', kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute

validate_uniform_types: bool = field(default=False, kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute

value: Sequence[T] = 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]:
    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:
    return self.value[key]

__iter__()

Source code in griptape/artifacts/list_artifact.py
def __iter__(self) -> Iterator[T]:
    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)
    else:
        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])

validate_value(_, value)

Source code in griptape/artifacts/list_artifact.py
@value.validator  # pyright: ignore[reportAttributeAccessIssue]
def validate_value(self, _: Attribute, value: list[T]) -> 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")

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_string(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: Optional[list[float]] = field(default=None, kw_only=True) class-attribute instance-attribute

value: str = 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_string(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))