Skip to content
BIASED

Context and memory

Window budgets, compaction, external memory, and the economics of prompt caching.

Append-only and the budget

The ReAct loop appends every thought, action and observation. With prefix ss and dd tokens per step, step tt reads Lt=s+(t−1)dL_t = s + (t-1)d, so a whole run of TT steps costs

∑t=1TLt=Ts+d T(T−1)2\sum_{t=1}^{T} L_t = T s + d\,\frac{T(T-1)}{2}

input tokens — quadratic in TT. For s=3000s=3000, d=1500d=1500, window W=128000W=128000 with 4000 reserved for the reply, the last fitting step is t=81t=81; eighty steps already read about 4.98 million tokens, and the last step alone reads 121 500. Three failures arrive together: the run hits the window, each later step is more expensive, and (next) the model uses a long context worse than a short one.

Key idea. Treat the context as a budget the runtime spends on purpose: only what the next step needs, in an order the model and the cache can use, with old material summarised and anything that must survive moved to a store outside the window.

What to put, and in what order

Context engineering is choosing the smallest high-signal set of tokens for the desired behaviour. A managed step typically assembles: a stable prefix (instructions, schemas, fixed exemplars) first — identical every step, so cacheable; a few retrieved memories; a recursive summary of the far past plus recent steps verbatim; and a short restated goal or to-do at the end, next to where the model writes. The budget is one inequality: prefix, memories, summary, recent and reply must fit in WW. Every part competes with every other.

Lost in the middle

Models do not read long contexts uniformly. Liu et al. (2024) moved the single answer-bearing Wikipedia passage among twenty (~4k tokens) on NaturalQuestions-Open: for GPT-3.5-Turbo, accuracy was 75.8% when the passage was first, 53.8% in the middle (worse than the 56.1% closed-book baseline), and 63.2% last. Longer-window variants of the same models kept nearly the same U-curves. Later “context rot” measurements (2025) show accuracy still falling with length and with semantically similar distractors. Cheap rules: put instructions first and the task plus key material last; restate the goal near the end on long runs; clear spent tool outputs to one-line notes; prefer fewer sharp memories over many distractors.

Compaction

Compaction replaces older steps by a model-written summary when the context passes a high-water mark H≤WH\le W. Keep the last kk steps verbatim and a summary of size σ\sigma; right after compaction the context holds s+σ+kds+\sigma+kd tokens, then grows by dd until HH again. With H=64000H=64000, k=8k=8, σ=2000\sigma=2000 on the run above, an 80-step compacted loop reads about 2.79M tokens plus ~105k for two summarizer calls — ~58% of append-only — and can continue past step 82. Compaction is lossy: summarise with an explicit keep/drop list, keep recent steps verbatim, and write anything that might be needed again to an external store before it is summarised away.

Long-term memory

Long-term memory is RAG over a corpus the agent wrote. Cognitive architectures (Sumers et al., 2024) split working (the context), episodic (what happened), semantic (facts), and procedural (how — including prompts and weights). MemGPT pages between a main context and external recall/archival stores via tool calls, with memory-pressure messages before a flush. Generative Agents score memories for query qq as

score(m)=αrec rec^(m)+αimp ι^(m)+αrel rel^(m,q)\mathrm{score}(m)=\alpha_{\mathrm{rec}}\,\widehat{\mathrm{rec}}(m)+\alpha_{\mathrm{imp}}\,\widehat{\iota}(m)+\alpha_{\mathrm{rel}}\,\widehat{\mathrm{rel}}(m,q)

with rec(m)=0.995h\mathrm{rec}(m)=0.995^{h}, importance ι∈{1,…,10}\iota\in\{1,\dots,10\}, relevance cosine similarity, and hats for min–max over candidates. In the deploy-failure example, the oldest relevant memory still wins. Voyager stores only verified Minecraft skills as code keyed by embeddings — procedural memory that does not accumulate broken programs. Writing is harder than retrieval: near-duplicates, stale facts, wrong memories, and injected content that persists across sessions all argue for writing less — confirmed outcomes, user-confirmed facts, procedures that passed a check.

Prompt caching and next

Prompt caching reuses KV for an exact prefix match. If a cached token costs ρ\rho and a newly written one ω\omega (relative to base input price 1), an append-only run costs

Ccache=ρ(∑t=1TLt−LT)+ω LT.C_{\mathrm{cache}}=\rho\Big(\sum_{t=1}^{T} L_t - L_T\Big)+\omega\, L_T.

With ρ=0.1\rho=0.1, ω=1.25\omega=1.25, the 80-step append-only example drops from 4.98M to about 638k base-price tokens. Compaction still helps under caching when rewrites are rare; editing the early context every step (timestamps, memories before history) throws the cache away. Keep the prefix stable, append between rare compactions, put volatile material last, and keep tool lists in deterministic order.

Next: memory keeps what was learned — it does not choose the next action. Planning with language models puts search and classical planners back around the LM.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.