Sub topic 14
Going further: long-term memory and retrieval
This chapter assumes you have built the chat loop from the earlier chapters. That means a role-tagged message list, a sliding-window trim_history, and JSON save and load. It also assumes you are comfortable with Python sets and regular expressions.
What the history cannot do
Trimming drops old turns. Summarizing keeps a compressed version of them. Both still treat memory as part of one conversation. If you start a new session with /reset, everything is gone. A fact such as "my name is Priya" may also be pushed out of the window long before the session ends.
Long-term memory stores facts outside the history. On each turn, the program looks up the few facts relevant to the new message and adds them to the request. This is called retrieval.
A small memory store
The store is a JSON list of short strings. The sketch below scores each fact by how many words it shares with the user's message and returns the best few.
import json
import re
from pathlib import Path
def words(text):
return set(re.findall(r"[a-z0-9']+", text.lower()))
def load_memories(path):
p = Path(path)
if not p.exists():
return []
return json.loads(p.read_text(encoding="utf-8"))
def recall(memories, query, k=3):
q = words(query)
scored = [(len(q & words(m)), m) for m in memories]
scored = [s for s in scored if s[0] > 0]
scored.sort(key=lambda s: s[0], reverse=True)
return [m for _, m in scored[:k]]
def build_messages(history, memories, user_text):
system = [m for m in history if m["role"] == "system"]
rest = [m for m in history if m["role"] != "system"]
found = recall(memories, user_text)
if found:
note = "Known facts about the user:\n" + "\n".join("- " + f for f in found)
system = system + [{"role": "system", "content": note}]
return system + rest + [{"role": "user", "content": user_text}]
memories = [
"The user's name is Priya.",
"The user prefers Python over Java.",
"The user lives in Lisbon.",
]
print(recall(memories, "Should I use Python for this?"))Running it prints:
['The user prefers Python over Java.']build_messages returns a new list and does not modify history. The recalled facts are sent with this one request only. They never enter the saved history, so they cannot pile up or go stale there.
Choosing what to remember
Retrieval is the easy half. The harder question is what to write into the store. There are three common options:
| Approach | How it works | Trade-off |
|---|---|---|
| Explicit command | The user types `/remember I use Linux` | Predictable, but needs user effort |
| Model extraction | After a turn, ask the model to list durable facts | Hands-free, but can store wrong facts |
| Summary reuse | Keep the summaries from the summarization chapter | Simple, but loses detail |
Whichever you choose, let the user list and delete memories. Stored facts can be wrong, outdated, or private.
Gotchas
- Word overlap is crude. "prefers" does not match "prefer", and "car" does not match "vehicle". Embeddings fix this. An embedding turns text into a vector of numbers, so similar meanings land close together. You rank facts by vector similarity instead of shared words. Your provider's SDK or a local library supplies the embedding function.
- Every recalled fact uses context tokens. Keep
ksmall and each fact short. - Do not treat recalled text as trusted instructions. A stored string can contain anything the user, or a model, once wrote.
- Save the store with the temporary-file pattern from the persistence chapter, so a crash cannot leave half a file.
Where to go next
For a few hundred facts, a JSON list with simple scoring is enough. For thousands, use a vector index or a database with similarity search. The shape of the code stays the same: look up, build the message list, call complete.
Exercise
Why does build_messages add the recalled facts to a copy of the message list instead of appending them to the saved history?
Show answer
Recalled facts are relevant only to the current request. Adding them to the saved history would repeat them on every later turn, use up context tokens, and keep outdated facts in the conversation. A copy keeps the history clean and the facts fresh, since recall runs again on each message.