Agent with Storage

Persist conversation history across runs.

Storage lets your agent remember conversations. With the same session_id, it picks up where you left off, even after restarting.

Create a Python file

1from kern.agent import Agent
2from kern.db.sqlite import SqliteDb
3from kern.models.openai import OpenAIResponses
4from kern.tools.yfinance import YFinanceTools
5
6db = SqliteDb(db_file="tmp/agents.db")
7
8agent = Agent(
9 model=OpenAIResponses(id="gpt-5.2"),
10 tools=[YFinanceTools()],
11 db=db,
12 add_history_to_context=True,
13 num_history_runs=5,
14 markdown=True,
15)
16
17session_id = "finance-session"
18
19# Turn 1: Analyze a stock
20agent.print_response(
21 "Give me a quick analysis of NVIDIA",
22 session_id=session_id,
23 stream=True,
24)
25
26# Turn 2: The agent remembers NVDA from turn 1
27agent.print_response(
28 "Compare that to AMD",
29 session_id=session_id,
30 stream=True,
31)
32
33# Turn 3: Ask based on full conversation
34agent.print_response(
35 "Which looks like the better investment?",
36 session_id=session_id,
37 stream=True,
38)

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 yfinance sqlalchemy

Export your OpenAI API key

1export OPENAI_API_KEY="your_openai_api_key_here"
1$Env:OPENAI_API_KEY="your_openai_api_key_here"

Run Agent

1python agent_with_storage.py

Key Concepts

  • Session: A conversation thread identified by session_id
  • Same session_id = continuous conversation, even across script runs
  • add_history_to_context=True: Includes previous messages in context
  • num_history_runs=5: Number of previous runs to include