Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

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.

By the numbers

Worked example: a 20-turn chat in an 8,000-token window

Say the window is 8,000 tokens. Reserve 1,000 for the reply and 500 for the system prompt. Every turn (user message plus agent reply) costs 400 tokens, and the user gave their name in turn 2. Apply the page’s rules with ρ = 0.25.

StepQuestionArithmeticAnswer
1Budget B8,000 − 1,000 − 5006,500 tokens
2History at turn 2020 × 4008,000: over budget by 1,500
3Evict (FIFO): what fits?newest turns while Σ ≤ 6,500: 16 × 4006,400 kept; turns 1–4 evicted
4Where is the user’s name?it was in turn 2Gone from context
5Summarize turns 1–10 instead10 × 400 × 0.251,000-token summary
6Summary + turns 11–201,000 + 4,0005,000; 1,500 spare
7Retrieve 3 facts from the store5,000 + 3 × 1005,300 sent; name recalled exactly
8Turn 30, same ratio20 × 400 × 0.25 + 10 × 400 + 3006,300: nearly full again

Step 4 is the silent failure: the agent works fine and has simply forgotten who it is talking to. Step 7 is why the name should have gone to the store when it was said, not left for a summary that may or may not keep it. Step 8 shows that a summary at a fixed ratio still grows with the conversation. Around turn 30 you must summarize the summary itself, and every pass loses a little more detail. So durable facts belong in the store, not the summary.

Trade-offs

Cost and trade-offs of each memory policy

Time is the extra work per turn, Space is the tokens each turn sends, and the last column is what you give up. The totals use the example’s 400-token turns and 6,500-token budget.

CaseTimeSpaceWhy
Resend everythingNoneGrows every turn: 84,000 tokens over 20 turns, 510,000 over 50Total cost grows with the square of the conversation length, and it overflows the window at turn 17 anyway.
FIFO evictionA sum over recent turnsCapped at the budget: 272,000 tokens over 50 turnsCheapest policy that fits. Forgets everything past the window, including the important parts.
Rolling summaryAn extra model call each time you compressSummary ρ·T plus recent turnsKeeps the gist of everything. Loses exact numbers, ids and wording, and each re-summary loses more.
External store + retrievalEmbed the query and search the store each turnOnly the top few hits enter context; the store grows on diskExact recall of what was written down. Only as good as the ranking, and it needs its own forgetting policy.
A bigger windowNone per turn, but every turn costs moreUp to the larger budgetDelays the problem rather than solving it, and the middle of a long context is attended to less reliably.

Production agents stack the last three rows: recent turns verbatim, a summary for the gist, and a store for facts that must survive exactly. The eviction row is not a strategy on its own. It is what happens anyway when nothing else is in place.

In the wild

Where this shows up in production and interviews

  • Assistant memory features

    ChatGPT’s memory saves facts about the user (name, preferences, ongoing projects) and brings them into later conversations. That is the semantic tier from the table above, kept apart from the chat history.

  • Coding agents compacting context

    Long coding sessions overflow the window fast, because tool results are large. Claude Code’s /compact replaces the history with a summary and carries on, which is the rolling-summary move done on demand. Project files such as CLAUDE.md act as the durable store that every session reloads.

  • Framework building blocks

    LangChain shipped this recipe as a ready-made class, ConversationSummaryBufferMemory: recent turns verbatim, older ones summarized, switched by a token limit. MemGPT’s RAM-and-disk paging became the Letta project.

  • The interview version

    For “design a support agent that remembers customers”, do the step 1 arithmetic out loud, then say what goes where: the last few turns in context, a running summary per conversation, and account facts in a store keyed by customer id. Then cover deletion. A user who asks to be forgotten must be removed from the store, not just from the window.

Self-check

Check yourself

B = 6,500 and every turn is 400 tokens. With FIFO eviction, how many turns does the agent see, and what is the oldest turn it remembers at turn 25?

6,500 ÷ 400 rounds down to 16 turns (6,400 tokens). At turn 25 it sees turns 10–25, so the oldest it remembers is turn 10. Anything said in turns 1–9 is gone unless it was summarized or stored.

A user says “my order id is A-7731” early on. Hours later the agent needs it. Which of evict, summarize or store is the only safe place for it?

The store. Eviction drops it once it leaves the window. A summary may paraphrase it away or garble a digit, and nothing tells you it did. An exact identifier must be written to external memory when it appears and retrieved by key or by relevance later.

You double the window and the agent gets worse at using a detail from the middle of the conversation. Why?

Fitting is not the same as attending. Models use the middle of a very long context less reliably than its start and end, so stuffing more history in can bury the detail. Retrieving the relevant fact and placing it near the end of the prompt often beats a bigger window.

After a month, retrieval keeps pulling in stale, duplicate memories. What is wrong, and what do you add?

The store only grows. Add a forgetting policy: deduplicate on write, let old items decay, weight by importance, and overwrite a fact when it changes (a new address replaces the old one) instead of keeping both.

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 / 209 Handbooks done
NextThe Loop Engineering Handbook Next on the “Building agents” ladder · rung 4 of 10

Explore the topic

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

More Handbooks