Skip to content
AgenticAIWiki
  1. Learn
  2. Part 10
  3. 57. Managing memory over time
  4. 57.2

Lesson 57.2 · 2 of 5 · 4 min read · Reviewed 24 Nov 2026

Retrieving the right memory

By the end, you can

  • Retrieve the right memories for the current task.
  • Rank memories by relevance, recency and importance.

The retrieval step

current task: "Can you help with my invoice again?"
   |
   v
filter: owner = C-2201, type in (episode, preference)
   |
   v
rank: relevance x recency x importance
   |
   v
top 3 memories --> into context, each with date and source

Ranking signals

Signal Example
Relevance Similarity between the task and the memory
Recency Last week’s episode beats one from two years ago
Importance A recorded decision beats a passing remark
Usage Memories that helped before get a small boost

A simple score multiplies or adds weighted signals. Tune weights with a few test cases: “for this task, which memories should come back?”

Show your sources

Insert memories with their date and type:

<memories>
- [episode, 2026-03-14] Invoice error on March bill; resolved with credit.
- [preference, 2026-01-05] Prefers email follow-up.
</memories>

The model can then weigh old against new, and you can debug what it saw.

Retrieval as a tool

Instead of loading memories up front, you can give the agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. a search_memory(query) tool and let it decide when to look (chapter 24 does the same for documents).

Key points

  • Retrieve a few relevant memories, not all of them; more memory isn't better context.
  • Rank by a mix of relevance (similarity to the task), recency, and importance.
  • Filter by owner and type first, then rank; show memories with their date and source.
Hands-on labRuns in the Playground

Rank memories by relevance, recency, importance

Score stored memories for a task with a weighted mix of relevance, recency and importance, load the top 3, and tune the weights against a test case.

You will have: A score function, the top 3 memories for a task, and the result of a small weight test.

Steps

  1. Read the MEMORIES list: text, age in days and importance.
  2. Write relevance as word overlap between the task and the memory (share of task words found).
  3. Write recency as 0.5 ** (age / half_life).
  4. Combine them with weights, rank, and print the top 3 with their scores.
  5. Try a recency-heavy weighting and check whether the expected memory still comes first.

Done when

  • With balanced weights the invoice episode is the top memory.
  • With recency-heavy weights the test prints FAIL, showing why weights need test cases.
  • Only 3 memories are loaded.

Open in the Playground No API key needed.

Starter code (Python)
MEMORIES = [
    {"text": "invoice error on march bill resolved with credit", "age": 250, "imp": 0.7},
    {"text": "prefers email follow up", "age": 320, "imp": 0.6},
    {"text": "holiday in lisbon mentioned", "age": 5, "imp": 0.1},
    {"text": "chose annual billing", "age": 120, "imp": 0.9},
    {"text": "likes short answers", "age": 300, "imp": 0.5},
]
TASK = "help with my invoice error again"

def relevance(task, text):
    # TODO: share of task words that appear in the memory text
    return 0.0

def score(m, w_rel, w_rec, w_imp, half_life=90):
    # TODO: weighted sum of relevance, recency (0.5 ** (age / half_life)) and importance
    return 0.0

def top3(weights):
    ranked = sorted(MEMORIES, key=lambda m: score(m, *weights), reverse=True)
    return ranked[:3]

for m in top3((0.6, 0.2, 0.2)):
    print("%.2f %s" % (score(m, 0.6, 0.2, 0.2), m["text"]))
Show a solution
MEMORIES = [
    {"text": "invoice error on march bill resolved with credit", "age": 250, "imp": 0.7},
    {"text": "prefers email follow up", "age": 320, "imp": 0.6},
    {"text": "holiday in lisbon mentioned", "age": 5, "imp": 0.1},
    {"text": "chose annual billing", "age": 120, "imp": 0.9},
    {"text": "likes short answers", "age": 300, "imp": 0.5},
]
TASK = "help with my invoice error again"

def relevance(task, text):
    words = task.split()
    have = set(text.split())
    return sum(w in have for w in words) / len(words)

def score(m, w_rel, w_rec, w_imp, half_life=90):
    rec = 0.5 ** (m["age"] / half_life)
    return w_rel * relevance(TASK, m["text"]) + w_rec * rec + w_imp * m["imp"]

def top3(weights):
    ranked = sorted(MEMORIES, key=lambda m: score(m, *weights), reverse=True)
    return ranked[:3]

for name, w in (("balanced", (0.6, 0.2, 0.2)), ("recency-heavy", (0.1, 0.8, 0.1))):
    best = top3(w)
    print(name, "Top 3:")
    for m in best:
        print("  %.2f %s" % (score(m, *w), m["text"]))
    print("  test, invoice episode first:", "PASS" if best[0]["text"].startswith("invoice") else "FAIL")
Quick checkAn agent loads all 400 memories about a user at the start of every chat. What's the main problem?
How sure are you?
Pick an answer and how sure you are