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

<a href="./#griptape.artifacts.ActionArtifact.value" title="value = field(metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.ActionArtifact.value)"><code class="language-python">value</code></a>

<a href="../common#griptape.common.ToolAction" title="ToolAction (griptape.common.ToolAction)"><code class="language-python">ToolAction</code></a>

The Action to take. Currently only supports ToolAction.<br/>

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

<a href="./#griptape.artifacts.AudioArtifact.format" title="format = field(kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.AudioArtifact.format)"><code class="language-python">format</code></a>

str

The audio format, e.g. "wav" or "mp3".<br/>

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

  • mime_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

<a href="./#griptape.artifacts.BaseArtifact.id" title="id = field(default=Factory(lambda: uuid.uuid4().hex), kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.BaseArtifact.id)"><code class="language-python">id</code></a>

str

The unique identifier of the Artifact. Defaults to a random UUID.<br/>

<a href="./#griptape.artifacts.BaseArtifact.reference" title="reference = field(default=None, kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.BaseArtifact.reference)"><code class="language-python">reference</code></a>

<a href="../common#griptape.common.Reference" title="Reference (griptape.common.Reference)"><code class="language-python">Optional[Reference]</code></a>

The optional Reference to the Artifact.<br/>

<a href="./#griptape.artifacts.BaseArtifact.meta" title="meta = field(factory=dict, kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.BaseArtifact.meta)"><code class="language-python">meta</code></a>

dict[str, Any]

The metadata associated with the Artifact. Defaults to an empty dictionary.<br/>

<a href="./#griptape.artifacts.BaseArtifact.name" title="name = field(default=Factory(lambda self: self.id, takes_self=True), kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.BaseArtifact.name)"><code class="language-python">name</code></a>

str

The name of the Artifact. Defaults to the id.<br/>

<a href="./#griptape.artifacts.BaseArtifact.value" title="value = field() class-attribute instance-attribute (griptape.artifacts.BaseArtifact.value)"><code class="language-python">value</code></a>

Any

The value of the Artifact.<br/>

<a href="./#griptape.artifacts.BaseArtifact.encoding" title="encoding = field(default='utf-8', kw_only=True) class-attribute instance-attribute (griptape.artifacts.BaseArtifact.encoding)"><code class="language-python">encoding</code></a>

str

The encoding to use when encoding/decoding the value.<br/>

<a href="./#griptape.artifacts.BaseArtifact.encoding_error_handler" title="encoding_error_handler = field(default='strict', kw_only=True) class-attribute instance-attribute (griptape.artifacts.BaseArtifact.encoding_error_handler)"><code class="language-python">encoding_error_handler</code></a>

str

The error on_event to use when encoding/decoding the value.<br/>

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

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

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

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

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

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

  • value = 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

<a href="./#griptape.artifacts.BlobArtifact.value" title="value = field(converter=lambda value: value if isinstance(value, bytes) else str(value).encode(), metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.BlobArtifact.value)"><code class="language-python">value</code></a>

bytes

The binary data.<br/>

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 property

  • mime_type property

  • value = 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

<a href="./#griptape.artifacts.BooleanArtifact.value" title="value = field(converter=bool, metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.BooleanArtifact.value)"><code class="language-python">value</code></a>

bool

The boolean value.<br/>

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

<a href="./#griptape.artifacts.ErrorArtifact.value" title="value = field(converter=str, metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.ErrorArtifact.value)"><code class="language-python">value</code></a>

str

The error message.<br/>

<a href="./#griptape.artifacts.ErrorArtifact.exception" title="exception = field(default=None, kw_only=True, metadata={'serializable': False}) class-attribute instance-attribute (griptape.artifacts.ErrorArtifact.exception)"><code class="language-python">exception</code></a>

Optional[Exception]

The exception that caused the error. Defaults to None.<br/>

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

  • value = 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#

Name

Type

Description

<a href="./#griptape.artifacts.GenericArtifact.value" title="value = field(metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.GenericArtifact.value)"><code class="language-python">value</code></a>

<a href="generic_artifact.mdx#griptape.artifacts.generic_artifact.T" title="T = TypeVar('T') module-attribute (griptape.artifacts.generic_artifact.T)"><code class="language-python">T</code></a>

The value of the Artifact.<br/>

Source Code in griptape/artifacts/generic_artifact.py

@define
class GenericArtifact(BaseArtifact, Generic[T]):
    """Serves as an escape hatch for artifacts that dont 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

<a href="./#griptape.artifacts.ImageArtifact.format" title="format = field(kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.ImageArtifact.format)"><code class="language-python">format</code></a>

str

The format of the image data. Used when building the MIME type.<br/>

<a href="./#griptape.artifacts.ImageArtifact.width" title="width = field(kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.ImageArtifact.width)"><code class="language-python">width</code></a>

int

The width of the image.<br/>

<a href="./#griptape.artifacts.ImageArtifact.height" title="height = field(kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.ImageArtifact.height)"><code class="language-python">height</code></a>

int

The height of the image<br/>

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

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

  • mime_type property

  • width = 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: ImageUrlArtifact “)

Attributes#

Name

Type

Description

<a href="./#griptape.artifacts.UrlArtifact.value" title="value = field(metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.ImageUrlArtifact.value)"><code class="language-python">value</code></a>

str

The url.<br/>

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

<a href="./#griptape.artifacts.InfoArtifact.value" title="value = field(converter=str, metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.InfoArtifact.value)"><code class="language-python">value</code></a>

str

The info to convey.<br/>

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

<a href="./#griptape.artifacts.JsonArtifact.value" title="value = field(converter=lambda value: JsonArtifact.value_to_json(value), metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.JsonArtifact.value)"><code class="language-python">value</code></a>

<a href="json_artifact.mdx#griptape.artifacts.json_artifact.Json" title="Json = Union[dict[str, 'Json'], list['Json'], str, int, float, bool, None] module-attribute (griptape.artifacts.json_artifact.Json)"><code class="language-python">Json</code></a>

The JSON data. Values will automatically be converted to a JSON-compatible format.<br/>

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 property

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

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

  • value = 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

<a href="./#griptape.artifacts.ModelArtifact.value" title="value = field(metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.ModelArtifact.value)"><code class="language-python">value</code></a>

BaseModel

The pydantic model to store.<br/>

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

  • value = 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

<a href="./#griptape.artifacts.UrlArtifact.value" title="value = field(metadata={'serializable': True}) class-attribute instance-attribute (griptape.artifacts.UrlArtifact.value)"><code class="language-python">value</code></a>

str

The url.<br/>

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 I None

Optional headers to include in the request.<br/>

None

**kwargs

dict

Additional keyword arguments, not used.<br/>

{}

Returns#

Name

Type

Description

bytes

bytes

The content of the URL as bytes.<br/>

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