Custom Memory Instructions

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
3from kern.models.anthropic.claude import Claude
4from kern.models.message import Message
5from kern.models.openai import OpenAIResponses
6from rich.pretty import pprint
7
8db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
9
10memory_db = PostgresDb(db_url=db_url)
11
12memory = MemoryManager(
13 model=OpenAIResponses(id="gpt-5.2"),
14 memory_capture_instructions="""\
15 Memories should only include details about the user's academic interests.
16 Only include which subjects they are interested in.
17 Ignore names, hobbies, and personal interests.
18 """,
19 db=memory_db,
20)
21
22john_doe_id = "john_doe@example.com"
23
24memory.create_user_memories(
25 input="""\
26My name is John Doe.
27
28I enjoy hiking in the mountains on weekends,
29reading science fiction novels before bed,
30cooking new recipes from different cultures,
31playing chess with friends.
32
33I am interested to learn about the history of the universe and other astronomical topics.
34""",
35 user_id=john_doe_id,
36)
37
38
39memories = memory.get_user_memories(user_id=john_doe_id)
40print("John Doe's memories:")
41pprint(memories)
42
43
44# Use default memory manager
45memory = MemoryManager(model=Claude(id="claude-3-5-sonnet-latest"), db=memory_db)
46jane_doe_id = "jane_doe@example.com"
47
48# Send a history of messages and add memories
49memory.create_user_memories(
50 messages=[
51 Message(role="user", content="Hi, how are you?"),
52 Message(role="assistant", content="I'm good, thank you!"),
53 Message(role="user", content="What are you capable of?"),
54 Message(
55 role="assistant",
56 content="I can help you with your homework and answer questions about the universe.",
57 ),
58 Message(role="user", content="My name is Jane Doe"),
59 Message(role="user", content="I like to play chess"),
60 Message(
61 role="user",
62 content="Actually, forget that I like to play chess. I more enjoy playing table top games like dungeons and dragons",
63 ),
64 Message(
65 role="user",
66 content="I'm also interested in learning about the history of the universe and other astronomical topics.",
67 ),
68 Message(role="assistant", content="That is great!"),
69 Message(
70 role="user",
71 content="I am really interested in physics. Tell me about quantum mechanics?",
72 ),
73 ],
74 user_id=jane_doe_id,
75)
76
77memories = memory.get_user_memories(user_id=jane_doe_id)
78print("Jane Doe's memories:")
79pprint(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 custom-memory-instructions.py
1python custom-memory-instructions.py