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 dedent23from kern.agent import Agent4from kern.db.sqlite import SqliteDb5from kern.models.openai import OpenAIResponses6from kern.run import RunContext789# Define tools to manage our shopping list10def 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 = {}1415 # Add the item if it's not already in the list16 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: ignore18 return f"Added '{item}' to the shopping list"19 else:20 return f"'{item}' is already in the shopping list"212223def 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 = {}2728 # Case-insensitive search29 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"3334 return f"'{item}' was not found in the shopping list"353637def 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 = {}4142 shopping_list = run_context.session_state["shopping_list"]4344 if not shopping_list:45 return "The shopping list is empty."4647 items_text = "\n".join([f"- {item}" for item in shopping_list])48 return f"Current shopping list:\n{items_text}"495051# Create a Shopping List Manager Agent that maintains state52agent = 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 instructions59 instructions=dedent("""\60 Your job is to manage a shopping list.6162 The shopping list starts empty. You can add items, remove items by name, and list all items.6364 Current shopping list: {shopping_list}65 """),66 markdown=True,67)6869# Example usage70agent.print_response("Add milk, eggs, and bread to the shopping list", stream=True)71print(f"Session state: {agent.get_session_state()}")7273agent.print_response("I got bread", stream=True)74print(f"Session state: {agent.get_session_state()}")7576agent.print_response("I need apples and oranges", stream=True)77print(f"Session state: {agent.get_session_state()}")7879agent.print_response("whats on my list?", stream=True)80print(f"Session state: {agent.get_session_state()}")8182agent.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.122source .venv/bin/activate1uv venv --python 3.122.venv\Scripts\activateInstall dependencies
1uv pip install -U kern-ai openaiExport 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