Skip to content

Mixins

__all__ = ['ActivityMixin', 'ExponentialBackoffMixin', 'ActionSubtaskOriginMixin', 'RuleMixin', 'ImageArtifactFileOutputMixin'] module-attribute

ActionSubtaskOriginMixin

Source code in griptape/griptape/mixins/action_subtask_origin_mixin.py
@define(slots=False)
class ActionSubtaskOriginMixin:
    @abstractmethod
    def find_tool(self, tool_name: str) -> BaseTool | None:
        ...

    @abstractmethod
    def find_memory(self, memory_name: str) -> TaskMemory | None:
        ...

    @abstractmethod
    def find_subtask(self, subtask_id: str) -> ActionSubtask | None:
        ...

    @abstractmethod
    def add_subtask(self, subtask: ActionSubtask) -> ActionSubtask:
        ...

add_subtask(subtask) abstractmethod

Source code in griptape/griptape/mixins/action_subtask_origin_mixin.py
@abstractmethod
def add_subtask(self, subtask: ActionSubtask) -> ActionSubtask:
    ...

find_memory(memory_name) abstractmethod

Source code in griptape/griptape/mixins/action_subtask_origin_mixin.py
@abstractmethod
def find_memory(self, memory_name: str) -> TaskMemory | None:
    ...

find_subtask(subtask_id) abstractmethod

Source code in griptape/griptape/mixins/action_subtask_origin_mixin.py
@abstractmethod
def find_subtask(self, subtask_id: str) -> ActionSubtask | None:
    ...

find_tool(tool_name) abstractmethod

Source code in griptape/griptape/mixins/action_subtask_origin_mixin.py
@abstractmethod
def find_tool(self, tool_name: str) -> BaseTool | None:
    ...

ActivityMixin

Source code in griptape/griptape/mixins/activity_mixin.py
@define(slots=False)
class ActivityMixin:
    allowlist: Optional[list[str]] = field(default=None, kw_only=True)
    denylist: Optional[list[str]] = field(default=None, kw_only=True)

    @allowlist.validator  # pyright: ignore
    def validate_allowlist(self, _, allowlist: Optional[list[str]]) -> None:
        if allowlist is None:
            return

        if self.denylist is not None:
            raise ValueError("can't have both allowlist and denylist specified")

        for activity_name in allowlist:
            self._validate_tool_activity(activity_name)

    @denylist.validator  # pyright: ignore
    def validate_denylist(self, _, denylist: Optional[list[str]]) -> None:
        if denylist is None:
            return

        if self.allowlist is not None:
            raise ValueError("can't have both allowlist and denylist specified")

        for activity_name in denylist:
            self._validate_tool_activity(activity_name)

    def enable_activities(self) -> None:
        self.allowlist = None
        self.denylist = None

    def disable_activities(self) -> None:
        self.allowlist = []
        self.denylist = None

    # This method has to remain a method and can't be decorated with @property because
    # of the max depth recursion issue in `inspect.getmembers`.
    def activities(self) -> list[Callable]:
        methods = []

        for name, method in inspect.getmembers(self, predicate=inspect.ismethod):
            allowlist_condition = self.allowlist is None or name in self.allowlist
            denylist_condition = self.denylist is None or name not in self.denylist

            if getattr(method, "is_activity", False) and allowlist_condition and denylist_condition:
                methods.append(method)

        return methods

    def find_activity(self, name: str) -> Optional[Callable]:
        for activity in self.activities():
            if getattr(activity, "is_activity", False) and getattr(activity, "name") == name:
                return activity

        return None

    def activity_name(self, activity: Callable) -> str:
        if activity is None or not getattr(activity, "is_activity", False):
            raise Exception("This method is not an activity.")
        else:
            return getattr(activity, "name")

    def activity_description(self, activity: Callable) -> str:
        if activity is None or not getattr(activity, "is_activity", False):
            raise Exception("This method is not an activity.")
        else:
            return Template(getattr(activity, "config")["description"]).render({"_self": self})

    def activity_schema(self, activity: Callable) -> Optional[dict]:
        if activity is None or not getattr(activity, "is_activity", False):
            raise Exception("This method is not an activity.")
        elif getattr(activity, "config")["schema"]:
            full_schema = {
                "values": getattr(activity, "config")["schema"].schema if getattr(activity, "config")["schema"] else {}
            }

            return Schema(full_schema).json_schema("InputSchema")
        else:
            return None

    def _validate_tool_activity(self, activity_name):
        tool = self.__class__

        activity = getattr(tool, activity_name, None)

        if not activity or not getattr(activity, "is_activity", False):
            raise ValueError(f"activity {activity_name} is not a valid activity for {tool}")

allowlist: Optional[list[str]] = field(default=None, kw_only=True) class-attribute instance-attribute

denylist: Optional[list[str]] = field(default=None, kw_only=True) class-attribute instance-attribute

activities()

Source code in griptape/griptape/mixins/activity_mixin.py
def activities(self) -> list[Callable]:
    methods = []

    for name, method in inspect.getmembers(self, predicate=inspect.ismethod):
        allowlist_condition = self.allowlist is None or name in self.allowlist
        denylist_condition = self.denylist is None or name not in self.denylist

        if getattr(method, "is_activity", False) and allowlist_condition and denylist_condition:
            methods.append(method)

    return methods

activity_description(activity)

Source code in griptape/griptape/mixins/activity_mixin.py
def activity_description(self, activity: Callable) -> str:
    if activity is None or not getattr(activity, "is_activity", False):
        raise Exception("This method is not an activity.")
    else:
        return Template(getattr(activity, "config")["description"]).render({"_self": self})

activity_name(activity)

Source code in griptape/griptape/mixins/activity_mixin.py
def activity_name(self, activity: Callable) -> str:
    if activity is None or not getattr(activity, "is_activity", False):
        raise Exception("This method is not an activity.")
    else:
        return getattr(activity, "name")

activity_schema(activity)

Source code in griptape/griptape/mixins/activity_mixin.py
def activity_schema(self, activity: Callable) -> Optional[dict]:
    if activity is None or not getattr(activity, "is_activity", False):
        raise Exception("This method is not an activity.")
    elif getattr(activity, "config")["schema"]:
        full_schema = {
            "values": getattr(activity, "config")["schema"].schema if getattr(activity, "config")["schema"] else {}
        }

        return Schema(full_schema).json_schema("InputSchema")
    else:
        return None

disable_activities()

Source code in griptape/griptape/mixins/activity_mixin.py
def disable_activities(self) -> None:
    self.allowlist = []
    self.denylist = None

enable_activities()

Source code in griptape/griptape/mixins/activity_mixin.py
def enable_activities(self) -> None:
    self.allowlist = None
    self.denylist = None

find_activity(name)

Source code in griptape/griptape/mixins/activity_mixin.py
def find_activity(self, name: str) -> Optional[Callable]:
    for activity in self.activities():
        if getattr(activity, "is_activity", False) and getattr(activity, "name") == name:
            return activity

    return None

validate_allowlist(_, allowlist)

Source code in griptape/griptape/mixins/activity_mixin.py
@allowlist.validator  # pyright: ignore
def validate_allowlist(self, _, allowlist: Optional[list[str]]) -> None:
    if allowlist is None:
        return

    if self.denylist is not None:
        raise ValueError("can't have both allowlist and denylist specified")

    for activity_name in allowlist:
        self._validate_tool_activity(activity_name)

validate_denylist(_, denylist)

Source code in griptape/griptape/mixins/activity_mixin.py
@denylist.validator  # pyright: ignore
def validate_denylist(self, _, denylist: Optional[list[str]]) -> None:
    if denylist is None:
        return

    if self.allowlist is not None:
        raise ValueError("can't have both allowlist and denylist specified")

    for activity_name in denylist:
        self._validate_tool_activity(activity_name)

ExponentialBackoffMixin

Bases: ABC

Source code in griptape/griptape/mixins/exponential_backoff_mixin.py
@define(slots=False)
class ExponentialBackoffMixin(ABC):
    min_retry_delay: float = field(default=2, kw_only=True)
    max_retry_delay: float = field(default=10, kw_only=True)
    max_attempts: int = field(default=10, kw_only=True)
    after_hook: Callable = field(default=lambda s: logging.warning(s), kw_only=True)
    ignored_exception_types: Tuple[Type[Exception], ...] = field(factory=tuple, kw_only=True)

    def retrying(self) -> Retrying:
        return Retrying(
            wait=wait_exponential(min=self.min_retry_delay, max=self.max_retry_delay),
            retry=retry_if_not_exception_type(self.ignored_exception_types),
            stop=stop_after_attempt(self.max_attempts),
            reraise=True,
            after=self.after_hook,
        )

after_hook: Callable = field(default=lambda : logging.warning(s), kw_only=True) class-attribute instance-attribute

ignored_exception_types: Tuple[Type[Exception], ...] = field(factory=tuple, kw_only=True) class-attribute instance-attribute

max_attempts: int = field(default=10, kw_only=True) class-attribute instance-attribute

max_retry_delay: float = field(default=10, kw_only=True) class-attribute instance-attribute

min_retry_delay: float = field(default=2, kw_only=True) class-attribute instance-attribute

retrying()

Source code in griptape/griptape/mixins/exponential_backoff_mixin.py
def retrying(self) -> Retrying:
    return Retrying(
        wait=wait_exponential(min=self.min_retry_delay, max=self.max_retry_delay),
        retry=retry_if_not_exception_type(self.ignored_exception_types),
        stop=stop_after_attempt(self.max_attempts),
        reraise=True,
        after=self.after_hook,
    )

ImageArtifactFileOutputMixin

Source code in griptape/griptape/mixins/image_artifact_file_output_mixin.py
@define(slots=False)
class ImageArtifactFileOutputMixin:
    output_dir: str | None = field(default=None, kw_only=True)
    output_file: str | None = field(default=None, kw_only=True)

    @output_dir.validator  # pyright: ignore
    def validate_output_dir(self, _, output_dir: str) -> None:
        if not output_dir:
            return

        if self.output_file:
            raise ValueError("Can't have both output_dir and output_file specified.")

    @output_file.validator  # pyright: ignore
    def validate_output_file(self, _, output_file: str) -> None:
        if not output_file:
            return

        if self.output_dir:
            raise ValueError("Can't have both output_dir and output_file specified.")

    def _write_to_file(self, artifact: ImageArtifact) -> None:
        if self.output_file:
            outfile = self.output_file
        elif self.output_dir:
            outfile = os.path.join(self.output_dir, artifact.name)
        else:
            raise ValueError("No output_file or output_dir specified.")

        if os.path.dirname(outfile):
            os.makedirs(os.path.dirname(outfile), exist_ok=True)

        with open(outfile, "wb") as f:
            f.write(artifact.value)

output_dir: str | None = field(default=None, kw_only=True) class-attribute instance-attribute

output_file: str | None = field(default=None, kw_only=True) class-attribute instance-attribute

validate_output_dir(_, output_dir)

Source code in griptape/griptape/mixins/image_artifact_file_output_mixin.py
@output_dir.validator  # pyright: ignore
def validate_output_dir(self, _, output_dir: str) -> None:
    if not output_dir:
        return

    if self.output_file:
        raise ValueError("Can't have both output_dir and output_file specified.")

validate_output_file(_, output_file)

Source code in griptape/griptape/mixins/image_artifact_file_output_mixin.py
@output_file.validator  # pyright: ignore
def validate_output_file(self, _, output_file: str) -> None:
    if not output_file:
        return

    if self.output_dir:
        raise ValueError("Can't have both output_dir and output_file specified.")

RuleMixin

Source code in griptape/griptape/mixins/rule_mixin.py
@define(slots=False)
class RuleMixin:
    DEFAULT_RULESET_NAME = "Default Ruleset"
    ADDITIONAL_RULESET_NAME = "Additional Ruleset"

    rulesets: list[Ruleset] = field(factory=list, kw_only=True)
    rules: list[Rule] = field(factory=list, kw_only=True)
    structure: Structure = field(default=None, kw_only=True)

    @rulesets.validator  # pyright: ignore
    def validate_rulesets(self, _, rulesets: list[Ruleset]) -> None:
        if not rulesets:
            return

        if self.rules:
            raise ValueError("Can't have both rulesets and rules specified.")

    @rules.validator  # pyright: ignore
    def validate_rules(self, _, rules: list[Rule]) -> None:
        if not rules:
            return

        if self.rulesets:
            raise ValueError("Can't have both rules and rulesets specified.")

    @property
    def all_rulesets(self) -> list[Ruleset]:
        structure_rulesets = []

        if self.structure:
            if self.structure.rulesets:
                structure_rulesets = self.structure.rulesets
            elif self.structure.rules:
                structure_rulesets = [Ruleset(name=self.DEFAULT_RULESET_NAME, rules=self.structure.rules)]

        task_rulesets = []
        if self.rulesets:
            task_rulesets = self.rulesets
        elif self.rules:
            if structure_rulesets:
                task_ruleset_name = self.ADDITIONAL_RULESET_NAME
            else:
                task_ruleset_name = self.DEFAULT_RULESET_NAME

            task_rulesets = [Ruleset(name=task_ruleset_name, rules=self.rules)]

        return structure_rulesets + task_rulesets

ADDITIONAL_RULESET_NAME = 'Additional Ruleset' class-attribute instance-attribute

DEFAULT_RULESET_NAME = 'Default Ruleset' class-attribute instance-attribute

all_rulesets: list[Ruleset] property

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

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

structure: Structure = field(default=None, kw_only=True) class-attribute instance-attribute

validate_rules(_, rules)

Source code in griptape/griptape/mixins/rule_mixin.py
@rules.validator  # pyright: ignore
def validate_rules(self, _, rules: list[Rule]) -> None:
    if not rules:
        return

    if self.rulesets:
        raise ValueError("Can't have both rules and rulesets specified.")

validate_rulesets(_, rulesets)

Source code in griptape/griptape/mixins/rule_mixin.py
@rulesets.validator  # pyright: ignore
def validate_rulesets(self, _, rulesets: list[Ruleset]) -> None:
    if not rulesets:
        return

    if self.rules:
        raise ValueError("Can't have both rulesets and rules specified.")