Sub topic 10
Deciding what is worth remembering
This chapter assumes you know basic Python, have called a chat-style LLM API, and understand an agent as an LLM running in a loop. It also assumes you have seen the MemoryStore class from the previous chapters, which has a write method and a search method.
Why not remember everything?
The easiest policy is to save every message. It fails in practice for three reasons:
- Retrieval quality drops. Small talk and one-off questions crowd out the facts that matter.
- Storage and embedding costs grow with every turn.
- Stored data is a privacy liability. The more you keep, the more you must protect.
A write policy decides which parts of a conversation become long-term memories. A good policy keeps information that will still be useful in a later session.
A simple test for a memory worth keeping
Ask three questions about a candidate:
- Will it still be true and useful next week?
- Would the agent behave worse without it?
- Is it safe to store?
The table applies these questions to some examples.
| Candidate | Keep? | Kind | Reason |
|---|---|---|---|
| "My name is Priya." | Yes | semantic | Stable fact, used often |
| "I prefer short answers." | Yes | procedural | Changes how the agent should respond |
| "Booking the flight failed because the card expired." | Yes | episodic | Useful past event |
| "Thanks!" | No | none | No future value |
| "What is 17 times 3?" | No | none | One-off, easy to recompute |
| "My card number is 4111..." | No | none | Sensitive and risky to store |
When to write
You can write at different moments. Each has a cost.
- During the turn (hot path): the agent calls a "save memory" tool. Memories appear immediately, but each turn gets slower and the model may over-save.
- After the session (background): a separate step reviews the whole conversation. It is cheaper per turn and sees more context, but memories arrive late.
Letting the model extract memories
A common approach is to ask the LLM to list durable facts as JSON. The code below shows the filter around that call. The call_llm argument stands for your own function that sends a prompt and returns text.
import json
EXTRACT_PROMPT = """From the conversation below, list facts worth remembering
for future sessions: stable preferences, personal facts, and important events.
Skip small talk, one-off questions, and secrets such as passwords or card numbers.
Reply with only a JSON list of objects with keys "text" and "kind",
where kind is "semantic", "episodic", or "procedural".
Conversation:
{conversation}
"""
ALLOWED_KINDS = {"semantic", "episodic", "procedural"}
def extract_memories(conversation, call_llm):
raw = call_llm(EXTRACT_PROMPT.format(conversation=conversation))
try:
candidates = json.loads(raw)
except json.JSONDecodeError:
return [] # a bad reply writes nothing
good = []
for c in candidates:
if not isinstance(c, dict):
continue
text = str(c.get("text", "")).strip()
kind = c.get("kind")
if len(text) >= 8 and kind in ALLOWED_KINDS:
good.append({"text": text, "kind": kind})
return good
def save_session(store, user_id, conversation, call_llm):
for m in extract_memories(conversation, call_llm):
store.write(user_id, m["text"], kind=m["kind"])
# Fake model reply so the example runs without an API key
fake_llm = lambda prompt: (
'[{"text": "User name is Priya", "kind": "semantic"},'
' {"text": "ok", "kind": "semantic"}]'
)
print(extract_memories("user: My name is Priya.", fake_llm))The output keeps the first item and drops "ok", because it is too short to be useful.
Common errors
- Trusting the model's output. The model can return invalid JSON or invented kinds. Validate before writing, as the code does.
- Storing guesses as facts. If the user only asked about Paris, do not save "lives in Paris". Tell the extractor to save only what the user stated.
- Writing duplicates. Saving "likes tea" every session floods retrieval. Check for a near match first. The maintenance chapter covers this.
- Saving secrets. A prompt instruction is not a guarantee. Add a pattern check for card numbers and passwords before the write.
Exercise
A user says, "Remind me that I always want code examples in TypeScript, and by the way I'm asking for a friend's birthday gift today." Which parts should be written to long-term memory, and what kind is each?
Show answer
Save "The user wants code examples in TypeScript" as a procedural memory, because it changes how the agent responds in future sessions. Do not save the gift request. It is a one-off task, so it fails the "useful next week" test. If the agent later helps with the gift and picks a store, that outcome could be saved as an episodic memory.