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 os
2
3from kern.agent import Agent
4from kern.db.sqlite import SqliteDb
5from kern.models.openai import OpenAIResponses
6
7# Remove the tmp db file before running the script
8os.remove("tmp/data.db")
9
10agent = 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 sessions
17 num_history_sessions=2, # only include the last 2 sessions in the search to avoid context length issues
18)
19
20session_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"
25
26agent.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_id
32) # It should only include the last 2 sessions

Set up your virtual environment

1uv venv --python 3.12
2source .venv/bin/activate
1uv venv --python 3.12
2.venv\Scripts\activate

Install dependencies

1uv pip install -U kern-ai openai

Export 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