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 Agent2from kern.db.in_memory import InMemoryDb3from kern.models.openai import OpenAIResponses45agent = 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)1112# 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)1920# 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")2223# 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)3031# 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.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 change_state_on_run.py