Agent with Memory

Give agents persistent memory across sessions.

This example shows you how to use persistent memory with an Agent.

After each run, user memories are created/updated.

To enable this, set update_memory_on_run=True in the Agent config.

Code

1from uuid import uuid4
2
3from kern.agent import Agent
4from kern.db.postgres import PostgresDb
5from kern.models.openai import OpenAIResponses
6from rich.pretty import pprint
7
8db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
9
10db = PostgresDb(db_url=db_url)
11
12db.clear_memories()
13
14session_id = str(uuid4())
15john_doe_id = "john_doe@example.com"
16
17agent = Agent(
18 model=OpenAIResponses(id="gpt-5.2"),
19 db=db,
20 update_memory_on_run=True,
21)
22
23agent.print_response(
24 "My name is John Doe and I like to hike in the mountains on weekends.",
25 stream=True,
26 user_id=john_doe_id,
27 session_id=session_id,
28)
29
30agent.print_response(
31 "What are my hobbies?", stream=True, user_id=john_doe_id, session_id=session_id
32)
33
34memories = agent.get_user_memories(user_id=john_doe_id)
35print("John Doe's memories:")
36pprint(memories)
37
38agent.print_response(
39 "Ok i dont like hiking anymore, i like to play soccer instead.",
40 stream=True,
41 user_id=john_doe_id,
42 session_id=session_id,
43)
44
45# You can also get the user memories from the agent
46memories = agent.get_user_memories(user_id=john_doe_id)
47print("John Doe's memories:")
48pprint(memories)

Usage

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

Run Example

1python agent_with_memory.py