Multiple Users
This example demonstrates how to maintain separate session state for multiple users in a multi-user environment, with each user having their own shopping lists and sessions.
Create a Python file
1"""2This example demonstrates how to maintain state for each user in a multi-user environment.34The shopping list is stored in a dictionary, organized by user ID and session ID.56Kern automatically creates the "current_user_id" and "current_session_id" variables in the session state.78You can access these variables in your functions using the `agent.get_session_state()` dictionary.9"""1011import json1213from kern.agent import Agent14from kern.db.sqlite import SqliteDb15from kern.models.openai import OpenAIResponses16from kern.run.base import run_context1718# In-memory database to store user shopping lists19# Organized by user ID and session ID20shopping_list = {}212223def add_item(run_context: RunContext, item: str) -> str:24 """Add an item to the current user's shopping list."""2526 if not run_context.session_state:27 run_context.session_state = {}2829 current_user_id = run_context.session_state["current_user_id"]30 current_session_id = run_context.session_state["current_session_id"]31 shopping_list.setdefault(current_user_id, {}).setdefault(32 current_session_id, []33 ).append(item)3435 return f"Item {item} added to the shopping list"363738def remove_item(run_context: RunContext, item: str) -> str:39 """Remove an item from the current user's shopping list."""4041 if not run_context.session_state:42 run_context.session_state = {}4344 current_user_id = run_context.session_state["current_user_id"]45 current_session_id = run_context.session_state["current_session_id"]4647 if (48 current_user_id not in shopping_list49 or current_session_id not in shopping_list[current_user_id]50 ):51 return f"No shopping list found for user {current_user_id} and session {current_session_id}"5253 if item not in shopping_list[current_user_id][current_session_id]:54 return f"Item '{item}' not found in the shopping list for user {current_user_id} and session {current_session_id}"5556 shopping_list[current_user_id][current_session_id].remove(item)57 return f"Item {item} removed from the shopping list"585960def get_shopping_list(run_context: RunContext) -> str:61 """Get the current user's shopping list."""6263 if not run_context.session_state:64 run_context.session_state = {}6566 current_user_id = run_context.session_state["current_user_id"]67 current_session_id = run_context.session_state["current_session_id"]68 return f"Shopping list for user {current_user_id} and session {current_session_id}: \n{json.dumps(shopping_list[current_user_id][current_session_id], indent=2)}"697071# Create an Agent that maintains state72agent = Agent(73 model=OpenAIResponses(id="gpt-5.2"),74 db=SqliteDb(db_file="tmp/data.db"),75 tools=[add_item, remove_item, get_shopping_list],76 # Reference the in-memory database77 instructions=[78 "Current User ID: {current_user_id}",79 "Current Session ID: {current_session_id}",80 ],81 markdown=True,82)8384user_id_1 = "john_doe"85user_id_2 = "mark_smith"86user_id_3 = "carmen_sandiago"8788# Example usage89agent.print_response(90 "Add milk, eggs, and bread to the shopping list",91 stream=True,92 user_id=user_id_1,93 session_id="user_1_session_1",94)95agent.print_response(96 "Add tacos to the shopping list",97 stream=True,98 user_id=user_id_2,99 session_id="user_2_session_1",100)101agent.print_response(102 "Add apples and grapes to the shopping list",103 stream=True,104 user_id=user_id_3,105 session_id="user_3_session_1",106)107agent.print_response(108 "Remove milk from the shopping list",109 stream=True,110 user_id=user_id_1,111 session_id="user_1_session_1",112)113agent.print_response(114 "Add minced beef to the shopping list",115 stream=True,116 user_id=user_id_2,117 session_id="user_2_session_1",118)119120# What is on Mark Smith's shopping list?121agent.print_response(122 "What is on Mark Smith's shopping list?",123 stream=True,124 user_id=user_id_2,125 session_id="user_2_session_1",126)127128# New session, so new shopping list129agent.print_response(130 "Add chicken and soup to my list.",131 stream=True,132 user_id=user_id_2,133 session_id="user_3_session_2",134)135136print(f"Final shopping lists: \n{json.dumps(shopping_list, indent=2)}")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_multiple_users.py