Contents
TL;DR
- Context is everything the model can see when it runs. The prompt is only one part of it.
- The longer the context, the harder it is for the model to use it well. Put in a small amount of useful information.
- Make the system prompt clear but not rigid. Give each tool a clear job. Pick a few good examples.
- Leave out data you may not need. Let the agent fetch it with tools when it needs it.
- For long tasks, use compaction, notes, or sub-agents to manage context. Start with the simplest one and add more only when needed.
The context window is like a desk. The model can only see what's on the desk.
| Problem | What to do | Desk comparison |
|---|---|---|
| Too much at the start | Keep the system prompt, tools, and examples small | Only keep what this job needs on the desk |
| You don't know what data you'll need | Just-in-time retrieval | Get it from the bookshelf when you need it |
| Data piles up over time | Compaction, notes, sub-agents | Clean the desk, take notes, ask a coworker to look things up |
1. How context engineering differs from prompt engineering
Prompt engineering is about writing instructions. You define a role, set an output format, add a few examples, and explain when to use a tool. Early LLM apps usually called the LLM once, to classify or generate text. A good prompt solved most of the problems.
Agents are different. An agent calls the LLM again and again in an agent loop. The LLM picks the next step, the code runs a tool, and the result goes back to the LLM. This repeats until the task is done. One task can take dozens of LLM calls, and each call adds new tool results and new state.
Managing this information is context engineering. Anthropic sees it as the next step after prompt engineering. Context is everything the model can see when it runs. Context engineering decides what goes into each LLM call, how to organize it, and how to keep it up to date. Context can include:
- The system prompt
- User messages and chat history
- Tool definitions and tool results
- External documents
- Memory: what the agent saves outside the context, such as note files
- Tools and data connected through MCP. MCP is a standard from Anthropic for connecting tools and data sources to an LLM.
Here is how the context differs between a single query and an agent:
Single query (prompt engineering)
Context window
├─ System prompt
└─ User message
↓
LLM
↓
Answer
Agent (context engineering), using a hotel booking agent
Turn 1
├─ System prompt
├─ Tool definitions
└─ User: "Find me a hotel in Taipei."
↓ The LLM calls the search tool
Turn 2
├─ Everything from turn 1
└─ Tool result: Hotel A, Hotel B
↓ The LLM answers: "I found two hotels..."
Turn 3
├─ Everything from turns 1 and 2
├─ User: "If I book Hotel B, is there a fee to cancel?"
└─ Cancellation policy: the code picked it from 10 booking policies
↓ The LLM answers based on the cancellation policyA single query only needs a good prompt. For an agent, each turn carries the earlier chat and tool results, so the context keeps growing. The code also decides what other data to add. In turn 3, it adds only the cancellation policy, not all 10 policies. Adding everything would not fit, and it would distract the model. When the chat history gets too long, it needs to be shrunk, which section 5 covers.
1.1 How context changes in a hotel booking agent
In the first LLM call, the context is only this:
System prompt: You are a hotel booking assistant.
User: Find me a hotel in Taipei.The agent calls a search tool and gets two hotels. Then the user says "Book the second one." Now the context for the second LLM call is:
System prompt: You are a hotel booking assistant.
User: Find me a hotel in Taipei.
Tool result:
- Hotel A: NT$2,500
- Hotel B: NT$2,800
User: Book the second one.If the second call does not include the search results, the model can't know which hotel is "the second one." The prompt is only part of the context. The model can use everything that this call includes.
1.2 How prompts, context, and the agent harness split the work
The agent harness is the code that runs the agent. It builds the context, calls the LLM, runs tools, and runs the agent loop.
| Term | The question it answers |
|---|---|
| Prompt engineering | How do I write instructions the model will follow? |
| Context engineering | What goes into each LLM call? |
| Agent harness | How does the code build context, run the loop, and run tools? |
Agent harness
├─ Build context: system prompt, chat history, tool results, memory
├─ Call the LLM
├─ Run tools
└─ Repeat until the task is doneThese three overlap. For example, formatting search results so the model can read them easily is both prompt engineering and context engineering.
2. The longer the context, the harder it is to use
A token is the unit a model reads text in. A common English word is often one token, and longer words can be several. The context window is the most tokens a model can read at once.
The context window is like a desk. The model can see what's on the desk, but not the books on the shelf. And the desk has a size limit.
2.1 Context rot
As the number of tokens grows, the model has a harder time finding and using the information in the context. This is context rot. It's like a desk: the more papers you pile on it, the easier it is to lose the one you need.
For example, give an LLM a log with 1,000 lines, and it can easily find an error. Give it 1 million lines, and it may miss the same error, even though the error is still in the context.
Researchers often test this with a "needle in a haystack" test. They hide one sentence in a very long document and ask the model about it:
Lots of unrelated text...
The secret code is 9527.
Lots of unrelated text...
Question: What is the secret code in the document?Then they change the document length and where the sentence is, and check if the model still gets the answer. This test only measures how well the model finds information. It does not measure how well the model reasons over long context.
2.2 Two causes of context rot
- For each token, the model looks back at all earlier tokens. The longer the context, the more it has to look at, and the more spread out its attention gets.
- Models see more short text than long text during training, so they get less practice with very long context.
Some techniques, like position interpolation, let a model accept longer context than it was trained on. But accepting it does not mean the model can find what's inside, like the 1-million-line log in 2.1. So a bigger context window alone does not solve context rot.
2.3 Context is a limited resource
Anthropic says the model's attention is like a budget (an attention budget). Each extra token spends a little of it. This is only a way to think about it. There is no exact budget inside the model that you can measure.
So when you design context, don't only ask how much fits in the context window. Ask which tokens actually help the model finish the task.
3. What good context is made of
Anthropic's rule is: use the smallest set of high-signal tokens that gets the result you want. High-signal tokens are the information that actually helps. Small does not mean as short as possible. You still need to give the model what it needs.
3.1 Write the system prompt at the right level
Anthropic calls this the right altitude: not too detailed, and not too vague. If you write too much detail, the system prompt turns into a pile of hardcoded if-else rules. As cases grow, the rules get longer. They become hard to maintain, and the agent can't adapt to cases you didn't write down. On the other hand, "You are a helpful assistant" is too vague. The model doesn't know what to do.
A better prompt states the goal, the limits, and the rules for making decisions. Then it lets the model handle the details.
Here is an example for a hotel booking assistant:
Too specific:
If the user wants a room, ask for dates first.
If it's a weekend, add 20% to the price.
If the user says "cheaper," only show hotels under NT$2,000.
...and 50 more rules
Just right:
You are a hotel booking assistant. Help users find a hotel that fits their budget and dates.
First, confirm the dates, place, and budget.
Always check prices and rooms with tools. Don't guess.
If information is missing, ask the user. Get the user's OK before paying.
Too vague:
You are a helpful assistant.You can use XML tags or Markdown headings to separate different kinds of content, such as background, instructions, tool guidance, and output format. But the format matters less. In practice, start with the smallest prompt you can, test it with the best model, and add instructions where it fails.
3.2 Tools are part of the context too
Tools are how the agent gets new information. They also affect the context directly:
- The tool description affects which tool the model picks.
- The tool parameters affect whether the model calls it correctly.
- The tool result goes into the context of the next call.
Say the agent has four similar tools:
search_customer()
find_customer()
lookup_customer()
query_customer()If their jobs overlap, the model may still pick the wrong one, even if you add more rules to the system prompt. Here is a simple test: if an engineer can't say which tool to use in a given case, don't expect the agent to choose correctly.
Tool results should also save tokens. For example, when you check an API's error logs, you don't need to send back tens of thousands of raw lines. Send the error counts and a few samples first. The agent can ask for more if it needs it.
3.3 Pick a few good examples
Few-shot prompting means putting a few examples in the prompt to show the input and output you want:
Input: The food here is terrible. → Negative
Input: The service here is great. → Positive
Input: The prices here are average. → Neutral
Input: The food is good, but the service is bad. →The first three lines are examples. The last line is the real input. No examples is called zero-shot, one is one-shot, a few is few-shot, and many is many-shot.
Anthropic does not suggest putting every edge case into the prompt. Pick a few varied examples that show the typical cases. Examples also take up context.
To improve an agent, you don't always need more prompt text. You can also remove overlapping tools, rewrite tool descriptions, or drop information the agent doesn't need.
4. Let the agent find data when it needs it
Sometimes you don't know in advance whether some data will be needed. A coding agent working in a large repository can't put the whole codebase into the context every time.
4.1 Fetch data first, or fetch it when needed
RAG (retrieval-augmented generation) finds related documents first, then gives them to the LLM with the question. In classic RAG, the code finds the data before calling the LLM (carry every book you might need to the desk first):
User question → Code finds documents → Build context → LLM answersAn agent can use just-in-time retrieval instead. The LLM decides what to look for, then uses tools to get it (get the book from the shelf when you need it):
User question
↓
LLM decides what data it needs
↓
Call a tool to get the data
↓
LLM keeps going, and looks for more if neededThe difference is when the data is fetched and who decides what to fetch. A vector database finds documents with similar meaning. RAG often uses one, but either approach can work with or without it.
4.2 References: keep the location, read later
An agent can start with only references, which are clues about where to find data. Examples are file paths, saved queries, and links (the titles and shelf locations of the books).
Having a file path does not mean the model has read the file, or that it has permission to read it. The agent still needs a tool to get the content. This way, the agent doesn't load lots of data it may never use.
4.3 Progressive disclosure in Claude Code
Say you ask Claude Code to fix a 500 error in the Chatflow API. It doesn't need to read the whole repository first. It can search step by step:
LLM call 1: rg "chatflow"
→ gets two paths: routes/chatflow.ts, services/chatflow.ts
↓
LLM call 2: decides routes/chatflow.ts may be related, reads the file
↓
LLM call 3: finds the problem is in the service, reads services/chatflow.ts
↓
Decides the next step based on what it readThe paths from the first step are references. Opening information one layer at a time like this is called progressive disclosure. The agent doesn't need to know everything at the start. It learns about the environment as it explores.
4.4 Metadata is a clue too
File names, folders, file sizes, and edit times all help the agent decide whether to read a file. For example, tests/test_utils.py and src/core_logic/test_utils.py have the same name. But the folder tells you one is a test and the other is core logic.
4.5 A mixed approach: load the basics, fetch the rest
You can load common data at the start. Claude Code loads project guides like CLAUDE.md at the start (a handbook that always stays on the desk). It finds the rest of the code with glob and grep.
Just-in-time retrieval has costs too. Each extra tool call adds time. If the tools are poorly designed or the agent guesses wrong, it can keep searching in the wrong place and waste even more context. For areas where the content doesn't change much, like legal or finance documents, fetching data first may work better. The rule is the same: do the simplest thing that works.
5. Managing context in long tasks
Even if the context starts small, chat history and tool results keep growing in a long task. For example, a coding agent that spends hours on a large migration will go past the context window. There are three ways to handle this: compaction, structured note-taking, and sub-agents.
5.1 Compaction: summarize the chat history
When the context is almost full, summarize the history and start a new context with the summary (turn a stack of papers into a one-page summary and put the rest away):
Old context
├─ System prompt
├─ User request
├─ Read file A + result
├─ Read file B + result
├─ Edit files, run tests
└─ ...lots of history
↓ Compaction
New context
├─ System prompt
├─ Compaction summary
└─ Recent messages and related filesIn Claude Code, the model writes the summary itself. It keeps architecture decisions, unfixed bugs, and implementation details, and drops repeated tool results. Then it continues with the summary plus the five files it read most recently.
The biggest risk of compaction is losing important information. Say the agent is doing an authentication migration, and the history includes:
- The API must stay backward compatible.
- JWT validation is done.
- The session middleware is not done yet.
- One integration test still fails.
If the summary leaves out "the API must stay backward compatible," the agent may make the wrong changes later.
So when you tune the compaction prompt, first raise recall, then improve precision. Recall asks whether all the important information was kept. Precision asks how much of what was kept is actually useful. A summary that keeps everything rarely misses anything, but it doesn't save context either. In practice, use real agent traces as test data. Check that the summary keeps the limits, decisions, and to-dos. Then slowly remove the extra content.
5.1.1 Tool result clearing
A simpler option is to clear old tool results (put away search results you're done with). For example, the agent once used rg and got hundreds of files back, but it has since found the code that matters. That search result no longer needs to take up context. This is the safest and lightest kind of compaction, because the LLM doesn't need to write a new summary.
5.1.2 Storing chat history after compaction
A simple backend design is to keep the full history in the database, and send only the latest summary and the messages after it on each LLM call:
History in the database
├─ M1 User message
├─ M2 Assistant message
├─ M3 Tool result
├─ M4 Assistant message
├─ M5 Compaction summary
├─ M6 User message
├─ M7 Assistant message
└─ M8 Tool result
Sent on the next LLM call
├─ System prompt
├─ M5 summary
├─ M6, M7, M8
└─ New user messageM1 to M4 stay in the database. They just aren't sent every time. When the history gets too long again, summarize M5 and the messages after it into a new summary.
You can mark a checkpoint on the message, or save the latest summary ID in the chat's metadata. Either way, record which message the summary covers up to. Otherwise, new messages written while the summary is being made may get skipped.
5.2 Structured note-taking: keep important information outside the context
Even compaction can lose information after a few rounds. Another option is to let the agent write important information to an outside file and read it back later (write it in a notebook, put it in a drawer, and check it when needed).
For example, during a large migration, the agent can keep a migration.md:
Goal: Migrate the authentication module
Done: JWT validation
To do: Session middleware, integration tests
Key decision: The API must stay backward compatibleEven if the context is cleared or compacted, the agent can read this note and continue. Anthropic did this when Claude played Pokémon. Claude writes notes like "For the last 1,234 steps I've been training Pikachu in Route 1. It has gained 8 levels toward the target of 10." It also draws its own maps and records battle strategies that worked. After the context resets, it reads its notes and keeps playing for hours.
There are many ways to build note-taking. A common one is to give the agent a set of tools that read and write files. The LLM decides what to write and returns a tool call, like write_file("migration.md", "..."). Our code then writes it to a file or database. The system prompt can say when to write, for example "update migration.md after each step." The memory tool that Anthropic released on the Claude Developer Platform is one example. The model sends commands like create and str_replace, and the developer's code decides where to store the data.
Who decides what is worth writing down? When it takes understanding to judge, the LLM usually decides. For example, while reading code, the agent finds that "old clients still use the legacy middleware, so changes to the authentication flow must stay compatible." It can follow the system prompt and call a note-writing tool. The code doesn't need to know in advance when the agent will find this.
The risk is that the LLM may miss things, write them down wrong, or treat a guess as a fact. So the LLM only decides what is worth writing down. We set the other rules:
| Rule | Example |
|---|---|
| Limit where it can write | Only allow the memories/ directory |
| Limit the format | Check fields with a schema and reject bad writes |
| Let code write the facts | Write test results and order IDs straight from tool results |
| Mark guesses | "The Redis connection pool may be running out" |
| Check notes after reading them | If a note says "tests passed," run the tests first |
If the state lives in an external system, like orders and payments, the note only needs the order ID and what the agent is doing. The agent checks the external system for the real state every time. Take the hotel booking agent from 1.1:
Note: Order B-123 sent, waiting for payment
↓
Context resets, the agent reads the note
↓
Call get_payment_status("B-123")
↓
The payment system returns: paid
↓
The agent sends the booking confirmation based on the payment systemThe note's "waiting for payment" is already out of date. But it tells the agent which order to check. This is the same as references in 4.2: keep the location, read later.
Actions that change external state, like booking and payment, also need an idempotency key. An idempotency key is a unique ID for each action. If the external system gets the same ID twice, it doesn't do the action again. For example, the agent calls the booking API but stops before it writes the note. When it retries with the same ID, the booking system knows this booking already exists and doesn't book a second room.
5.2.1 Notes vs. compaction
| Compare | Compaction | Notes |
|---|---|---|
| What it does | Shrinks past chat history | Saves key information outside the context |
| Works across sessions | Usually only within one chat | Yes |
| How it's organized | The whole history at once | Split by task or topic |
| How it's updated | A new summary replaces the old one | Each note is updated on its own |
You can use both. For example, the summary can just say "Working on the authentication migration. Progress is in migration.md." The agent reads the note when it needs to, instead of putting the whole note in every context.
It's fine if the notes and the summary sometimes repeat the same thing, because they serve different purposes. If the task is short and the full history still fits, you don't need notes.
5.3 Sub-agents: split the work with separate contexts
The third option is to give subtasks to sub-agents. A sub-agent is another agent with its own system prompt, tools, chat history, and agent loop. When it's done, it only sends its findings back to the main agent (ask a coworker to look things up at their own desk and hand you a one-page report).
For example, to find out why an API got slow, the main agent can give logs and metrics to two sub-agents:
Main agent
├─ Log agent: checks logs, analyzes errors, reports findings
├─ Metrics agent: checks metrics, analyzes latency, reports findings
└─ Combines the findings from bothEach sub-agent may use tens of thousands of tokens to explore, but only returns a summary of 1,000 to 2,000 tokens. The main agent doesn't need to keep the exploration details, so it can save its context for combining results and making decisions.
If your code switches system prompts or tools based on what the user wants, but everything shares the same chat history, that's closer to routing. A sub-agent runs its own separate agent loop. You don't need a multi-agent framework for this. The main agent can call a delegate_task() tool, and your code uses the existing agent runner to start a new loop.
Sub-agents add more LLM calls, cost, and latency, and they are harder to coordinate. They are worth it when subtasks can run on their own and produce lots of details that don't need to be shared.
5.4 Choosing between the three
| Approach | Problem it solves | Good fit |
|---|---|---|
| Compaction | Chat history keeps growing | Tasks with lots of back-and-forth |
| Notes | Key information must be kept long-term | Step-by-step work with clear milestones |
| Sub-agents | Each subtask's details should stay separate | Research and analysis that can run in parallel |
You can combine these three, and not every agent needs them.
Conclusion
How much fits in the context window and how much the model can use well are two different things. Every method in this article aims to make sure each LLM call has enough useful information in its context.
You don't need all of these at once. A simple agent only needs a system prompt, tools, and chat history. Add compaction when the chat gets too long. Add notes when information must last across sessions. Consider sub-agents when the task can be split up.
Anthropic says that as models get stronger, people will need to plan fewer details, and agents can explore more on their own. But context will still be limited, so managing it will still be key to building reliable agents.