Session State Manual Update
Create an Agent that maintains state.
Session State Manual Update.
1"""2Session State Manual Update3=============================45Session State Manual Update.6"""78from kern.agent import Agent9from kern.db.sqlite import SqliteDb10from kern.models.openai import OpenAIResponses11from kern.run import RunContext121314def add_item(run_context: RunContext, item: str) -> str:15 """Add an item to the shopping list."""16 if run_context.session_state is None:17 run_context.session_state = {}1819 run_context.session_state["shopping_list"].append(item) # type: ignore20 return f"The shopping list is now {run_context.session_state['shopping_list']}" # type: ignore212223# Create an Agent that maintains state24# ---------------------------------------------------------------------------25# Create Agent26# ---------------------------------------------------------------------------27agent = Agent(28 model=OpenAIResponses(id="gpt-5-mini"),29 # Initialize the session state with an empty shopping list (this is the default session state for all users)30 session_state={"shopping_list": []},31 db=SqliteDb(db_file="tmp/agents.db"),32 tools=[add_item],33 # You can use variables from the session state in the instructions34 instructions="Current state (shopping list) is: {shopping_list}",35 markdown=True,36)3738# ---------------------------------------------------------------------------39# Run Agent40# ---------------------------------------------------------------------------41if __name__ == "__main__":42 # Example usage43 agent.print_response("Add milk, eggs, and bread to the shopping list", stream=True)4445 current_session_state = agent.get_session_state()46 current_session_state["shopping_list"].append("chocolate")47 agent.update_session_state(current_session_state)4849 agent.print_response("What's on my list?", stream=True, debug_mode=True)5051 print(f"Final 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_manual_update.py