Slides · Context, memory and multi-agent systems
Context engineering and memory
1 / 28
Context engineering and memory
What the model sees at each step, how to keep it small and cacheable, what to remember across sessions, and how to tell why a long-running agent has started to fail.
Concept
Why a long-running agent needs a plan for its context
- Aarav’s customer chat is forty messages long. Most of the recent ones say “ok” and “any update?”. The facts that matter sit two days back.
- Anthropic describes context engineering as strategies for choosing and maintaining the best set of tokens while the model runs.
- Agents often fail for context reasons, not because the model is “not smart enough”. Each step re-sends the context, so waste is paid for again and again.
Four things you will be able to do:
- Apply the four context moves (write, select, compress, isolate) to a long-running agent problem.
- Order a prompt so a stable prefix can be cached, and name an edit that breaks the cache.
- Choose a memory type for a fact and specify its write, recall, forget and privacy rules.
- Diagnose a degrading agent as overflow, distraction, drift or tool-output bloat.
Concept
Mental model: a small desk
- The context window is a desk. Only so many papers fit, and you read all of them every time.
- A filing cabinet holds what you may need later (memory, notes, files).
- A colleague on their own desk handles a side job and hands back a one-page brief (a sub-agent).
- Anthropic’s version of the same idea: the model has a finite attention budget, so aim for a minimal set of tokens that carries the most useful signal for the result you want.
A tidy desk is faster to work at. Nothing is lost when you clear it, as long as the important pages were filed first.
Diagram
The four moves on one picture
Source[2] Context Engineering
Compare
Write, select, compress, isolate
The LangChain team groups the techniques into these four moves. Anthropic uses other names for the same ideas, such as note-taking, compaction and sub-agents.
| Move | What it does | Example | Main risk |
|---|---|---|---|
| Write | Save information outside the window | Plan file, scratchpad, memory store | Writing things nobody reads again |
| Select | Pull in only what matters now | Retrieval, memory recall, a subset of tools | Missing the one fact that mattered |
| Compress | Fewer tokens, same meaning | Summarise old turns, clear old tool results | Losing a detail (drift) |
| Isolate | Give a sub-task its own clean context | Sub-agent returning a short brief | Coordination cost, lost detail in the hand-off |
- Every move has a price. Pick the one whose risk you can measure and afford.
Sources[2] Context Engineering[1] Effective context engineering for AI agents
Concept
Compress and isolate in practice
- Tool result clearing. Anthropic calls it one of the safest, lightest-touch forms of compaction: once a raw tool output has been used, it rarely needs to stay in the window verbatim.
- Compaction. Summarise a conversation near the limit and start a fresh window with the summary. Anthropic advises tuning for recall first (keep everything that might matter), then trimming for precision.
- Structured notes. The agent writes a to-do list or a notes file outside the window and reads it back later.
- Sub-agents. Each explores at length in its own window and returns a condensed summary. Anthropic says this is often 1,000 to 2,000 tokens.
Trade-off: a summary that is too thin loses the detail the next step needed; a hand-off that is too long fills the lead’s window again.
Concept
Why a bigger window does not remove the problem
- Cost and latency grow with the tokens you send, and an agent re-sends its history every step.
- Accuracy can fall. Liu et al. found that models used information in the middle of a long input less reliably than information at the start or end.
- Chroma’s context-rot report tested 18 models and found that performance consistently degraded as input length grew in its experiments.
- Anthropic’s explanation is a finite attention budget: recall of content in the window weakens as it grows.
- The size of the effect depends on the model and the task. Measure it on your own data.
More text is also more attack surface: every document, tool result or memory is text an attacker may have written.
Sources[3] Lost in the Middle: How Language Models Use Long Contexts[4] Context Rot: How Increasing Input Tokens Impacts LLM Performance[1] Effective context engineering for AI agents
Worked example
Worked example: what re-sending costs
Illustrative agent: 2,000 tokens of system prompt and task, then ten steps. Each step adds one tool result and the whole history is sent again.
| Design | Added to history per step | Input tokens at step i | Total input over 10 steps |
|---|---|---|---|
| Keep raw results | 1,500 | 2,000+1,500(i−1) | 20,000+1,500×45=87,500 |
| Clear raw result, keep 300-token digest | 300 | 2,000+300(i−1) | 20,000+300×45=33,500 |
- The sum of (i−1) for i=1 to 10 is ∑i=110(i−1)=0+1+⋯+9=45.
- Saving: 87,500−33,500=54,000 tokens, which is 61.7% of the first design.
- The cost grows faster than the number of steps, because each added token is paid for in every later step.
- The 300-token digest is a choice. If the next step needs a field the digest dropped, you have traded cost for drift.
Check yourself
Check: pick the move
A support agent must follow a 400-page policy manual. Any single ticket needs about two pages, but the agent loads the whole manual every turn and runs out of room. Which move fixes this, and what is its main risk?
Answer
Select: keep the manual outside the window and retrieve only the pages the ticket needs (Anthropic describes this as loading content just in time through lightweight references). The risk is missing the one page that mattered, so measure retrieval on real tickets. Write is not the fix because nothing new needs saving, and compress would shorten text that should not be in the window at all.
Concept
Prompt caching: stable first, variable last
- Providers can reuse the work already done for a prompt prefix, so a repeated prefix costs less and returns faster.
- It matches from the start of the prompt, so the rule is: stable content first, variable content last.
- Anthropic’s order is tools, then system, then messages (docs checked 2026-10-23).
- Put the system prompt, tool definitions and reference documents at the top. The conversation follows, then the new user message.
Mental model: a cache is a bookmark at the end of the stable part. Change a page before the bookmark and it is gone.
Source[5] Prompt caching
Diagram
What sits where in a cached request
Source[5] Prompt caching
Compare
What an edit invalidates
Anthropic documents which edits break which part of the cache (checked 2026-10-23).
| You change | Tools cache | System cache | Messages cache |
|---|---|---|---|
| A tool definition | Invalidated | Invalidated | Invalidated |
| Web search toggle | Reused | Invalidated | Invalidated |
| Tool choice | Reused | Reused | Invalidated |
- Course inference, not a row in Anthropic’s table: if only the newest message changes, the tools, system and earlier messages are still reused, and only the new message is processed fresh.
- A timestamp or user name at the top of the system prompt invalidates the system prompt and everything after it on every request. The tools block can still hit if a cache breakpoint sits at the end of it.
- The cache is short-lived: 5 minutes by default, refreshed each time the cached content is used. A 1-hour option costs more.
- Below a minimum prompt length nothing is cached and no error is returned. The minimum depends on the model (512 to 4,096 tokens in the current table).
Source[5] Prompt caching
Worked example
Worked example: when caching pays
Anthropic’s default multipliers on the base input price: a 5-minute cache write costs 1.25×, a cache read costs 0.1×. Some models have a lower read multiplier, so check your model’s page.
Illustrative: a stable 8,000-token prefix, 10 requests inside the 5-minute window. Count only the prefix, in token-price units.
| Case | Calculation | Prefix cost |
|---|---|---|
| No caching | 10×8,000×1.0 | 80,000 |
| Caching | write 8,000×1.25=10,000, plus 9×8,000×0.1=7,200 reads | 17,200 |
- 17,200/80,000=21.5% of the uncached cost.
- If the prefix changes on every request (say a timestamp at the very start of the prompt), every request is a write at 1.25×: 10×8,000×1.25=100,000. Worse than not caching.
- Caching saves money and time. It does not fix context rot: a long, noisy cached prompt is still long and noisy.
Source[5] Prompt caching
Check yourself
Check: switching tool choice
Midway through a long conversation, a developer changes the tool_choice setting between requests (for example from automatic to forcing one tool). The tool list and system prompt are unchanged. Which parts of the cache can still be reused, and what does this suggest?
Answer
Anthropic’s invalidation table (checked 2026-10-23) lists tool choice as leaving the tools and system caches valid and invalidating the messages cache. So the long conversation has to be processed fresh after the change. If the conversation is long and cached, avoid changing tool choice mid-conversation unless you need to.
Compare
Four kinds of memory
Memory is how an agent keeps information beyond one window. The split follows the CoALA paper (Sumers et al.), which describes short-term working memory and long-term episodic, semantic and procedural memory.
| Type | Holds | Typical storage | Example fact |
|---|---|---|---|
| Working | Current task, conversation, scratchpad | The context window, a rolling summary | “Order 9 is being refunded now” |
| Episodic | What happened earlier | Timestamped summaries in a vector store | “On 3 March the user asked to cancel the trial” |
| Semantic | Facts about the user or world | Profile, key-value store, knowledge graph | “Prefers email, lives in Pune” |
| Procedural | How to do things | Instruction files, prompts, playbooks | “Steps to escalate a chargeback” |
- CoALA places procedural knowledge in the model weights and the agent’s code. Instruction and skill files are the practical form in many products.
- This is a teaching split, not a standard every framework uses.
Diagram
The life of a memory
Math
Recall: rank by more than similarity
The Generative Agents paper scores each memory as a weighted sum, then fits the top ones into the prompt.
score=arecency⋅recency+aimportance⋅importance+arelevance⋅relevance| Symbol | Meaning |
|---|---|
| recency | Higher for recently used memories. The paper uses an exponential decay with factor 0.995 per sandbox hour since last retrieval. |
| importance | How much the memory matters. The paper asks the language model for a 1 to 10 rating when the memory is created. |
| relevance | Cosine similarity between the memory embedding and the query embedding. |
| a… | Weights. The paper sets all of them to 1 after min-max scaling each component to [0, 1]. |
That is one design, not the only one. Your weights are your choice and need an eval.
Source[7] Generative Agents: Interactive Simulacra of Human Behavior
Worked example
Worked example: why similarity alone misleads
Query: “Is this customer still interested in the premium plan?” Illustrative normalised scores (as if min-max scaled to 0 to 1), all weights 1.
| Memory | Recency | Importance | Relevance | Score |
|---|---|---|---|---|
| Asked about premium pricing, 18 months ago | 0.05 | 0.35 | 0.92 | 1.32 |
| Cancelled the premium trial last week: “too expensive” | 0.90 | 0.80 | 0.85 | 2.55 |
| Prefers email follow-ups | 0.55 | 0.25 | 0.10 | 0.90 |
- By relevance alone the old pricing question ranks first (0.92 against 0.85) and would mislead the answer.
- With all three terms the recent cancellation ranks first (2.55).
- Ranking decides what is recalled. It does not decide what is still true: a conflicting or expired memory also needs an update rule.
Source[7] Generative Agents: Interactive Simulacra of Human Behavior
Concept
Update, forget and protect
Pick the type first, then answer five questions: what to write, when, how to recall, how to update or forget, and who may see it.
- Write what is likely to matter again (a preference, a decision, a finished task), not every message. Storing everything buys noise, cost and privacy risk.
- Update and expire. Handle conflicts (the user moved), expiry (last year’s price) and deletion on request. Anthropic’s memory-tool docs suggest periodically deleting memory files not accessed in a long time, and capping file sizes.
- Delete everywhere. A deletion must reach the raw records, any summaries built from them, and the embeddings.
- Isolate users. One user’s memory must never be readable in another user’s session. Tell users what is remembered.
- Treat recalled memory as data, not instructions. A memory written from a web page or an email may carry text an attacker planted. Label it, limit the tools it can trigger, and require approval for risky actions.
This course does not give legal advice. Check obligations with the right people.
Source[8] Memory tool
Check yourself
Check: file each fact under a memory type
Choose a memory type for each, and write one forget rule.
- “The account is on the EU data region.”
- “On Tuesday we agreed to ship on Friday.”
- “To handle a chargeback, check the payment status, then open a dispute form.”
Answer
- Semantic (a stable fact about the account). Forget rule: replace it when the account migrates, and delete it with the account.
- Episodic (something that happened, with a date). Forget rule: expire it after the shipment closes, or summarise it into a project note.
- Procedural (how to do something), usually an instruction or playbook file. Forget rule: it is versioned by the team, not deleted per user. Change it only through review, because wrong procedures are risky to edit automatically.
Diagram
Which failure is it?
Compare
Four ways context fails: remedy and measure
These four names are this course’s working taxonomy, not an industry standard. Pair each remedy with a number you can track.
| Failure | What you see | Remedy | Measure |
|---|---|---|---|
| Overflow | Errors, or the oldest content silently cut | Compress earlier or isolate sub-tasks; budget tokens per section | Tokens per step against the limit; count of truncated or rejected calls |
| Distraction | Wrong answers although the right fact is present | Select less; drop irrelevant chunks; put key facts at the start or end | Accuracy on a fixed task set with and without the extra context |
| Drift | A rule or goal from earlier is forgotten or changed | Pin must-keep facts verbatim outside the summary; restate the goal each step | A probe question about each pinned fact after every compaction |
| Tool-output bloat | One tool call adds thousands of tokens | Filter or paginate in the tool; clear old results; return only needed fields | Share of tokens from tool results; p95 tokens per tool call |
- Related names exist in the wild. Drew Breunig, quoted by LangChain, uses poisoning, distraction, confusion and clash. Compare the lists before you reuse a label in an interview.
Source[2] Context Engineering
Worked example
Worked example: a rule lost in summaries
A refund agent is told “refunds go back to the original payment card only”. One aggressive compaction cuts a long history to a short summary. This timeline is a reconstruction for teaching, not a recorded run.
| Point in the run | What the context says about the rule |
|---|---|
| Start | Instruction in the first user turn: “refunds go back to the original payment card only” |
| After one aggressive compaction | “Handles refund requests for open tickets” (rule gone) |
| Step 22 | A refund is sent to a new card the customer typed in chat |
- No step chose to break the rule; it was compressed out of the context.
- Diagnosis: drift, because the rule was present early and absent later.
- Fix: move the rule into the system prompt or a pinned note that compaction never rewrites.
- Measure: after every compaction, ask the agent a probe question about the rule and fail the test if the answer is wrong.
Check yourself
Check: name the failure
A retrieval agent puts 30 chunks into the prompt. The one chunk with the answer is there, but the agent answers from a different chunk. No errors, and token use is normal. Which failure is it, what do you change, and how do you know it worked?
Answer
Distraction: the right fact is present but outcompeted by irrelevant text. Use the select move more strictly: retrieve fewer chunks, drop weak ones, and place the key chunk at the start or end (Liu et al. found middle positions are used less reliably). Measure accuracy on a fixed question set with the 30-chunk prompt and with the trimmed prompt. If accuracy rises, the change helped; if not, the cause lies elsewhere.
Source[3] Lost in the Middle: How Language Models Use Long Contexts
Concept
What to avoid, and what interviewers listen for
Anti-patterns:
- Dumping the whole history into every call.
- Loading every tool definition when the task needs three.
- Passing raw tool output straight into the window.
- Storing everything forever.
- Trusting recalled memory as if it were instructions.
A strong answer to “the agent degrades after 10 steps” names the failure (overflow, distraction, drift or bloat), the move that fixes it, and how you would measure the fix. A weak answer is “use a bigger context window”, with no forgetting or privacy story.
Summary
Recap
- Four moves: write, select, compress, isolate. Each has a risk to measure.
- Cache layout: stable prefix first; an edit invalidates its level and everything after it.
- Memory: working, episodic, semantic, procedural. Define write, recall, forget and privacy; rank recall by more than similarity.
- Failures: overflow, distraction, drift, tool-output bloat. Each has a remedy and a metric.
- More context is not better, and recalled memory is untrusted data.
References
References & Sources (1 of 2)
Effective context engineering for AI agents (opens in a new tab)
Prithvi Rajasekaran, Ethan Dixon, Carly Ryan, Jeremy Hadfield2025Article
https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents
Used for Context engineering as curating the tokens the model sees; attention budget; compaction, tool result clearing, structured notes, sub-agents returning condensed summaries, and just-in-time retrieval.
Context Engineering (opens in a new tab)
LangChain2025Article
https://www.langchain.com/blog/context-engineering-for-agents
Used for The grouping of context techniques into write, select, compress and isolate, and Drew Breunig's named failure modes (poisoning, distraction, confusion, clash).
Lost in the Middle: How Language Models Use Long Contexts (opens in a new tab)
Nelson F. Liu, Kevin Lin, John Hewitt, Ashwin Paranjape, et al.2023Transactions of the Association for Computational Linguistics (TACL)Paper
arXiv 2307.03172 (opens in a new tab)https://arxiv.org/abs/2307.03172
Used for Models used information in the middle of a long input less reliably than information at the start or end.
Context Rot: How Increasing Input Tokens Impacts LLM Performance (opens in a new tab)
Kelly Hong, Anton Troynikov, Jeff Huber2025Article
https://www.trychroma.com/research/context-rot
Used for Across 18 models, performance consistently degraded as input length grew in the report's experiments.
Prompt caching (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/build-with-claude/prompt-caching
Used for Cache prefix order (tools, system, messages), what each kind of edit invalidates, the 5-minute default lifetime, model-specific minimum lengths and the default write and read price multipliers.
References
References & Sources (2 of 2)
Cognitive Architectures for Language Agents (opens in a new tab)
Theodore R. Sumers, Shunyu Yao, Karthik Narasimhan, Thomas L. Griffiths2023Transactions on Machine Learning Research (TMLR), 2024Paper
arXiv 2309.02427 (opens in a new tab)https://arxiv.org/abs/2309.02427
Used for Working memory plus long-term episodic, semantic and procedural memory for language agents; procedural memory lives in the weights and the agent's code.
Generative Agents: Interactive Simulacra of Human Behavior (opens in a new tab)
Joon Sung Park, Joseph C. O'Brien, Carrie J. Cai, Meredith Ringel Morris, et al.2023UIST '23Paper
arXiv 2304.03442 (opens in a new tab)https://arxiv.org/abs/2304.03442
Used for Memory retrieval scored as a weighted sum of recency (decay factor 0.995), importance (a 1 to 10 rating from the model) and relevance (cosine similarity), with all weights set to 1.
Memory tool (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/agents-and-tools/tool-use/memory-tool
Used for Security considerations for an agent memory store: size caps, expiration of unused files and validating paths.
Keys: ← → move, Home End first and last, F full screen.