Serialization#
Overview#
Many components in Gen AI Builder can be serialized and deserialized using the to_dict(*, types_overrides=None, serializable_overrides=None) and from_dict(data, *, types_overrides=None, serializable_overrides=None)classmethod methods. There are also value_to_json(value)classmethod and from_json(data, *, types_overrides=None, serializable_overrides=None)classmethod as a convenience.
Here is how we can serialize an Agent and then deserialize it back:
from griptape.structures import Agent
agent = Agent()
agent.run("My name is Collin")
agent_dict = agent.to_dict()
new_agent = Agent.from_dict(agent_dict)
new_agent.run("Whats my name?")
Serialization Overrides#
All classes that implement the SerializableMixin can be serialized using the
above methods. However, only fields marked with
metadata={"serializable": True} will be included in the
serialization process. If you need to add or remove fields in the
serialization process, you can pass serialization_overrides to any of the
serialization methods.
from rich.pretty import pprint
from griptape.structures import Agent
agent = Agent()
agent.run("My name is Collin")
agent_dict = agent.to_dict(serializable_overrides={"max_meta_memory_entries": True, "id": False})
# `max_meta_memory_entries` will be included, `id` will not
pprint(agent_dict)
Types Overrides#
Due to some unfortunate internals of the Gen AI Builder’s serialization
process, you may occasionally run into a NameError when serializing.
It will look something like this:
This is something we’re actively working on fixing, but in the meantime, you can use the from_dict(data, *, types_overrides=None, serializable_overrides=None)classmethod parameter to pass in a dictionary of types that need to be overridden during serialization.
Here is an example of how you can use types_overrides :
from duckduckgo_search import DDGS
from rich.pretty import pprint
from griptape.drivers.web_search import BaseWebSearchDriver
from griptape.drivers.web_search.duck_duck_go import DuckDuckGoWebSearchDriver
from griptape.tools import WebSearchTool
web_driver = DuckDuckGoWebSearchDriver()
web_tool = WebSearchTool(web_search_driver=web_driver)
web_tool_dict = web_tool.to_dict(
serializable_overrides={"web_search_driver": True},
types_overrides={"BaseWebSearchDriver": BaseWebSearchDriver, "DDGS": DDGS},
)
pprint(web_tool_dict)