Memory Creation

Create user memories with an Agent by providing a either text or a list of messages.

Code

1from kern.db.postgres import PostgresDb
2from kern.memory import MemoryManager, UserMemory
3from kern.models.message import Message
4from kern.models.openai import OpenAIResponses
5from rich.pretty import pprint
6
7db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
8
9memory_db = PostgresDb(db_url=db_url)
10
11memory = MemoryManager(model=OpenAIResponses(id="gpt-5.2"), db=memory_db)
12
13john_doe_id = "john_doe@example.com"
14memory.add_user_memory(
15 memory=UserMemory(
16 memory="""
17I enjoy hiking in the mountains on weekends,
18reading science fiction novels before bed,
19cooking new recipes from different cultures,
20playing chess with friends,
21and attending live music concerts whenever possible.
22Photography has become a recent passion of mine, especially capturing landscapes and street scenes.
23I also like to meditate in the mornings and practice yoga to stay centered.
24"""
25 ),
26 user_id=john_doe_id,
27)
28
29
30memories = memory.get_user_memories(user_id=john_doe_id)
31print("John Doe's memories:")
32pprint(memories)
33
34jane_doe_id = "jane_doe@example.com"
35# Send a history of messages and add memories
36memory.create_user_memories(
37 messages=[
38 Message(role="user", content="My name is Jane Doe"),
39 Message(role="assistant", content="That is great!"),
40 Message(role="user", content="I like to play chess"),
41 Message(role="assistant", content="That is great!"),
42 ],
43 user_id=jane_doe_id,
44)
45
46memories = memory.get_user_memories(user_id=jane_doe_id)
47print("Jane 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 memory-creation.py
1python memory-creation.py