Advanced State

This example demonstrates advanced session state management with multiple tools for managing a shopping list, including add, remove, and list operations.

Create a Python file

1from textwrap import dedent
2
3from kern.agent import Agent
4from kern.db.sqlite import SqliteDb
5from kern.models.openai import OpenAIResponses
6from kern.run import RunContext
7
8
9# Define tools to manage our shopping list
10def add_item(run_context: RunContext, item: str) -> str:
11 """Add an item to the shopping list and return confirmation."""
12 if not run_context.session_state:
13 run_context.session_state = {}
14
15 # Add the item if it's not already in the list
16 if item.lower() not in [i.lower() for i in run_context.session_state["shopping_list"]]:
17 run_context.session_state["shopping_list"].append(item) # type: ignore
18 return f"Added '{item}' to the shopping list"
19 else:
20 return f"'{item}' is already in the shopping list"
21
22
23def remove_item(run_context: RunContext, item: str) -> str:
24 """Remove an item from the shopping list by name."""
25 if not run_context.session_state:
26 run_context.session_state = {}
27
28 # Case-insensitive search
29 for i, list_item in enumerate(run_context.session_state["shopping_list"]):
30 if list_item.lower() == item.lower():
31 run_context.session_state["shopping_list"].pop(i)
32 return f"Removed '{list_item}' from the shopping list"
33
34 return f"'{item}' was not found in the shopping list"
35
36
37def list_items(run_context: RunContext) -> str:
38 """List all items in the shopping list."""
39 if not run_context.session_state:
40 run_context.session_state = {}
41
42 shopping_list = run_context.session_state["shopping_list"]
43
44 if not shopping_list:
45 return "The shopping list is empty."
46
47 items_text = "\n".join([f"- {item}" for item in shopping_list])
48 return f"Current shopping list:\n{items_text}"
49
50
51# Create a Shopping List Manager Agent that maintains state
52agent = Agent(
53 model=OpenAIResponses(id="gpt-5.2"),
54 # Initialize the session state with an empty shopping list (default session state for all sessions)
55 session_state={"shopping_list": []},
56 db=SqliteDb(db_file="tmp/example.db"),
57 tools=[add_item, remove_item, list_items],
58 # You can use variables from the session state in the instructions
59 instructions=dedent("""\
60 Your job is to manage a shopping list.
61
62 The shopping list starts empty. You can add items, remove items by name, and list all items.
63
64 Current shopping list: {shopping_list}
65 """),
66 markdown=True,
67)
68
69# Example usage
70agent.print_response("Add milk, eggs, and bread to the shopping list", stream=True)
71print(f"Session state: {agent.get_session_state()}")
72
73agent.print_response("I got bread", stream=True)
74print(f"Session state: {agent.get_session_state()}")
75
76agent.print_response("I need apples and oranges", stream=True)
77print(f"Session state: {agent.get_session_state()}")
78
79agent.print_response("whats on my list?", stream=True)
80print(f"Session state: {agent.get_session_state()}")
81
82agent.print_response(
83 "Clear everything from my list and start over with just bananas and yogurt",
84 stream=True,
85)
86print(f"Session state: {agent.get_session_state()}")

Set up your virtual environment

1uv venv --python 3.12
2source .venv/bin/activate
1uv venv --python 3.12
2.venv\Scripts\activate

Install dependencies

1uv pip install -U kern-ai openai

Export your OpenAI API key

Set OpenAI Key

Set your OPENAI_API_KEY as an environment variable. You can get one from OpenAI.

1export OPENAI_API_KEY=sk-***
1setx OPENAI_API_KEY sk-***

Run Agent

1python session_state_advanced.py