Change State on Run

This example demonstrates how to manage session state across different runs for different users. It shows how session state persists within the same session but is isolated between different sessions and users.

Create a Python file

1from kern.agent import Agent
2from kern.db.in_memory import InMemoryDb
3from kern.models.openai import OpenAIResponses
4
5agent = Agent(
6 db=InMemoryDb(),
7 model=OpenAIResponses(id="gpt-5.2"),
8 instructions="Users name is {user_name} and age is {age}",
9 debug_mode=True,
10)
11
12# Sets the session state for the session with the id "user_1_session_1"
13agent.print_response(
14 "What is my name?",
15 session_id="user_1_session_1",
16 user_id="user_1",
17 session_state={"user_name": "John", "age": 30},
18)
19
20# Will load the session state from the session with the id "user_1_session_1"
21agent.print_response("How old am I?", session_id="user_1_session_1", user_id="user_1")
22
23# Sets the session state for the session with the id "user_2_session_1"
24agent.print_response(
25 "What is my name?",
26 session_id="user_2_session_1",
27 user_id="user_2",
28 session_state={"user_name": "Jane", "age": 25},
29)
30
31# Will load the session state from the session with the id "user_2_session_1"
32agent.print_response("How old am I?", session_id="user_2_session_1", user_id="user_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 change_state_on_run.py