Handbooks  /  Agent Memory
Handbook~15 min readAgentsworked math + runnable code
The Agent Memory Handbook

A finite window,
an endless task.

An agent's context window is a whiteboard of fixed size, but the conversation keeps coming. Sooner or later the board is full — and now every turn is a decision: what do you erase? Erase the wrong thing and the agent forgets the user's name, the plan, the fact that mattered. This is the memory problem, and it has a clean shape: a token budget you can't exceed, two ways to make room (forget, or compress), and an external notebook the agent can search when it needs something it wrote down long ago. Here's the arithmetic of remembering.

01

The board fills up

Every LLM call is stateless — the model only knows what's in its context window right now. To give an agent continuity, you resend the conversation history each turn. But the window holds a fixed number of tokens, and a real agent's history — messages, tool calls, tool results, retrieved documents — grows without bound. The collision is inevitable: at some point the history no longer fits, and you must decide what to drop.

That decision is agent memory. It's not a fancy neural mechanism; it's a budgeting problem. You have a token budget (the window minus room for the model's reply and system prompt), a stream of content that exceeds it, and a policy for choosing what survives into the next turn and what gets stored elsewhere. Get the policy right and the agent stays coherent over hours; get it wrong and it forgets the thing it needed most, mid-task. Everything else in this handbook is refinements of that budget.

The one-sentence version

A finite context window forces a memory policy: keep recent turns, evict or summarize old ones to fit the token budget, and push durable facts to external memory you can retrieve.

02

Short-term vs long-term

Memory splits into two tiers, mirroring how we usually think about it. Short-term (working) memory is the context window itself — the recent messages the model sees directly this turn. It's fast and fully available, but tiny and volatile: anything not in it, the model simply doesn't know. Long-term memory is an external store — a database or vector index — that holds facts, summaries, and past events indefinitely, outside the window.

The agent's job is to shuttle between them: keep the relevant recent turns in short-term memory, write durable facts to long-term memory, and retrieve from long-term back into the context when a turn needs them. This is exactly the architecture MemGPT framed as an operating system for memory — the context window is RAM, external memory is disk, and the agent pages information between them. With that split, an agent can "remember" far more than its window ever holds, because most of its memory lives on disk and only the relevant page is loaded at a time.

03

Forget or compress

When the context exceeds budget, you have two moves to make room. Eviction drops the oldest messages until the rest fit — first-in-first-out, like a sliding window over the conversation. It's dead simple and keeps the most recent, most relevant turns, but it forgets: whatever falls off the back is gone from context entirely.

Two ways to fit a growing history in a fixed budget
Evict (FIFO)Drop the oldest messages to fit — simple, keeps recent, but forgets.
SummarizeCompress old turns into a short summary — keeps the gist for far fewer tokens.
RetrieveStore facts externally; pull the relevant ones back when needed.
CombineRecent verbatim + rolling summary + external memory = the production recipe.

Summarization is the smarter move: replace a block of old messages with a short summary that preserves the essential facts for a fraction of the tokens. A rolling summary lets the agent carry a trace of the whole conversation in a small, fixed budget, so it doesn't fully forget the early context — it just holds a compressed version of it. The trade-off is fidelity: summaries lose detail, and a fact dropped from a summary is as gone as an evicted one. That's why the third leg — external memory you can retrieve exact facts from — matters, and why production agents combine all three.

04

The budget math

The whole problem is a token inequality. The messages you send must fit the budget B (the window minus reply and system-prompt room). Eviction keeps the newest messages whose total stays under B:

keep newest messages while   Σ tokens ≤ B   ⟹   the rest (oldest) are evicted

FIFO: the newest turns survive, the oldest fall off. Simple, but everything evicted is gone from context.

Summarization changes the arithmetic. Replace a block of history costing T tokens with a summary costing a fraction ρ·T (the compression ratio, e.g. ρ=0.25), and you free most of that budget while keeping the gist:

summary tokens = ρ·T  (ρ < 1)   ⟹   summary + recent  <  full history   (more coverage per token)

Compressing old turns to ρ·T lets the agent retain a trace of history it would otherwise evict — trading detail for coverage. The runnable version below fits messages to a budget by eviction, compresses evicted history, and retrieves a fact from external memory.

RUN IT YOURSELF

Fit history to a budget

Agent memory is a token budget with a policy. Eviction keeps the newest messages that fit and drops the oldest (FIFO) — so the context stays under budget but the earliest turns are forgotten. Summarization compresses a block of history to a fraction of its tokens, so a summary plus the recent turns costs far less than the full history while keeping the gist. And an external memory store recalls a specific fact by key even after it left the context entirely. Change the budget, the compression ratio, or the messages and watch what survives.

CPython · WebAssembly
05

The external notebook

Eviction and summarization both lose information — the only question is how gracefully. The fix for durable facts is an external memory store the agent can search. It writes facts and past events out (often to a vector index keyed by embeddings), and when a new turn needs something old, it retrieves the relevant items back into context — recalling a specific fact long after it scrolled out of the window.

Memory typeWhat it holds
Working (context)Recent messages the model sees this turn — fast, fully available, tiny.
EpisodicPast interactions and events, retrievable by relevance ("what did we decide yesterday?").
SemanticDurable facts and preferences (user's name, project constraints) stored as key-value or vectors.
Summary bufferA rolling compressed summary of the conversation so far, carried in context cheaply.

The production recipe combines all of it: keep the last few turns verbatim (working memory), maintain a rolling summary of older turns (compression), and retrieve durable facts on demand from external memory (retrieval). This is the memory-stream idea behind generative agents — store observations, retrieve the relevant ones, and let the agent act with a memory far larger than its window. The window is just the desk; the filing cabinet is where most of the memory lives.

06

Pitfalls

The subtle failure is summarizing away the load-bearing detail. A summary that reads well can quietly drop the exact number, id, or constraint the agent will need later — and once it's out of both context and summary, it's unrecoverable unless it also went to external memory. So route durable specifics (ids, decisions, user facts) to a store, and let summaries carry only the gist. Another trap is retrieval that fetches the wrong memories: bad relevance ranking pulls in irrelevant history and pushes out what mattered, so memory quality depends on retrieval quality just as much as RAG does.

Two more. Recall context rot — a bigger window is not a free pass, because models attend less reliably to the middle of a very long context, so stuffing everything in can hurt even when it fits. And beware unbounded external memory: a store that only ever grows makes retrieval slower and noisier over time, so agents need forgetting policies (decay, deduplication, importance weighting) for long-term memory too. Good agent memory isn't about remembering everything — it's about spending a small token budget on the right things, and knowing where the rest is filed.

Worth knowing

A fact only survives if it's in context, in the summary, or in external memory. Summaries and evictions both lose detail — so route anything you must recall exactly (ids, decisions, user preferences) to a durable store, not just a summary.

Frequently asked

Quick answers

Why do agents need memory?

The context window is a fixed token budget but the conversation grows without bound, so the agent must decide what to keep, compress, or store externally.

Short-term vs long-term?

Short-term is the context window (recent, fast, tiny); long-term is an external store retrieved into context when needed.

How to stay in budget?

Evict the oldest messages (simple, forgets) or summarize them (compress the gist for fewer tokens) — production agents combine both plus retrieval.

How does retrieval memory work?

Write facts to an external store (often a vector index), then retrieve the relevant ones back into context — recalling facts long after they left the window.

Finished this one? 0 / 99 Handbooks done

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.