Agent memory: what gets written, what gets found, and what goes stale
智能体记忆
Score a memory stream by recency, importance and relevance, then compare a bounded message queue, recall search and an editable working context on synthetic conversations with updated facts.
agent-memoryThe model forgets at the edge of its context window
A language model conditions only on the tokens in its current context. An agent that runs for days, or holds a conversation across many sessions, accumulates far more history than fits. Something outside the model has to decide what to store, what to bring back for the current step, and what to overwrite when a fact changes. That “something” is the agent’s memory system, and its decisions are visible in behavior: an assistant that keeps sending you to last month’s meeting room has a memory problem, not a reasoning problem.
Two 2023 systems make the design choices concrete. Generative Agents keeps a complete, append-only log of an agent’s experiences in natural language, called the memory stream, and retrieves a small subset for each decision by combining recency, importance and relevance. Memory and retrieval, Section 4.1 MemGPT borrows from operating systems: the prompt is treated like main memory, external databases like disk, and the model itself issues function calls to move information between them, warned by the system when the context is filling up. Sections 2.1–2.3
The two designs answer different questions. Generative Agents asks: given a large store, which items should the model see now? MemGPT asks: given a fixed window, who moves what in and out, and when? Both leave a third question partly open: when two stored items disagree, which one is current? This article works through all three with a deterministic program. It does not cover retrieval-augmented generation over document collections or vector index structures, which have their own entries; the focus is memory of the agent’s own experience.
Retrieval scores, normalization and memory tiers
In Generative Agents, each memory object stores a natural-language description, a creation timestamp and a most-recent-access timestamp. Three scores are computed for a query at time . Recency is an exponential decay over game hours since the memory was last retrieved, with decay factor 0.995. Importance is an integer from 1 to 10 assigned by the language model when the memory is created. Relevance is the cosine similarity between embedding vectors of the memory and the query. Section 4.1, page 9 Each score is min-max scaled to the range from 0 to 1 over the candidate memories,
and the final score is a weighted sum; the paper sets all three weights to 1 and puts the top-ranked memories that fit into the context window into the prompt: Section 4.1, page 9
Here is the memory’s last-access time, its importance and an embedding. Min-max scaling has a consequence that is easy to miss. Because , moving forward multiplies every raw recency by the same positive constant, and the constant cancels in the normalization:
So, as long as access times do not change between queries, normalized recency encodes only the order and spacing of past accesses, not how long ago “now” is. An agent that was idle for a long time ranks its memories exactly as before. This is a property of the formula as written, derived here; it is not a claim the paper makes. In the paper, retrieval also refreshes access times, so frequently retrieved memories stay recent, which creates a feedback loop.
Generative Agents adds a second kind of memory object, the reflection. When the summed importance of recent events exceeds a threshold (150 in their implementation), the model is asked for salient high-level questions about the 100 most recent records, retrieves evidence for each, and writes insights that cite the records they rest on. Reflections enter the same stream and can be retrieved and reflected on again, forming trees. Section 4.2, pages 9–10 Reflection as an agent-level error-correction loop is a separate topic (agent reflection); here it is a memory-compression mechanism.
MemGPT divides the prompt into three contiguous parts: read-only system instructions, a fixed-size read/write working context that can be changed only through function calls, and a first-in, first-out (FIFO) message queue whose first entry holds a recursive summary of evicted messages. Outside the prompt are recall storage, which keeps every message, and archival storage, a read/write database for arbitrary text. Sections 2.1–2.2, pages 2–3 With context capacity tokens, the constraint and the two thresholds from the paper’s description are:
At the warning threshold the queue manager inserts a memory-pressure message so the model can save important items to working context or archival storage; at the flush threshold it evicts messages, updates the recursive summary, and leaves the evicted messages searchable in recall storage. The 70% and 50% figures are the paper’s examples, not fixed constants. Section 2.2, page 3 The model edits and searches memory itself through function calls; outputs are parsed and validated, errors are fed back, retrieval results are paginated, and a flag lets the model chain several calls before yielding control. Sections 2.3–2.4, pages 3–4 The paper’s conversation example replaces the working-context entry “Boyfriend named James” with “Ex-boyfriend named James” after the user reports a breakup. Figure 4, page 4 That replace operation is the mechanism for the third question above.
Retrieval weights and three memory policies on synthetic data
The program has two parts and uses no language model, no embedding model and no network.
Part A scores a hand-written stream of eleven synthetic office memories with the Generative Agents formula. Relevance is cosine similarity between bag-of-words count vectors after removing a short stop-word list, which stands in for embeddings. Importance values are fixed by hand. Recency uses creation time only; access-time refresh is omitted. The query, asked at hour 100, is “where is the team meeting this week”. The stream contains an old fact (hour 2: the meeting is in Room Birch) and an update (hour 58: the meeting moved to Room Cedar).
Part B generates 200 synthetic conversations of 48 messages. Sixteen messages per conversation are facts “key = value” over eight keys, so each key is stated and later updated once; the rest are chat. A quarter of fact messages are marked as paraphrased: the agent understands them while they are in context, but an exact-key search over recall storage cannot find them. The context holds 12 messages; the system warns at 70% (9 messages) and flushes half when full. Policies:
fifo: answer only from messages still in the queue;recall-first-hit: if not in the queue, search recall storage and return the first (oldest) match;recall-latest: as above but return the newest match;working: at each warning, a scripted writer copies every not-yet-written fact in the queue into a key-value working context, replacing older values; answers come from the queue, then working context, then recall;working-missed: the same writer skips every fourth write, standing in for a model that fails to save something.
"""Original synthetic memory study. No language model, embedding model or network is used.
Part A scores a memory stream with recency, importance and relevance.
Part B compares a bounded message queue with recall search and an editable working context.
A paraphrased fact is understood while it is in context but is invisible to exact-key recall search.
"""
import math
import random
import re
from collections import Counter
STOP = {'the', 'a', 'is', 'at', 'in', 'to', 'of', 'on', 'for', 'and', 'this', 'with', 'now', 'will', 'be'}
def words(text):
return Counter(w for w in re.findall(r'[a-z]+', text.lower()) if w not in STOP)
def cosine(a, b):
dot = sum(a[k] * b[k] for k in a)
na, nb = math.sqrt(sum(v * v for v in a.values())), math.sqrt(sum(v * v for v in b.values()))
return dot / (na * nb) if na and nb else 0.0
def minmax(xs):
lo, hi = min(xs), max(xs)
return [0.0 if hi == lo else (x - lo) / (hi - lo) for x in xs]
STREAM = [
(2, 3, 'Weekly team meeting is in Room Birch on Thursday'),
(5, 2, 'Bought coffee beans for the office kitchen'),
(9, 6, 'Dana prefers short written summaries before meetings'),
(20, 2, 'Watered the plants near the window'),
(31, 8, 'Release deadline for the billing service is Friday'),
(44, 2, 'Printer on floor two is out of toner'),
(58, 7, 'Team meeting moved from Room Birch to Room Cedar starting this week'),
(63, 2, 'Lunch order arrived late'),
(77, 3, 'Read an article about meeting room booking software'),
(90, 2, 'Cleaned the whiteboard in Room Birch'),
(96, 4, 'Dana asked for the billing release checklist'),
]
def retrieve(query, now, weights, k=3, decay=0.995):
q = words(query)
rec = minmax([decay ** (now - t) for t, _, _ in STREAM])
imp = minmax([i for _, i, _ in STREAM])
rel = minmax([cosine(q, words(text)) for _, _, text in STREAM])
a, b, c = weights
scores = [a * r + b * m + c * v for r, m, v in zip(rec, imp, rel)]
order = sorted(range(len(STREAM)), key=lambda j: (-scores[j], j))[:k]
return [(STREAM[j][0], round(scores[j], 3)) for j in order]
def conversation(rng, n=48, keys=8):
msgs, truth = [], {}
fact_slots = sorted(rng.sample(range(n), 16))
for t in range(n):
if t in fact_slots:
key = 'k%d' % (fact_slots.index(t) % keys)
value = 'v%d' % rng.randrange(100)
truth[key] = value
paraphrased = rng.random() < 0.25
msgs.append((t, 'fact', key, value, paraphrased))
else:
msgs.append((t, 'chat', None, None, False))
return msgs, truth
def run(msgs, policy, capacity=12, warn=0.7, flush=0.5, miss_every=0):
queue, recall, working, writes, seen = [], [], {}, 0, set()
for m in msgs:
queue.append(m)
recall.append(m)
if policy == 'working' and len(queue) >= math.ceil(warn * capacity):
for item in queue:
if item[1] == 'fact' and item[0] not in seen:
seen.add(item[0])
writes += 1
if miss_every and writes % miss_every == 0:
continue
working[item[2]] = item[3]
if len(queue) >= capacity:
queue = queue[int(flush * capacity):]
return queue, recall, working
def answer(key, queue, recall, working, policy):
in_queue = [m for m in queue if m[2] == key]
if in_queue:
return in_queue[-1][3]
if policy == 'fifo':
return None
if policy == 'working' and key in working:
return working[key]
hits = [m for m in recall if m[2] == key and not m[4]]
if not hits:
return None
return hits[0][3] if policy == 'recall-first-hit' else hits[-1][3]
def main(seed=0, trials=200):
query = 'where is the team meeting this week'
print('A: query at hour 100 =', repr(query))
for name, w in [('equal', (1, 1, 1)), ('relevance_only', (0, 0, 1)), ('recency_only', (1, 0, 0)),
('importance_only', (0, 1, 0))]:
print(' ', name, retrieve(query, 100, w))
print(' equal_weights_top1_if_now_is_hour_1000', retrieve(query, 1000, (1, 1, 1), k=1))
rng = random.Random(seed)
policies = ['fifo', 'recall-first-hit', 'recall-latest', 'working', 'working-missed']
correct = {p: 0 for p in policies}
missing = {p: 0 for p in policies}
total = 0
for _ in range(trials):
msgs, truth = conversation(rng)
for p in policies:
base = 'working' if p.startswith('working') else p
queue, recall, working = run(msgs, base, miss_every=4 if p == 'working-missed' else 0)
replies = {k: answer(k, queue, recall, working, base) for k in truth}
correct[p] += sum(replies[k] == v for k, v in truth.items())
missing[p] += sum(r is None for r in replies.values())
total += len(truth)
print('B: conversations', trials, 'questions', total, 'capacity 12, warn at 70%, flush 50%')
for p in policies:
wrong = total - correct[p]
print(' %-17s accuracy %.3f no_answer %4d stale_answer %4d' % (p, correct[p] / total, missing[p], wrong - missing[p]))
if __name__ == '__main__':
main()
The recorded output is:
A: query at hour 100 = 'where is the team meeting this week'
equal [(58, 2.372), (96, 1.333), (77, 1.333)]
relevance_only [(58, 1.0), (2, 0.943), (77, 0.408)]
recency_only [(96, 1.0), (90, 0.921), (77, 0.758)]
importance_only [(31, 1.0), (58, 0.833), (9, 0.667)]
equal_weights_top1_if_now_is_hour_1000 [(58, 2.372)]
B: conversations 200 questions 1600 capacity 12, warn at 70%, flush 50%
fifo accuracy 0.249 no_answer 1201 stale_answer 0
recall-first-hit accuracy 0.386 no_answer 81 stale_answer 901
recall-latest accuracy 0.816 no_answer 81 stale_answer 214
working accuracy 1.000 no_answer 0 stale_answer 0
working-missed accuracy 0.971 no_answer 14 stale_answer 32
Part A. With equal weights, the hour-58 update ranks first with score 2.372 (relevance 1, importance 0.833 and recency about 0.539 after scaling). Relevance alone also ranks it first, but the stale hour-2 fact is a close second at 0.943: both mention the team meeting, and nothing in cosine similarity marks one as superseded. Recency alone returns three recent but useless memories, including “Cleaned the whiteboard in Room Birch”, which would mislead an agent that reads it as evidence. Importance alone puts the billing deadline first. Moving “now” to hour 1000 leaves the top result and its score unchanged at 2.372, which is the normalization identity derived above.
Part B. A bounded queue alone answers 24.9% of the 1,600 questions; the other 1,201 facts have been evicted. Searching recall storage recovers most of them, but returning the oldest match gives a stale value 901 times: retrieval found the right key and the wrong version. Returning the newest match raises accuracy to 81.6%, with 214 stale answers caused by paraphrased updates that search cannot see (the newest visible match is then the old value) and 81 questions where no visible mention exists at all. Writing facts into an editable working context while they are still in context reaches 100% in this toy, because the scripted writer never misreads a fact. When every fourth write is skipped, accuracy drops to 97.1%. Because the sixteen facts cycle through the eight keys in order, the skipped writes (the 4th, 8th, 12th and 16th) land on the same two keys both times, so those keys never enter working context at all. Their questions fall back to recall search: 32 of the 46 errors are stale answers from a paraphrased update that search cannot see, and 14 are questions with no visible mention. None of the errors is a stale value in working context, so this row is a structured artifact of the skip pattern, not a model of random write failures.
The cost per query is linear in the number of stored memories for Part A, since every memory is scored; real systems use approximate nearest-neighbor indexes to avoid that. Part B’s policies cost one queue scan and at most one recall scan per question.
What the synthetic results do and do not support
Part B’s 100% for working context is a property of the scripted writer, which reads perfectly structured “key = value” messages. A language model deciding what to save, under a memory-pressure warning, can miss facts, save the wrong span or overwrite a correct value; the working-missed row is only one crude version of that. No number here estimates how often a real model does any of these things.
Bag-of-words cosine is not an embedding. It cannot match paraphrases, which is why the program models paraphrase as invisibility to search. Dense embeddings match paraphrases better but introduce their own errors, such as ranking a topically similar but outdated fact highly, which is exactly what happened to the hour-2 memory under relevance-only scoring.
Both papers evaluate believability, consistency or task accuracy in their own settings: Generative Agents with 25 agents in a sandbox town and an ablation of observation, planning and reflection; MemGPT on multi-session chat and document question answering. This article read only the architecture sections listed in its source notes and does not report or reproduce their evaluation numbers.
Long-term memory also raises issues no ranking formula addresses: what a user has consented to have stored, how to delete it, and how to prevent instructions hidden in stored text from being treated as commands when retrieved later. A memory that persists across sessions persists its errors and its injected content too.
Exercises
-
Why does Generative Agents retrieve a subset of the memory stream instead of summarizing or including all of it?
Answer: The paper gives two reasons: the full stream does not fit in the context window, and including too much distracts the model. It also reports that summarizing everything produced an uninformative answer in its example, whereas retrieval surfaced specific relevant memories. Retrieval is a choice about what the model sees, made outside the model.
-
Using the program’s tokenization, the query keeps the words where, team, meeting, week. Memory 2 keeps weekly, team, meeting, room, birch, thursday. Memory 58 keeps team, meeting, moved, from, room (twice), birch, cedar, starting, week. Compute both cosine similarities and the normalized relevance of memory 2, given that 58 has the maximum and some memory has 0.
Answer: Memory 2 shares team and meeting: cosine = 2 / (2 × √6) ≈ 0.408. Memory 58 shares team, meeting and week; its squared norm is 8 × 1 + 2² = 12: cosine = 3 / (2 × √12) ≈ 0.433. Normalized relevance of memory 2 is 0.408 / 0.433 ≈ 0.943, matching the output. The stale fact is nearly as relevant as the update.
-
An agent is idle for 900 hours and then answers the same query. Under the program’s scoring, does the long gap push old memories further down? What would you change if you wanted absolute age to matter?
Answer: No. With fixed timestamps, every raw recency is multiplied by the same factor γ to the power 900, and min-max scaling removes that factor, so ranks and scores are unchanged (2.372 at hour 1000). To make absolute age matter, use the unnormalized decay, a fixed reference scale, or an explicit expiry or validity interval for facts that can go out of date.
-
A support assistant must always use a customer’s current shipping address, which customers update occasionally and sometimes describe in different words. Which memory design would you choose, and what would you test?
Answer: Keep the address as a single editable slot (a working-context or database field with replace semantics and a timestamp) rather than relying on similarity search over the message history, because search returns old and new statements alike and may miss paraphrased updates; in the toy, newest-match search still gave 214 stale answers. Test the write step directly: whether updates expressed in varied wording are captured, what happens when a write is missed, and whether stale slots are detected, for example by confirming the address with the user before shipping.
Open questions
Generative Agents shows that a retrieval score combining recency, importance and relevance, plus periodic reflection, supports believable long-running behavior in a sandbox; its weights are all set to 1 and its importance scores come from the model itself. Section 4.1 MemGPT shows a way to give a fixed-window model access to unbounded history by letting it manage memory tiers with function calls and system warnings. Section 2 Neither design settles how to resolve conflicting memories in general, how to evaluate the write policy separately from the read policy, or how to bound the influence of an incorrect memory once it has been stored and reflected on.
When comparing memory systems, report the write rule, the read rule and the conflict rule separately, and test with facts that change over time and are restated in different words. Accuracy on facts that never change measures storage, not memory management. Related entries cover context windows and long-context models, retrieval-augmented generation, vector databases and agent reflection.
Make a prediction, then check
Recall search finds both an old and a new statement of the same fact. What is the most likely problem with ranking by relevance alone?
Learning objectives
- Compute and interpret a combined recency, importance and relevance retrieval score, including how min-max scaling makes normalized recency independent of the current time.
- Separate write, read and conflict rules, and test a bounded queue, recall search and an editable working context with facts that are updated and paraphrased.
Prerequisites & connections
Explore related knowledge →References
- Generative Agents: Interactive Simulacra of Human Behavior — scoped arXiv v2 (UIST 2023)
Joon Sung Park; Joseph C. O'Brien; Carrie J. Cai; Meredith Ringel Morris; Percy Liang; Michael S. Bernstein · 2023 - MemGPT: Towards LLMs as Operating Systems — scoped arXiv v2
Charles Packer; Sarah Wooders; Kevin Lin; Vivian Fang; Shishir G. Patil; Ion Stoica; Joseph E. Gonzalez · 2024
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Claude · 2026-12-02 · Independent AI check (Claude subagent, not the author; not a human or expert review). Ran example.py with python3 3.12 and diffed it against example.stdout.txt (identical); confirmed the python block is byte-identical in en.mdx and zh.mdx and the four display equations match. Re-derived the min-max recency identity (gamma^t > 0 factors out of numerator and denominator, so normalized recency is t-invariant for fixed access times) and confirmed the article labels it as its own derivation, not a paper claim; recomputed recency 0.538 for the hour-58 memory, 1 + 0.833 + 0.539 = 2.372, exercise 2 cosines 2/(2*sqrt 6) = 0.408 and 3/(2*sqrt 12) = 0.433 and ratio 0.943, and the Part B accounting. Instrumented the working-missed run to classify its 46 errors. Downloaded Generative Agents arXiv v2 and MemGPT arXiv v2 PDFs with curl and read pdftotext output of Generative Agents pp. 8-10 (Section 4.1 memory fields, 0.995 decay over game hours since last retrieval, 1-10 importance, cosine relevance, min-max scaling, all alphas 1; Section 4.2 threshold 150, 100 recent records) and MemGPT pp. 1-4 (three-part main context, recursive summary, recall/archival storage, warning e.g. 70%, flush evicting e.g. 50%, error feedback, heartbeat, Figure 4 caption). Compared zh and en section by section and checked data.json IDs. Did not read either paper's evaluation sections and did not render the MDX.
- Code output matches the recording; code blocks are byte-identical; all Part A and Part B numbers match the output.
- The min-max t-invariance derivation is correct (gamma^t > 0 cancels in numerator and denominator) and is labelled as the article's derivation, not a paper claim; exercise 2 values 0.408, 0.433, 0.943 recomputed.
- Generative Agents' 0.995, 1-10 importance, min-max, weights 1, threshold 150 and 100 records, and MemGPT's three-part main context, 70%/50% as examples, and the Figure 4 replace example all match the PDFs.
- Found and corrected a wrong explanation of the working-missed errors; zh and en correspond section by section; IDs exist; quiz answer is correct.
Source locations checked:
- Generative Agents: Interactive Simulacra of Human Behavior — scoped arXiv v2 (UIST 2023) · arXiv v2 PDF pages 8–10 (Sections 4, 4.1, 4.2, start of 4.3): memory object fields; recency decay 0.995 over game hours since last retrieval; LLM importance 1–10 with the poignancy prompt; cosine relevance on embeddings; min-max to [0,1]; all alphas 1; top memories that fit context; reflection trigger at importance sum 150, 100 most recent records, cited evidence, reflection trees; gpt3.5-turbo. arXiv abstract page for 25 agents and ablation claim. Evaluation sections, appendix not read. The t-invariance of normalized recency is the author's derivation, not a paper claim.
- MemGPT: Towards LLMs as Operating Systems — scoped arXiv v2 · arXiv v2 PDF pages 2–4 (Sections 2–2.4, Figures 1–4, Table 1 caption, start of Section 3): main vs external context; system instructions / working context / FIFO queue with recursive summary; recall and archival storage; warning token count e.g. 70%, flush e.g. evict 50%; self-directed function calls with parsing, error feedback, pagination; events and heartbeat chaining; working_context.replace example. Experimental results not read; no code run.
Related topics