Session State Hooks
Example demonstrating how to use a pre_hook to update the session_state.
1"""2Session State Hooks3=============================45Example demonstrating how to use a pre_hook to update the session_state.6"""78from typing import List910from kern.agent import Agent11from kern.db.sqlite import SqliteDb12from kern.models.openai import OpenAIResponses13from kern.run import RunContext14from kern.run.agent import RunInput15from pydantic import BaseModel, Field161718class ConversationTopics(BaseModel):19 topics: List[str] = Field(description="Topics present in the user messages")202122# This will be our pre-hook function23def track_conversation_topics(run_context: RunContext, run_input: RunInput) -> None:24 """Simple pre-hook function to track conversation topics in the session state"""2526 # Initialize the session state if it doesn't exist yet27 if run_context.session_state is None:28 run_context.session_state = {"topics": []}29 elif run_context.session_state.get("topics") is None:30 run_context.session_state["topics"] = []3132 # Setup an Agent to get the topics discussed in the conversation33 # ---------------------------------------------------------------------------34 # Create Agent35 # ---------------------------------------------------------------------------3637 topics_analyzer_agent = Agent(38 name="Topics Analyzer",39 model=OpenAIResponses(id="gpt-5-mini"),40 instructions=[41 "Your task is to analyze a user query and extract the topics."42 "You will be presented with a user message sent to an agent."43 "You need to extract the topics present in the user message."44 "Be concise and brief. Topics should be one or two words, and only want the one or two main topics."45 "Respond just with the list of topics, no other text or explanation."46 ],47 output_schema=ConversationTopics,48 )4950 # Run the Agent to get the topics discussed in the conversation51 response = topics_analyzer_agent.run(52 input=f"Extract the topics present in the following user message: {run_input.input_content}"53 )5455 # Update the session state to track the topics discussed in the conversation56 run_context.session_state["topics"].extend(response.content.topics) # type: ignore575859# ---------------------------------------------------------------------------60# Create Agent61# ---------------------------------------------------------------------------62# Create a simple agent and equip it with our pre-hook63agent = Agent(64 name="Simple Agent",65 model=OpenAIResponses(id="gpt-5-mini"),66 pre_hooks=[track_conversation_topics],67 db=SqliteDb(db_file="test.db"),68)6970# ---------------------------------------------------------------------------71# Run Agent72# ---------------------------------------------------------------------------73if __name__ == "__main__":74 agent.print_response(75 input="I want to know more about AI Agents.",76 session_id="topics_analyzer_session",77 )78 print(79 f"Current session state, after the first run: {agent.get_session_state(session_id='topics_analyzer_session')}"80 )8182 agent.print_response(83 input="I also want to know more about Kern, the framework to build AI Agents.",84 session_id="topics_analyzer_session",85 )86 print(87 f"Current session state, after the second run: {agent.get_session_state(session_id='topics_analyzer_session')}"88 )Run the Example
1# Clone and setup repo2git clone https://github.com/kern-ai/kern.git3cd kern/cookbook/02_agents/09_hooks45# Create and activate virtual environment6./scripts/demo_setup.sh7source .venvs/demo/bin/activate89python session_state_hooks.py