Dynamic State
This example demonstrates how to use tool hooks to dynamically manage session state. It shows how to create a customer management system that updates session state through tool interactions rather than direct modification.
Create a Python file
1import json2from typing import Any, Callable, Dict34from kern.agent import Agent5from kern.db.in_memory import InMemoryDb6from kern.models.openai import OpenAIResponses7from kern.tools.toolkit import Toolkit8from kern.utils.log import log_info, log_warning9from kern.run import RunContext101112class CustomerDBTools(Toolkit):13 def __init__(self, *args, **kwargs):14 super().__init__(*args, **kwargs)15 self.register(self.process_customer_request)1617 def process_customer_request(18 self,19 agent: Agent,20 customer_id: str,21 action: str = "retrieve",22 name: str = "John Doe",23 ):24 log_warning("Tool called, this shouldn't happen.")25 return "This should not be seen."262728def customer_management_hook(29 run_context: RunContext,30 function_name: str,31 function_call: Callable,32 arguments: Dict[str, Any],33):34 if not run_context.session_state:35 run_context.session_state = {}3637 action = arguments.get("action", "retrieve")38 cust_id = arguments.get("customer_id")39 name = arguments.get("name", None)4041 if not cust_id:42 raise ValueError("customer_id is required.")4344 if action == "create":45 run_context.session_state["customer_profiles"][cust_id] = {"name": name}46 log_info(f"Hook: UPDATED session_state for customer '{cust_id}'.")47 return f"Success! Customer {cust_id} has been created."4849 if action == "retrieve":50 profile = run_context.session_state.get("customer_profiles", {}).get(cust_id)51 if profile:52 log_info(f"Hook: FOUND customer '{cust_id}' in session_state.")53 return f"Profile for {cust_id}: {json.dumps(profile)}"54 else:55 raise ValueError(f"Customer '{cust_id}' not found.")5657 log_info(f"Session state: {run_context.session_state}")585960def run_test():61 agent = Agent(62 model=OpenAIResponses(id="gpt-5.2"),63 tools=[CustomerDBTools()],64 tool_hooks=[customer_management_hook],65 session_state={"customer_profiles": {"123": {"name": "Jane Doe"}}},66 instructions="Your profiles: {customer_profiles}. Use `process_customer_request`. Use either create or retrieve as action for the tool.",67 resolve_in_context=True,68 db=InMemoryDb(),69 )7071 prompt = "First, create customer 789 named 'Tom'. Then, retrieve Tom's profile. Step by step."72 log_info(f"Prompting: '{prompt}'")73 agent.print_response(prompt, stream=False)7475 log_info("\n--- TEST ANALYSIS ---")76 log_info(77 "Check logs for the second tool call. The system prompt will NOT contain customer '789'."78 )798081if __name__ == "__main__":82 run_test()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 dynamic_session_state.py