Prompt and context engineering
Build prompts and context that give the same good result on the ten-thousandth request, and change them as safely as code.
AI tools change fast: we review this lesson every quarter (next by 7 Feb 2027).
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
A team runs a support tool. An LLM reads each new ticket and returns a category and a one-line summary. It works well for three months.
On a Friday, a developer adds five examples to the prompt to fix the summary style. All five happen to be billing tickets. The tests pass, because the tests only check that the JSON parses.
On Monday, the billing queue is full. About a third of all tickets now say "billing", including login problems. The model copied the pattern in the examples, not only the style.
Nobody can say which prompt is live. It was edited in a web console, not in the repo. There is no list of past versions and no test set to compare against. Rolling back takes a day of guessing.
This story is made up. Each failure in it is common, and each one has a known fix.
The idea in simple words
You already know from LLM fundamentals that the model only knows what is in the request. Prompt engineering is writing the instructions in that request. Context engineering is the larger job: choosing everything the model sees, and in what order. 2
In a product, the prompt is code. It has inputs, outputs, bugs and versions. It needs review and tests like any other code.
The key idea. A good prompt is clear to a smart new colleague. Fixed parts come first. User text is fenced and treated as data. Every change runs through an eval set.
How it works
Step through the parts of one request, in the order a careful team builds it. Use Next and Back.
- First come the tool definitions, then the system prompt. The system prompt gives the model a role and the rules, with the reason for each. The output schema is sent as its own setting in the request. Changing it breaks the prompt cache.
- Next come a few worked examples. Parts 1 and 2 are the same on every request, so the provider can cache them. One changed character breaks the cache.
- Now the parts that change. Long documents, such as search results, go before the question, each one in its own tag.
- The user's text goes in its own tag, so the model can tell it from your rules. Treat it as data. Tags make injection harder, but they do not stop it.
- The task or question goes at the very end, after the long text. Anthropic and Google both advise this order for long inputs.
- The reply follows the schema you sent as a request setting. The schema fixes the shape, not the truth. Your code still checks each value, and checks permissions before any action.
Clear instructions and a role
Anthropic suggests a simple test. Show your prompt to a colleague who does not know the task. If they would be confused, the model will be too. 1 Say the exact output format and limits you want. Use numbered steps when order matters. 1
Give the reason behind each rule. "Never use ellipses" works less well than "The reply is read aloud by a speech engine, so never use ellipses." The model can then apply the reason to cases you did not list. 1
A role in the system prompt, even one sentence, focuses the model's behaviour and tone. 1 OpenAI's API has a developer role for your instructions, which ranks above user messages. 5
Aim for what Anthropic calls the "right altitude". Avoid long, brittle if-else logic, and avoid vague advice. Start with a short prompt, then add rules only for failures you have seen. 2
Examples (few-shot prompting)
Anthropic finds that examples work very well for controlling format, tone and structure. 1 Anthropic suggests 3 to 5 examples. Make them relevant, varied, and wrapped in <example> tags. 1 Google goes further and recommends always including examples. 7
Two warnings. With too many examples, the model may copy them too closely. 7 And examples that all look alike teach a pattern you did not mean, as in the story. 1 Keep every example in exactly the same format. 7
Delimiting input, and why it does not stop injection
Wrap each kind of content in its own tag, such as <instructions>, <context> and <input>. This helps the model tell them apart. 1 OpenAI suggests Markdown headings or XML tags for the same reason. 5
Tags are not a security wall. In September 2022, Simon Willison wrote about an early example found by Riley Goodside. A translation prompt obeyed "Ignore the above directions" written inside its input. 9 A warning in the prompt did not stop it, and neither did quoting the input as a JSON string. 9
OWASP still lists prompt injection first. It says it is unclear if there are fool-proof ways to prevent it. 8 Injection can also be indirect: hidden in a web page or file the model reads. 8 The danger grows with power. If an email assistant can send mail, an email it reads can tell it to. 10
So use layers. OWASP lists them: constrain the model's behaviour, validate output formats, filter input and output, apply least privilege, ask a human before risky actions, mark outside content, and test with attacks. 8 In our view, the strongest layer is in your code: the model cannot do what its tools do not allow. 8 10
Structured output
Ask for JSON that matches a schema, not free text. With structured outputs, the API constrains the reply to your JSON Schema. 4 OpenAI recommends Structured Outputs over plain JSON mode, because only Structured Outputs follow the schema. 6 Use a tool call when the model should trigger your code. Use a response format when you only want a shaped reply. 6
The guarantee has limits. A refusal, or a reply cut off at max_tokens, may not match the schema. 4 6 Claude's structured outputs do not support numerical limits such as minimum and maximum. 4 So check ranges, IDs and allowed values in your own code.
What goes in the context, and in what order
Context is a limited budget. Anthropic calls it "a finite resource with diminishing marginal returns". 2 As the token count grows, the model recalls facts less accurately. This is called context rot, and tests show it in all models. 2 A very large window does not mean you should fill it.
Put in only what this request needs: the rules, a few examples, the top search results, and recent history. For agents, Anthropic suggests loading data only when it is needed, using file paths or saved queries. 2 Retrieval is its own skill: see RAG.
For long inputs (Anthropic says 20,000 tokens or more), put the documents before the question. Anthropic says a question at the end improved quality by up to 30% in tests. 1 Google gives the same advice. 7 Anthropic would also put documents above the examples. 1 If you cache a fixed prefix of rules and examples, you trade a little of that for cheaper calls.
Prompt caching
The provider can reuse the work on a fixed start of your prompt. On Claude, the cache is built in this order: tools, then system, then messages. 3 A hit needs a 100% identical prefix. 3 So put fixed parts first and anything that changes after them. OpenAI gives the same advice. 5
Writing to the cache costs a little more than normal input. Reading from it costs a small fraction of the normal input price. 3 Prices differ by model and change often, so check the current pricing table. The default cache lives 5 minutes, and each hit refreshes it. 3 A timestamp at the top of your system prompt breaks every cache hit. 3
Version prompts like code and test them with evals
OpenAI now says: store production prompts in your application code. It is shutting down its stored-prompt API, v1/prompts, on 30 November 2026. 5 Code-managed prompts get typed inputs, code review, tests and normal deploys. 5
OpenAI also advises pinning production apps to a model snapshot, and building evals that measure prompt behaviour. 5 Then a prompt change is a pull request with an eval score, as in Evals for LLM systems. A model upgrade is a separate change, with its own eval run.
Trade-offs
This table is our own summary, except where a source is cited.
| Option | Reliability gain | Cost | Use it when |
|---|---|---|---|
| Clear rules with reasons | Yes Fewer vague failures. 1 | A few hundred tokens. | Always. |
| Few-shot examples | Yes Strong control of format and tone. 1 | More input tokens. Can skew output if they all look alike. | The output has a set style or format. |
| Structured output | Yes The shape is fixed in most cases. 4 | Values still need checks. Some schema features are missing. | Code reads the reply. |
| More context | Only up to a point. Recall drops as it grows. 2 | More tokens and latency. | Each added part answers a real failure. |
| Prompt caching | No change to quality. | Lower. Cached input is cheaper and faster. 3 | Large fixed prefix, many calls. |
| Input tags and warnings | Some. The model can tell parts apart. 1 | Almost free. | Always, but never as the only injection defence. 8 |
Simple rule: start short and clear. Add examples, context and rules only when an eval shows a failure.
At work: how a senior uses this
- Keep the prompt in the repo, next to the code that calls it. One file per prompt, reviewed in pull requests.
- Log the prompt version and model snapshot with every request. Then you can link a bad answer to a change.
- Ask: "Which eval cases did this prompt change move?" Never merge on "it looked better on three tries."
- Ask: "If this input is hostile, what is the worst the model can do?" Then remove that power from its tools.
- Keep the fixed prefix stable. Move dates, user names and IDs to the end.
- When you add a rule, add an eval case for the failure that caused it.
- For coding agents, the same ideas apply to project memory files.
With AI
What to ask the agent
"Here is our system prompt. Rewrite it so each rule has its reason. Put fixed parts first and anything that changes per request last. List what you removed and why."
"These are our five few-shot examples. Check them for variety. Point out any pattern they share that the model might copy by mistake."
"Write a validator for this JSON schema output. Check ranges, allowed values and IDs against our database, and handle refusals and cut-off replies."
"Write 20 eval cases for this prompt, including five prompt injection attempts hidden in the user input and in retrieved documents."
What to check yourself
- The agent did not paste user text into the system prompt, outside any tag.
- Nothing that changes per request, such as a date, sits before the cached prefix.
- The validator checks values, not only that the JSON parses.
- The eval set has cases from every category, not only the easy ones.
- No tool lets the model take a risky action without a check in code.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 10 sources and related lessons
- Anthropic, “Prompting best practices”, Claude documentation (opens in a new tab)
Clear instructions, the reason behind each rule, roles, examples, XML tags, and how to order long documents. - Anthropic Applied AI team, “Effective context engineering for AI agents”, Anthropic Engineering, 29 September 2025 (opens in a new tab)
Why context is a limited budget, the "right altitude" for system prompts, and how to pick examples and tools. - Anthropic, “Prompt caching”, Claude documentation (opens in a new tab)
The cache order (tools, system, messages), the exact-match rule, cache lifetime and prices. Prices change, so read the current table. - Anthropic, “Structured outputs”, Claude documentation (opens in a new tab)
What schema-constrained output guarantees, when it can still fail, and which JSON Schema features are not supported. - OpenAI, “Prompt engineering”, API documentation (opens in a new tab)
Message roles, delimiters, few-shot examples, pinning model snapshots, evals, and keeping prompts in code. - OpenAI, “Structured Outputs”, API documentation (opens in a new tab)
Structured Outputs versus JSON mode, refusals, and when to use function calling instead. - Google, “Prompt design strategies”, Gemini API documentation (opens in a new tab)
A third vendor's view. Few-shot examples, consistent example format, and putting the question after long context. - OWASP, “LLM01:2025 Prompt Injection”, OWASP Top 10 for LLM Applications 2025 (opens in a new tab)
Direct and indirect prompt injection, and seven layered ways to reduce the risk. - Simon Willison, “Prompt injection attacks against GPT-3”, 12 September 2022 (opens in a new tab)
The post that named the attack. Shows why warnings and quoting in the prompt did not stop it. - Simon Willison, “Prompt injection: What's the worst that can happen?”, 14 April 2023 (opens in a new tab)
Why the risk grows when the model can read private data or take actions, with an email assistant example.
Related: LLM fundamentals for product engineers · Evals for LLM systems · RAG: retrieval-augmented generation · Tool use and agents in products (coming soon) · Project memory: CLAUDE.md and rules files · Guardrails, cost and latency for LLM features (coming soon) · OWASP Top 10 and secure coding
- LLM fundamentals: tokens, the context window, and cost.
- Evals for LLM systems: how to build the test set that every prompt change runs through.
- RAG: retrieval-augmented generation: how to choose which documents go into the context.
- Tool use and agents in products: giving the model tools, and limiting what they can do.
- Project memory: CLAUDE.md and rules files: context engineering for coding agents.