Session State Advanced
Define tools to manage our shopping list.
Session State Advanced.
1"""2Session State Advanced3=============================45Session State Advanced.6"""78from textwrap import dedent910from kern.agent import Agent11from kern.db.sqlite import SqliteDb12from kern.models.openai import OpenAIResponses13from kern.run import RunContext141516# Define tools to manage our shopping list17def 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 list20 if run_context.session_state is None:21 run_context.session_state = {}2223 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: ignore27 return f"Added '{item}' to the shopping list"28 else:29 return f"'{item}' is already in the shopping list"303132def 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 = {}3637 # Case-insensitive search38 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"4243 return f"'{item}' was not found in the shopping list"444546def 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 = {}5051 shopping_list = run_context.session_state["shopping_list"]5253 if not shopping_list:54 return "The shopping list is empty."5556 items_text = "\n".join([f"- {item}" for item in shopping_list])57 return f"Current shopping list:\n{items_text}"585960# Create a Shopping List Manager Agent that maintains state61# ---------------------------------------------------------------------------62# Create Agent63# ---------------------------------------------------------------------------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 instructions71 instructions=dedent("""\72 Your job is to manage a shopping list.7374 The shopping list starts empty. You can add items, remove items by name, and list all items.7576 Current shopping list: {shopping_list}77 """),78 markdown=True,79)8081# ---------------------------------------------------------------------------82# Run Agent83# ---------------------------------------------------------------------------84if __name__ == "__main__":85 # Example usage86 agent.print_response("Add milk, eggs, and bread to the shopping list", stream=True)87 print(f"Session state: {agent.get_session_state()}")8889 agent.print_response("I got bread", stream=True)90 print(f"Session state: {agent.get_session_state()}")9192 agent.print_response("I need apples and oranges", stream=True)93 print(f"Session state: {agent.get_session_state()}")9495 agent.print_response("whats on my list?", stream=True)96 print(f"Session state: {agent.get_session_state()}")9798 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 repo2git clone https://github.com/kern-ai/kern.git3cd kern/cookbook/02_agents/05_state_and_session45# Create and activate virtual environment6./scripts/demo_setup.sh7source .venvs/demo/bin/activate89python session_state_advanced.py