Retrieve agent memories by similarity and recency

MediumAgentsPro

Why it matters Agent memory systems and generative-agent simulations rank memories with similarity plus a recency decay like this.

Long-running agents store memories and must recall the right ones. A good score mixes how related a memory is to the query with how recent it is.

Write retrieve_memories(query, mem_vecs, ages, k, w, half_life). query is (D,), mem_vecs (N, D), ages (N,) in hours since the memory was written.
- sim_i = cosine similarity of query and mem_vecs[i] (0 if either vector has zero norm).
- rec_i = 0.5 ** (ages_i / half_life).
- score_i = w * sim_i + (1 - w) * rec_i.
Return (list of the top min(k, N) indices by score descending, ties broken by smaller index, and the numpy array of all scores).

Signaturedef retrieve_memories(query, mem_vecs, ages, k, w, half_life)

Example

retrieve_memories([1, 0], [[1, 0], [0, 1], [1, 1]], [10, 0, 0], 2, 0.5, 10) gives ([2, 0], array([0.75, 0.5, 0.8536])).

Understand the idea

An agent that remembers everything needs a way to pick what matters for the current question. Pure similarity search returns old memories that happen to match; pure recency returns whatever just happened. Mixing the two works better, like how you recall both what is relevant and what is fresh.

Example: query [1, 0]. Memory 0 is [1, 0] (similarity 1) but 10 hours old with half-life 10, so recency 0.5. Memory 2 is [1, 1] (similarity 0.707) and brand new, recency 1. With w = 0.5: memory 0 scores 0.75 and memory 2 scores 0.854, so the fresh, fairly related memory ranks first.

Rules: sim = cos(q, m); rec = 0.5^(age / half_life); score = w * sim + (1 - w) * rec.

Assistant memory features and simulated agents rank recall candidates with formulas like this, often adding an importance term too.

Shapes and data flow

query: (D,), mem_vecs: (N, D) -> sim, rec, score: (N,) -> top k indices
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleretrieve_memories([1, 0], [[1, 0], [0, 1], [1, 1]], [10, 0, 0], 2, 0.5, 10)
  • Sample 2: scale mattersretrieve_memories([1, 1], [[10, 10], [1, 0], [0, 0.5]], [48, 1, 0], 3, 0.7, 24)