Team with Memory Manager

This example demonstrates how to use persistent memory with a team. After each run, user memories are created and updated, allowing the team to remember information about users across sessions and provide personalized experiences.

Code

1"""
2This example shows you how to use persistent memory with an Agent.
3
4After each run, user memories are created/updated.
5
6To enable this, set `update_memory_on_run=True` in the Agent config.
7"""
8
9from uuid import uuid4
10
11from kern.agent import Agent
12from kern.db.postgres import PostgresDb
13from kern.memory import MemoryManager # noqa: F401
14from kern.models.openai import OpenAIResponses
15from kern.team import Team
16
17db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
18db = PostgresDb(db_url=db_url)
19
20session_id = str(uuid4())
21john_doe_id = "john_doe@example.com"
22
23# 1. Create memories by setting `update_memory_on_run=True` in the Agent
24agent = Agent(
25 model=OpenAIResponses(id="gpt-5.2"),
26)
27team = Team(
28 model=OpenAIResponses(id="gpt-5.2"),
29 members=[agent],
30 db=db,
31 update_memory_on_run=True,
32)
33
34team.print_response(
35 "My name is John Doe and I like to hike in the mountains on weekends.",
36 stream=True,
37 user_id=john_doe_id,
38 session_id=session_id,
39)
40
41team.print_response(
42 "What are my hobbies?", stream=True, user_id=john_doe_id, session_id=session_id
43)
44
45# 2. Set a custom MemoryManager on the agent
46# memory_manager = MemoryManager(model=OpenAIResponses(id="gpt-5.2"))
47
48# memory_manager.clear()
49
50# agent = Agent(
51# model=OpenAIResponses(id="gpt-5.2"),
52# memory_manager=memory_manager,
53# )
54
55# team = Team(
56# model=OpenAIResponses(id="gpt-5.2"),
57# members=[agent],
58# db=db,
59# update_memory_on_run=True,
60# )
61
62# team.print_response(
63# "My name is John Doe and I like to hike in the mountains on weekends.",
64# stream=True,
65# user_id=john_doe_id,
66# session_id=session_id,
67# )
68
69# # You can also get the user memories from the agent
70# memories = agent.get_user_memories(user_id=john_doe_id)
71# print("John Doe's memories:")
72# pprint(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 openai psycopg sqlalchemy

Set up PostgreSQL database

Start PostgreSQL with pgvector and update the connection string in the code as needed.

Set environment variables

1export OPENAI_API_KEY=your_openai_api_key_here

Run the example

1python team_with_memory_manager.py