Last N Session Messages
Remove the tmp db file before running the script.
Last N Session Messages.
1"""2Last N Session Messages3=============================45Last N Session Messages.6"""78import asyncio9import os1011from kern.agent import Agent12from kern.db.sqlite import AsyncSqliteDb13from kern.models.openai import OpenAIResponses1415# ---------------------------------------------------------------------------16# Create Agent17# ---------------------------------------------------------------------------18# Remove the tmp db file before running the script19if os.path.exists("tmp/data.db"):20 os.remove("tmp/data.db")2122# Create agents for different users to demonstrate user-specific session history23agent = Agent(24 model=OpenAIResponses(id="gpt-5-mini"),25 db=AsyncSqliteDb(db_file="tmp/data.db"),26 search_session_history=True, # allow searching previous sessions27 num_history_sessions=2, # only include the last 2 sessions in the search to avoid context length issues28)293031async def main():32 # User 1 sessions33 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 )4546 # User 2 sessions47 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 )5657 # Now test session history search - each user should only see their own sessions58 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 )6768 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 )767778# ---------------------------------------------------------------------------79# Run Agent80# ---------------------------------------------------------------------------81if __name__ == "__main__":82 asyncio.run(main())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 last_n_session_messages.py