Lesson 9.1: Context engineering for agents
Learn context engineering: deciding what an agent sees at each step, budgeting the window, keeping tool output lean, compacting history and fetching just in time.
By the end of this lesson you will be able to explain context engineering and how it differs from writing a prompt, divide a context window into a budget, keep the useful part of tool output, compact a growing history, fetch information just in time instead of up front, and test whether a context change helped. You will work out that a 30-step run whose tool results are only 20 per cent useful sends about 802,500 input tokens when everything is kept and about 280,500 when only the useful part is kept, and that a 70,000-token context fills 35 per cent of a 200,000-token window and costs about ₹1.98 in input per call at an example price. You should have read Lessons 4.3, 4.4, 6.2 and 7.4. No code is needed. The mathematics is sums and percentages.
The earlier lessons on prompts taught you to write instructions well. For an agent that is only a small part of the job. An agent runs for many steps, and at each step the model sees a fresh context built from many sources: the instructions, the tool definitions, the memory, the results of earlier tool calls, retrieved documents, the history of the run and the current task. What goes into that context, in what order, in what form and at what size, decides how well the agent performs. Context engineering is the practice of designing and managing that whole input, not just the instruction at the top of it. A common summary is that the aim is to find the smallest set of high-signal tokens that makes the desired behaviour most likely.
Why context needs engineering
A model reads everything in its context at every step, and treats all of it as potentially relevant. Four facts follow.
Context is finite. Every model has a window, a maximum number of tokens. Long runs can exceed it, and a full window leaves no room to think or answer.
Context is costly. Each step pays for every token again, as Lesson 7.2 of the AI Engineering track showed. A large context makes every later step dearer and slower.
More is not better. Irrelevant material is not harmless. It distracts the model, and as a context grows, models tend to find a needed fact less reliably, especially when it sits in the middle of a long input. People call this context rot. Adding more text can lower accuracy.
Context is the only channel. The model knows nothing except what is in the context and what it learned in training. If a needed fact is not there, it will guess. If a misleading fact is there, it may follow it.
The goal is therefore a context that is small, relevant, well organised and fresh at every step.
What goes into the context
It helps to list the parts and give each a purpose and an owner.
Part · What it is · How it changesInstructions · Role, rules, style, constraints · Fixed for a version
Tool definitions · Names, descriptions, schemas · Fixed per run, or loaded on demand
Memory · Facts and preferences retrieved from long-term storage · Chosen per run or per step
Task and goal · What this run is for · Fixed per run, restated at checkpoints
Retrieved material · Documents and passages found by search · Chosen per step
History · The record of earlier steps: reasoning, calls, results · Grows each step
Working notes · The agent's own plan and progress · Updated each step
Current input · The latest message or result · Changes each step
Each part competes for the same window. Engineering the context means deciding the size, the content and the placement of each.
The context budget
Treat the window as a budget and plan how to spend it. Suppose a model has a 200,000-token window. A reasonable design might allocate:
Part · TokensInstructions · 3,000
Tool definitions · 6,000
Memory · 2,000
Retrieved material · 10,000
History · 40,000
Working notes · 5,000
Reserve for the model's output · 4,000
Total used · 70,000
That is 35 per cent of the window, leaving 130,000 tokens of headroom. At an example price of ₹30 per million input tokens, each call with 66,000 tokens of input (leaving out the output reserve) costs about ₹1.98. The point of a budget is not the exact numbers. It is that every part has a limit, and the biggest one, history, is the one that grows without a rule.
A useful habit is to set a target size, far below the window, for the typical call, and a hard limit at which compaction begins. Many teams find that agents perform better with 30,000 well-chosen tokens than with 150,000 of everything, so the target is set by quality and cost, not by the window.
Keeping tool output lean
In most agents, the largest growth is tool results. A search returns ten pages, a database query returns a hundred rows, a file read returns a whole document. The model needs perhaps a tenth of it. Yet all of it enters the context, and is re-sent at every later step.
Five habits keep results lean.
Shape the result in the tool. Return only the fields the model needs, as Lesson 6.1 advised. A customer record of 60 fields becomes six.
Limit size. Cap rows, characters and pages, and say clearly when a result was cut and how to get more.
Return a summary and a handle. Instead of a whole document, return a short summary, a few key passages and an ID. If the model needs more, it asks for a particular part.
Put bulky results outside the context. Write a large result to a file or a store and give the model a short reference and a tool to query it. The model can ask for "rows where status is failed" without ever seeing the other 9,900.
Drop results once used. After the model has extracted what it needs from a result, the raw result can be replaced by the extract. This is sometimes called clearing old tool results.
The effect is large. Suppose an agent runs 30 steps. Its fixed base, made up of instructions, tools and goal, is 5,000 tokens. Each step adds about 1,500 tokens of tool output to the history, and only 20 per cent of that, 300 tokens, is useful later.
If everything is kept, the context at step n holds 5,000 + 1,500 × (n − 1) tokens. Summing the input over 30 steps gives 30 × 5,000 + 1,500 × (0 + 1 + … + 29) = 150,000 + 1,500 × 435 = 150,000 + 652,500 = 802,500 tokens. At the last step the context is 5,000 + 1,500 × 29 = 48,500 tokens.
If each result is trimmed to its useful 300 tokens, the sum is 150,000 + 300 × 435 = 150,000 + 130,500 = 280,500 tokens, and the last context is 5,000 + 300 × 29 = 13,700.
Trimming cuts the total input by 65 per cent and keeps the last step's context under a third of the size. It also removes the noise the model would otherwise read at every step.
Predict first: a 30-step run has a base of 5,000 tokens and adds 1,500 tokens of tool output at each step, of which only 20 per cent is useful. About how much smaller is the total input if you keep only the useful part? Make a guess before reading on.
The total falls from about 802,500 to about 280,500 tokens, a saving of 65 per cent.
Compacting the history
Even with lean results, history grows with every step: the model's reasoning, each call and each reply. For long runs you need a rule for shrinking it. Lesson 4.3 introduced summaries. In context engineering the practice is called compaction, and a few forms are in use.
Sliding window. Keep the last k steps in full and drop the rest. Simple, and it forgets early decisions.
Summarise old steps. Replace the older part of the history with a short summary of what was done, found and decided. Keep the last few steps verbatim. The summary must preserve what matters: the goal, constraints, decisions made, facts established and open questions, in the form of the hand-off record from Lesson 5.3. A summary that loses a constraint can cause an error later.
Structured notes. The agent keeps its own notes file, a running record of its plan, findings and next steps, outside the context, and reads it back when needed. This is robust, since the notes survive any compaction and can persist across sessions.
Restart with a handoff. For very long runs, start a fresh context seeded with the notes and the goal, as Lesson 8.3 described.
Decide when to compact. A simple rule is to compact when the context passes a set share of the window, for example 60 per cent, or a set size, for example 40,000 tokens. Test compaction on tasks that depend on early information, since that is where it fails.
Just-in-time information
A tempting design loads everything the agent might need at the start: all policies, all customer data, all documents. This up-front loading wastes tokens on material that is not used, and leaves the agent holding stale information. The alternative is just-in-time retrieval: the agent keeps lightweight pointers, such as file names, record IDs and search queries, and loads the content only when it needs it, using tools.
Compare the two for a support agent that might need any of 200 policy documents. Up front, loading all 200 at 1,500 tokens is 300,000 tokens, which does not fit and would be wasteful if it did. Just in time, it holds a list of 200 titles of about 15 tokens each, 3,000 tokens, and retrieves the one or two it needs, about 3,000 tokens. The context holds 6,000 tokens in place of 300,000.
Just-in-time has costs. Each retrieval is a tool call, which adds time and a chance of error, and the agent must know what to ask for. A good middle path is to load a small, stable core up front, such as the rules that always apply, and fetch the rest on demand. This also lets the agent explore: it finds a file name, reads a summary, and decides whether to open the file, building up understanding in layers while keeping only what is relevant in view. This idea underlies progressive disclosure, which Lesson 9.3 uses for skills.
Order and structure
How the context is arranged matters, not only what it holds.
Put stable material first and changing material last. Instructions and tool definitions come at the start, and the latest input at the end. This is also what makes prompt caching work: a provider can cache an unchanging prefix and charge less to re-read it, as the AI Engineering track explained. A change early in the context breaks the cache for everything after it, so do not put timestamps or random data near the top.
Put the most important instructions where the model attends. Models tend to attend more to the start and end of a long context than to the middle. Put the critical constraints at the start and restate the goal near the end of a long context.
Separate sections clearly. Use labelled blocks, such as <instructions>, <memory> and <toolresult>, so the model can tell what each part is, and so that untrusted content is plainly marked as such, as Lesson 7.3 advised.
Be consistent. Use the same format for the same kind of item. A result that sometimes arrives as a table and sometimes as prose is harder to use.
Write for the reader. The model is the reader of every piece of the context. Words that a human would skim, such as long courtesy phrases or repeated warnings, take up space. Be clear and brief.
Use examples sparingly. A few diverse, canonical examples of the behaviour you want beat a long list of rules. Too many examples eat the budget and can lead the model to copy them too closely.
Sub-agents as a context tool
Lesson 5.1 gave context isolation as a reason to use sub-agents. In context-engineering terms, a sub-agent is a way to do a messy, token-hungry piece of work in a separate window and bring back only a condensed result. A sub-agent that reads fifty pages and returns a 500-token summary spends fifty pages of context to save the parent from them. Use sub-agents when a task would otherwise pollute the main context, and ask them to return short, structured results.
Testing context changes
Context changes are easy to make and hard to judge by eye. Test them like any change, using the evaluation approach of Lesson 7.1.
Pick the metric. Task success, cost per task, steps and time.
Change one thing at a time. Trim results, or change the order, or add compaction, and measure each alone.
Test on long runs and on tasks that need early information, where compaction and trimming can hurt.
Look at traces. Read what the model actually saw at the failing step, as Lesson 7.4 said. Often the needed fact was missing or buried.
Watch the long tail. A change that helps the typical run can hurt the longest.
Three worked examples
Example 1: trimming search results
A research agent called a web search that returned ten results of 800 tokens each. The agent used two or three. The team changed the tool to return titles, a two-line snippet and an ID for each of ten results, 100 tokens each, and added a tool to read a chosen result in full. The average run's input fell by 52 per cent, and the success rate rose by 3 points, because the model chose sources by looking at a clean list.
Example 2: compaction that lost a constraint
An agent summarised its history after 25 steps to save space. In 4 per cent of long runs it later broke a rule given in the user's first message, such as "do not contact the supplier". The summary had dropped it. The team changed the summary to a structured record with a fixed section for constraints, copied word for word from the original task, and restated at every checkpoint. The violations stopped.
Example 3: reordering for the cache
A team's prompt began with the current date and time, then the instructions and tool definitions. Each call changed the first line, so the cache never hit. They moved the date to the end, next to the current input. The stable prefix of 9,000 tokens was now cached, and the cost per call fell by about a third, with no change in behaviour.
A checklist for context engineering
1. List the parts of the context and give each a size limit. Set a target size and a compaction point well below the window.
2. Shape, cap and summarise tool results. Return handles for bulky data.
3. Clear raw results once the useful part has been extracted.
4. Choose a compaction method and keep constraints, decisions and open questions intact.
5. Load a small stable core up front and fetch the rest just in time.
6. Put stable material first for caching, critical instructions at the start and a restated goal near the end.
7. Mark sections clearly, especially untrusted content.
8. Use sub-agents to keep messy work out of the main context.
9. Test each change alone, on long runs, with traces.
Common mistakes
Treating the window as free space. More tokens cost money and attention.
Keeping every tool result. Most of it is never used again.
Loading everything up front. It wastes tokens and goes stale.
Summaries that drop constraints. Keep a structured record with a fixed constraints section.
Unstable prefixes. A changing first line defeats caching.
Burying the key instruction in the middle. Put it first, and restate it.
Too many examples. They crowd out everything else.
Changing several things at once. You will not know what helped.
Judging a context by reading it once. Measure on real runs.
Key takeaways
Context engineering is the design of everything the model sees at each step, not only the prompt. The aim is the smallest set of high-signal tokens that makes the right behaviour likely.
More context is not better. It costs money, distracts the model and can lower accuracy.
Plan a budget for each part. A 70,000-token context fills 35 per cent of a 200,000-token window.
Keep tool output lean by shaping, capping, summarising, storing bulky data outside the context and clearing used results. In a 30-step example, keeping the useful 20 per cent cut input from 802,500 to 280,500 tokens.
Compact history with windows, summaries, structured notes or restarts, and protect constraints, decisions and open questions.
Load a stable core and fetch the rest just in time. Put stable content first, key instructions where the model attends and mark each section.
Use sub-agents to isolate messy work, and test each change on long runs.
Check yourself
1. What is context engineering, and how does it differ from writing a prompt?
It is designing everything the model sees at each step: instructions, tools, memory, retrieved material, history and notes. A prompt is only one part of it.
2. Name three ways to keep tool output lean.
Any three of: return only needed fields, cap the size, return a summary and a handle, store bulky results outside the context, and clear results once used.
3. A run has 20 steps, a base of 4,000 tokens and 1,000 tokens of tool output added per step, all kept. What is the total input over the run?
20 × 4,000 + 1,000 × (0 + 1 + … + 19) = 80,000 + 1,000 × 190 = 270,000 tokens.
4. Why put stable content at the start of the context?
Stable content at the start can be cached by the provider, which lowers cost and delay. A change early in the context breaks the cache for what follows.
5. What must a summary of history always preserve?
The goal, constraints, decisions made, facts established and open questions.
6. What is just-in-time retrieval?
The agent holds lightweight pointers such as titles or IDs and loads content only when needed, in place of loading everything up front.
Try this
Set aside seventy-five minutes.
1. Pick an agent and list every part of its context with a size estimate. Set a target size and a compaction point.
2. Use the first simulator to see how full the window is, and which part is biggest.
3. Take the agent's three most used tools. For each, write what a lean result looks like, with a cap and a handle for more.
4. Use the trimming simulator with your own numbers to see what lean results would save.
5. Design the compaction: the method, the trigger and the structured record, with a constraints section.
6. Decide what to load up front and what to fetch just in time.
7. Write the test: five long tasks, three that need early information, and the metrics you will compare.
A good result is a context design: a budget, lean tool outputs, a compaction method, an ordering and a test plan. Lesson 9.2 turns to how agents built by different teams talk to one another.
Tags: Agentic AI Context engineering Context window Compaction Agent design