Dynamic Session State
Update session state dynamically during agent runs.
Dynamic Session State.
1"""2Dynamic Session State3=============================45Dynamic Session State.6"""78import json9from typing import Any, Dict1011from kern.agent import Agent12from kern.db.in_memory import InMemoryDb13from kern.models.openai import OpenAIResponses14from kern.run import RunContext15from kern.tools.toolkit import Toolkit16from kern.utils.log import log_info, log_warning171819class CustomerDBTools(Toolkit):20 def __init__(self, *args, **kwargs):21 super().__init__(*args, **kwargs)22 self.register(self.process_customer_request)2324 def process_customer_request(25 self,26 agent: Agent,27 customer_id: str,28 action: str = "retrieve",29 name: str = "John Doe",30 ):31 log_warning("Tool called, this shouldn't happen.")32 return "This should not be seen."333435def customer_management_hook(run_context: RunContext, arguments: Dict[str, Any]):36 if run_context.session_state is None:37 run_context.session_state = {}3839 action = arguments.get("action", "retrieve")40 cust_id = arguments.get("customer_id")41 name = arguments.get("name", None)4243 if not cust_id:44 raise ValueError("customer_id is required.")4546 if action == "create":47 run_context.session_state["customer_profiles"][cust_id] = {"name": name}48 log_info(f"Hook: UPDATED session_state for customer '{cust_id}'.")49 return f"Success! Customer {cust_id} has been created."5051 if action == "retrieve":52 profile = run_context.session_state.get("customer_profiles", {}).get(cust_id)53 if profile:54 log_info(f"Hook: FOUND customer '{cust_id}' in session_state.")55 return f"Profile for {cust_id}: {json.dumps(profile)}"56 else:57 raise ValueError(f"Customer '{cust_id}' not found.")5859 log_info(f"Session state: {run_context.session_state}")606162# ---------------------------------------------------------------------------63# Create Agent64# ---------------------------------------------------------------------------65def run_test():66 # ---------------------------------------------------------------------------67 # Create Agent68 # ---------------------------------------------------------------------------6970 agent = Agent(71 model=OpenAIResponses(id="gpt-5.2"),72 tools=[CustomerDBTools()],73 tool_hooks=[customer_management_hook],74 session_state={"customer_profiles": {"123": {"name": "Jane Doe"}}},75 instructions="Your profiles: {customer_profiles}. Use `process_customer_request`. Use either create or retrieve as action for the tool.",76 resolve_in_context=True,77 db=InMemoryDb(),78 )7980 prompt = "First, create customer 789 named 'Tom'. Then, retrieve Tom's profile. Step by step."81 log_info(f" Prompting: '{prompt}'")82 agent.print_response(prompt, stream=False)8384 log_info("\n--- TEST ANALYSIS ---")85 log_info(86 "Check logs for the second tool call. The system prompt will NOT contain customer '789'."87 )888990# ---------------------------------------------------------------------------91# Run Agent92# ---------------------------------------------------------------------------93if __name__ == "__main__":94 run_test()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 dynamic_session_state.py