Sub topic 11
Retrieving and ranking relevant memories
This chapter assumes you can write basic Python and know what an embedding is. It also assumes you have seen the MemoryStore from the earlier chapters, which stores each memory with a vector, an owner, and a creation time. Here you improve its search method so the agent gets the right memories, not just the nearest ones.
Why top-k similarity is not enough
Plain similarity search always returns k results, even when nothing is relevant. It also treats a fact from last year the same as one from yesterday. Both problems put noise into the prompt. The model may then treat that noise as true.
A better read path has four steps:
- Filter by owner, so one user never sees another user's memories.
- Score each remaining memory.
- Drop memories below a minimum score.
- Keep the top k.
Combining similarity and recency
A simple score mixes two signals. Similarity measures how close the memory is to the query. Recency measures how new the memory is. Recency uses exponential decay: the value halves every half_life_days.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b) if norm_a and norm_b else 0.0
def rank_memories(items, query_vec, user_id, now, k=3, min_sim=0.3,
half_life_days=30, w_sim=0.8, w_rec=0.2):
scored = []
for m in items:
if m["user_id"] != user_id:
continue
sim = cosine(query_vec, m["vec"])
if sim < min_sim:
continue
age_days = (now - m["created"]) / 86400
recency = 0.5 ** (age_days / half_life_days)
scored.append((w_sim * sim + w_rec * recency, m))
scored.sort(key=lambda pair: pair[0], reverse=True)
return [m for _, m in scored[:k]]
DAY = 86400
now = 1_000_000_000
items = [
{"user_id": "u1", "text": "Likes tea", "vec": [1.0, 0.0], "created": now - 90 * DAY},
{"user_id": "u1", "text": "Now prefers coffee", "vec": [0.9, 0.3], "created": now - 2 * DAY},
{"user_id": "u1", "text": "Lives in Pune", "vec": [0.0, 1.0], "created": now - 1 * DAY},
{"user_id": "u2", "text": "Likes mangoes", "vec": [1.0, 0.2], "created": now},
]
result = rank_memories(items, [1.0, 0.2], "u1", now)
print([m["text"] for m in result])The output is ['Now prefers coffee', 'Likes tea']. Both drink memories match the query closely. The newer one wins because of recency. "Lives in Pune" falls below the similarity threshold. The memory belonging to u2 is filtered out before scoring.
Choosing the parameters
| Parameter | Effect | Typical failure |
|---|---|---|
| `k` | Number of memories in the prompt | Too high fills the context budget |
| `min_sim` | Cuts irrelevant results | Too high returns nothing, too low adds noise |
| `half_life_days` | How fast old memories fade | Too short forgets stable facts such as a user's name |
| `w_rec` | Weight of recency | Too high lets recent chatter beat relevant facts |
Embedding models differ in how they spread scores, so tune min_sim on your own data. Do not copy a value from another system.
Common errors
- Filtering by user after taking the top k. The top k may all belong to other users, leaving you with none. Filter first.
- Applying recency decay to every memory type. Semantic facts such as "allergic to peanuts" should not fade. Consider decaying only episodic memories.
- Returning stale contradictions. If the user changed their mind, both memories may match. Recency helps, but the real fix is updating or removing the old one, covered in the maintenance chapter.
- Forgetting the budget. Retrieved memories take space in the context window, so trim them together with the history, as
build_promptdoes.
Exercise
A user told the agent "I'm vegetarian" two years ago. The agent never recalls it, although the user asks about dinner ideas. Your ranking uses a 30-day half-life with w_rec=0.2. Name two likely causes and one change for each.
Show answer
First, similarity may be below min_sim because "dinner ideas" is not close to "I'm vegetarian" in embedding space. Lower the threshold or also embed a richer summary of the memory, such as "dietary preference: vegetarian". Second, recency decay has pushed the score under newer but less important memories. Exempt semantic memories from decay or lower w_rec.