Last N Session Messages

Remove the tmp db file before running the script.

Last N Session Messages.

1"""
2Last N Session Messages
3=============================
4
5Last N Session Messages.
6"""
7
8import asyncio
9import os
10
11from kern.agent import Agent
12from kern.db.sqlite import AsyncSqliteDb
13from kern.models.openai import OpenAIResponses
14
15# ---------------------------------------------------------------------------
16# Create Agent
17# ---------------------------------------------------------------------------
18# Remove the tmp db file before running the script
19if os.path.exists("tmp/data.db"):
20 os.remove("tmp/data.db")
21
22# Create agents for different users to demonstrate user-specific session history
23agent = Agent(
24 model=OpenAIResponses(id="gpt-5-mini"),
25 db=AsyncSqliteDb(db_file="tmp/data.db"),
26 search_session_history=True, # allow searching previous sessions
27 num_history_sessions=2, # only include the last 2 sessions in the search to avoid context length issues
28)
29
30
31async def main():
32 # User 1 sessions
33 print("=== User 1 Sessions ===")
34 await agent.aprint_response(
35 "What is the capital of South Africa?",
36 session_id="user1_session_1",
37 user_id="user_1",
38 )
39 await agent.aprint_response(
40 "What is the capital of China?", session_id="user1_session_2", user_id="user_1"
41 )
42 await agent.aprint_response(
43 "What is the capital of France?", session_id="user1_session_3", user_id="user_1"
44 )
45
46 # User 2 sessions
47 print("\n=== User 2 Sessions ===")
48 await agent.aprint_response(
49 "What is the population of India?",
50 session_id="user2_session_1",
51 user_id="user_2",
52 )
53 await agent.aprint_response(
54 "What is the currency of Japan?", session_id="user2_session_2", user_id="user_2"
55 )
56
57 # Now test session history search - each user should only see their own sessions
58 print("\n=== Testing Session History Search ===")
59 print(
60 "User 1 asking about previous conversations (should only see capitals, not population/currency):"
61 )
62 await agent.aprint_response(
63 "What did I discuss in my previous conversations?",
64 session_id="user1_session_4",
65 user_id="user_1",
66 )
67
68 print(
69 "\nUser 2 asking about previous conversations (should only see population/currency, not capitals):"
70 )
71 await agent.aprint_response(
72 "What did I discuss in my previous conversations?",
73 session_id="user2_session_3",
74 user_id="user_2",
75 )
76
77
78# ---------------------------------------------------------------------------
79# Run Agent
80# ---------------------------------------------------------------------------
81if __name__ == "__main__":
82 asyncio.run(main())

Run the Example

1# Clone and setup repo
2git clone https://github.com/kern-ai/kern.git
3cd kern/cookbook/02_agents/05_state_and_session
4
5# Create and activate virtual environment
6./scripts/demo_setup.sh
7source .venvs/demo/bin/activate
8
9python last_n_session_messages.py