Agent Serialization

Serialize and deserialize agents using to_dict/from_dict and save/load with a database.

Agent Serialization.

1"""
2Agent Serialization
3=============================
4
5Agent Serialization.
6"""
7
8from kern.agent import Agent
9from kern.db.sqlite import SqliteDb
10from kern.models.openai import OpenAIResponses
11
12# ---------------------------------------------------------------------------
13# Setup
14# ---------------------------------------------------------------------------
15agent_db = SqliteDb(db_file="tmp/agents.db")
16
17# ---------------------------------------------------------------------------
18# Create Agent
19# ---------------------------------------------------------------------------
20agent = Agent(
21 id="serialization-demo-agent",
22 name="Serialization Demo Agent",
23 model=OpenAIResponses(id="gpt-5.2"),
24 db=agent_db,
25)
26
27# ---------------------------------------------------------------------------
28# Run Agent
29# ---------------------------------------------------------------------------
30if __name__ == "__main__":
31 config = agent.to_dict()
32 recreated = Agent.from_dict(config)
33
34 version = agent.save()
35 loaded = Agent.load(id=agent.id, db=agent_db, version=version)
36
37 recreated.print_response("Say hello from a recreated agent.", stream=True)
38 loaded.print_response("Say hello from a loaded agent.", stream=True)

Run the Example

1# Clone and setup repo
2git clone https://github.com/kern-ai/kern.git
3cd kern/cookbook/02_agents/14_advanced
4
5# Create and activate virtual environment
6./scripts/demo_setup.sh
7source .venvs/demo/bin/activate
8
9python agent_serialization.py