Sub topic 11
Retrieving and ranking relevant memories
This chapter covers the read side of long-term memory: given the user's current input, which stored memories should go into the prompt? It assumes you can write basic Python and know what an embedding is (text turned into a vector, where similar meanings give nearby vectors). It also assumes you have seen a simple store that writes memories with embeddings and searches by cosine similarity. The code here builds on that idea.
Why retrieval is more than "top-k by similarity"
A prompt has a fixed token budget, so only a few memories fit. Retrieval decides which ones. Two failures are common:
- Missing the useful memory. The query wording differs from the stored text, or many similar memories crowd out the one that matters.
- Injecting noise. Top-k always returns k items, even when nothing relevant exists. The model then sees unrelated facts and may use them.
A good retriever filters, scores, ranks, and then trims to a budget. Each stage addresses one of these failures.
Stage 1: filter before you score
Apply hard constraints first. The most important is the owner: only memories with the current user_id are candidates. Filtering first is cheaper and safer than scoring everything and hoping the wrong user's memories rank low. You can also filter by kind (for example, only procedural memories when the agent is choosing how to do a task) or by a time range.
Production vector databases usually support metadata filters inside the search call. Prefer that over filtering the results afterward. If you fetch the top 5 across all users and then discard other users' items, you may be left with zero results.
Stage 2: similarity and the threshold
Cosine similarity compares the angle between two vectors. For many text embedding models it falls between about 0 and 1 for related text, but the range depends on the model, so you cannot copy a threshold from another system.
Set a minimum similarity and drop candidates below it. With a threshold, "no relevant memory" becomes a valid result, and the prompt gets no memory block at all. To choose the value, run 20 to 50 realistic queries against your own store. Note the scores of memories you judge relevant and of those you judge irrelevant, and pick a value between the two groups.
Stage 3: combine signals into a rank
Similarity says a memory is on topic. It does not say whether the memory is current or important. A common fix is a weighted score:
score = w_sim * similarity + w_rec * recency + w_imp * importance
| Signal | What it captures | Typical computation | Risk if overweighted |
|---|---|---|---|
| Similarity | Topical match to the current input | Cosine of query and memory vectors | Near-duplicates fill all slots |
| Recency | Newer facts are more likely to still be true | Exponential decay with a half-life | Old but vital facts disappear |
| Importance | Some memories matter more (allergies, deadlines) | Value assigned at write time | Everything gets marked important |
Recency with a half-life means a memory's recency value halves every N days: 0.5 ** (age_days / half_life_days). A 30-day half-life gives 1.0 today, 0.5 at 30 days, and 0.25 at 60 days.
Apply the similarity threshold before combining. Otherwise a recent, important, irrelevant memory can outscore a relevant one.
A working retriever
This version is self-contained. The toy embed function counts words so the example runs without an embedding model. In real use you would replace it with a call to an embedding model and keep the rest.
import math
import re
from collections import Counter
DAY = 86400
def embed(text):
"""Toy stand-in for an embedding model: word counts as a sparse vector."""
return Counter(re.findall(r"[a-z]+", text.lower()))
def cosine(a, b):
dot = sum(a[w] * b[w] for w in a if w in b)
norm_a = math.sqrt(sum(v * v for v in a.values()))
norm_b = math.sqrt(sum(v * v for v in b.values()))
return dot / (norm_a * norm_b) if norm_a and norm_b else 0.0
def retrieve(items, user_id, query, now, k=3, min_similarity=0.2,
half_life_days=30, weights=(0.7, 0.2, 0.1)):
w_sim, w_rec, w_imp = weights
q = embed(query)
scored = []
for m in items:
if m["user_id"] != user_id:
continue # hard filter: never score another user's memory
sim = cosine(q, m["vec"])
if sim < min_similarity:
continue # threshold: irrelevant memories are not candidates
age_days = (now - m["created"]) / DAY
recency = 0.5 ** (age_days / half_life_days)
importance = m.get("importance", 0.5)
score = w_sim * sim + w_rec * recency + w_imp * importance
scored.append((score, m))
scored.sort(key=lambda pair: pair[0], reverse=True)
return scored[:k]
now = 1_000_000_000
def memory(user_id, text, days_old, importance=None):
item = {"user_id": user_id, "text": text, "vec": embed(text),
"created": now - days_old * DAY}
if importance is not None:
item["importance"] = importance
return item
items = [
memory("alice", "User prefers Python for code examples", 2, 0.9),
memory("alice", "User asked for Python code examples last week", 40),
memory("alice", "User prefers tea over coffee", 200),
memory("bob", "Bob wants Python code examples", 1, 0.9),
]
for score, m in retrieve(items, "alice", "Show code examples in Python", now):
print(f"{score:.2f} {m['text']}")The output is:
0.66 User prefers Python for code examples
0.46 User asked for Python code examples last weekThe tea memory shares no words with the query, so the threshold removes it. Bob's memory matches the query well, but the user filter removes it before scoring. The two remaining memories rank by a blend of match quality, age, and importance.
Failure modes to design for
Near-duplicate crowding
If the store holds five phrasings of "prefers Python", the top 3 slots may all say the same thing. Two mitigations help:
- Deduplicate at write time, which a later chapter covers.
- Rerank for diversity. Pick the best item, then penalize remaining candidates that are very similar to what you already picked. This approach is called maximal marginal relevance (MMR).
Query mismatch
The raw user message is often a poor search query. "Yes, do that" retrieves nothing useful. Two fixes are common. Build the query from the last few turns instead of one message. Or ask the model to rewrite the input into a standalone search query before embedding it. Both add a little latency or cost, so use them only if evaluation shows retrieval misses.
Stale facts outranking fresh ones
A user who said "I live in Oslo" in January and "I moved to Lisbon" in June has two highly similar memories. Recency helps, but the cleaner fix is updating the old memory when the new one is written.
Prompt injection through memories
Retrieved text goes into the prompt, so a stored memory can contain instructions, such as text copied from a web page. Label the block as data ("Known facts about the user") and do not store raw tool output as memory without review.
Stage 4: fit the budget
After ranking, the memory block must fit alongside the system prompt, conversation buffer, and room for the reply. Two practical rules:
- Reserve a fixed share of the context for memories, for example 10 to 15 percent, instead of letting them take whatever is left.
- Add memories in rank order until the share is used up, and skip any single memory that is too long instead of stopping. Order matters inside the prompt, too. Some models attend less to text in the middle of a long prompt, so keep the memory block short and place it near the system message.
Count memory tokens with the same tokenizer you use for trimming the buffer. Otherwise the two budgets will disagree.
Choosing the knobs
| Knob | Start with | Raise it when | Lower it when |
|---|---|---|---|
| `k` | 3 to 5 | Relevant memories are missing from the prompt | The prompt is crowded or the model drifts off topic |
| `min_similarity` | A value from your own score samples | Irrelevant memories appear | Relevant memories are being dropped |
| `half_life_days` | 30 | Old facts stay valid for long | Facts change quickly |
| `w_imp` | 0.1 | Critical facts are missed | Everything looks important |
Change one knob at a time and re-run your test queries.
Exercise
A user says "Yes, go ahead." The agent's retriever embeds that message and returns the top 3 memories, but they are unrelated to the task. Name two causes in the retrieval design and one fix for each.
Show answer
First, the query is too short and has no topical content, so every memory scores low. Fix: build the query from the last few turns, or have the model rewrite it into a standalone query. Second, top-k always returns k items regardless of quality. Fix: add a minimum similarity threshold so low-scoring memories are dropped and the memory block is left out when nothing is relevant.
Exercise
In the code above, why is the similarity threshold applied before the weighted score instead of after?
Show answer
A recent, high-importance memory can earn enough recency and importance points to outscore a relevant memory even if its similarity is near zero. Dropping low-similarity candidates first guarantees that every ranked memory is on topic, and that recency and importance only reorder relevant candidates.