Session State Basic

Create an Agent that maintains state.

Session State Basic.

1"""
2Session State Basic
3=============================
4
5Session State Basic.
6"""
7
8from kern.agent import Agent, RunOutput # noqa
9from kern.db.sqlite import SqliteDb
10from kern.models.openai import OpenAIResponses
11from kern.run import RunContext
12
13
14def add_item(run_context: RunContext, item: str) -> str:
15 """Add an item to the shopping list."""
16 if run_context.session_state is None:
17 run_context.session_state = {}
18
19 run_context.session_state["shopping_list"].append(item) # type: ignore
20 return f"The shopping list is now {run_context.session_state['shopping_list']}" # type: ignore
21
22
23# Create an Agent that maintains state
24# ---------------------------------------------------------------------------
25# Create Agent
26# ---------------------------------------------------------------------------
27agent = Agent(
28 model=OpenAIResponses(id="gpt-5-mini"),
29 # Initialize the session state with a counter starting at 0 (this is the default session state for all users)
30 session_state={"shopping_list": []},
31 db=SqliteDb(db_file="tmp/agents.db"),
32 tools=[add_item],
33 # You can use variables from the session state in the instructions
34 instructions="Current state (shopping list) is: {shopping_list}",
35 markdown=True,
36)
37
38# ---------------------------------------------------------------------------
39# Run Agent
40# ---------------------------------------------------------------------------
41if __name__ == "__main__":
42 # Example usage
43 agent.print_response("Add milk, eggs, and bread to the shopping list", stream=True)
44 print(f"Final session state: {agent.get_session_state()}")
45
46 # Alternatively,
47 # response: RunOutput = agent.run("Add milk, eggs, and bread to the shopping list")
48 # print(f"Final session state: {response.session_state}")

Run the Example

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