From prompt to context
In the APIs lesson you sent one request and got one reply. An agent sends many requests, and each carries far more than your words. Anthropic’s engineers call the work of choosing all of it context engineering, the natural next step after prompt engineering: not only how to word an instruction, but which tokens the model should see at each step, out of everything that could be put in front of it.
- System promptrules and role
- Tool definitionsnames, descriptions, parameters
- Taskwhat the user asked
- Historyevery earlier call, result and thought
- Newest resultwhat the last tool returned
The model keeps nothing between requests (the APIs lesson). At every step the harness sends the whole context again, and the model reads it from the first token. An agent that takes 50 steps reads its system prompt 50 times. That is why agents read far more than they write: the team behind the Manus agent reported about 100 input tokens for every output token, with around 50 tool calls in a typical task.
| Written by | Changes | |
|---|---|---|
| System prompt | You, or the harness | Almost never during a task |
| Tool definitions | The harness and any connected tool servers | Rarely |
| Instruction files such as AGENTS.md | You | Between sessions |
| Task | The user | Once, at the start |
| Tool calls and results | The model and the tools | Every step |
| Notes and memory | The model, through tools | Now and then |
The top of this table changes least. Keep it that way: it is the part the prompt cache can reuse.
Quick check
More context is not better context
Context windows keep growing; DeepSeek’s current models accept a million tokens. But the long-context lesson showed that a window that fits is not a window that is used well. Facts in the middle are found less often than facts at the start or end, and RULER found that of 17 models that all claimed at least 32,000 tokens, only half still did well at that length.
In July 2025 Chroma, the company behind an open-source vector database, looked closer. It tested 18 models, including GPT, Claude, Gemini and Qwen models, on deliberately simple tasks, and changed mainly the amount of text around the answer. What it found:
- Longer input, worse answers. Results fell as the input grew, even on simple tasks, and not evenly: models do not use every part of their context equally well.
- Look-alikes hurt. One passage that resembled the answer but was wrong, a distractor, lowered accuracy; four lowered it further.
- Indirect questions suffer first. When the question and the answer shared few words, accuracy dropped sooner and faster as the input grew.
- Focused beats full. On LongMemEval, a test of memory in long chats, models did clearly better when given only the relevant part, about 300 tokens, than when given the whole history of about 113,000 tokens that contained it.
- Even copying fails. Asked to repeat a long run of one word with a single different word inside it, models made more mistakes as the run grew, and some refused or produced random text.
Quick check
The cache, inside a loop
The APIs lesson gave the rules for prompt caching: the same start, token for token, earns a cache hit at a fraction of the price, and anything that changes near the top spoils it. At DeepSeek in October 2026 a cached input token costs 2 % of a fresh one. In an agent those rules matter far more than in a chat, because of the way the bill grows.
tokens read at step k = S + k × tS tokens of rules, tools and task, plus k tool results of about t tokens each.
whole run = n × S + t × n(n + 1) ÷ 2Add up all n steps. The history part grows with the square of the number of steps.
S = 10,000, t = 2,000, n = 50 → 3,050,000 tokensThe window never holds more than 110,000 tokens, yet the run reads over 3 million.
all fresh ≈ $0.46; with the cache ≈ $0.025At DeepSeek’s off-peak Flash prices, if only each step’s new tokens are fresh: about 18 times cheaper, and each step starts sooner.
The Manus team called the cache hit rate the single most important number for an agent in production. Besides the rules you already know, three habits matter in a loop:
- Write the same data the same way. Many languages and libraries do not promise a fixed order of keys when they turn an object into JSON. The same tool result can then come out as different text, and the cache misses from there on.
- Keep the tool list fixed. Tool definitions sit near the start, so adding or removing one mid-task makes everything after it fresh. It also confuses the model when earlier steps mention a tool that has gone. Manus keeps every tool defined and instead blocks the ones not allowed at that moment while the next token is chosen, a kind of constrained decoding. Tool names with shared prefixes, such as
browser_andshell_, let it block a whole group at once. - Clean up rarely, and late. Every change to the history, even a helpful one, makes everything after it fresh again. So harnesses leave the context alone until it is nearly full, then make room in one go.
import json
RULES = "You are a careful research assistant. Give a source for every fact."
task = "Find this week's rainfall in Lahore and compare it with the same week last year."
messages = [
{"role": "system", "content": RULES}, # the same for the whole run
{"role": "user", "content": task}, # the same once the task has started
]
def as_text(result):
# The same result must always become exactly the same text
return json.dumps(result, sort_keys=True, ensure_ascii=False)
def add_result(call_id, result):
# Only add to the end: never edit, reorder or delete earlier messages
messages.append({"role": "tool", "tool_call_id": call_id, "content": as_text(result)})
- Everything before the newest message is exactly what the last request sent, so all of it can be a cache hit.
sort_keys=Truefixes the order of keys.ensure_ascii=Falsekeeps Urdu or Chinese text as itself instead of escape codes such as\u0644, which also saves tokens.- In the full loop from the agent-loop lesson, the model’s reply with its tool calls is appended first, then one result for each call, in order.
Quick check
When the window fills up
Even with care, a long task fills the window. The harness must make room, and every way of doing it gives something up. From the lightest to the heaviest:
| What it does | What you lose | |
|---|---|---|
| Clear old tool results | Replaces old outputs with a short note but keeps the calls, so the model knows what it did | The details, unless it runs the tool again. Anthropic calls this one of the safest and lightest kinds of compaction. |
| Keep the address, drop the content | Removes a long page or file from the context but keeps its URL or path | Nothing, as long as the agent can open it again. Manus calls this restorable compression. |
| Summarise | The model summarises the history; the run continues from the summary and the latest turns | Whatever the summary leaves out. Claude Code keeps decisions, unsolved bugs and implementation details, plus the five files it used most recently. |
| Discard and restart | Throws away the tool history, keeps the task and starts again | All progress held in the context. It works like a fresh attempt at the task. |
Press “Next turn” until the window is about two-thirds full and read the bottom lines: almost every token of each request comes from the cache, because the context only grows at the end. Now press “Elide old tool outputs”. The window shrinks, but the striped cache bar under it shrinks too, back to the first output that changed: the next request must read everything after that point fresh. “Summarise oldest turns” frees even more room and loses even more of the cache, and of the details. Keep going and watch the share of cached tokens for the whole run. This is why harnesses wait until the window is nearly full before they clean up.
This interactive part needs JavaScript.
DeepSeek tested these choices with DeepSeek-V3.2 as a search agent on BrowseComp, a hard test of finding facts on the web (December 2025). Its runs often grew past the 128,000-token window, partly because the model kept re-checking its own findings. When the context passed 80 % of the window, the harness stepped in:
From the DeepSeek-V3.2 report, section 4.4. BrowseComp questions need many searches before the answer can be found.
Quick check
Load it now, or fetch it later
Some knowledge must be in the context before the model starts; the rest can wait until it is needed. There are two ways to bring it in:
Load it up front
- Search a prepared index for the passages closest in meaning to the question, and paste the best few into the prompt
- Fast: one search, one request
- Suits large collections that rarely change, such as manuals or a help centre
- Can miss, or paste a passage that looks right but is not; the index goes out of date
Fetch it just in time
- Give the agent tools to list, search and open things, and keep only addresses and paths in the context
- Slower: every lookup is a step
- Suits code, files and the web, which change all the time
- The agent sees what is there now and can follow one clue to the next
The first is retrieval-augmented generation, RAG, from the embeddings lesson. The second, just-in-time retrieval, is how coding agents work: Claude Code loads its instruction files at the start, then uses search tools such as grep to find and open only the files a step needs. Many systems mix the two.
Tools that fetch must not flood the context in turn. A tool that returns a whole 5,000-line file in one go undoes all the care above. Return a page at a time, and say how to get more:
def read_file(path, start=1, count=200):
"""Return up to `count` lines of a text file, starting at line `start`."""
with open(path, encoding="utf-8") as f:
lines = f.read().splitlines()
if start > len(lines):
return f"[The file has only {len(lines)} lines.]"
end = min(start - 1 + count, len(lines))
page = [f"{n}: {lines[n - 1]}" for n in range(start, end + 1)]
if end < len(lines):
page.append(f"[Lines {start} to {end} of {len(lines)}. "
f"Call read_file again with start={end + 1} for more.]")
return "\n".join(page)
- Line numbers let the model point to an exact place when it edits or quotes.
- The last line tells the model that the file goes on, and exactly how to read more, so a cut-off page is never mistaken for the whole file.
- Search tools should do the same: return the first matches and say how many there are in total.
Quick check
Notes and memory
Information that must outlive the window has to be written somewhere else. Agents do this through tools:
- Notes for this task. The agent keeps a file such as
NOTES.mdor a to-do list, and reads it back after the context has been summarised. Anthropic describes Claude playing a Pokémon game over thousands of steps: it kept tallies of its progress, maps of where it had been and notes on which attacks worked, and carried on from its notes after each reset of the context. - Instruction files. AGENTS.md and similar files (the harnesses lesson) carry your rules into every session.
- Memory across sessions. Anthropic’s memory tool (September 2025) lets a model create, read, change and delete files in a memory folder that you host. In Anthropic’s own test of a search agent, memory together with clearing old tool results did 39 % better than the agent without them; clearing alone, 29 %. In a 100-turn web search test, clearing alone cut token use by 84 %.
- Memory as a system. MemGPT (2023, University of California, Berkeley) treated the context like a computer’s working memory and outside storage like its disk, with the model moving information between them. MemOS (2025), from MemTensor in Shanghai with several Chinese universities, goes further and manages three kinds of memory together: plain text, saved KV caches and changes to the model’s weights.
| Lasts | Costs | Main risk | |
|---|---|---|---|
| In the context | Until it is cleared or the session ends | Paid again on every request | Crowded out by everything else |
| In files it reads and writes | As long as the files exist | Only when opened | Old or wrong notes that keep misleading it |
| In a searchable store | As long as the store exists | One search per lookup | Finding something similar but wrong |
| In the model’s weights | Until the model is trained again | Training, once | Hard to check, correct or remove (the fine-tuning lesson) |
Quick check
Subagents and other lessons from real agents
A subagent (the harnesses lesson) is the strongest way to keep a context clean. The main agent hands one job, such as finding the cause of a crash in the logs, to a second agent that starts with a fresh context. The subagent may read tens of thousands of tokens and returns a summary, often of 1,000 to 2,000 tokens, Anthropic writes. The main agent sees the result, not the search. The price is more tokens in total, and a summary can drop the one detail that turns out to matter; the multi-agent lesson looks at both.
Three more lessons from the Manus team:
- Keep the mistakes in. When a step fails, leave the failed action and its error message in the context. Seeing what went wrong makes the model less likely to try the same thing again. Hiding errors hides the evidence.
- Avoid ruts. Models copy the patterns in their context. Reviewing 20 CVs in a row, an agent fell into a rhythm and repeated similar actions because that is what its context showed, even where they no longer fitted. Small, deliberate variations in wording and order break the pattern.
- Use the file system as memory. Files are unlimited, they last, and the agent can use them directly. Write big things to files and keep only their paths in the context.
A July 2025 survey of more than 1,400 papers maps the whole field: getting context (retrieval and generation), processing it, and managing it, then building on those with RAG, memory, tools and multi-agent systems. Its authors note a gap that remains: models have become good at understanding long, complex context, but much weaker at writing equally long and complex output.
In practice, context engineering comes down to four questions at every step: what does the model need now, what can it fetch later, what can go, and what must be written down so that it is never lost?
Does each one help an agent’s context, or hurt it?
-
Returning a file’s path and first 200 lines instead of the whole 5,000-line file
Answer: Helps
-
Putting the current time, to the second, at the top of the system prompt
Answer: Hurts
-
Deleting a failed command and its error from the history
Answer: Hurts
-
A to-do list the agent rewrites as it works
Answer: Helps
-
Loading 80 tools from every connected server, just in case
Answer: Hurts
-
Asking a subagent to search the logs and report back in a few lines
Answer: Helps
-
Writing JSON keys in the same order every time
Answer: Helps
-
Twenty nearly identical examples in a row
Answer: Hurts
Remember
- An agent’s context is everything the model reads at each step, and all of it is sent again with every request.
- More context is not better: answers get worse as the window fills, and look-alike distractors hurt most. This is context rot.
- In a loop the tokens read grow with the square of the steps, so keep the start fixed and only add to the end; cached tokens cost a small fraction of fresh ones.
- When the window fills, clear old tool results first, then summarise or restart. Each frees room and loses something.
- Load knowledge that rarely changes up front with retrieval; fetch changing things just in time, with tools that return a page at a time.
- Notes, memory files and subagents keep knowledge outside the window. Review what they store, because their mistakes last.
- Keep errors in the history and vary repeated patterns, so the model learns from mistakes and does not fall into ruts.
Words to know
- Context engineering
- Choosing which tokens a model sees at each step: rules, tools, history, retrieved text and notes.
- Context rot
- Answers getting worse as the context grows, even when the information needed is in it.
- Attention budget
- The idea that every token in the context competes for the model’s limited attention, so each extra token has a cost.
- Distractor
- Text that looks like the answer but is not, and draws the model away from the right one.
- Cache hit rate
- The share of input tokens that were read from the prompt cache instead of computed again.
- Append-only history
- A history that only grows at the end, so each request starts with exactly what the last one sent.
- Tool result clearing
- Replacing old tool outputs with a short note to free room in the context. Anthropic calls it context editing.
- Restorable compression
- Dropping content from the context but keeping its path or address, so it can be fetched again.
- Discard-all
- Throwing away the whole tool history when the context gets too long, and starting the task again.
- Just-in-time retrieval
- Letting an agent fetch information with tools when it needs it, instead of loading it in advance.
- Recitation
- Rewriting the plan or to-do list near the end of the context, so the goal stays in the model’s recent attention.
- Memory tool
- A tool that lets a model save and read files that last beyond one context or one session.
- Optical compression
- Storing text as an image so it takes fewer tokens, as studied in DeepSeek-OCR.
Go to the source
This lesson is built on these papers and documents. Paper links open arxiv.org, a separate site.
-
Effective context engineering for AI agents
The attention budget, system prompts, just-in-time retrieval, compaction, notes and subagents.
-
Context Engineering for AI Agents: Lessons from Building Manus
The cache hit rate, masking tools, the file system as memory, recitation, keeping errors and avoiding ruts.
-
Context Rot: How Increasing Input Tokens Impacts LLM Performance
18 models on simple tasks, and how distractors, question wording and text structure change long-context results.
-
Lost in the Middle: How Language Models Use Long Contexts
The U-shaped curve: facts at the start and end of the context are used best.
-
RULER: What’s the Real Context Size of Your Long-Context Language Models?
Why advertised context lengths overstate the length a model really uses well.
-
DeepSeek-V3.2: Pushing the Frontier of Open Large Language Models
Section 4.4: summarising versus discarding a search agent’s context at 80 % of the window.
-
Step 3.5 Flash: Open Frontier-Level Intelligence with 11B Active Parameters
StepFun’s use of discard-all, explained as giving the model fresh attempts.
-
Claude: context editing and the memory tool
Clearing old tool results automatically, a file-based memory, and the 29 %, 39 % and 84 % results.
-
DeepSeek API: Context caching
How automatic caching matches the start of a request, and the fields that report hits and misses.
-
Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks
The paper that named RAG.
-
MemGPT: Towards LLMs as Operating Systems
Managing context like an operating system manages memory and disk.
-
MemOS: A Memory OS for AI System
Memory as a managed resource: plain text, activations and weights in one system.
-
DeepSeek-OCR: Contexts Optical Compression
Text stored as images at 10 to 20 times fewer tokens, and the idea of memories that fade.
-
A Survey of Context Engineering for Large Language Models
A map of more than 1,400 papers on retrieval, processing, management, memory and multi-agent systems.
Check yourself
5 questions. Tap the answer you think is right.
0 of 5 answered
Lesson complete
Answer every question above to complete this lesson.
Your progress is saved on this device only.
Next lessonMCP: one plug for every tool