Skip to content

common

__all__ = ['BaseMessage', 'BaseDeltaMessageContent', 'BaseMessageContent', 'DeltaMessage', 'Message', 'TextDeltaMessageContent', 'TextMessageContent', 'ImageMessageContent', 'GenericMessageContent', 'ActionCallDeltaMessageContent', 'ActionCallMessageContent', 'ActionResultMessageContent', 'PromptStack', 'Reference', 'BaseAction', 'ToolAction', 'observable', 'Observable'] module-attribute

ActionCallDeltaMessageContent

Bases: BaseDeltaMessageContent

Source code in griptape/common/prompt_stack/contents/action_call_delta_message_content.py
@define
class ActionCallDeltaMessageContent(BaseDeltaMessageContent):
    tag: Optional[str] = field(default=None, metadata={"serializable": True})
    name: Optional[str] = field(default=None, metadata={"serializable": True})
    path: Optional[str] = field(default=None, metadata={"serializable": True})
    partial_input: Optional[str] = field(default=None, metadata={"serializable": True})

    def __str__(self) -> str:
        parts = []

        if self.name:
            parts.append(self.name)
            if self.path:
                parts.append(f".{self.path}")
                if self.tag:
                    parts.append(f" ({self.tag})")

        if self.partial_input:
            if parts:
                parts.append(f" {self.partial_input}")
            else:
                parts.append(self.partial_input)

        return "".join(parts)

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

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

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

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

__str__()

Source code in griptape/common/prompt_stack/contents/action_call_delta_message_content.py
def __str__(self) -> str:
    parts = []

    if self.name:
        parts.append(self.name)
        if self.path:
            parts.append(f".{self.path}")
            if self.tag:
                parts.append(f" ({self.tag})")

    if self.partial_input:
        if parts:
            parts.append(f" {self.partial_input}")
        else:
            parts.append(self.partial_input)

    return "".join(parts)

ActionCallMessageContent

Bases: BaseMessageContent

Source code in griptape/common/prompt_stack/contents/action_call_message_content.py
@define
class ActionCallMessageContent(BaseMessageContent):
    artifact: ActionArtifact = field(metadata={"serializable": True})

    @classmethod
    def from_deltas(cls, deltas: Sequence[BaseDeltaMessageContent]) -> ActionCallMessageContent:
        action_call_deltas = [delta for delta in deltas if isinstance(delta, ActionCallDeltaMessageContent)]

        tag = None
        name = None
        path = None
        json_input = ""

        for delta in action_call_deltas:
            if delta.tag is not None:
                tag = delta.tag
            if delta.name is not None:
                name = delta.name
            if delta.path is not None:
                path = delta.path
            if delta.partial_input is not None:
                json_input += delta.partial_input

        if tag is not None and name is not None and path is not None:
            try:
                parsed_input = json.loads(json_input)
            except json.JSONDecodeError as exc:
                raise ValueError("Invalid JSON input for ToolAction") from exc
            action = ToolAction(tag=tag, name=name, path=path, input=parsed_input)
        else:
            raise ValueError("Missing required fields for ToolAction")

        artifact = ActionArtifact(value=action)

        return cls(artifact=artifact)

artifact: ActionArtifact = field(metadata={'serializable': True}) class-attribute instance-attribute

from_deltas(deltas) classmethod

Source code in griptape/common/prompt_stack/contents/action_call_message_content.py
@classmethod
def from_deltas(cls, deltas: Sequence[BaseDeltaMessageContent]) -> ActionCallMessageContent:
    action_call_deltas = [delta for delta in deltas if isinstance(delta, ActionCallDeltaMessageContent)]

    tag = None
    name = None
    path = None
    json_input = ""

    for delta in action_call_deltas:
        if delta.tag is not None:
            tag = delta.tag
        if delta.name is not None:
            name = delta.name
        if delta.path is not None:
            path = delta.path
        if delta.partial_input is not None:
            json_input += delta.partial_input

    if tag is not None and name is not None and path is not None:
        try:
            parsed_input = json.loads(json_input)
        except json.JSONDecodeError as exc:
            raise ValueError("Invalid JSON input for ToolAction") from exc
        action = ToolAction(tag=tag, name=name, path=path, input=parsed_input)
    else:
        raise ValueError("Missing required fields for ToolAction")

    artifact = ActionArtifact(value=action)

    return cls(artifact=artifact)

ActionResultMessageContent

Bases: BaseMessageContent

Source code in griptape/common/prompt_stack/contents/action_result_message_content.py
@define
class ActionResultMessageContent(BaseMessageContent):
    artifact: BaseArtifact = field(metadata={"serializable": True})
    action: ToolAction = field(metadata={"serializable": True})

    @classmethod
    def from_deltas(cls, deltas: Sequence[BaseDeltaMessageContent]) -> ActionResultMessageContent:
        raise NotImplementedError

action: ToolAction = field(metadata={'serializable': True}) class-attribute instance-attribute

artifact: BaseArtifact = field(metadata={'serializable': True}) class-attribute instance-attribute

from_deltas(deltas) classmethod

Source code in griptape/common/prompt_stack/contents/action_result_message_content.py
@classmethod
def from_deltas(cls, deltas: Sequence[BaseDeltaMessageContent]) -> ActionResultMessageContent:
    raise NotImplementedError

BaseAction

Bases: SerializableMixin, ABC

Source code in griptape/common/actions/base_action.py
class BaseAction(SerializableMixin, ABC): ...

BaseDeltaMessageContent

Bases: ABC, SerializableMixin

Source code in griptape/common/prompt_stack/contents/base_delta_message_content.py
@define
class BaseDeltaMessageContent(ABC, SerializableMixin):
    index: int = field(kw_only=True, default=0, metadata={"serializable": True})

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

BaseMessage

Bases: ABC, SerializableMixin

Source code in griptape/common/prompt_stack/messages/base_message.py
@define
class BaseMessage(ABC, SerializableMixin):
    @define
    class Usage(SerializableMixin):
        input_tokens: Optional[float] = field(kw_only=True, default=None, metadata={"serializable": True})
        output_tokens: Optional[float] = field(kw_only=True, default=None, metadata={"serializable": True})

        @property
        def total_tokens(self) -> float:
            return (self.input_tokens or 0) + (self.output_tokens or 0)

        def __add__(self, other: BaseMessage.Usage) -> BaseMessage.Usage:
            return BaseMessage.Usage(
                input_tokens=(self.input_tokens or 0) + (other.input_tokens or 0),
                output_tokens=(self.output_tokens or 0) + (other.output_tokens or 0),
            )

    USER_ROLE = "user"
    ASSISTANT_ROLE = "assistant"
    SYSTEM_ROLE = "system"

    content: list[Union[BaseMessageContent, BaseDeltaMessageContent]] = field(metadata={"serializable": True})
    role: str = field(kw_only=True, metadata={"serializable": True})
    usage: Usage = field(kw_only=True, default=Factory(lambda: BaseMessage.Usage()), metadata={"serializable": True})

    def is_system(self) -> bool:
        return self.role == self.SYSTEM_ROLE

    def is_user(self) -> bool:
        return self.role == self.USER_ROLE

    def is_assistant(self) -> bool:
        return self.role == self.ASSISTANT_ROLE

ASSISTANT_ROLE = 'assistant' class-attribute instance-attribute

SYSTEM_ROLE = 'system' class-attribute instance-attribute

USER_ROLE = 'user' class-attribute instance-attribute

content: list[Union[BaseMessageContent, BaseDeltaMessageContent]] = field(metadata={'serializable': True}) class-attribute instance-attribute

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

usage: Usage = field(kw_only=True, default=Factory(lambda: BaseMessage.Usage()), metadata={'serializable': True}) class-attribute instance-attribute

Usage

Bases: SerializableMixin

Source code in griptape/common/prompt_stack/messages/base_message.py
@define
class Usage(SerializableMixin):
    input_tokens: Optional[float] = field(kw_only=True, default=None, metadata={"serializable": True})
    output_tokens: Optional[float] = field(kw_only=True, default=None, metadata={"serializable": True})

    @property
    def total_tokens(self) -> float:
        return (self.input_tokens or 0) + (self.output_tokens or 0)

    def __add__(self, other: BaseMessage.Usage) -> BaseMessage.Usage:
        return BaseMessage.Usage(
            input_tokens=(self.input_tokens or 0) + (other.input_tokens or 0),
            output_tokens=(self.output_tokens or 0) + (other.output_tokens or 0),
        )
input_tokens: Optional[float] = field(kw_only=True, default=None, metadata={'serializable': True}) class-attribute instance-attribute
output_tokens: Optional[float] = field(kw_only=True, default=None, metadata={'serializable': True}) class-attribute instance-attribute
total_tokens: float property
__add__(other)
Source code in griptape/common/prompt_stack/messages/base_message.py
def __add__(self, other: BaseMessage.Usage) -> BaseMessage.Usage:
    return BaseMessage.Usage(
        input_tokens=(self.input_tokens or 0) + (other.input_tokens or 0),
        output_tokens=(self.output_tokens or 0) + (other.output_tokens or 0),
    )

is_assistant()

Source code in griptape/common/prompt_stack/messages/base_message.py
def is_assistant(self) -> bool:
    return self.role == self.ASSISTANT_ROLE

is_system()

Source code in griptape/common/prompt_stack/messages/base_message.py
def is_system(self) -> bool:
    return self.role == self.SYSTEM_ROLE

is_user()

Source code in griptape/common/prompt_stack/messages/base_message.py
def is_user(self) -> bool:
    return self.role == self.USER_ROLE

BaseMessageContent

Bases: ABC, SerializableMixin

Source code in griptape/common/prompt_stack/contents/base_message_content.py
@define
class BaseMessageContent(ABC, SerializableMixin):
    artifact: BaseArtifact = field(metadata={"serializable": True})

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

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

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

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

    @classmethod
    @abstractmethod
    def from_deltas(cls, deltas: Sequence[BaseDeltaMessageContent]) -> BaseMessageContent: ...

artifact: BaseArtifact = field(metadata={'serializable': True}) class-attribute instance-attribute

__bool__()

Source code in griptape/common/prompt_stack/contents/base_message_content.py
def __bool__(self) -> bool:
    return bool(self.artifact)

__len__()

Source code in griptape/common/prompt_stack/contents/base_message_content.py
def __len__(self) -> int:
    return len(self.artifact)

__str__()

Source code in griptape/common/prompt_stack/contents/base_message_content.py
def __str__(self) -> str:
    return self.artifact.to_text()

from_deltas(deltas) abstractmethod classmethod

Source code in griptape/common/prompt_stack/contents/base_message_content.py
@classmethod
@abstractmethod
def from_deltas(cls, deltas: Sequence[BaseDeltaMessageContent]) -> BaseMessageContent: ...

to_text()

Source code in griptape/common/prompt_stack/contents/base_message_content.py
def to_text(self) -> str:
    return str(self.artifact)

DeltaMessage

Bases: BaseMessage

Source code in griptape/common/prompt_stack/messages/delta_message.py
@define
class DeltaMessage(BaseMessage):
    role: Optional[str] = field(kw_only=True, default=None, metadata={"serializable": True})
    content: Optional[BaseDeltaMessageContent] = field(kw_only=True, default=None, metadata={"serializable": True})

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

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

GenericMessageContent

Bases: BaseMessageContent

Source code in griptape/common/prompt_stack/contents/generic_message_content.py
@define
class GenericMessageContent(BaseMessageContent):
    artifact: GenericArtifact = field(metadata={"serializable": True})

    @classmethod
    def from_deltas(cls, deltas: Sequence[BaseDeltaMessageContent]) -> GenericMessageContent:
        raise NotImplementedError()

artifact: GenericArtifact = field(metadata={'serializable': True}) class-attribute instance-attribute

from_deltas(deltas) classmethod

Source code in griptape/common/prompt_stack/contents/generic_message_content.py
@classmethod
def from_deltas(cls, deltas: Sequence[BaseDeltaMessageContent]) -> GenericMessageContent:
    raise NotImplementedError()

ImageMessageContent

Bases: BaseMessageContent

Source code in griptape/common/prompt_stack/contents/image_message_content.py
@define
class ImageMessageContent(BaseMessageContent):
    artifact: ImageArtifact = field(metadata={"serializable": True})

    @classmethod
    def from_deltas(cls, deltas: Sequence[BaseDeltaMessageContent]) -> ImageMessageContent:
        raise NotImplementedError()

artifact: ImageArtifact = field(metadata={'serializable': True}) class-attribute instance-attribute

from_deltas(deltas) classmethod

Source code in griptape/common/prompt_stack/contents/image_message_content.py
@classmethod
def from_deltas(cls, deltas: Sequence[BaseDeltaMessageContent]) -> ImageMessageContent:
    raise NotImplementedError()

Message

Bases: BaseMessage

Source code in griptape/common/prompt_stack/messages/message.py
@define
class Message(BaseMessage):
    def __init__(self, content: str | list[BaseMessageContent], **kwargs: Any) -> None:
        if isinstance(content, str):
            content = [TextMessageContent(TextArtifact(value=content))]
        self.__attrs_init__(content, **kwargs)  # pyright: ignore[reportAttributeAccessIssue]

    content: list[BaseMessageContent] = field(metadata={"serializable": True})

    @property
    def value(self) -> Any:
        return self.to_artifact().value

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

    def has_all_content_type(self, content_type: type[T]) -> bool:
        return all(isinstance(content, content_type) for content in self.content)

    def has_any_content_type(self, content_type: type[T]) -> bool:
        return any(isinstance(content, content_type) for content in self.content)

    def get_content_type(self, content_type: type[T]) -> list[T]:
        return [content for content in self.content if isinstance(content, content_type)]

    def is_text(self) -> bool:
        return all(isinstance(content, TextMessageContent) for content in self.content)

    def to_text(self) -> str:
        return "".join(
            [content.artifact.to_text() for content in self.content if isinstance(content, TextMessageContent)],
        )

    def to_artifact(self) -> BaseArtifact:
        if len(self.content) == 1:
            return self.content[0].artifact
        else:
            return ListArtifact([content.artifact for content in self.content])

content: list[BaseMessageContent] = field(metadata={'serializable': True}) class-attribute instance-attribute

value: Any property

__init__(content, **kwargs)

Source code in griptape/common/prompt_stack/messages/message.py
def __init__(self, content: str | list[BaseMessageContent], **kwargs: Any) -> None:
    if isinstance(content, str):
        content = [TextMessageContent(TextArtifact(value=content))]
    self.__attrs_init__(content, **kwargs)  # pyright: ignore[reportAttributeAccessIssue]

__str__()

Source code in griptape/common/prompt_stack/messages/message.py
def __str__(self) -> str:
    return self.to_text()

get_content_type(content_type)

Source code in griptape/common/prompt_stack/messages/message.py
def get_content_type(self, content_type: type[T]) -> list[T]:
    return [content for content in self.content if isinstance(content, content_type)]

has_all_content_type(content_type)

Source code in griptape/common/prompt_stack/messages/message.py
def has_all_content_type(self, content_type: type[T]) -> bool:
    return all(isinstance(content, content_type) for content in self.content)

has_any_content_type(content_type)

Source code in griptape/common/prompt_stack/messages/message.py
def has_any_content_type(self, content_type: type[T]) -> bool:
    return any(isinstance(content, content_type) for content in self.content)

is_text()

Source code in griptape/common/prompt_stack/messages/message.py
def is_text(self) -> bool:
    return all(isinstance(content, TextMessageContent) for content in self.content)

to_artifact()

Source code in griptape/common/prompt_stack/messages/message.py
def to_artifact(self) -> BaseArtifact:
    if len(self.content) == 1:
        return self.content[0].artifact
    else:
        return ListArtifact([content.artifact for content in self.content])

to_text()

Source code in griptape/common/prompt_stack/messages/message.py
def to_text(self) -> str:
    return "".join(
        [content.artifact.to_text() for content in self.content if isinstance(content, TextMessageContent)],
    )

Observable

Source code in griptape/common/observable.py
class Observable:
    @define
    class Call:
        func: Callable = field(kw_only=True)
        instance: Optional[Any] = field(default=None, kw_only=True)
        args: tuple[Any, ...] = field(default=Factory(tuple), kw_only=True)
        kwargs: dict[str, Any] = field(default=Factory(dict), kw_only=True)
        decorator_args: tuple[Any, ...] = field(default=Factory(tuple), kw_only=True)
        decorator_kwargs: dict[str, Any] = field(default=Factory(dict), kw_only=True)

        def __call__(self) -> Any:
            # If self.func has a __self__ attribute, it is a bound method and we do not need to pass the instance.
            args = (self.instance, *self.args) if self.instance and not hasattr(self.func, "__self__") else self.args
            return self.func(*args, **self.kwargs)

        @property
        def tags(self) -> Optional[list[str]]:
            return self.decorator_kwargs.get("tags")

    def __init__(self, *args, **kwargs) -> None:
        self._instance = None
        if len(args) == 1 and len(kwargs) == 0 and isfunction(args[0]):
            # Parameterless call. In otherwords, the `@observable` annotation
            # was not followed by parentheses.
            self._func = args[0]
            functools.update_wrapper(self, self._func)
            self.decorator_args = ()
            self.decorator_kwargs = {}
        else:
            # Parameterized call. In otherwords, the `@observable` annotation
            # was followed by parentheses, for example `@observable()`,
            # `@observable("x")` or `@observable(y="y")`.
            self._func = None
            self.decorator_args = args
            self.decorator_kwargs = kwargs

    def __get__(self, obj: Any, objtype: Any = None) -> Observable:
        self._instance = obj
        return self

    def __call__(self, *args, **kwargs) -> Any:
        if self._func:
            # Parameterless call (self._func was a set in __init__)
            from griptape.observability.observability import Observability

            return Observability.observe(
                Observable.Call(
                    func=self._func,
                    instance=self._instance,
                    args=args,
                    kwargs=kwargs,
                    decorator_args=self.decorator_args,
                    decorator_kwargs=self.decorator_kwargs,
                )
            )
        else:
            # Parameterized call, create and return the "real" observable decorator
            func = args[0]
            decorated_func = Observable(func)
            decorated_func.decorator_args = self.decorator_args
            decorated_func.decorator_kwargs = self.decorator_kwargs
            return decorated_func

decorator_args = () instance-attribute

decorator_kwargs = {} instance-attribute

Call

Source code in griptape/common/observable.py
@define
class Call:
    func: Callable = field(kw_only=True)
    instance: Optional[Any] = field(default=None, kw_only=True)
    args: tuple[Any, ...] = field(default=Factory(tuple), kw_only=True)
    kwargs: dict[str, Any] = field(default=Factory(dict), kw_only=True)
    decorator_args: tuple[Any, ...] = field(default=Factory(tuple), kw_only=True)
    decorator_kwargs: dict[str, Any] = field(default=Factory(dict), kw_only=True)

    def __call__(self) -> Any:
        # If self.func has a __self__ attribute, it is a bound method and we do not need to pass the instance.
        args = (self.instance, *self.args) if self.instance and not hasattr(self.func, "__self__") else self.args
        return self.func(*args, **self.kwargs)

    @property
    def tags(self) -> Optional[list[str]]:
        return self.decorator_kwargs.get("tags")
args: tuple[Any, ...] = field(default=Factory(tuple), kw_only=True) class-attribute instance-attribute
decorator_args: tuple[Any, ...] = field(default=Factory(tuple), kw_only=True) class-attribute instance-attribute
decorator_kwargs: dict[str, Any] = field(default=Factory(dict), kw_only=True) class-attribute instance-attribute
func: Callable = field(kw_only=True) class-attribute instance-attribute
instance: Optional[Any] = field(default=None, kw_only=True) class-attribute instance-attribute
kwargs: dict[str, Any] = field(default=Factory(dict), kw_only=True) class-attribute instance-attribute
tags: Optional[list[str]] property
__call__()
Source code in griptape/common/observable.py
def __call__(self) -> Any:
    # If self.func has a __self__ attribute, it is a bound method and we do not need to pass the instance.
    args = (self.instance, *self.args) if self.instance and not hasattr(self.func, "__self__") else self.args
    return self.func(*args, **self.kwargs)

__call__(*args, **kwargs)

Source code in griptape/common/observable.py
def __call__(self, *args, **kwargs) -> Any:
    if self._func:
        # Parameterless call (self._func was a set in __init__)
        from griptape.observability.observability import Observability

        return Observability.observe(
            Observable.Call(
                func=self._func,
                instance=self._instance,
                args=args,
                kwargs=kwargs,
                decorator_args=self.decorator_args,
                decorator_kwargs=self.decorator_kwargs,
            )
        )
    else:
        # Parameterized call, create and return the "real" observable decorator
        func = args[0]
        decorated_func = Observable(func)
        decorated_func.decorator_args = self.decorator_args
        decorated_func.decorator_kwargs = self.decorator_kwargs
        return decorated_func

__get__(obj, objtype=None)

Source code in griptape/common/observable.py
def __get__(self, obj: Any, objtype: Any = None) -> Observable:
    self._instance = obj
    return self

__init__(*args, **kwargs)

Source code in griptape/common/observable.py
def __init__(self, *args, **kwargs) -> None:
    self._instance = None
    if len(args) == 1 and len(kwargs) == 0 and isfunction(args[0]):
        # Parameterless call. In otherwords, the `@observable` annotation
        # was not followed by parentheses.
        self._func = args[0]
        functools.update_wrapper(self, self._func)
        self.decorator_args = ()
        self.decorator_kwargs = {}
    else:
        # Parameterized call. In otherwords, the `@observable` annotation
        # was followed by parentheses, for example `@observable()`,
        # `@observable("x")` or `@observable(y="y")`.
        self._func = None
        self.decorator_args = args
        self.decorator_kwargs = kwargs

PromptStack

Bases: SerializableMixin

Source code in griptape/common/prompt_stack/prompt_stack.py
@define
class PromptStack(SerializableMixin):
    messages: list[Message] = field(factory=list, kw_only=True, metadata={"serializable": True})
    tools: list[BaseTool] = field(factory=list, kw_only=True)

    @property
    def system_messages(self) -> list[Message]:
        return [message for message in self.messages if message.is_system()]

    @property
    def user_messages(self) -> list[Message]:
        return [message for message in self.messages if message.is_user()]

    @property
    def assistant_messages(self) -> list[Message]:
        return [message for message in self.messages if message.is_assistant()]

    def add_message(self, artifact: str | BaseArtifact, role: str) -> Message:
        content = self.__to_message_content(artifact)

        self.messages.append(Message(content=content, role=role))

        return self.messages[-1]

    def add_system_message(self, artifact: str | BaseArtifact) -> Message:
        return self.add_message(artifact, Message.SYSTEM_ROLE)

    def add_user_message(self, artifact: str | BaseArtifact) -> Message:
        return self.add_message(artifact, Message.USER_ROLE)

    def add_assistant_message(self, artifact: str | BaseArtifact) -> Message:
        return self.add_message(artifact, Message.ASSISTANT_ROLE)

    def __to_message_content(self, artifact: str | BaseArtifact) -> list[BaseMessageContent]:
        if isinstance(artifact, str):
            return [TextMessageContent(TextArtifact(artifact))]
        elif isinstance(artifact, TextArtifact):
            return [TextMessageContent(artifact)]
        elif isinstance(artifact, ImageArtifact):
            return [ImageMessageContent(artifact)]
        elif isinstance(artifact, GenericArtifact):
            return [GenericMessageContent(artifact)]
        elif isinstance(artifact, ActionArtifact):
            action = artifact.value
            output = action.output
            if output is None:
                return [ActionCallMessageContent(artifact)]
            else:
                return [ActionResultMessageContent(output, action=action)]
        elif isinstance(artifact, ListArtifact):
            processed_contents = [self.__to_message_content(artifact) for artifact in artifact.value]

            return [sub_content for processed_content in processed_contents for sub_content in processed_content]
        else:
            return [TextMessageContent(TextArtifact(artifact.to_text()))]

assistant_messages: list[Message] property

messages: list[Message] = field(factory=list, kw_only=True, metadata={'serializable': True}) class-attribute instance-attribute

system_messages: list[Message] property

tools: list[BaseTool] = field(factory=list, kw_only=True) class-attribute instance-attribute

user_messages: list[Message] property

__to_message_content(artifact)

Source code in griptape/common/prompt_stack/prompt_stack.py
def __to_message_content(self, artifact: str | BaseArtifact) -> list[BaseMessageContent]:
    if isinstance(artifact, str):
        return [TextMessageContent(TextArtifact(artifact))]
    elif isinstance(artifact, TextArtifact):
        return [TextMessageContent(artifact)]
    elif isinstance(artifact, ImageArtifact):
        return [ImageMessageContent(artifact)]
    elif isinstance(artifact, GenericArtifact):
        return [GenericMessageContent(artifact)]
    elif isinstance(artifact, ActionArtifact):
        action = artifact.value
        output = action.output
        if output is None:
            return [ActionCallMessageContent(artifact)]
        else:
            return [ActionResultMessageContent(output, action=action)]
    elif isinstance(artifact, ListArtifact):
        processed_contents = [self.__to_message_content(artifact) for artifact in artifact.value]

        return [sub_content for processed_content in processed_contents for sub_content in processed_content]
    else:
        return [TextMessageContent(TextArtifact(artifact.to_text()))]

add_assistant_message(artifact)

Source code in griptape/common/prompt_stack/prompt_stack.py
def add_assistant_message(self, artifact: str | BaseArtifact) -> Message:
    return self.add_message(artifact, Message.ASSISTANT_ROLE)

add_message(artifact, role)

Source code in griptape/common/prompt_stack/prompt_stack.py
def add_message(self, artifact: str | BaseArtifact, role: str) -> Message:
    content = self.__to_message_content(artifact)

    self.messages.append(Message(content=content, role=role))

    return self.messages[-1]

add_system_message(artifact)

Source code in griptape/common/prompt_stack/prompt_stack.py
def add_system_message(self, artifact: str | BaseArtifact) -> Message:
    return self.add_message(artifact, Message.SYSTEM_ROLE)

add_user_message(artifact)

Source code in griptape/common/prompt_stack/prompt_stack.py
def add_user_message(self, artifact: str | BaseArtifact) -> Message:
    return self.add_message(artifact, Message.USER_ROLE)

Reference

Bases: SerializableMixin

Source code in griptape/common/reference.py
@define(kw_only=True)
class Reference(SerializableMixin):
    id: str = field(default=Factory(lambda: uuid.uuid4().hex), metadata={"serializable": True})
    title: str = field(metadata={"serializable": True})
    authors: list[str] = field(factory=list, metadata={"serializable": True})
    source: Optional[str] = field(default=None, metadata={"serializable": True})
    year: Optional[str] = field(default=None, metadata={"serializable": True})
    url: Optional[str] = field(default=None, metadata={"serializable": True})

authors: list[str] = field(factory=list, metadata={'serializable': True}) class-attribute instance-attribute

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

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

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

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

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

TextDeltaMessageContent

Bases: BaseDeltaMessageContent

Source code in griptape/common/prompt_stack/contents/text_delta_message_content.py
@define
class TextDeltaMessageContent(BaseDeltaMessageContent):
    text: str = field(metadata={"serializable": True})

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

TextMessageContent

Bases: BaseMessageContent

Source code in griptape/common/prompt_stack/contents/text_message_content.py
@define
class TextMessageContent(BaseMessageContent):
    artifact: TextArtifact = field(metadata={"serializable": True})

    @classmethod
    def from_deltas(cls, deltas: Sequence[BaseDeltaMessageContent]) -> TextMessageContent:
        text_deltas = [delta for delta in deltas if isinstance(delta, TextDeltaMessageContent)]

        artifact = TextArtifact(value="".join(delta.text for delta in text_deltas))

        return cls(artifact=artifact)

artifact: TextArtifact = field(metadata={'serializable': True}) class-attribute instance-attribute

from_deltas(deltas) classmethod

Source code in griptape/common/prompt_stack/contents/text_message_content.py
@classmethod
def from_deltas(cls, deltas: Sequence[BaseDeltaMessageContent]) -> TextMessageContent:
    text_deltas = [delta for delta in deltas if isinstance(delta, TextDeltaMessageContent)]

    artifact = TextArtifact(value="".join(delta.text for delta in text_deltas))

    return cls(artifact=artifact)

ToolAction

Bases: BaseAction

Represents an instance of an LLM using a Tool.

Attributes:

Name Type Description
tag str

The tag (unique identifier) of the action.

name str

The name (Tool name) of the action.

path Optional[str]

The path (Tool activity name) of the action.

input dict

The input (Tool params) of the action.

tool Optional[BaseTool]

The matched Tool of the action.

output Optional[BaseArtifact]

The output (Tool result) of the action.

Source code in griptape/common/actions/tool_action.py
@define(kw_only=True)
class ToolAction(BaseAction):
    """Represents an instance of an LLM using a Tool.

    Attributes:
        tag: The tag (unique identifier) of the action.
        name: The name (Tool name) of the action.
        path: The path (Tool activity name) of the action.
        input: The input (Tool params) of the action.
        tool: The matched Tool of the action.
        output: The output (Tool result) of the action.
    """

    tag: str = field(metadata={"serializable": True})
    name: str = field(metadata={"serializable": True})
    path: Optional[str] = field(default=None, metadata={"serializable": True})
    input: dict = field(factory=dict, metadata={"serializable": True})
    tool: Optional[BaseTool] = field(default=None)
    output: Optional[BaseArtifact] = field(default=None)

    def __str__(self) -> str:
        return json.dumps(self.to_dict())

    def to_native_tool_name(self) -> str:
        parts = [self.name]

        if self.path is not None:
            parts.append(self.path)

        return "_".join(parts)

    @classmethod
    def from_native_tool_name(cls, native_tool_name: str) -> tuple[str, Optional[str]]:
        parts = native_tool_name.split("_", 1)

        if len(parts) == 1:
            name, path = parts[0], None
        else:
            name, path = parts

        return name, path

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

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

output: Optional[BaseArtifact] = field(default=None) class-attribute instance-attribute

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

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

tool: Optional[BaseTool] = field(default=None) class-attribute instance-attribute

__str__()

Source code in griptape/common/actions/tool_action.py
def __str__(self) -> str:
    return json.dumps(self.to_dict())

from_native_tool_name(native_tool_name) classmethod

Source code in griptape/common/actions/tool_action.py
@classmethod
def from_native_tool_name(cls, native_tool_name: str) -> tuple[str, Optional[str]]:
    parts = native_tool_name.split("_", 1)

    if len(parts) == 1:
        name, path = parts[0], None
    else:
        name, path = parts

    return name, path

to_native_tool_name()

Source code in griptape/common/actions/tool_action.py
def to_native_tool_name(self) -> str:
    parts = [self.name]

    if self.path is not None:
        parts.append(self.path)

    return "_".join(parts)