State Management

Persist and share data across agent runs, team coordination, and workflow execution

State is data that persists across multiple runs within a session, enabling agents, teams, and workflows to maintain context and remember information.

Common use cases include managing user-specific data like shopping lists, todo lists, preferences, or any information that needs to persist across interactions. State is managed through session_state, which can be accessed and updated in tools, then automatically persisted to your database.

How State Works

State in Kern follows this pattern:

  1. Initialize - Set default session_state when creating agents, teams, or workflows
  2. Access - Tools access state via run_context.session_state
  3. Update - Modifications are automatically persisted to the database
  4. Load - Subsequent runs in the same session retrieve the stored state

Basic Example

Here's a simple agent that maintains a shopping list:

1from kern.agent import Agent
2from kern.db.sqlite import SqliteDb
3from kern.run import RunContext
4
5def add_item(run_context: RunContext, item: str) -> str:
6 """Add an item to the shopping list."""
7 run_context.session_state["shopping_list"].append(item)
8 return f"Added {item}"
9
10agent = Agent(
11 db=SqliteDb(db_file="tmp/state.db"),
12 session_state={"shopping_list": []}, # Default state
13 tools=[add_item],
14 instructions="Shopping list: {shopping_list}", # State in instructions
15)
16
17agent.print_response("Add milk and eggs")
18print(agent.get_session_state()) # {'shopping_list': ['milk', 'eggs']}

Learn more

Developer Resources