Memory

Code

1"""
2This recipe shows how to use personalized memories and summaries in an agent.
3Steps:
41. Run: `./cookbook/scripts/run_pgvector.sh` to start a postgres container with pgvector
52. Run: `uv pip install openai sqlalchemy 'psycopg[binary]' pgvector` to install the dependencies
63. Run: `python cookbook/03_agents/personalized_memories_and_summaries.py` to run the agent
7"""
8
9from kern.agent import Agent
10from kern.db.base import SessionType
11from kern.db.postgres import PostgresDb
12from kern.models.openai import OpenAIResponses
13from rich.pretty import pprint
14
15# Setup the database
16db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
17db = PostgresDb(db_url=db_url)
18
19agent = Agent(
20 model=OpenAIResponses(id="gpt-5-mini"),
21 user_id="test_user",
22 session_id="test_session",
23 # Pass the database to the Agent
24 db=db,
25 # Enable user memories
26 update_memory_on_run=True,
27 # Enable session summaries
28 enable_session_summaries=True,
29 # Show debug logs so, you can see the memory being created
30)
31
32# -*- Share personal information
33agent.print_response("My name is john billings", stream=True)
34# -*- Print memories and summary
35if agent.db:
36 pprint(agent.db.get_user_memories(user_id="test_user"))
37 pprint(
38 agent.db.get_session(
39 session_id="test_session", session_type=SessionType.AGENT
40 ).summary # type: ignore
41 )
42
43# -*- Share personal information
44agent.print_response("I live in nyc", stream=True)
45# -*- Print memories
46if agent.db:
47 pprint(agent.db.get_user_memories(user_id="test_user"))
48 pprint(
49 agent.db.get_session(
50 session_id="test_session", session_type=SessionType.AGENT
51 ).summary # type: ignore
52 )
53
54# -*- Share personal information
55agent.print_response("I'm going to a concert tomorrow", stream=True)
56# -*- Print memories
57if agent.db:
58 pprint(agent.db.get_user_memories(user_id="test_user"))
59 pprint(
60 agent.db.get_session(
61 session_id="test_session", session_type=SessionType.AGENT
62 ).summary # type: ignore
63 )
64
65# Ask about the conversation
66agent.print_response(
67 "What have we been talking about, do you know my name?", stream=True
68)

Usage

Set up your virtual environment

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

Set your API key

1export OPENAI_API_KEY=xxx

Install dependencies

1uv pip install -U openai kern-ai

Run Agent

1python cookbook/11_models/openai/responses/memory.py