Skip to content

Artifacts

__all__ = ['BaseArtifact', 'ErrorArtifact', 'InfoArtifact', 'TextArtifact', 'BlobArtifact', 'CsvRowArtifact', 'ListArtifact', 'ImageArtifact', 'MediaArtifact'] module-attribute

BaseArtifact

Bases: SerializableMixin, ABC

Source code in griptape/artifacts/base_artifact.py
@define()
class BaseArtifact(SerializableMixin, ABC):
    id: str = field(default=Factory(lambda: uuid.uuid4().hex), 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()

    @classmethod
    def value_to_bytes(cls, value: Any) -> bytes:
        if isinstance(value, bytes):
            return value
        else:
            return str(value).encode()

    @classmethod
    def value_to_dict(cls, value: Any) -> dict:
        if isinstance(value, dict):
            dict_value = value
        else:
            dict_value = json.loads(value)

        return {k: v for k, v in dict_value.items()}

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

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

    def __bool__(self) -> bool:
        return bool(self.value)

    def __len__(self) -> int:
        return len(self.value)

    @abstractmethod
    def __add__(self, other: BaseArtifact) -> BaseArtifact:
        ...

id: str = field(default=Factory(lambda: uuid.uuid4().hex), 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

value: Any = field() class-attribute instance-attribute

__add__(other) abstractmethod

Source code in griptape/artifacts/base_artifact.py
@abstractmethod
def __add__(self, other: BaseArtifact) -> BaseArtifact:
    ...

__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_text()

Source code in griptape/artifacts/base_artifact.py
def to_text(self) -> str:
    return str(self.value)

value_to_bytes(value) classmethod

Source code in griptape/artifacts/base_artifact.py
@classmethod
def value_to_bytes(cls, value: Any) -> bytes:
    if isinstance(value, bytes):
        return value
    else:
        return str(value).encode()

value_to_dict(value) classmethod

Source code in griptape/artifacts/base_artifact.py
@classmethod
def value_to_dict(cls, value: Any) -> dict:
    if isinstance(value, dict):
        dict_value = value
    else:
        dict_value = json.loads(value)

    return {k: v for k, v in dict_value.items()}

BlobArtifact

Bases: BaseArtifact

Source code in griptape/artifacts/blob_artifact.py
@define
class BlobArtifact(BaseArtifact):
    value: bytes = field(converter=BaseArtifact.value_to_bytes, metadata={"serializable": True})
    dir_name: Optional[str] = field(default=None, kw_only=True, metadata={"serializable": True})
    encoding: str = field(default="utf-8", kw_only=True)
    encoding_error_handler: str = field(default="strict", kw_only=True)

    def __add__(self, other: BaseArtifact) -> BlobArtifact:
        return BlobArtifact(self.value + other.value, name=self.name)

    @property
    def full_path(self) -> str:
        return os.path.join(self.dir_name, self.name) if self.dir_name else self.name

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

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

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

full_path: str property

value: bytes = field(converter=BaseArtifact.value_to_bytes, metadata={'serializable': True}) class-attribute instance-attribute

__add__(other)

Source code in griptape/artifacts/blob_artifact.py
def __add__(self, other: BaseArtifact) -> BlobArtifact:
    return BlobArtifact(self.value + other.value, name=self.name)

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)

CsvRowArtifact

Bases: TextArtifact

Source code in griptape/artifacts/csv_row_artifact.py
@define
class CsvRowArtifact(TextArtifact):
    value: dict[str, str] = field(converter=BaseArtifact.value_to_dict, metadata={"serializable": True})
    delimiter: str = field(default=",", kw_only=True, metadata={"serializable": True})

    def __add__(self, other: BaseArtifact) -> CsvRowArtifact:
        return CsvRowArtifact(self.value | other.value)

    def to_text(self) -> str:
        with io.StringIO() as csvfile:
            writer = csv.DictWriter(
                csvfile, fieldnames=self.value.keys(), quoting=csv.QUOTE_MINIMAL, delimiter=self.delimiter
            )

            writer.writerow(self.value)

            return csvfile.getvalue().strip()

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

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

value: dict[str, str] = field(converter=BaseArtifact.value_to_dict, metadata={'serializable': True}) class-attribute instance-attribute

__add__(other)

Source code in griptape/artifacts/csv_row_artifact.py
def __add__(self, other: BaseArtifact) -> CsvRowArtifact:
    return CsvRowArtifact(self.value | other.value)

__bool__()

Source code in griptape/artifacts/csv_row_artifact.py
def __bool__(self) -> bool:
    return len(self) > 0

to_text()

Source code in griptape/artifacts/csv_row_artifact.py
def to_text(self) -> str:
    with io.StringIO() as csvfile:
        writer = csv.DictWriter(
            csvfile, fieldnames=self.value.keys(), quoting=csv.QUOTE_MINIMAL, delimiter=self.delimiter
        )

        writer.writerow(self.value)

        return csvfile.getvalue().strip()

ErrorArtifact

Bases: BaseArtifact

Source code in griptape/artifacts/error_artifact.py
@define
class ErrorArtifact(BaseArtifact):
    value: str = field(converter=str, metadata={"serializable": True})
    exception: Optional[Exception] = field(default=None, kw_only=True, metadata={"serializable": False})

    def __add__(self, other: BaseArtifact) -> ErrorArtifact:
        return ErrorArtifact(self.value + other.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

__add__(other)

Source code in griptape/artifacts/error_artifact.py
def __add__(self, other: BaseArtifact) -> ErrorArtifact:
    return ErrorArtifact(self.value + other.value)

ImageArtifact

Bases: MediaArtifact

ImageArtifact is a type of MediaArtifact representing an image.

Attributes:

Name Type Description
value

Raw bytes representing media data.

media_type str

The type of media, defaults to "image".

format str

The format of the media, like png, jpeg, or gif.

name str

Artifact name, generated using creation time and a random string.

model str

Optionally specify the model used to generate the media.

prompt str

Optionally specify the prompt used to generate the media.

Source code in griptape/artifacts/image_artifact.py
@define
class ImageArtifact(MediaArtifact):
    """ImageArtifact is a type of MediaArtifact representing an image.

    Attributes:
        value: Raw bytes representing media data.
        media_type: The type of media, defaults to "image".
        format: The format of the media, like png, jpeg, or gif.
        name: Artifact name, generated using creation time and a random string.
        model: Optionally specify the model used to generate the media.
        prompt: Optionally specify the prompt used to generate the media.
    """

    media_type: str = "image"
    width: int = field(kw_only=True, metadata={"serializable": True})
    height: int = field(kw_only=True, metadata={"serializable": True})

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

media_type: str = 'image' class-attribute instance-attribute

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

InfoArtifact

Bases: BaseArtifact

Source code in griptape/artifacts/info_artifact.py
@define
class InfoArtifact(BaseArtifact):
    value: str = field(converter=str, metadata={"serializable": True})

    def __add__(self, other: BaseArtifact) -> InfoArtifact:
        return InfoArtifact(self.value + other.value)

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

__add__(other)

Source code in griptape/artifacts/info_artifact.py
def __add__(self, other: BaseArtifact) -> InfoArtifact:
    return InfoArtifact(self.value + other.value)

ListArtifact

Bases: BaseArtifact

Source code in griptape/artifacts/list_artifact.py
@define
class ListArtifact(BaseArtifact):
    value: Sequence[BaseArtifact] = field(factory=list, metadata={"serializable": True})
    item_separator: str = field(default="\n\n", kw_only=True, metadata={"serializable": True})

    @value.validator  # pyright: ignore
    def validate_value(self, _, value: list[BaseArtifact]) -> None:
        if 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) -> BaseArtifact:
        return self.value[key]

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

    def to_text(self) -> str:
        return self.item_separator.join([v.to_text() for v in self.value])

    def __add__(self, other: BaseArtifact) -> BaseArtifact:
        return ListArtifact(self.value + other.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

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

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
def validate_value(self, _, value: list[BaseArtifact]) -> None:
    if 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")

MediaArtifact

Bases: BlobArtifact

MediaArtifact is a type of BlobArtifact that represents media (image, audio, video, etc.) and can be extended to support a specific media type.

Attributes:

Name Type Description
value

Raw bytes representing media data.

media_type str

The type of media, like image, audio, or video.

format str

The format of the media, like png, wav, or mp4.

name str

Artifact name, generated using creation time and a random string.

model Optional[str]

Optionally specify the model used to generate the media.

prompt Optional[str]

Optionally specify the prompt used to generate the media.

Source code in griptape/artifacts/media_artifact.py
@define
class MediaArtifact(BlobArtifact):
    """MediaArtifact is a type of BlobArtifact that represents media (image, audio, video, etc.)
    and can be extended to support a specific media type.

    Attributes:
        value: Raw bytes representing media data.
        media_type: The type of media, like image, audio, or video.
        format: The format of the media, like png, wav, or mp4.
        name: Artifact name, generated using creation time and a random string.
        model: Optionally specify the model used to generate the media.
        prompt: Optionally specify the prompt used to generate the media.
    """

    media_type: str = field(default="media", kw_only=True, metadata={"serializable": True})
    format: str = field(kw_only=True, metadata={"serializable": True})
    model: Optional[str] = field(default=None, kw_only=True, metadata={"serializable": True})
    prompt: Optional[str] = field(default=None, kw_only=True, metadata={"serializable": True})

    def __attrs_post_init__(self):
        # 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"{self.media_type}/{self.format}"

    @property
    def base64(self) -> str:
        return base64.b64encode(self.value).decode("utf-8")

    def to_text(self) -> str:
        return f"Media, type: {self.mime_type}, 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"{self.media_type}_artifact_{fmt_time}_{entropy}.{self.format}"

base64: str property

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

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

mime_type: str property

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

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

__attrs_post_init__()

Source code in griptape/artifacts/media_artifact.py
def __attrs_post_init__(self):
    # 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/media_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"{self.media_type}_artifact_{fmt_time}_{entropy}.{self.format}"

to_text()

Source code in griptape/artifacts/media_artifact.py
def to_text(self) -> str:
    return f"Media, type: {self.mime_type}, size: {len(self.value)} bytes"

TextArtifact

Bases: BaseArtifact

Source code in griptape/artifacts/text_artifact.py
@define
class TextArtifact(BaseArtifact):
    value: str = field(converter=str, metadata={"serializable": True})
    encoding: str = field(default="utf-8", kw_only=True)
    encoding_error_handler: str = field(default="strict", kw_only=True)
    _embedding: list[float] = field(factory=list, kw_only=True)

    @property
    def embedding(self) -> Optional[list[float]]:
        return None if len(self._embedding) == 0 else self._embedding

    def __add__(self, other: BaseArtifact) -> TextArtifact:
        return TextArtifact(self.value + other.value)

    def __bool__(self) -> bool:
        return bool(self.value.strip())

    def generate_embedding(self, driver: BaseEmbeddingDriver) -> Optional[list[float]]:
        self._embedding.clear()
        self._embedding.extend(driver.embed_string(str(self.value)))

        return self.embedding

    def token_count(self, tokenizer: BaseTokenizer) -> int:
        return tokenizer.count_tokens(str(self.value))

    def to_bytes(self) -> bytes:
        return self.value.encode(encoding=self.encoding, errors=self.encoding_error_handler)

embedding: Optional[list[float]] property

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

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) -> Optional[list[float]]:
    self._embedding.clear()
    self._embedding.extend(driver.embed_string(str(self.value)))

    return self.embedding

to_bytes()

Source code in griptape/artifacts/text_artifact.py
def to_bytes(self) -> bytes:
    return self.value.encode(encoding=self.encoding, errors=self.encoding_error_handler)

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