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 uuid423from kern.agent import Agent4from kern.db.postgres import PostgresDb5from kern.models.openai import OpenAIResponses6from rich.pretty import pprint78db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"910db = PostgresDb(db_url=db_url)1112db.clear_memories()1314session_id = str(uuid4())15john_doe_id = "john_doe@example.com"1617agent = Agent(18 model=OpenAIResponses(id="gpt-5.2"),19 db=db,20 update_memory_on_run=True,21)2223agent.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)2930agent.print_response(31 "What are my hobbies?", stream=True, user_id=john_doe_id, session_id=session_id32)3334memories = agent.get_user_memories(user_id=john_doe_id)35print("John Doe's memories:")36pprint(memories)3738agent.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)4445# You can also get the user memories from the agent46memories = 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.122source .venv/bin/activate1uv venv --python 3.122.venv\Scripts\activateInstall dependencies
1uv pip install -U kern-aiRun Example
1python agent_with_memory.py