Session State Advanced

Define tools to manage our shopping list.

Session State Advanced.

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