Last N Messages
This example demonstrates how to configure agents to search through previous sessions and limit the number of historical sessions included in context. This helps manage context length while maintaining relevant conversation history.
Create a Python file
1import os23from kern.agent import Agent4from kern.db.sqlite import SqliteDb5from kern.models.openai import OpenAIResponses67# Remove the tmp db file before running the script8os.remove("tmp/data.db")910agent = Agent(11 model=OpenAIResponses(id="gpt-5.2"),12 user_id="user_1",13 db=SqliteDb(db_file="tmp/data.db"),14 add_history_to_context=True,15 num_history_runs=3,16 search_session_history=True, # allow searching previous sessions17 num_history_sessions=2, # only include the last 2 sessions in the search to avoid context length issues18)1920session_1_id = "session_1_id"21session_2_id = "session_2_id"22session_3_id = "session_3_id"23session_4_id = "session_4_id"24session_5_id = "session_5_id"2526agent.print_response("What is the capital of South Africa?", session_id=session_1_id)27agent.print_response("What is the capital of China?", session_id=session_2_id)28agent.print_response("What is the capital of France?", session_id=session_3_id)29agent.print_response("What is the capital of Japan?", session_id=session_4_id)30agent.print_response(31 "What did I discuss in my previous conversations?", session_id=session_5_id32) # It should only include the last 2 sessionsSet 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 last_n_session_messages.py