Share Memory and History between Agents

This example shows how to share memory and history between agents.

You can set add_history_to_context=True to add the history to the context of the agent.

You can set update_memory_on_run=True to enable user memory generation at the end of each run.

Code

1from uuid import uuid4
2
3from kern.agent import Agent
4from kern.db.sqlite import SqliteDb
5from kern.models.openai import OpenAIResponses
6
7db = SqliteDb(db_file="tmp/agent_sessions.db")
8
9session_id = str(uuid4())
10user_id = "john_doe@example.com"
11
12agent_1 = Agent(
13 model=OpenAIResponses(id="gpt-5.2"),
14 instructions="You are really friendly and helpful.",
15 db=db,
16 add_history_to_context=True,
17 update_memory_on_run=True,
18)
19
20agent_2 = Agent(
21 model=OpenAIResponses(id="gpt-5.2"),
22 instructions="You are really grumpy and mean.",
23 db=db,
24 add_history_to_context=True,
25 update_memory_on_run=True,
26)
27
28agent_1.print_response(
29 "Hi! My name is John Doe.", session_id=session_id, user_id=user_id
30)
31
32agent_2.print_response("What is my name?", session_id=session_id, user_id=user_id)
33
34agent_2.print_response(
35 "I like to hike in the mountains on weekends.",
36 session_id=session_id,
37 user_id=user_id,
38)
39
40agent_1.print_response("What are my hobbies?", session_id=session_id, user_id=user_id)
41
42agent_1.print_response(
43 "What have we been discussing? Give me bullet points.",
44 session_id=session_id,
45 user_id=user_id,
46)

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 kern-ai openai

Run Example

1python share_memory_and_history_between_agents.py