Session State Hooks

Example demonstrating how to use a pre_hook to update the session_state.

1"""
2Session State Hooks
3=============================
4
5Example demonstrating how to use a pre_hook to update the session_state.
6"""
7
8from typing import List
9
10from kern.agent import Agent
11from kern.db.sqlite import SqliteDb
12from kern.models.openai import OpenAIResponses
13from kern.run import RunContext
14from kern.run.agent import RunInput
15from pydantic import BaseModel, Field
16
17
18class ConversationTopics(BaseModel):
19 topics: List[str] = Field(description="Topics present in the user messages")
20
21
22# This will be our pre-hook function
23def track_conversation_topics(run_context: RunContext, run_input: RunInput) -> None:
24 """Simple pre-hook function to track conversation topics in the session state"""
25
26 # Initialize the session state if it doesn't exist yet
27 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"] = []
31
32 # Setup an Agent to get the topics discussed in the conversation
33 # ---------------------------------------------------------------------------
34 # Create Agent
35 # ---------------------------------------------------------------------------
36
37 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 )
49
50 # Run the Agent to get the topics discussed in the conversation
51 response = topics_analyzer_agent.run(
52 input=f"Extract the topics present in the following user message: {run_input.input_content}"
53 )
54
55 # Update the session state to track the topics discussed in the conversation
56 run_context.session_state["topics"].extend(response.content.topics) # type: ignore
57
58
59# ---------------------------------------------------------------------------
60# Create Agent
61# ---------------------------------------------------------------------------
62# Create a simple agent and equip it with our pre-hook
63agent = 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)
69
70# ---------------------------------------------------------------------------
71# Run Agent
72# ---------------------------------------------------------------------------
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 )
81
82 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 repo
2git clone https://github.com/kern-ai/kern.git
3cd kern/cookbook/02_agents/09_hooks
4
5# Create and activate virtual environment
6./scripts/demo_setup.sh
7source .venvs/demo/bin/activate
8
9python session_state_hooks.py