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:
- Initialize - Set default
session_statewhen creating agents, teams, or workflows - Access - Tools access state via
run_context.session_state - Update - Modifications are automatically persisted to the database
- 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 Agent2from kern.db.sqlite import SqliteDb3from kern.run import RunContext45def 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}"910agent = Agent(11 db=SqliteDb(db_file="tmp/state.db"),12 session_state={"shopping_list": []}, # Default state13 tools=[add_item],14 instructions="Shopping list: {shopping_list}", # State in instructions15)1617agent.print_response("Add milk and eggs")18print(agent.get_session_state()) # {'shopping_list': ['milk', 'eggs']}Learn more
robot
Agent State
Learn about state in agents.
users
Team State
Learn about state in teams.
diagram-project
Workflow State
Learn about state in workflows.
Developer Resources
- View the Agent schema
- View the Team schema
- View the Workflow schema
- View the RunContext schema