Part IV · Applied concepts · Chapter 22
Context engineering and choosing models
Prompt engineering is about the words of the instructions. Context engineering is about everything else that goes into the window on each call: which history, which documents, which tool results, in what order and how much of each. The second half of the chapter covers the other big lever you control: which model gets the call.
Most failures of a working AI feature are context failures: the fact the model needed was not in the window, was buried in the middle of it, or was crowded out by things it did not need. And most of the bill is input tokens sent again on every call. Getting the context right improves quality and cost at the same time.
The window is a budget
A model sees only what is in its context window on this call (chapter 16). A typical call of an assistant that uses tools might hold:
| Part | Tokens | Changes between calls? |
|---|---|---|
| System prompt | 1,500 | No |
| Tool definitions | 2,000 | No |
| Earlier turns of the chat | 6,000 | Grows each turn |
| Retrieved passages (3 × 400) | 1,200 | Per question |
| Tool results | 2,500 | Per question |
| The question | 50 | Per question |
| Total input | 13,250 |
At $2 per million input tokens and $10 per million output tokens, with a 600-token answer, one call costs 13,250 × 2 / 106 + 600 × 10 / 106 = $0.0265 + $0.006 = $0.0325, or $32.50 per thousand questions. Notice that the question is 0.4% of the input. Almost everything you pay for is context you chose to send.
Five things to do with context
- Select. Send what this question needs, not everything that might help. Retrieve the top few passages (chapter 24) instead of pasting whole documents; give each step only the tools it needs.
- Order. Stable material first, the changing material after it, and the question last. Models use the start and end of a long input better than the middle: in "Lost in the Middle: How Language Models Use Long Contexts" (2023), accuracy dropped when the needed fact sat mid-window. Put what matters most near an edge.
- Compress. Summarise or drop old turns, trim tool results to the fields the model needs, and remove duplicates. Long agent sessions often "compact" their history: replace the oldest part with a summary written by the model, keeping decisions and open questions.
- Isolate. Give a side task its own fresh context and take back only its conclusion. That is the main idea behind subagents (chapter 32): a search that reads 40 files should not leave those 40 files in the main window.
- Persist outside the window. Facts that must survive across chats belong in storage your code reads back deliberately, such as a memory store (chapter 37) or notes files, not in an ever-growing history.
Two cheap limits go with these. Cap how much chat history is sent, for example the last three exchanges, rebuilt from stored text. And cap the length of the question a user may submit, so one huge paste cannot fill the window. Both put a ceiling on the size, and so on the cost, of every call.
A useful test for any piece of context: if a careful human expert were given this window, would this piece help them answer, or would they have to skip over it?
Prompt caching
Providers can cache the processed form of a prompt's opening, so a later call that starts with exactly the same tokens skips that work and pays less for it. On Anthropic's API, as its documentation described it when this book was checked:
- The cached prefix is built in the order tools, then system prompt, then messages. You mark where it ends with a
cache_controlbreakpoint, up to 4 per request. - A cached prefix lives 5 minutes by default, refreshed each time it is used; a 1-hour lifetime costs more to write.
- Writing to the 5-minute cache costs 1.25 times the input price; reading from it costs a small fraction, 0.1 times for most models.
- Prompts below a minimum length are not cached at all (512 tokens for the newest models, more for older ones), silently.
The design rule that follows: put everything stable at the start and keep it byte-identical. A timestamp or a user's name near the top of the system prompt breaks the cache on every call. In the example, the 3,500 stable tokens read from cache at 0.1 times the price bring the call from $0.0325 to $0.0262, a saving of about 19% (before the cost of the occasional cache write).
Choosing a model
There is no best model, only the best model for a step. Compare candidates on the things that matter for that step:
| Property | Why it matters | How to measure |
|---|---|---|
| Quality on your task | Leaderboards measure someone else's task | Your own eval set (chapter 44) |
| Price per input and output token | Multiplied by every call, forever | Provider price list, times your token counts |
| Latency | Time to first token and tokens per second shape how a product feels to its users | Timed calls with realistic prompts |
| Tool use and structured output | Some models follow schemas and tool protocols far more reliably | Count invalid outputs and repairs in your evals |
| Context window | Sets the ceiling on what one call can see | Model card |
| Data handling | Retention and where requests are processed matter for sensitive data | Provider terms and routing settings (chapter 43) |
Routing: small models for easy questions
If most questions are easy, sending all of them to the largest model wastes money and time. A router classifies each request and sends it to a model tier. Worked with prices per million tokens (input/output) like those of the three Claude models used in the labs: a small model at $0.10/$0.50, a medium one at $2/$10, a large one at $4/$20, and a call of 10,000 input and 500 output tokens:
| Tier | Cost per call | Share of questions | Contribution |
|---|---|---|---|
| small | $0.00125 | 60% | $0.00075 |
| medium | $0.025 | 35% | $0.00875 |
| large | $0.05 | 5% | $0.0025 |
| Average with routing | $0.012 | ||
Against $0.025 for sending everything to the medium model, that is 52% cheaper, before the router's own cost. The catch is misrouting: a hard question sent to the small model gets a worse answer. Routers should fail towards the safer tier, keep a floor under categories where a weak answer is costly, and let a failed answer retry one tier up.
A chat sends its full history on every turn, and each turn adds about 800 tokens. How many history tokens does turn 20 send, and how many history tokens have been paid for across all 20 turns?
Answer
Turn 20 sends the 19 earlier turns: 19 × 800 = 15,200 tokens. Across all turns: 800 × (0 + 1 + … + 19) = 800 × 190 = 152,000 tokens. The cost of full history grows with the square of the chat's length, which is why apps cap or summarise it.
In Lab 1 every reply carries its input and output token counts and its cost, so you can check the budget table above against a real call and watch the input grow as you add history.
Self-check
Why can adding more context make answers worse?
Irrelevant material competes for the model's attention, and facts in the middle of a long input are used less reliably. More tokens also cost more and slow the call.
What breaks a prompt cache, and how do you avoid it?
Any change in the cached prefix, such as a timestamp or a user name near the top. Keep stable content first and byte-identical, and put changing content after it.
What should a router do when it is unsure or fails?
Fall back to a safe default tier rather than the cheapest one, and let a failed answer retry one tier up.
Name two cheap limits that cap the size of every call.
A cap on how much chat history is sent (the last few exchanges) and a cap on the length of the question a user may submit.
Further reading
- Lost in the Middle: How Language Models Use Long Contexts (2023) paper advanced
Finds models use information at the start and end of long prompts better than in the middle. - Effective context engineering for AI agents article intermediate
Practical guidance on what to put in context, in what order, and when to compact. - Context windows (Claude API docs) docs beginner
How the context window fills across turns, tool calls and thinking. - Compaction overview (Claude API docs) docs intermediate
Summarising older conversation to stay within the window on long tasks.
Free, checked on 2026-10-21. All resources for this chapter and 5 more.