Omar ran the new email tagger on ten buyer emails, and all ten tags were right. The eleventh came from a buyer named Ana: “Can I swap my two Friday tickets for Saturday? If that’s not possible, just refund me.” The tagger said refund, so the email would go to Leo.
“She wants to come on Saturday,” Leo said. “Why would I give her money back?”
Maya, Leo and TinyTickets are invented, and so are the numbers in their story.
In Module 2 you sent the model one loose message and searched its answer for a number. This module is about context engineering, which decides what goes into the context window, in what shape and in what order. You’ll take Module 1’s email tagger from “works on ten emails” to a version that handles the eleventh, returns a tag your code can trust, and costs less per email.
After this module, you can:
- write a system prompt and examples that carry your team’s rules, and check them on a test set
- get an answer your code can parse with structured outputs, and say what a schema doesn’t guarantee
- decide what goes into the context window and what stays out, and explain why more context can make answers worse
- cache the part of a prompt that repeats, and read in
usagewhether the cache worked - work out what a call costs from its uncached, cached and output tokens
Ten emails right, and the eleventh goes to Leo
Start from the prompt you wrote in Module 1. It has four tags and one rule for emails that ask for two things:
You tag emails that buyers send to a ticket website.
Reply with exactly one tag and nothing else:
refund the buyer wants money back
resend the buyer has not received their tickets or lost them
change_date the buyer wants to move their tickets to another show or date
other anything else
If an email asks for two things, choose the one the buyer asks for last.
Suppose you run it on twelve emails that a person on the team has already tagged. Ten are clear: three ask for money back, three for missing tickets, two for another date, and two are questions about the show. The last two are harder:
- Email 11, Ana’s: “Hi, can I swap my two Friday tickets for Saturday? If that’s not possible, just refund me. Thanks, Ana” The team tagged it
change_date. - Email 12: “I don’t want a refund. I just want the tickets you never sent me.” The team tagged it
resend.
Figure 1 shows what the model reads for Ana’s email.
Context window: Module 1's prompt with Ana's email
+-------------------------------------------------------------+
| You tag emails that buyers send to a ticket website. | the task
| refund / resend / change_date / other, one line each | the tags
| If an email asks for two things, choose ... last. | one rule
| Can I swap my two Friday tickets for Saturday? |
| If that's not possible, just refund me. | the input
+-------------------------------------------------------------+
|
v
[Model] --> the rule points to "refund" X
(the team wants change_date)
Figure 1: the prompt holds one rule for mixed emails, and that rule sends Ana to Leo.
Pause and predict. Which tag does the prompt tell the model to give Ana’s email, and why does the team disagree?
Answer
refund. Ana asks for two things, and the refund comes last, so the prompt’s own rule says refund.
The team disagrees because Ana still wants to come. The refund is only what she’ll accept if the swap is impossible, and the team tries a swap before anyone sends money back. The model follows the text it gets, and nobody wrote that decision into the text.
The lab runs this prompt on all twelve emails. If your run tags Ana’s email change_date, run it again. Each answer is sampled (Module 2), and the rule that points to refund is still in the prompt.
You may also see a second kind of failure. The prompt asks for “exactly one tag and nothing else”, but that’s a request in words. An answer such as Refund. or change_date (or refund) fails a check like answer === "change_date", even when the model’s judgment is right.
The model knows only what is in the request. So this module answers one question. What goes into the request, in what shape and order, so that the answer is right, your code can read it, and the call is worth what it costs?
Context engineering decides what the model reads
Module 2 showed that the API is stateless. On each call the model reads the context window and nothing else. So everything the model knows about TinyTickets, its tags and its team has to be in the request.
The prompt in Figure 1 holds the task, the tags and one rule. It doesn’t say who reads each tag, why the tags exist, or how the team treats a fallback.
Context engineering is the work of choosing what goes into the context window on each call, in what shape and in what order. In a post on X on June 25, 2025, Karpathy gave the name his “+1” over “prompt engineering”. He described the work as “filling the context window with just the right information for the next step.”
The name isn’t his alone. He was quoting a post by Tobi Lütke from a week earlier, which preferred it to “prompt engineering”. Two days later, Simon Willison wrote that the name might stick, because “prompt engineering” had come to mean typing into a chatbot.
In the same post, Karpathy listed what goes into the window: task descriptions, examples, retrieved data, tools, state and history. He also named both ways to get it wrong. With too little context, or context in the wrong form, the model lacks what it needs. With too much, or with context that doesn’t matter, costs can go up and the answers can get worse.
Figure 2 shows the context window this module builds for one tagging call. It is the stack from Module 2’s Figure 3, filled in. There are no tools yet, because Module 4 adds them.
Context window of one tagging call (claude-haiku-5-5)
+-------------------------------------------------------------+
| system prompt |
| who sends the emails, who reads each tag, and why |
| the four tags, defined by what the buyer wants |
| the team's rules for two requests and for a fallback |
| five examples, each an email and its answer |
|-------------------------------------------------------------|
| message 1 user: <email> one buyer's email </email> |
|-------------------------------------------------------------|
| output: thinking + {"tag": "..."}, at most max_tokens, |
| in the shape a schema allows |
+-------------------------------------------------------------+
stays out: other emails, rules for cases that never happen,
data the model could look up later, the time
Figure 2: the parts that never change come first, the one email comes last, and the answer has a fixed shape.
Karpathy has an analogy for this window. In a 2023 sketch of an “LLM OS” (post on X, November 11, 2023), he listed the context window as the computer’s RAM. The literal fact is narrower. The context window is the fixed number of tokens the model reads in one request, and anything you leave out doesn’t exist for the model on that call.
What changed recently is that the name moved from posts into vendor docs. Anthropic’s engineers published Effective context engineering for AI agents on September 29, 2025. They describe the goal as the smallest set of useful tokens that makes the result you want most likely.
They also contrast the two names. Writing a prompt is one task, while context engineering goes on for as long as the program runs. That difference grows in Module 4, where each step of an agent adds tool results to the window.
The cost of all this is testing. You can’t see what a change to the context does without running it, so every section below ends at the test set.
Rule: The model knows only what is in the request, so it has to guess anything your team knows that the request doesn’t say.
A system prompt that carries the team’s rules
Module 1 sent the instructions and the email as one text. But the instructions are the same for every email, and only the email changes. So they belong in a separate place.
The system prompt is text you send in the request’s system field, apart from messages, to give the model its task, its rules and its background. The API puts it at the start of the context window, before the messages. It is still tokens in the same window, read on every call and billed as input on every call.
// Excerpt from tag.ts (lab step 2): instructions in system, the email in messages
const message = await client.messages.create({
model,
max_tokens: 1000,
output_config: { effort: "low" },
system: SYSTEM,
messages: [{ role: "user", content: email.text }],
});
Notice that system is a field of the request, not a turn of the conversation. The email is now the only thing in messages, so the instructions stay the same from call to call.
Anthropic’s prompting best practices (checked 2026-11-22) give a test for what goes in it. Show the prompt to a colleague who knows nothing about the task; if they’d be confused, the model will be too. Three habits follow from that guide:
- Say who and why. Say who sends the emails and who reads each tag. The guide shows that a reason helps the model handle cases the rule didn’t name. Its example replaces an all-caps “never use ellipses” with one sentence saying that a text-to-speech engine will read the reply.
- Define each tag by what the buyer wants done, not by words in the email. Email 12 contains the word “refund” and wants something else.
- Write the team’s decisions down. How to treat a fallback is a business decision. A model can’t infer it, because another ticket site could decide the opposite.
Anthropic’s engineering post names two ways a system prompt fails. One spells out complex if-then logic in prose, which breaks on the first case it didn’t list. The other gives vague, high-level guidance with nothing concrete to act on. Aim between them, with one plain rule for each decision the team has made and its reason.
Here are the lines of the lab’s new system prompt that handle Ana’s email:
<rules>
If an email asks for two things, tag the one the buyer asks for last.
Exception: an option the buyer offers only in case the first one is
impossible ("if not", "otherwise") is a fallback, not a request.
For a fallback, tag the first request. The buyer still wants it, and
the team tries it before anyone sends money back.
</rules>
The first line keeps Module 1’s rule for emails that ask for two things. The exception is the decision the team made after Ana’s email, and the last line says why.
A system prompt has limits. Every line is billed on every call, so a long one costs money on every email (prompt caching, below, lowers that).
It is also an instruction, and the model can still miss it. The model samples its answer, so it can skip a rule on some runs. And text inside an email can try to give the model orders, a risk Module 9 covers.
Instructions in the user message, as in Module 1, still work for a one-off question in a chat. The choice flips to a system prompt as soon as the same rules apply to many inputs. Then the stable part stays identical from call to call, which the cache needs.
What changed recently is the code around prompts more than the advice. Older classification tutorials set temperature: 0, which API version 2026-10-21 rejects (Module 2). Some also started the model’s answer for it, which the structured outputs section covers.
Rule: Write every decision the team has made into the system prompt, with its reason, because the model can’t know a rule nobody wrote.
Examples show what the rules mean
A rule in words still leaves room to read it differently. “Fallback” is clear to you, but one worked case shows the model what you mean faster than another paragraph.
Few-shot prompting is putting a few worked examples, each an input with the answer you want, into the prompt. The model learns nothing permanent from them. Its weights don’t change (Module 2), and the examples work only on calls that include them.
Anthropic’s guide calls examples one of the most reliable ways to steer an answer’s format and tone, and suggests three to five. It asks for three things:
- Relevant: they look like the real input.
- Diverse: they vary enough that the model doesn’t copy a pattern you didn’t mean. If every refund example mentioned illness, the model could start tying refunds to illness.
- Structured: each one is wrapped in XML tags.
XML tags are labels in angle brackets, such as <email> and </email>, that mark where each part of a prompt starts and ends. The API doesn’t check them. The model reads them as text, and they help it keep instructions, examples and input apart. (They have nothing to do with the four tags the tagger outputs, so this module always calls them XML tags.)
Here is one of the lab’s five examples:
<example>
<email>Could you resend my tickets to my new address? If that's a
problem, refund me instead.</email>
<answer>{"tag": "resend"}</answer>
</example>
It teaches the fallback rule with a different pair of tags: resend first, refund as the fallback. So Ana’s email still tests whether the model applies the rule to a case it hasn’t seen.
Reader’s question. Why not add Ana’s email itself as an example, since it’s the one that failed? Because then the test set can’t tell you whether the rule works. The model could copy the answer from the example, and a perfect score would prove nothing.
So keep every test email out of the examples. Module 8 builds on this when it turns the test set into an eval.
Examples cost input tokens on every call, like the rest of the system prompt. They can also mislead. A 2021 study of GPT-3 found that the choice and order of the examples could swing accuracy widely (see “Going deeper”). That model is old, but the habit still applies, so run the test set again after you change the examples.
With no examples at all, rules alone are enough if the test set passes. Many examples, or a classifier trained on thousands of tagged emails as in Module 1’s Software 2.0, start to pay off once you have that much labeled data. Anthropic’s engineering post advises against stuffing a long list of edge cases into a prompt.
The advice has stayed stable across model generations. The current guide (checked 2026-11-22) gives the same three-to-five advice for every model it covers, from Fable 5.2 down to Haiku 4.5.
Structured outputs: an answer your code can parse
Module 1 asked for “exactly one tag and nothing else”, and Module 2 searched the answer with includes. Both depend on the model writing exactly what you asked for. You want a guarantee your code can rely on.
Structured outputs is an API feature that makes the model’s answer match a JSON Schema you send with the request. A JSON Schema is a JSON document that describes the shape another JSON document must have: its fields, their types and their allowed values. Here is the schema for one tag, as it appears in the request body:
{
"output_config": {
"effort": "low",
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {
"tag": {
"type": "string",
"enum": ["refund", "resend", "change_date", "other"]
}
},
"required": ["tag"],
"additionalProperties": false
}
}
}
}
Every object in the schema needs "additionalProperties": false, so the model can’t add fields of its own. In TypeScript you don’t write this by hand. Zod, a library that describes a data shape once and checks values against it, builds it for you:
// Excerpt from tag.ts (lab step 3)
const Tag = z.object({
tag: z.enum(["refund", "resend", "change_date", "other"]),
});
const message = await client.messages.parse({
model,
max_tokens: 1000,
output_config: { effort: "low", format: zodOutputFormat(Tag) },
system: SYSTEM,
messages: [{ role: "user", content: `<email>\n${text}\n</email>` }],
});
console.log(message.parsed_output?.tag);
zodOutputFormat turns the Zod object into the schema above. messages.parse sends the request, then parses the answer and checks it with Zod. parsed_output is the typed object, or null. If the text isn’t valid JSON for the schema, the SDK throws an error.
How the schema reaches the sampling step
Constrained sampling is sampling in which tokens that would break a set of rules are removed before each pick. Module 2 showed that the model gives every token a share, and sampling picks one. With structured outputs, the API compiles your schema into a grammar, a set of rules for which text may come next. Figure 3 shows the first pick of an answer.
Answer so far: nothing yet
next token fits the schema? free sampling constrained sampling
{ yes can be picked can be picked
Sure no can be picked removed before the pick
refund no can be picked removed before the pick
Figure 3: before each pick, the schema removes the tokens that would break the shape.
So a bare refund, the kind of answer Module 1 hoped for, can’t start a structured answer, because the answer must start with {. The structured outputs docs (checked 2026-11-22) add two costs. The first request with a new schema waits while the grammar compiles, and compiled grammars are cached for 24 hours after their last use. The API also adds a short system prompt of its own that describes the format, and you pay for its tokens.
What a schema doesn’t guarantee
The same docs list cases where the answer can still break the schema:
stop_reason: "refusal". The model declined, the response still has status 200 and is billed, and the text may not match the schema. A field that asks for the model’s step-by-step reasoning can cause a refusal of the categoryreasoning_extraction. Ask for a short explanation instead, or for none.stop_reason: "max_tokens". The answer was cut off, so it may be incomplete JSON.- Capital letters. The docs don’t guarantee the casing of enum values, so they advise comparing them case-insensitively. With Zod, a
"Refund"makesparsethrow, so the lab catches errors and counts them as wrong.
Some schema features return a 400 error, such as minimum, maxLength and oneOf. Changing the schema between calls also invalidates the prompt cache for that conversation (see below). So check stop_reason before you use parsed_output.
The largest limit has nothing to do with these cases. Ana’s email can come back as a perfectly valid {"tag": "refund"}.
Rule: A schema fixes the shape of the answer, not whether the answer is right.
Other ways to get JSON, and when to pick them
- Plain text is right when a person reads the answer, such as a reply draft.
- A tool with
strict: trueguarantees that the model’s tool input matches the tool’s schema. Pick it when the model must decide whether to act and which action to take (Module 4). A request can combine both features. - Starting the model’s answer for it with
{, an old trick called prefill, returns a400error on Claude 4.6 models and later (Module 2’s Common mistakes showed the message). - Forcing a tool call with
tool_choiceset totoolwas the standard JSON trick before structured outputs. The API refuses it on Fable 5.1 (from September 1, 2026), Opus 5.5 (from September 22, 2026) and Sonnet 5.5. The error istool_choice: type "tool" and "any" are not supported for this model.(Opus 5.5 migration guide). Haiku 5.5 and older models still accept it.
What changed recently is the feature’s status. Structured outputs started as a public beta on November 14, 2025. They left beta on the Claude API on January 29, 2026, when the request field moved from output_format to output_config.format (release notes). Without the old beta header, the old field returns a 400.
More context can make answers worse
If five examples help, why not paste in every email the team has ever tagged? Haiku 5.5’s window holds 1,000,000 tokens (Module 2), so they would fit. Both the bill and the tags would suffer.
Context rot is the drop in a model’s accuracy as its context window fills, even when the task stays the same. Module 2 quoted the line in the Claude context windows docs that accuracy and recall degrade as the token count grows. That page gives the effect this name.
The main evidence comes from two studies:
- Chroma’s Context Rot report (Hong, Troynikov and Huber, July 14, 2025) tested 18 models, among them Claude Opus 4 and Sonnet 4, GPT-4.1, Gemini 2.5 Pro and Qwen3. Results changed with input length even on simple tasks. On 306 questions from a memory test called LongMemEval, every model did better with a focused prompt of about 300 tokens than with the full one of about 113,000. Text that looked relevant but wasn’t hurt, and more of it hurt more.
- Lost in the Middle (Liu and others, 2023) found that 2023 models often did best when the useful document sat at the start or the end of the input. GPT-3.5-Turbo dropped by more than 20 points depending on where the document was.
The studies disagree on position. Chroma found no notable effect of where the useful text sat, in its own setup. Its tasks were simple on purpose, and the authors say length is hard to separate from difficulty. So take two points from both. More text that doesn’t help the task makes answers worse. And the position effect is a 2023 finding about 2023 models.
Anthropic’s engineering post offers an explanation. The model’s attention works like a budget spread over every pair of tokens, so it gets thinner as the window grows. That is their explanation, not a measured result, and the math behind it is outside this course.
Figure 4 sorts what earns a place in a tagging call.
| Put in the window | Keep out of the window |
|---|---|
| The task, who reads each tag, and why | Every email the team has ever tagged |
| The tag definitions and the team’s rules | Rules for cases that never happen |
| Three to five varied examples | Data the model could look up later with a tool (Module 4) |
The one email being tagged, last, in <email> XML tags |
A request for step-by-step reasoning inside the JSON |
| A schema for the answer | Values that change on every call, such as the time, near the start |
Figure 4: each line on the left helps the tag; each line on the right costs tokens, accuracy or the cache.
Order matters too. Put what never changes first and the input last. For long documents of 20,000 tokens or more, Anthropic’s guide says to place the documents at the top and the question at the end. It reports answers up to 30 percent better in its own tests, which it hasn’t published.
The next section gives a second reason for that order, because the cache needs an identical beginning.
For data the model needs only sometimes, Anthropic’s engineering post suggests loading it when it’s needed. The window then holds a short pointer, such as a file path, and a tool fetches the content (Module 4). Retrieval systems and vector databases are another way to choose context, and they are outside this course.
Long contexts also cost more per call. Every input token is billed on every call. And Haiku 5.5 is priced by prompt length, so a prompt over 100,000 tokens pays a higher price for the whole request (pricing, checked 2026-11-22). Other current models bill the full window at their standard rates.
What changed recently is where the limit sits. Since 1,000,000-token windows became standard in March 2026 (Module 2), size rarely stops you. Quality and cost do.
Rule: Add context only when the test set shows that it helps.
Prompt caching: pay less for the part that repeats
In the lab, all twelve calls send the same system prompt, and you pay for it twelve times. Module 2 showed the same cost in a chat, where the first message is billed again on every turn.
Prompt caching is an API feature that stores the processed beginning of a request, so a later request with the same beginning pays less for it. The prompt caching docs (checked 2026-11-22) describe how it works:
- The API reads a request in a fixed order: tools, then the system prompt, then the messages. A prefix is everything from the start up to some point in that order.
- A cache breakpoint is the point you mark with
cache_controlon one content block. The prefix up to and including that block is what gets cached. - A cache write happens when that prefix isn’t in the cache yet. The API stores it, and those tokens cost a little more than normal input.
- A cache read happens when the prefix is already stored. Those tokens cost a small fraction of normal input.
A read needs the prefix to be identical, token for token. One changed character before the breakpoint means a new write. An entry lives for 5 minutes, and each read resets that time for free; you can ask for 1 hour instead. On Haiku 5.5, Sonnet 5.5 and Opus 5.5, a prefix shorter than 512 tokens is never cached, and no error tells you so.
To cache the system prompt, system becomes a list of blocks, and the block gets the breakpoint:
// Excerpt from tag.ts (lab step 5): the breakpoint goes on the system prompt
system: [{ type: "text", text: SYSTEM, cache_control: { type: "ephemeral" } }],
"ephemeral" is the only cache type. Every response then reports three input counts in usage:
cache_creation_input_tokens: tokens written to the cache on this call.cache_read_input_tokens: tokens read from the cache.input_tokens: only the tokens after the last breakpoint.
The total input is the sum of the three. If the first two are both 0 on every call, nothing was cached.
Figure 5 shows two requests with the breakpoint in the right place, then the same two with the breakpoint on the email.
Breakpoint after the system prompt
Request 1 [ system prompt + examples | <email> email 1 </email> ]
prefix not stored --> write = prefix, read = 0
Request 2 [ system prompt + examples | <email> email 2 </email> ]
(3 s later) same prefix --> write = 0, read = prefix
Breakpoint on the email
Request 1 [ system prompt + examples <email> email 1 </email> | ]
prefix ends after email 1 --> write
Request 2 [ system prompt + examples <email> email 2 </email> | ]
no stored prefix ends after email 2 --> write again, read = 0
Figure 5: the breakpoint must sit after the part that repeats and before the part that changes.
Pause and predict. Automatic caching, a single top-level cache_control field, moves the breakpoint to the last block of the request for you. In a loop that tags a different email on every call, what will usage show?
Answer
A write on every call and no reads, as in the bottom half of Figure 5. The last block is the email, which is different every time, and the cache writes only at the breakpoint. So every call pays the higher write price for the whole prompt and never gets the read price back. You can check this with two requests on different emails: cache_read_input_tokens should stay 0 on both.
The prices are multiples of the model’s base input price (pricing, checked 2026-11-22). A 5-minute write costs 1.25 times the base price, and a 1-hour write costs 2 times. A read costs 0.1 times on Haiku 5.5 and most models, and 0.05 times on Opus 5.5 and Sonnet 5.5. So a 5-minute entry pays for itself after one read.
Caching has limits:
- It doesn’t shrink the window. Cached tokens still count toward the context window. Caching changes what you pay for them, not whether they count.
- It doesn’t touch output. Output tokens cost the same, and the answer isn’t written any faster.
- Parallel requests miss. An entry can be read only after the first response has started, so identical requests sent at the same moment all pay full price.
- Some changes empty it. Changing the tool definitions invalidates the whole cache. Changing
tool_choice, images, thinking oreffortinvalidates the cached messages.
The main alternative for bulk work is the Message Batches API, which halves the price of input and output in return for answers that arrive later. The two discounts stack. If tags can wait for a nightly run, batch them; if each email must be routed as it arrives, cache the prefix. Ollama, the free path, has no prompt caching.
What changed recently is how you turn caching on and how short a prefix can be. Prompt caching left beta on December 17, 2024, and the 1-hour lifetime on August 13, 2025. Automatic caching arrived on February 19, 2026 (release notes). And the minimum fell, from 4,096 tokens on Haiku 4.5 to 512 on Haiku 5.5.
Rule: Put the parts that never change first, the breakpoint after them, and anything that changes per call after the breakpoint.
What one call costs
Module 2 showed that you pay for input and output tokens. With caching, usage has four counts, and each has its own price. Figure 6 lists them.
usage field |
What it counts | Price, times the base input price |
|---|---|---|
input_tokens |
tokens after the last breakpoint | 1 |
cache_creation_input_tokens |
the prefix, written to the cache | 1.25 (5-minute entry) |
cache_read_input_tokens |
the prefix, read from the cache | 0.1 |
output_tokens |
the answer, thinking included | 5 |
Figure 6: four counts, four prices, on Claude Haiku 5.5 (pricing, checked 2026-11-22).
Output costs 5 times as much as input on every current Claude model. Thinking tokens are billed as output, even when the response leaves the thinking text out, and usage.output_tokens_details.thinking_tokens tells you how many there were. The effort setting from Module 2 is the main control.
Suppose the system prompt is 800 tokens, each email 40 and each answer 30, thinking included. Count in units of the base input price:
- No cache, every email: 840 input + 30 × 5 output = 990 units.
- Cache, first email: 800 × 1.25 written + 40 + 150 = 1,190 units.
- Cache, each later email within 5 minutes: 800 × 0.1 read + 40 + 150 = 270 units.
For twelve emails, that’s 11,880 units without the cache and 4,160 with it. So caching cuts this bill to about a third, and output becomes the largest part of each later call (150 of 270). These numbers are invented; the lab gives you real ones.
To turn units into money, multiply by the base input price on the pricing page; this module doesn’t repeat the price, because prices change. To estimate before you send, countTokens from Module 2 still works. It counts with the model you name, it’s free, and it ignores the cache.
One email through the finished tagger
This trace follows Ana’s email through tag.ts as it stands after the lab. It is the eleventh call of a run, so the system prompt is already in the cache. Figure 7 shows the path.
tag.ts Claude API
1 build the request: system block
with cache_control, Ana's email in
<email> XML tags, the Zod schema
2 POST /v1/messages -------------------> 3 the prefix is in the cache:
read it, don't process it again
4 the schema's grammar is ready
(compiled on the first call)
5 [Model] reads the prefix and the
email, may think, and writes
JSON by constrained sampling
6 content, stop_reason, usage <---------
7 stop_reason is end_turn: read parsed_output
8 compare with "change_date"; a router would
send the email to the team, not to Leo
Figure 7: code builds and checks; the API reuses the cached prefix and the compiled schema; the model only reads and writes.
Step 1: the request. tagEmail puts the system prompt in one block with cache_control. Ana’s email, in <email> XML tags, is the only user message, and the Zod schema goes in output_config.format.
Step 2: the network. One HTTPS request goes out, with the whole context in it, as in Module 2.
Step 3: the cache. The API reads the request in order and finds the system prompt, token for token, among the entries written by the first call. Those tokens are read, at a tenth of the base price.
Step 4: the schema. The grammar for {"tag": ...} was compiled on the first call and is still cached, so this call doesn’t wait.
Step 5: the model. It reads the rules, the five examples and Ana’s email. Her second option starts with “If that’s not possible”, which is the fallback in the team’s rule, and one example shows a fallback with another pair of tags. Constrained sampling lets it write only a valid object. Step 4 of the lab shows which tag your model picks.
Pause and predict. What will usage show for this call?
Answer
cache_creation_input_tokens is 0, because nothing new was written. cache_read_input_tokens is about the size of the system prompt. input_tokens is small, because it covers only Ana’s email and its XML tags. output_tokens covers the JSON and any thinking. Step 5 of the lab prints these four numbers for your own run.
Step 6: the response. content holds one text block with a JSON object such as {"tag":"change_date"}, possibly after a thinking block. stop_reason and usage come with it.
Step 7: the stop check. stop_reason is end_turn, so the answer finished and parsed_output is safe to read. On refusal or max_tokens, tagEmail returns the stop reason in place of a tag.
Step 8: the decision. In the lab, code compares the tag with the team’s tag. In the design from Module 1’s Figure 6, router code would read the tag and send Ana’s email to the team. The model picks the tag, and code decides where the email goes.
Lab: tag buyer emails with a system prompt, a schema and a cache
Time: about 25 minutes. You’ll write a test set, watch Module 1’s prompt fail on Ana’s email, then fix the shape of the answer, the judgment and the cost, one at a time.
You need:
- Node.js 26 LTS, as in Modules 1 and 2.
- The API key from Module 2. It costs money per token (pricing), and the lab makes about 90 short calls. Or use Ollama for free (see the note at the end of the lab).
Model used: claude-haiku-5-5 at effort: "low", checked on 2026-11-22. Each file reads the model from a MODEL environment variable. With a later model, expect a different cache minimum and different token counts, and check the models overview and the prompt caching docs.
The outputs described below are the shapes the docs give, not a recorded run. Your own run shows the real text and numbers.
Step 1: set up the folder and write the test set first
Why: you need a way to know whether a change to the prompt helped. Anthropic’s prompt engineering overview puts success criteria and a way to test them before the first draft.
mkdir email-tagger
cd email-tagger
npm init -y
npm pkg set type=module
npm install @anthropic-ai/sdk zod
export ANTHROPIC_API_KEY="your key here"
You should see @anthropic-ai/sdk (1.12.0 or a later 1.x) and zod (4.x) under dependencies in package.json. Now create emails.ts. Each tag is the team’s decision, made before any prompt is written.
// emails.ts: the test set, tagged by a person on the team
export type Email = { id: string; text: string; expected: string };
export const emails: Email[] = [
{ id: "e01", text: "Please refund my two tickets, I can't come anymore.", expected: "refund" },
{ id: "e02", text: "I was charged twice for the same order. I want the extra money back.", expected: "refund" },
{ id: "e03", text: "The show was canceled. How do I get my money back?", expected: "refund" },
{ id: "e04", text: "I paid an hour ago and still have no tickets.", expected: "resend" },
{ id: "e05", text: "I deleted the email with my tickets by mistake. Can you send it again?", expected: "resend" },
{ id: "e06", text: "The QR code in my ticket email won't load.", expected: "resend" },
{ id: "e07", text: "Can I move my booking from Friday to Sunday?", expected: "change_date" },
{ id: "e08", text: "I bought tickets for the wrong night. Can I switch to the 21st?", expected: "change_date" },
{ id: "e09", text: "Can I bring a camera to the show?", expected: "other" },
{ id: "e10", text: "What time do the doors open on Saturday?", expected: "other" },
{ id: "e11", text: "Hi, can I swap my two Friday tickets for Saturday? If that's not possible, just refund me. Thanks, Ana", expected: "change_date" },
{ id: "e12", text: "I don't want a refund. I just want the tickets you never sent me.", expected: "resend" },
];
Step 2: run Module 1’s prompt, and watch the eleventh email fail
Why: you need to see the failure on your own machine before you fix it. Create prompt.ts with Module 1’s instructions:
// prompt.ts, version 1: Module 1's instructions, now a system prompt
export const SYSTEM = `You tag emails that buyers send to a ticket website.
Reply with exactly one tag and nothing else:
refund the buyer wants money back
resend the buyer has not received their tickets or lost them
change_date the buyer wants to move their tickets to another show or date
other anything else
If an email asks for two things, choose the one the buyer asks for last.`;
Then create tag.ts, which tags every email and compares each answer with the team’s tag:
// tag.ts, version 1: plain text answers
import Anthropic from "@anthropic-ai/sdk";
import { emails } from "./emails.ts";
import { SYSTEM } from "./prompt.ts";
const client = new Anthropic();
const model = process.env.MODEL ?? "claude-haiku-5-5";
let right = 0;
for (const email of emails) {
const message = await client.messages.create({
model,
max_tokens: 1000,
output_config: { effort: "low" },
system: SYSTEM,
messages: [{ role: "user", content: email.text }],
});
let answer = "";
for (const block of message.content) {
if (block.type === "text") {
answer += block.text;
}
}
const ok = answer.trim() === email.expected;
if (ok) {
right++;
}
console.log(email.id, email.expected.padEnd(12), JSON.stringify(answer), ok ? "ok" : "WRONG");
}
console.log(`${right}/${emails.length} correct`);
Pause and predict. Which emails will be marked WRONG, and will the two runs agree?
Run node tag.ts twice. You should see twelve lines, each with the team’s tag, the model’s answer in quotes and ok or WRONG, then a score. Look at two things. Is e11 tagged refund, as the prompt’s rule says? And is any answer more than a bare tag, such as "Refund."?
If e11 passes on both runs, run once or twice more, and write down what you see. The rule that points to refund is still in the prompt, so a pass here is luck, not design.
Step 3: fix the shape with a schema
Why: code that reads the tag needs one of four exact strings, every time. Replace tag.ts with this version:
// tag.ts, version 2: the answer must match a schema
import Anthropic from "@anthropic-ai/sdk";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
import { z } from "zod";
import { emails } from "./emails.ts";
import { SYSTEM } from "./prompt.ts";
const client = new Anthropic();
const model = process.env.MODEL ?? "claude-haiku-5-5";
const Tag = z.object({
tag: z.enum(["refund", "resend", "change_date", "other"]),
});
async function tagEmail(text: string): Promise<string> {
const message = await client.messages.parse({
model,
max_tokens: 1000,
output_config: { effort: "low", format: zodOutputFormat(Tag) },
system: SYSTEM,
messages: [{ role: "user", content: `<email>\n${text}\n</email>` }],
});
if (message.stop_reason !== "end_turn") {
return `stopped: ${message.stop_reason}`;
}
return message.parsed_output?.tag ?? "no tag";
}
let right = 0;
for (const email of emails) {
let tag: string;
try {
tag = await tagEmail(email.text);
} catch (error) {
tag = `error: ${(error as Error).message}`;
}
const ok = tag === email.expected;
if (ok) {
right++;
}
console.log(email.id, email.expected.padEnd(12), tag, ok ? "ok" : "WRONG");
}
console.log(`${right}/${emails.length} correct`);
The email now sits between <email> XML tags; the system prompt mentions them in step 4. Run node tag.ts. You should see one of the four tags on every line, or a stopped: or error: line, and never a sentence. E11 can still be refund, because the schema fixed the shape of the answer and nothing else.
Step 4: fix the judgment with context
Why: the model can’t know the team’s fallback rule until the prompt says it. Replace prompt.ts:
// prompt.ts, version 2: who, why, the team's rules and five examples
export const SYSTEM = `You sort emails that buyers send to TinyTickets, a website that sells tickets for live shows.
Each email gets one tag, and the tag decides who reads the email next.
Refund requests go to Leo, the organizer, because only he decides about money.
Everything else goes to the TinyTickets team.
A wrong tag sends the buyer to someone who can't help, so tag what the buyer wants done, not the words they use.
Buyers write in many languages. Tag every email, whatever its language.
The email to tag is between <email> XML tags.
<tags>
refund: the buyer wants money back.
resend: the buyer has not received their tickets, or lost them, and wants them sent again.
change_date: the buyer still wants to come, but on another date or to another show.
other: anything else, such as a question about the venue or the show.
</tags>
<rules>
If an email asks for two things, tag the one the buyer asks for last.
Exception: an option the buyer offers only in case the first one is impossible ("if not", "otherwise") is a fallback, not a request.
For a fallback, tag the first request. The buyer still wants it, and the team tries it before anyone sends money back.
</rules>
<examples>
<example>
<email>Quiero cambiar la fecha de mis entradas.</email>
<answer>{"tag": "change_date"}</answer>
</example>
<example>
<email>Could you resend my tickets to my new address? If that's a problem, refund me instead.</email>
<answer>{"tag": "resend"}</answer>
</example>
<example>
<email>Can I get my money back AND tickets for the Sunday show instead?</email>
<answer>{"tag": "change_date"}</answer>
</example>
<example>
<email>The show was moved to a night I can't make, so I want my money back.</email>
<answer>{"tag": "refund"}</answer>
</example>
<example>
<email>Is the venue wheelchair accessible?</email>
<answer>{"tag": "other"}</answer>
</example>
</examples>`;
The first example is the Spanish date-change email from Module 1’s lab (“I want to change the date of my tickets.”). The third is a Module 1 test email that asks for two things. None of the five is in emails.ts.
Run node tag.ts three times and write down the three scores and e11’s tag on each. E11 is likely to be tagged change_date on most runs, with the clear emails still right. If e11 still fails, reread the rules as a colleague who has never seen the team, and change the words before you add an example.
Step 5: count the tokens and cache the system prompt
Why: every call sends the same system prompt, and caching only works above a minimum size. First, create count.ts:
// count.ts: how many tokens the shared part of the prompt holds
import Anthropic from "@anthropic-ai/sdk";
import { SYSTEM } from "./prompt.ts";
const client = new Anthropic();
const model = process.env.MODEL ?? "claude-haiku-5-5";
const result = await client.messages.countTokens({
model,
system: SYSTEM,
messages: [{ role: "user", content: "<email>\nHello\n</email>" }],
});
console.log("system prompt + a one-word email:", result.input_tokens);
Run node count.ts. You should see one number, an estimate. If it is under 512, Haiku 5.5 won’t cache this prompt.
Now make two changes in tag.ts. Give the system block a breakpoint, and print usage inside tagEmail, right after the parse call:
// Excerpt from tag.ts, version 3: the system line in the parse call
system: [{ type: "text", text: SYSTEM, cache_control: { type: "ephemeral" } }],
// Excerpt from tag.ts, version 3: right after the parse call
const u = message.usage;
console.log(` write=${u.cache_creation_input_tokens} read=${u.cache_read_input_tokens} input=${u.input_tokens} output=${u.output_tokens}`);
Run node tag.ts. On the first email you should see write at about the size of the system prompt and read=0. On the next eleven you should see write=0 and read at the same size, because they run within 5 minutes of each other.
If write and read are 0 on every line, the prefix is under the minimum. That is the silent failure from the caching section: no error, no cache, a full price. For a prompt this short, accepting it is a fair choice; caching earns its keep when the shared part is long.
Step 6: read the bill
Why: the numbers in usage are what you pay for, so you should be able to turn them into money. From step 5’s output, add up each of the four counts over the twelve emails. Then work out the cost in base-price units with Figure 6’s multipliers, and multiply by the base input price for Haiku 5.5 on the pricing page.
Now change the system line back to system: SYSTEM and run node tag.ts once more. Compare the totals: input_tokens now carries the whole prompt on every call, and the two cache counts are 0. Put the breakpoint back afterward.
Ollama note. Point the same files at Ollama as in Module 2:
ANTHROPIC_BASE_URL=http://localhost:11434,ANTHROPIC_API_KEY=ollamaandMODEL=qwen3.5:4b, on Ollama v0.40.17. Steps 1, 2 and 4 work. Steps 5 and 6 don’t apply, because Ollama has no prompt caching and no token counting endpoint.Step 3 behaves differently. Ollama’s Anthropic-compatible API ignores
output_config.format(its source code keeps onlyeffort), so nothing constrains the sampling.parsethen checks the text itself and may throw “Failed to parse structured output as JSON”, whichtag.tscounts as wrong. The JSON answers in step 4’s examples help, but a small model may give more invalid JSON and more wrong tags. Check whatparsedoes with your answers.
Going deeper
Where few-shot prompting comes from
The GPT-3 paper, Language Models are Few-Shot Learners (Brown and others, May 2020), named the method. It gave tasks and demonstrations to the model only as text, with no further training.
A year later, Calibrate Before Use (Zhao and others, ICML 2021) showed how fragile it was with GPT-3. The prompt’s format, the choice of examples and their order moved accuracy from near chance to near the best results of the time. Among the causes, the model favored answers that appeared near the end of the prompt and answers common in its training text. Those are old models, so read the study as a reason to vary and test your examples, and not as a measurement of today’s models.
What the cache holds
The prompt caching docs say what stays in memory: the model’s processed form of the prefix (its “KV cache representations”) and hashes of it, for the entry’s lifetime. Your text isn’t stored as text. Entries are never shared between organizations and, on the Claude API, are separate per workspace.
A request can have up to four breakpoints. To find an earlier entry, each breakpoint looks back at most 20 blocks, and it can only find entries that earlier requests wrote.
Long runs: compaction, notes and fresh windows
A tagger sends one email per call, so its window never fills. An agent that works for an hour does fill it, and Anthropic’s engineering post describes three answers:
- Compaction: summarize the window when it nears the limit.
- Notes: the agent writes notes to a file outside the window and reads them back when needed.
- Subagents: helpers that work in fresh windows and return a short summary, often 1,000 to 2,000 tokens.
Module 4 builds the loop that needs these, and Module 10 uses subagents.
Common mistakes when you shape the context
- Copying a JSON trick from an older tutorial. Symptom: a
400error for a prefilled{, for a forced tool on Opus 5.5, or for the oldoutput_formatfield. Fix: useoutput_config.format, as in lab step 3. - Putting test emails into the examples. Symptom: a perfect score on the test set, then wrong tags on new emails. Fix: keep the examples and the test set apart, and add a new hard case to the test set before you write an example for it.
- Not checking
stop_reason. Symptom:parsed_outputisnull, orparsethrows, now and then. Fix: read the tag only whenstop_reasonisend_turn, and logrefusalandmax_tokenscases. - Asking for reasoning inside the JSON. Symptom: a
refusalwith the categoryreasoning_extraction. Fix: drop the field, or ask for a short explanation in place of step-by-step reasoning. - A changing value at the start of the system prompt. Symptom:
cache_read_input_tokensis 0 on every call, and the bill doesn’t fall. Fix: move the time, an ID or anything else that changes per call into the user message, after the breakpoint. - A prefix under the minimum. Symptom: both cache counts are 0, with no error. Fix: run
countTokens; on Haiku 5.5 a prefix needs 512 tokens. Below that, accept no caching. - The breakpoint on the varying part. Symptom: a write on every call and no reads, often from automatic caching in a loop. Fix: put
cache_controlon the last block of the shared part. - Sending identical requests in parallel to warm the cache. Symptom: every request pays full price. Fix: send one request first, then the rest.
Check yourself
Scenario. Nina wants fewer wrong tags, so she pastes the 300 emails the team tagged last month into the system prompt as examples. She also adds a first line, Now: ${new Date().toISOString()}, so the model knows the date. A week later the bill for tagging is much higher, cache_read_input_tokens is 0 on every call, and the test score hasn’t improved. What went wrong, and what would you change?
Answer
Three things went wrong. First, 300 examples add thousands of input tokens to every call. Many are near copies that don’t help, and context rot means extra text that doesn’t help can make tags worse.
Second, the time on the first line changes on every call, so the prefix is never identical and the cache never reads; every call pays a write. Third, the test emails may now be among the examples, so a good score would prove little.
Change it back to three to five varied examples, plus the hard cases the test set has shown, and run the test set after each change. Move the time into the user message, after the breakpoint, or remove it, because tagging doesn’t need it. Check that no test email appears in the examples.
- Module 1’s prompt tags Ana’s email
refund. Did the model make a mistake, and what fixed it? - With structured outputs on, can Ana’s email still get the wrong tag?
- Why must Ana’s email stay out of the examples in the system prompt?
- Every call shows
cache_creation_input_tokensandcache_read_input_tokensat 0. Name two causes. - A call writes many thinking tokens. Which price do they pay, and which setting controls them?
Answers
- The model followed the prompt’s own “asks for last” rule; writing the team’s fallback rule, with its reason and an example, into the system prompt fixed it.
- Yes, because a schema fixes the shape of the answer, and
{"tag": "refund"}has a valid shape. - Because then the test only checks that the model can copy an answer, not that it applies the rule.
- The prefix is shorter than the model’s minimum (512 tokens on Haiku 5.5), or the request has no
cache_controlbreakpoint. - They’re billed as output tokens, at 5 times the input price on current models, and
effortcontrols how many the model may write.
Cheat sheet
Context engineering for one call
- Context engineering: choose what the model reads on each call, its shape and its order.
- System prompt: the task, who reads the answer, the tags and the team’s rules, with reasons.
- Examples: three to five varied ones in XML tags; never the test inputs.
- Structured outputs:
output_config.formatwith a schema; checkstop_reason; right shape, not always right answer. - What stays out: what doesn’t help the task; more context can make answers worse (context rot).
- Order: stable parts first, the input last.
- Prompt caching:
cache_controlafter the stable part; 512 tokens minimum on Haiku 5.5; checkusage. - Cost: reads 0.1, writes 1.25, output 5 times the input price on Haiku 5.5 (2026-11-22).
Figure 8 is the whole module in one picture.
(Developer)
| test set first, then:
v
[ system prompt: why + tags + rules + examples ] <-- cache breakpoint
[ user: <email> one buyer's email </email> ] <-- changes every call
| + output_config.format (schema)
v
[Model] --> constrained sampling --> {"tag": "change_date"}
|
v
usage: write / read / input / output --> the bill
code: check stop_reason, compare, route
Figure 8: the stable context goes first and is cached, the email goes last, the schema fixes the shape, and code checks the result.
Next, Module 4 gives the model tools, so it can fetch what isn’t in its context window and act in a loop.
Sources
- Andrej Karpathy, post on X endorsing “context engineering”, June 25, 2025; “LLM OS” post on X, November 11, 2023.
- Tobi Lütke, post on X proposing “context engineering”, June 2025.
- Simon Willison, Context engineering, June 27, 2025.
- Anthropic, Effective context engineering for AI agents, September 29, 2025.
- Claude documentation, checked 2026-11-22: prompting best practices, prompt engineering overview, structured outputs, strict tool use, Opus 5.5 migration guide, context windows, prompt caching, token counting, thinking, pricing, release notes.
- Kelly Hong, Anton Troynikov and Jeff Huber, Context Rot, Chroma, July 14, 2025 (code).
- Papers: Liu et al., Lost in the Middle, 2023, published in TACL; Brown et al., Language Models are Few-Shot Learners, 2020; Zhao et al., Calibrate Before Use, 2021.
@anthropic-ai/sdkon GitHub, version 1.12.0 (messages.parseand the Zod helper).- Ollama docs: Anthropic compatibility, structured outputs.