Context engineering and memory¶
A language model knows two things at inference time: its weights, and the tokens in its context window. Context engineering is the discipline of deciding, at every step, which tokens go into that window, in what order and form; memory is everything you keep outside the window so you can bring the right part back later. The one idea: context is a scarce, degrading resource, so find the smallest set of high-signal tokens for the step at hand, and lay them out so the expensive part is computed once.
10,000 ft
Prompt engineering asks how to word an instruction. Context engineering asks what the model should be looking at: instructions, tool definitions, retrieved documents, conversation history, tool results, memories, its own notes. The term took hold in mid-2025, when agents running dozens of steps made the problem unavoidable; Anthropic defines it as "the set of strategies for curating and maintaining the optimal set of tokens (information) during LLM inference". It draws on three older threads: the mechanics of attention and the KV cache, the evidence that long contexts are used unevenly, and decades of work on memory in cognitive architectures. Retrieval is one of its tools, multi-agent isolation another, and prompt caching makes it an economic question as much as a quality one.
2,000 ft
Every source competes for one window. An assembler decides what enters, in what form and order; whatever is left out lives in external memory or in another agent's window.
LangChain's summary of the field names four moves, and every technique on this page is one of them:
- Write: save information outside the window (scratchpads, notes, long-term memory).
- Select: pull the relevant part back in when needed (retrieval, just-in-time loading).
- Compress: keep only the tokens the task needs (summaries, clearing old tool results).
- Isolate: give sub-tasks their own windows (sub-agents, sandboxes, separate state).
Ground level¶
Why more context is not better¶
Context windows grew from 4k tokens to a million and more. It is tempting to treat that as "put everything in". The evidence says otherwise.
- Position effects. Liu et al. (2023, "Lost in the Middle") found models use information at the beginning and end of a long context better than in the middle, even for explicitly long-context models.
- Needle tests flatter. RULER (Hsieh et al., 2024) evaluated 17 long-context models: nearly all scored near-perfectly on the vanilla needle-in-a-haystack test, yet "almost all models exhibit large performance drops as the context length increases", and only half of those claiming 32k tokens or more performed satisfactorily at 32k.
- Literal matching hides the problem. NoLiMa (Modarressi et al., 2025) removed word overlap between the question and the needle, so the model must make a latent association. At 32k tokens, 11 of 13 models dropped below 50% of their short-context scores; GPT-4o fell from 99.3% to 69.7%.
- Context rot. Chroma's 2025 report tested 18 models and found performance "varies significantly as input length changes, even on simple tasks": lower question-needle similarity degrades faster with length, topically related distractors hurt more than random text, and on LongMemEval questions, models did markedly better given a focused prompt of about 300 tokens than the full conversation of about 113k tokens containing the same answer.
Drew Breunig's taxonomy names the failure modes you will see in agents: context poisoning (a hallucination enters the context and is treated as fact thereafter), distraction (so much context that the model leans on it instead of what it learned in training), confusion (superfluous context shapes the answer) and clash (parts of the context contradict each other). Each is a reason to curate rather than accumulate.
The working principle, in Anthropic's words: find "the smallest possible set of high-signal tokens that maximize the likelihood of some desired outcome".
The anatomy of a well-built context¶
A useful mental model is a stack, from most stable to most volatile:
Instructions at the right altitude. The system prompt should state goals, constraints and heuristics in plain language: specific enough to guide behaviour, general enough not to be a brittle list of if-then rules. Anthropic calls this "the Goldilocks zone between two common failure modes": hard-coded logic on one side, vague exhortation on the other. Organise it in labelled sections (background, instructions, tool guidance, output format) and keep it as short as the behaviour allows.
Tools as context. Every tool definition is read on every step. Twenty verbose tools can cost several thousand tokens before the conversation starts, and similar tools confuse selection. Keep the set small, or load definitions on demand (below).
Examples, chosen not piled. A few diverse, canonical examples teach more than a long list of edge cases, and repetitive examples cause the model to copy their pattern (Manus calls this getting "few-shotted").
History, curated. Raw transcripts include failed attempts, verbose tool output and pleasantries. Decide what survives each turn (see compression), and drop earlier error messages and refusals that no longer help.
Prompt caching: the economics of layout¶
When a model processes a prompt it computes keys and values for every token at every layer (the KV cache). If the next request starts with exactly the same tokens, a provider can reuse those keys and values instead of recomputing them. That is prompt caching, and it only works for an identical prefix: change one token near the start and everything after it must be recomputed.
On Anthropic's API (as of 2026), the prefix is built in the order tools, system, messages; cache reads cost 0.1× the base input price for most models (less for some newer ones), writes to the default 5-minute cache cost 1.25× and to a 1-hour cache 2×, and "changes at each level invalidate that level and all subsequent levels", so editing a tool definition invalidates everything. Other providers cache automatically with different discounts; the principle is the same.
For agents this is the dominant cost lever. Manus reported an average input-to-output ratio of about 100:1 in their agent, with cached input at USD 0.30 per million tokens against USD 3 for uncached on the model they used, and called KV-cache hit rate "the single most important metric for a production-stage AI agent". The rules that follow:
- Keep the prefix stable. No timestamp to the second, request id or per-user greeting at the top of the system prompt. Put volatile data (today's date, the user's name) at the end.
- Append, never edit. Do not rewrite or reorder earlier messages; add new ones.
- Serialise deterministically. JSON with sorted keys, tools in a fixed order. (MCP's 2026-07-28 revision asks servers to return tools "in a deterministic order" for exactly this reason; see MCP.)
- Mask, don't remove, tools. Removing a tool mid-run changes the prefix and confuses the
model about earlier calls to it. Manus instead keeps all tools defined and constrains which
can be chosen at decode time (logit masking via response prefill, grouped by name prefixes
such as
browser_andshell_).
The Build-it code prices a 50-step run: append-only with a cached prefix costs 14% of no caching, while a single timestamp at the top of the prompt makes every step a cache miss and a cache write, costing 25% more than not caching at all.
Compress: compaction, clearing and summaries¶
When the window fills, something must go.
- Tool-result clearing. Once a tool's output has been used, replace it with a stub ("[result of search_docs cleared; 14 results, see notes]"). Anthropic calls this "one of the safest lightest touch forms of compaction".
- Compaction. Near the limit, have the model summarise the conversation and start a fresh window from the summary. Claude Code's compaction keeps "architectural decisions, unresolved bugs, and implementation details", drops redundant tool output, and continues "with this compressed context plus the five most recently accessed files". Tune the summariser for recall first (lose nothing important), then precision.
- Restorable compression. Drop the bulky part but keep a pointer to recover it: keep a web page's URL, not its text; a file's path, not its contents. Manus treats the file system as "the ultimate context": unlimited, persistent and directly operable by the agent.
- Token-level compression. LLMLingua (Jiang et al., 2023) uses a small model to delete low-information tokens, reporting up to 20× compression with little loss on its benchmarks. Useful for long, low-stakes reference text; risky for anything where exact wording matters.
Summaries are lossy, and the loss is silent
A summary cannot contain information it dropped, and later steps cannot know it was dropped. Compaction is where agents lose the constraint the user stated on turn 3. Keep critical facts (requirements, decisions, user preferences) in a structured, persistent note that compaction never rewrites, and test compaction against tasks that depend on early details.
Select: just-in-time context¶
Instead of loading everything that might be relevant up front, give the agent lightweight identifiers (file paths, URLs, query names, document ids) and tools to load the content when needed. This is how coding agents work: they see the directory tree and grep, then read the three files that matter. In Anthropic's description, agents built this way "maintain lightweight identifiers (file paths, stored queries, web links, etc.)" and use tools to load the data behind them at run time. The trade-off is latency (extra tool calls) against precision (only what is needed, when it is needed); hybrid designs preload a small core (a project's conventions file) and fetch the rest.
The same applies to tools and skills. When an agent has hundreds of tools, load only their
names and one-line descriptions, and fetch a full definition when the model chooses one.
Anthropic's Agent Skills (October 2025, published as an open standard in December 2025)
apply this "progressive disclosure" to instructions: each skill is a folder with a SKILL.md
whose name and description sit in the system prompt; the body loads only when the skill seems
relevant, and further files only when needed. Writing tool calls as code against
tools presented as files is the extreme version: Anthropic's "code execution with MCP" example
cut a workflow from 150,000 tokens to 2,000 by letting large intermediate results flow between
tools inside a sandbox rather than through the model's context.
Retrieval over documents (RAG, advanced RAG) is the classic selection mechanism; everything there about ranking quality applies, because a wrongly selected passage is a distractor.
Steer attention: recitation and keeping errors¶
Two counter-intuitive practices from production agents:
- Recitation. Manus has the agent maintain a
todo.mdand rewrite it as it works, which "pushes the global plan into the model's recent attention span". In a 50-step task the original goal is far back in the context; rewriting the plan keeps it near the end, where models attend best. - Keep the wrong stuff in. Erasing failed actions and error messages hides evidence the model needs to avoid repeating them. Leave the failure and its error in context (within budget), and the model updates.
Isolate: separate windows¶
When a sub-task needs a lot of exploration, run it in a separate context (a sub-agent) and bring back only the result: Anthropic's sub-agents may use "tens of thousands of tokens or more" and return a summary of often 1,000–2,000 tokens. Code sandboxes isolate in the same way: data stays in variables and files, and only what is printed enters the context. The price is the hand-off loss discussed in multi-agent systems.
Memory: what persists beyond the window¶
Memory is context engineering across sessions. The CoALA framework (Sumers et al., 2023), drawing on cognitive science, gives the vocabulary:
| Memory | Holds | In an LLM system |
|---|---|---|
| Working | The current task's state | The context window itself; scratchpads; the to-do file |
| Episodic | What happened, when | Past conversations and agent trajectories, timestamped |
| Semantic | Facts about the world and the user | Extracted facts ("salary is 24 lakh"), a profile, a knowledge graph |
| Procedural | How to do things | The system prompt, tools, skills, and the weights themselves |
MemGPT (Packer et al., 2023) framed memory as an operating-system problem: a small "main context" like RAM, larger external stores like disk, and the model itself issuing function calls to page information in and out. It is the ancestor of today's memory tools, where the model writes and reads its own notes.
A memory system has a write path and a read path:
- Writing is where most memory systems fail. Extract salient facts, then reconcile them with what is stored: Mem0 (Chhikara et al., 2025) has a model choose to add, update, delete or do nothing for each candidate, so "salary is 24 lakh" replaces "salary is 18 lakh" instead of sitting beside it. Zep's Graphiti (Rasmussen et al., 2025) keeps a temporal knowledge graph in which facts have validity intervals, so old facts are superseded but still answerable ("what was my salary last year?").
- Reading is retrieval with extra signals. Generative Agents (Park et al., 2023) scored each memory as recency + importance + relevance, each min–max normalised to [0, 1] with equal weights: recency decays by a factor of 0.995 per hour since the memory was last accessed, importance is an integer from 1 to 10 assigned by the model when the memory is written, and relevance is embedding similarity to the query. The Build-it code shows why recency matters: relevance alone retrieves a stale salary first.
- Evaluating memory needs its own benchmarks. LongMemEval (Wu et al., 2024) tests five abilities: information extraction, multi-session reasoning, temporal reasoning, knowledge updates and abstention (knowing you were never told). Commercial assistants and long-context models showed about a 30% accuracy drop when information had to be remembered across sustained interactions. Mem0 reported, on the LOCOMO benchmark, 26% relative improvement on an LLM-judge metric over OpenAI's memory, with 91% lower p95 latency and over 90% lower token cost than putting the full history in context.
Memory is personal data
Long-term memory about users is a database of personal information inferred by a model. It needs consent, user visibility ("what do you remember about me?"), correction and deletion that reaches every derived index (embeddings, graphs, summaries), tenancy isolation, and care that retrieved memories are not treated as instructions. A memory written from an injected web page is a persistent prompt injection.
Conversation state: replay, rewrite or structure¶
For chat products the most common memory problem is the follow-up: "and what about with my wife's income?". Three designs:
- Transcript replay. Send the last \(n\) turns. Simple, but the window fills with stale figures and earlier mistakes, and models get lost across long multi-turn chats.
- Query rewrite. Rewrite each follow-up into a standalone question using the history, then answer it with fresh context. The rewrite is gradable on its own.
- Structured session state. Keep a small typed record (current topic, entities in focus, the facts last shown) and pass that instead of transcripts.
Jarvis: structured state instead of transcripts, and a prefix built for the cache
Finny's assistant carries earlier answers forward as facts, not prose: after each turn, code stores up to eight self-contained lines of the figures that answer used, and the next turn's system prompt shows them under the question they answered, headed with the rule that where this turn's data gives a figure too, this turn's data wins. Its number gate treats those carried figures as legitimate because code computed them in their own turn. A proposed routing call goes further, rewriting each follow-up into a standalone query and keeping a small structured session state (the chunks and operation used, the plan type in focus); in offline tests every follow-up rewrite kept its keywords (14 of 14). The prompt is laid out for caching: static instructions and glossary first, today's date and the member's data after. With the routing catalogue moved into its own cached system message, a three-call check found 9,441 of 9,485 prompt tokens served from cache, about a tenth of the uncached price per call. One cautionary tale: a vector-memory table for semantic recall of old turns was built but never wired in, and the team now prefers structured state, because recalled old turns can carry stale plan figures and personal data. See the Jarvis case study.
First principles¶
Why distractors hurt: softmax is a competition. An attention head's output is a weighted average of value vectors with weights \(\operatorname{softmax}(\mathbf{q}^\top \mathbf{k}_i/\sqrt{d})\). Every token in the window takes a share of a fixed total weight of 1. Suppose the relevant token's score is \(s\) and the other \(n\) tokens' scores are random with mean 0 and variance \(\sigma^2\). The expected total weight of the background is about \(n e^{\sigma^2/2}\) against \(e^s\) for the needle, so the needle's weight is roughly
With \(s = 8\) and \(\sigma = 1\): 0.64 at \(n = 1{,}000\), 0.15 at \(10{,}000\), 0.018 at \(100{,}000\). Distractors with scores close to \(s\) are far worse than random tokens, because each takes a share comparable to the needle's: four at \(s - 0.5\) cut the weight at \(n = 1{,}000\) from 0.64 to about 0.25. Real models have many heads and layers and learn sharper scores, so this is a mechanism, not a prediction of accuracy; but it explains the empirical pattern above: degradation with length, and worse degradation with semantically similar distractors and with needles that share no words with the question.
Why caching changes design. Prefill (reading the prompt) costs compute proportional to the prompt length (and attention work that grows faster); decode reuses cached keys and values. A prefix shared across requests needs to be prefilled once. The economic consequence is that the order of context is now a cost decision: anything volatile placed early forces recomputation of everything after it. This is why "stable first, volatile last" is both a quality heuristic (recent tokens get attention) and a cost rule (stable tokens get cached), and why the two can conflict: the user's question is volatile but most important, so it goes last, which is also where attention is strongest.
Why memory needs forgetting. Retrieval quality depends on the competition in the store, just as attention depends on the competition in the window. A memory that never forgets accumulates superseded facts that are highly relevant to the query (an old salary is very similar to a new one) and therefore the most dangerous kind of distractor. Recency weighting, explicit updates and validity intervals are three ways of encoding the same principle: a fact's truth has a time index.
Why isolation is not free. Splitting context into windows trades interference within a window for information loss across windows. The data processing inequality (see multi-agent systems) bounds what a summary can carry. Good designs isolate where sub-tasks are loosely coupled and keep pointers to primary material so the loss is recoverable.
The maths¶
Expected needle weight. For background scores \(b_i \sim \mathcal{N}(0, \sigma^2)\), \(\mathbb{E}[e^{b_i}] = e^{\sigma^2/2}\) (the lognormal mean). By the law of large numbers \(\sum_{i=1}^n e^{b_i} \approx n e^{\sigma^2/2}\), giving the formula above. Adding \(m\) distractors at score \(s - \delta\):
At \(n = 1{,}000\), \(s = 8\), \(\sigma = 1\), \(m = 4\), \(\delta = 0.5\): the terms are \(1\), \(0.553\) and \(2.426\), so \(w \approx 0.251\). The distractor term dominates: one near-miss costs as much as hundreds of random tokens.
Cost of a cached agent run. With prefix \(P\), per-step growth \(s\), \(T\) steps, base price \(c\), cache-read multiplier \(\rho_r\) and cache-write multiplier \(\rho_w\), an append-only run where each step reads the previous context from cache and writes its new tokens costs
versus \(c\,\big(TP + sT(T-1)/2\big)\) uncached. With \(\rho_r = 0.1\) the quadratic term shrinks tenfold. A prefix that changes every step pays \(\rho_w\) on everything: \(\rho_w (TP + sT(T-1)/2)\), worse than not caching.
Memory retrieval score. For memory \(m\) with hours since last access \(h_m\), importance \(\iota_m \in \{1..10\}\) and embedding \(\mathbf{e}_m\), query embedding \(\mathbf{e}_q\):
where the tilde is min–max normalisation over candidates and Generative Agents set all \(\alpha = 1\). The recency half-life is \(\ln 0.5 / \ln 0.995 \approx 138\) hours, about six days.
Build it¶
Attention dilution and the economics of cache-friendly layout (NumPy):
import numpy as np
rng = np.random.default_rng(0)
# 1. Attention dilution: one "needle" key with logit 8 among n background keys with
# logits ~ N(0, 1), plus a few distractors that look almost as relevant (logit 7.5).
def needle_weight(n, distractors=0, s_needle=8.0, s_dist=7.5):
logits = np.concatenate([[s_needle], rng.normal(0, 1, n), np.full(distractors, s_dist)])
w = np.exp(logits - logits.max()); w /= w.sum()
return w[0]
for n in (1_000, 10_000, 100_000):
print(f"n={n:>7,}: needle weight {needle_weight(n):.3f}, with 4 distractors {needle_weight(n, 4):.3f}")
# 2. Prompt caching over a 50-step agent run: 4k-token prefix, 1.5k new tokens per step.
# Prices per million input tokens: base 3.00, cache read 0.30, 5-minute cache write 3.75.
P, s, T = 4_000, 1_500, 50
base, read, write = 3.00, 0.30, 3.75
ctx = P + s * np.arange(T) # input tokens at each step
no_cache = ctx.sum() * base / 1e6
append_only = (ctx[0] * write + (ctx[:-1] * read + s * write).sum()) / 1e6
print(f"\n{T} steps, {ctx.sum():,} input tokens")
print(f" no caching USD {no_cache:6.2f}")
print(f" append-only, cached prefix USD {append_only:6.2f} ({append_only / no_cache:.0%})")
print(f" timestamp at top of prompt USD {ctx.sum() * write / 1e6:6.2f} (every step a cache miss + write)")
n= 1,000: needle weight 0.662, with 4 distractors 0.251
n= 10,000: needle weight 0.152, with 4 distractors 0.112
n=100,000: needle weight 0.018, with 4 distractors 0.017
50 steps, 2,037,500 input tokens
no caching USD 6.11
append-only, cached prefix USD 0.88 (14%)
timestamp at top of prompt USD 7.64 (every step a cache miss + write)
The prices are illustrative (they match the base and cached rates Manus quoted, with a 1.25× write); use your provider's current ones. A memory store with Generative-Agents scoring, showing why relevance alone retrieves stale facts:
import numpy as np
# Generative-agents-style memory retrieval: score = recency + importance + relevance,
# each min-max normalised to [0, 1]; recency decays by 0.995 per hour since last access.
memories = [ # (text, hours since last accessed, importance 1-10, toy embedding)
("User's salary is 18 lakh a year", 2000, 8, [0.9, 0.1, 0.0]),
("User got a raise; salary now 24 lakh", 30, 9, [0.9, 0.2, 0.1]),
("User prefers answers in bullet points", 500, 4, [0.0, 0.1, 0.9]),
("User asked about index funds", 10, 3, [0.3, 0.9, 0.1]),
("User's daughter starts college in 2031", 900, 9, [0.2, 0.3, 0.2]),
("User said hello", 1, 1, [0.1, 0.1, 0.1])]
query = np.array([1.0, 0.1, 0.0]) # "how much do I earn?"
def minmax(x):
x = np.asarray(x, float); return (x - x.min()) / (x.max() - x.min())
E = np.array([m[3] for m in memories]); E /= np.linalg.norm(E, axis=1, keepdims=True)
relevance = minmax(E @ (query / np.linalg.norm(query)))
recency = minmax(0.995 ** np.array([m[1] for m in memories]))
importance = minmax([m[2] for m in memories])
for name, score in [("relevance only", relevance),
("recency + importance + relevance", recency + importance + relevance)]:
top = np.argsort(-score)[:2]
print(f"{name:34}", [memories[i][0] for i in top])
relevance only ["User's salary is 18 lakh a year", 'User got a raise; salary now 24 lakh']
recency + importance + relevance ['User got a raise; salary now 24 lakh', "User's salary is 18 lakh a year"]
Recency fixes the order here, but both salaries still reach the context. A reconciling write path (update the old fact rather than add a new one) is the real fix.
Things to try
- Vary the distractor gap \(\delta\) from 0 to 3 in
needle_weight. At what gap do distractors stop mattering at \(n = 1{,}000\)? - Move "today's date" from the end of the prompt to the top in the cost model: what fraction of the prefix is now uncacheable each day? Each request?
- Add an
updatestep to the memory store: when a new fact's embedding is within cosine 0.95 of an existing one with the same subject, ask (or simulate) a model deciding add, update or ignore. Re-run the salary query. - Build a compaction function for an agent transcript: keep the system prompt, the latest \(k\) turns and a summary of the rest. Write three test tasks whose answers depend on a turn-2 detail and see which compaction prompts preserve it.
- Measure your own model: place one fact at 10%, 50% and 90% depth of a 30k-token document of related text and ask about it with no shared keywords. Plot accuracy by depth.
In practice¶
- Track tokens by source per step (system, tools, retrieved, history, tool results). You cannot manage a budget you do not measure.
- Measure cache hit rate as a first-class metric for agents and high-volume chat.
- Budget for the long tail: cap tool-result size, paginate, and clear results once used.
- Put the question last and the most important evidence first; for long contexts, it can help to restate the question after the documents.
- Prefer structured state to prose history wherever the state has a known shape (a booking, a form, a plan); keep free-text history for genuinely open conversation.
- Give users control of memory: show it, let them edit and delete it, and scope it per user and per purpose.
Common misconceptions¶
- "A million-token window means I can stop worrying about context." Capacity is not accuracy. Effective use degrades with length and distractors well before the limit, and the cost grows with every token.
- "Memory means a vector database of past chats." That is one implementation of episodic recall. Most products need semantic memory (reconciled facts), and the hard part is the write path: what to keep, update and forget.
- "Summarising history is always safe." It silently drops details; important constraints belong in a structured note that summaries never rewrite.
- "Prompt caching is an infrastructure detail." It dictates prompt layout and can change an agent's cost by an order of magnitude.
Check yourself¶
Name the four context-engineering moves and give one technique for each.
Write (a to-do file or memory tool), select (just-in-time retrieval by identifier), compress (compaction or tool-result clearing), isolate (a sub-agent that returns a short summary).
Why does adding the current time to the first line of the system prompt raise costs, and where should it go instead?
Caching reuses only an identical prefix. A changing first line invalidates the cache for everything after it on every request, so each request pays full price (and, where writes are surcharged, more). Put volatile data at the end of the prompt, after the stable prefix.
Using the dilution formula, how many random background tokens cost as much attention as one distractor 1 logit below the needle (σ = 1)?
A distractor contributes \(e^{s-1}\); a background token on average \(e^{\sigma^2/2} = e^{0.5}\). The ratio is \(e^{s - 1.5}\); with \(s = 8\), \(e^{6.5} \approx 665\) background tokens.
A user said 'I moved to Bangalore' in January and 'I moved back to Pune' in June. In October they ask for cheap gyms near them. What can go wrong with relevance-only memory retrieval, and how do you fix it?
Both facts are highly relevant to "near them"; relevance alone may surface Bangalore first, or both, leaving the model to guess. Fixes: reconcile at write time (update the location fact, keeping history with validity dates), weight recency at read time, and have the model state which fact it used.
When is just-in-time loading worse than putting everything in context up front?
When the needed material is small, stable and needed on most turns (load it once and cache it), or when latency matters more than tokens (each lookup is a round trip), or when the model cannot know what to look for without seeing the material.
Hard: your agent works well for 20 steps and degrades after 60. Give three hypotheses and how to test each.
(1) Context rot: the window holds 60 steps of tool output; test by clearing used tool results and checking whether late-step accuracy recovers. (2) Goal drift: the original instructions are far back; test by reciting a plan/to-do at each step. (3) Poisoning: an early hallucinated fact is reused; test by inspecting traces for repeated false claims and by injecting a deliberate error early. Measure each change with the same task set and pass^k.
Hard: why can compaction make a 'knowledge update' worse rather than better?
A summariser compressing a long history may keep the earlier, more elaborated version of a fact and drop the brief later correction ("actually it's 24, not 18"), or merge the two into an ambiguous statement. The model then answers confidently from the stale version. Keep facts in a reconciled store rather than relying on summaries to carry corrections.
Go deeper¶
Papers
- Lost in the Middle: How Language Models Use Long Contexts — Liu et al., 2023.
- RULER: What's the Real Context Size of Your Long-Context Language Models? — Hsieh et al., 2024.
- NoLiMa: Long-Context Evaluation Beyond Literal Matching — Modarressi et al., 2025. What happens when the needle shares no words with the question.
- MemGPT: Towards LLMs as Operating Systems — Packer et al., 2023. Virtual context management.
- Generative Agents: Interactive Simulacra of Human Behavior — Park et al., 2023. Section 4: the memory stream, retrieval score and reflection.
- Cognitive Architectures for Language Agents (CoALA) — Sumers et al., 2023. Working, episodic, semantic and procedural memory for agents.
- LongMemEval: Benchmarking Chat Assistants on Long-Term Interactive Memory — Wu et al., 2024.
- Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory — Chhikara et al., 2025.
- Zep: A Temporal Knowledge Graph Architecture for Agent Memory — Rasmussen et al., 2025.
- LLMLingua: Compressing Prompts for Accelerated Inference — Jiang et al., 2023.
- A Survey of Context Engineering for Large Language Models — Mei et al., 2025. A broad map of the field, if you want every technique in one place.
Articles and blog posts
- Effective context engineering for AI agents — Anthropic, 2025. Attention budget, right-altitude prompts, just-in-time context, compaction, notes, sub-agents.
- Context Engineering for AI Agents: Lessons from Building Manus — Yichao "Peak" Ji, 2025. KV-cache-first design, masking, the file system as context, recitation.
- Context Rot: How Increasing Input Tokens Impacts LLM Performance — Hong, Troynikov and Huber (Chroma), 2025.
- How Long Contexts Fail — Drew Breunig, 2025. Poisoning, distraction, confusion, clash.
- Context Engineering for Agents — LangChain, 2025. Write, select, compress, isolate.
- Prompt caching — Anthropic documentation. Prefix order, breakpoints, what invalidates the cache, prices.
Videos
- Context Engineering for Agents — Lance Martin, Latent Space. The four strategies with worked examples.
- Context Rot: How Increasing Input Tokens Impacts LLM Performance — Chroma. The report's experiments, explained by its authors.
- Stateful Agents — Full Workshop with Charles Packer — Letta/MemGPT, AI Engineer. Memory as an agent capability, hands-on.
Code
- letta-ai/letta — the MemGPT lineage: agents with self-managed memory.
- gkamradt/needle-in-a-haystack — the original pressure test; extend it with distractors and no-overlap needles.
Where this leads¶
- MCP and tool protocols — how tools and resources reach the context, and why tool lists must be stable.
- Multi-agent systems and orchestration — isolation taken to its conclusion.
- Long context — the architecture side: positional encodings, efficient attention and why length is hard.
- Serving LLMs — the KV cache, prefix reuse and batching from the server's side.
- Guardrails and security — memory and retrieved content as injection vectors.