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.
3
4The shopping list is stored in a dictionary, organized by user ID and session ID.
5
6Kern automatically creates the "current_user_id" and "current_session_id" variables in the session state.
7
8You can access these variables in your functions using the `agent.get_session_state()` dictionary.
9"""
10
11import json
12
13from kern.agent import Agent
14from kern.db.sqlite import SqliteDb
15from kern.models.openai import OpenAIResponses
16from kern.run.base import run_context
17
18# In-memory database to store user shopping lists
19# Organized by user ID and session ID
20shopping_list = {}
21
22
23def add_item(run_context: RunContext, item: str) -> str:
24 """Add an item to the current user's shopping list."""
25
26 if not run_context.session_state:
27 run_context.session_state = {}
28
29 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)
34
35 return f"Item {item} added to the shopping list"
36
37
38def remove_item(run_context: RunContext, item: str) -> str:
39 """Remove an item from the current user's shopping list."""
40
41 if not run_context.session_state:
42 run_context.session_state = {}
43
44 current_user_id = run_context.session_state["current_user_id"]
45 current_session_id = run_context.session_state["current_session_id"]
46
47 if (
48 current_user_id not in shopping_list
49 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}"
52
53 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}"
55
56 shopping_list[current_user_id][current_session_id].remove(item)
57 return f"Item {item} removed from the shopping list"
58
59
60def get_shopping_list(run_context: RunContext) -> str:
61 """Get the current user's shopping list."""
62
63 if not run_context.session_state:
64 run_context.session_state = {}
65
66 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)}"
69
70
71# Create an Agent that maintains state
72agent = 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 database
77 instructions=[
78 "Current User ID: {current_user_id}",
79 "Current Session ID: {current_session_id}",
80 ],
81 markdown=True,
82)
83
84user_id_1 = "john_doe"
85user_id_2 = "mark_smith"
86user_id_3 = "carmen_sandiago"
87
88# Example usage
89agent.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)
119
120# 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)
127
128# New session, so new shopping list
129agent.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)
135
136print(f"Final shopping lists: \n{json.dumps(shopping_list, indent=2)}")

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_multiple_users.py