Contents
Key concepts
Anatomy of a production prompt
Role and audience, the task and success criteria, context and data clearly delimited (XML tags or headings), rules with the reason behind each, examples, and the output format. Put stable content first so prefix caching works, keep variable data in marked blocks, and explain why a rule exists: models generalise better from a stated purpose than from a bare command. Caching details now differ by provider and change often: OpenAI’s GPT-6.2 guide notes that top-level instructions are appended after the input, so reusable rules belong in the first developer message, and OpenAI added 12-hour cache retention in October 2026. Aim the system prompt at the ‘right altitude’ (Anthropic’s phrase): specific enough to steer, without brittle if-then logic.
Flow · 5 stepsAnatomy of a production prompt
- Set role and task State the role and audience, then the task and success criteria.
- Add rules with reasons Give each rule the reason behind it, so models generalise from the purpose.
- Add examples and format Add examples and the output format; examples are the strongest steer for format and tone.
- Mark variable data Keep variable context and data in marked blocks (XML tags or headings) after the stable prefix.
- Send to model The stable prefix is cached for prefix caching; the variable block is appended per request.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Set role and task | State the role and audience, then the task and success criteria. |
| 2 | Add rules with reasons | Give each rule the reason behind it, so models generalise from the purpose. |
| 3 | Add examples and format | Add examples and the output format; examples are the strongest steer for format and tone. |
| 4 | Mark variable data | Keep variable context and data in marked blocks (XML tags or headings) after the stable prefix. |
| 5 | Send to model | The stable prefix is cached for prefix caching; the variable block is appended per request. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Role and audience | Stable prefix | who the model is |
| Task and success criteria | Stable prefix | what success looks like |
| Rules with reasons | Stable prefix | why each rule exists |
| Examples | Stable prefix | steer format and tone |
| Output format | Stable prefix | schema-valid output |
| Context and data | Variable | delimited in marked blocks |
| Model | Model | prefix-cached stable prefix |
Source: This page's text
Placement and long inputs
With long documents, place the material at the top and the question and instructions at the end; Anthropic’s guidance reports up to 30% better responses with queries at the end on complex multi-document inputs. Ask the model to quote the relevant passages before answering to focus it. In long conversations, restate key constraints near the latest turn rather than relying on a distant system prompt.
Few-shot example selection
Examples are the strongest steer for format and tone. Choose relevant, diverse cases with consistent labels and include edge cases; 3–5 is a common starting point. Few-shot results are sensitive to format, choice and order: ‘Calibrate Before Use’ showed accuracy moving from near chance to near state of the art and identified majority-label and recency biases. Dynamic few-shot retrieves the most similar labelled examples per query.
Reasoning: chain of thought, self-consistency and reasoning models
Asking for intermediate steps improves multi-step tasks (chain of thought), and sampling several reasoning paths with a majority vote helps further (self-consistency, +17.9% on GSM8K in the paper). Reasoning models do this internally, steered by an effort setting: Claude 4.6 and later use adaptive thinking with low to max effort in place of fixed token budgets (budget_tokens returns an error from Claude 4.7), and OpenAI’s GPT-6.2 guide recommends starting new integrations at medium effort. Vendor guidance now prefers a general instruction such as ‘think thoroughly’ over a hand-written step-by-step plan, and some models decline requests to write their reasoning out in tags. The cost is more output tokens and latency, and gains vanish on simple lookups or classification. Measure accuracy per pound and per second, not accuracy alone.
CalculatorMajority vote over 5 samples
- Majority accuracy
- 83.7%
- Gain over single sample
- 13.7 points
Majority accuracy = 10 × Single-sample accuracy ^ 3 × (1 − Single-sample accuracy) ^ 2 + 5 × Single-sample accuracy ^ 3 × Single-sample accuracy × (1 − Single-sample accuracy) + Single-sample accuracy ^ 5 = 83.7%
Gain over single sample = (Majority accuracy − Single-sample accuracy) × 100 = 13.7 points
| Case | Single-sample accuracy | Majority accuracy | Gain over single sample |
|---|---|---|---|
| p = 0.7 | 0.7 | 83.7% | 13.7 points |
| p = 0.4 | 0.4 | 31.7% | −8.3 points |
Structured output
Options in increasing strength: instructions and examples; JSON mode (valid JSON, any shape); schema-constrained decoding, which masks invalid tokens using a grammar compiled from the JSON Schema (OpenAI reported 100% schema adherence on its eval versus under 40% for an older model by prompting; Claude’s API now offers the same through JSON outputs and strict tool use); and tool calls with typed parameters. Constrained decoding supports only a subset of JSON Schema (Claude rejects, for example, recursive schemas and numeric or length bounds) and the first request with a new schema pays a grammar compilation cost. Remaining failures are refusals, truncation at max tokens and semantically wrong but valid values, so keep a validator and a targeted retry.
Stack · 4 layersStructured output options in increasing strength
Instructions and examples are the weakest option.
JSON mode gives valid JSON, any shape.
Schema-constrained decoding masks invalid tokens using a grammar compiled from the JSON Schema.
Tool calls use typed parameters; refusals, truncation at max tokens and valid-but-wrong values still occur, so keep a validator and a targeted retry.
Schema design affects quality
Strict formats can reduce reasoning quality (‘Let Me Speak Freely?’ found significant drops under format restrictions). Mitigate by putting a reasoning or evidence field before the answer field, keeping schemas shallow, using enums for categories and separating ‘think’ and ‘format’ into two calls when quality matters.
Prompts as code
Version prompts with the model ID, tool schemas and retrieval config; run an eval suite in CI on every change; keep a regression set of past failures. Re-run the suite on every model upgrade, because prompts tuned for one model often over- or under-steer the next: Anthropic warns that emphatic ‘CRITICAL: you MUST’ wording written for older models makes newer ones over-trigger tools, and OpenAI says GPT-6.2 Astra writes more concisely by default, so old ‘be concise’ lines deserve review. Anthropic’s docs note that prefilled final assistant turns return a 400 error from Claude 4.6 onwards, so migrate prefill tricks to structured outputs or explicit instructions. Automatic optimisers such as DSPy’s GEPA can now search over prompts against your eval set, which only works if that set exists.
Instructions versus data
Anything inside retrieved documents, emails or tool results can contain instructions. Delimit untrusted content, tell the model to treat it as data, and enforce permissions outside the model; prompting reduces but never eliminates prompt injection.
Worked examples
Is self-consistency worth five times the cost?
A single chain-of-thought sample answers a yes/no compliance question correctly 70% of the time. Assuming independent samples, what accuracy does a majority vote over 5 samples give? What if single-sample accuracy were 40%? What does this ignore?
Majority of 5 is correct when at least 3 samples are correct: P = Σₖ₌₃⁵ C(5,k) pᵏ (1 − p)⁵⁻ᵏ
p = 0.7: 10 × 0.343 × 0.09 + 5 × 0.2401 × 0.3 + 0.16807 = 0.3087 + 0.3602 + 0.1681 = 0.837
p = 0.4: 10 × 0.064 × 0.36 + 5 × 0.0256 × 0.6 + 0.01024 = 0.2304 + 0.0768 + 0.0102 = 0.317
So voting amplifies whatever the base model tends to do: +13.7 points at 70%, −8.3 points at 40%.
What this ignores: samples from one model are correlated (the same misconception recurs), so real gains are smaller; cost is 5× output tokens and latency is the slowest of five unless run in parallel. Test on your eval: if a reasoning model at medium effort matches the vote at lower cost, prefer it.
Diagnosing 2% JSON parse failures with retry arithmetic
A pipeline makes 1,000,000 calls a day and 2% fail JSON parsing. If failures were random and independent, how many would remain after one retry? You observe that one retry only fixes 30% of failures. What does that tell you and what do you do?
If independent: P(fail twice) = 0.02² = 0.0004 → 1,000,000 × 0.0004 = 400 per day.
Observed: retry fixes 30% → 20,000 × 0.7 = 14,000 per day still failing.
Interpretation: most failures are input-dependent, not random. Bucket them:
- truncation at max_tokens on long inputs (check stop_reason / finish_reason)
- refusals or safety messages in place of JSON
- unescaped quotes or newlines from copied user text
- markdown fences around the JSON
Fixes in order: switch to schema-constrained structured output or a tool call (removes syntax errors), raise max tokens or shorten the schema for long inputs, handle refusals explicitly, and on validation errors retry once with the validator’s message. Add the failing inputs to the regression suite so the rate is tracked per release.
Flow · 5 stepsDiagnosing JSON parse failures
- Failures appear A pipeline makes 1,000,000 calls a day; 2% fail JSON parsing.
- Retry is weak One retry fixes only 30%, so failures are input-dependent, not random.
- Bucket failures Bucket the failures: truncation at max_tokens, refusals, unescaped quotes or newlines, markdown fences.
- Fix in order Apply fixes in order: schema-constrained structured output or a tool call, raise max tokens, handle refusals, retry once with the validator's message.
- Track per release Add the failing inputs to the regression suite so the rate is tracked per release.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Failures appear | A pipeline makes 1,000,000 calls a day; 2% fail JSON parsing. |
| 2 | Retry is weak | One retry fixes only 30%, so failures are input-dependent, not random. |
| 3 | Bucket failures | Bucket the failures: truncation at max_tokens, refusals, unescaped quotes or newlines, markdown fences. |
| 4 | Fix in order | Apply fixes in order: schema-constrained structured output or a tool call, raise max tokens, handle refusals, retry once with the validator's message. |
| 5 | Track per release | Add the failing inputs to the regression suite so the rate is tracked per release. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Pipeline calls | Input | 1,000,000 calls/day |
| JSON parse failures | Input | 2% of calls |
| Retry observation | Diagnose | one retry fixes 30% |
| Failure buckets | Diagnose | truncation, refusals, unescaped text, fences |
| Fixes in order | Fix | structured output, max tokens, refusals, retry |
| Regression suite | Track | track rate per release |
Source: This page's text
Turning token log-probabilities into a calibrated classifier
You prompt a model to answer ‘Yes’ or ‘No’ to ‘Is this message a complaint?’ and read the log-probabilities of the first token: log P(Yes) = −0.22 and log P(No) = −1.71. Compute a complaint probability and explain how you would set the threshold.
Convert and renormalise over the two allowed labels:
- P(Yes) = e^(−0.22) ≈ 0.803
- P(No) = e^(−1.71) ≈ 0.181
- mass on other tokens = 1 − 0.803 − 0.181 ≈ 0.017 (format leakage; watch it per release)
P(complaint) = 0.803 / (0.803 + 0.181) ≈ 0.816
Threshold: do not assume 0.5. On a labelled validation set, sweep thresholds and pick the one that meets the business target (e.g. precision ≥ 0.9 for auto-routing), then check calibration with a reliability curve; fit Platt or temperature scaling on held-out data if the scores are over- confident, which is common after instruction tuning. Keep label tokens single-token and identical in casing, and order-swap labels in the prompt to check for position bias.
What changed recently
GPT-6.2 prompting guidance: concise by default, effort from medium
OpenAI’s guide for GPT-6.2 Astra and Sol (released 17 November 2026) says Astra writes more concisely by default, so old ‘be concise’ instructions deserve review; recommends starting new integrations at medium reasoning effort and moving none or minimal users to low; and suggests letting agents make reversible, stated assumptions instead of stopping to ask. It also moves cacheable rules into the first developer message. Interviewers use such guides to test whether you re-tune prompts per model rather than carrying them over.
Adaptive thinking and effort replace thinking budgets
With Claude Opus 4.6, Anthropic replaced the on/off extended-thinking switch with adaptive thinking, in which the model decides when to reason, steered by low, medium, high (default) or max effort; fixed token budgets are deprecated in Anthropic’s docs. Candidates are now asked how they would trade quality, latency and cost with an effort setting instead of writing chain-of-thought instructions by hand.
Agent Skills: instructions loaded by progressive disclosure
Anthropic introduced Agent Skills: folders with a SKILL.md whose name and description sit in the system prompt, while the full instructions, extra files and scripts load only when a task needs them. Published as an open standard in December 2025, the pattern answers a common interview question: how to give an agent many specialised procedures without bloating every prompt, and what supply-chain risks that brings.
Context engineering supersedes prompt engineering
Anthropic described context engineering as the successor to prompt engineering: curating the smallest high-signal set of system instructions, tools, examples, retrieved data and history at every step, given ‘context rot’ as windows fill. It recommends prompts at the right altitude, a few canonical examples instead of exhaustive rules, and compaction, notes and sub-agents for long tasks. Expect the term, and the trade-offs behind it, in applied LLM interviews.
GEPA: reflective prompt optimisation rivals RL fine-tuning
GEPA, now in DSPy, evolves prompts by having a model reflect in natural language on execution traces and keeping a Pareto set of strong candidates. The revised paper (ICLR 2026 oral) reports beating GRPO by 6% on average and up to 20% with up to 35 times fewer rollouts, and beating MIPROv2 by over 10%. It makes ‘optimise the prompt against an eval set before fine-tuning’ a defensible default.
Pitfalls
- Long lists of capitalised MUST rules with no reasons, which strong models over-apply or ignore.
- Few-shot examples that all share one label or a surface pattern the model copies.
- Assuming chain of thought always helps; it adds cost and can hurt simple classification or extraction, and with reasoning models a prescribed step-by-step plan usually does worse than a general instruction plus the right effort setting.
- Parsing free text with regexes when structured outputs or tool calls are available.
- Treating JSON validity as correctness; valid JSON can still contain wrong values.
- Changing a prompt without re-running the eval suite, or keeping prompts outside version control.
How interviewers probe it
- Critique or write a system prompt live; explain each section and how you would test it.
- How do you pick few-shot examples, and how would you show they help rather than hurt?
- Compare JSON mode, constrained decoding and tool calls; what failures remain?
- When does reasoning help, and how do you trade accuracy against latency and cost?
- Given a dozen wrong outputs, diagnose the failure pattern and propose a measurable fix in 30 minutes.
- Migrate a prompt suite to a new model generation: prefill removed, thinking budgets replaced by effort, more literal instruction following. What breaks and how do you find out?
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
Write or critique a system prompt for a support assistant. How do you structure role, instructions, context, examples and output format, and where do long documents go?
Model answer, written in a candidate's voice
- Role, task, audience, constraints, unsure behaviour and success criteria are explicit
- Sections are delimited with XML tags or headings
- Long documents sit before the question/instructions and are labelled with metadata
- Examples are diverse and cover edge cases
- Output format is explicit via schema or prefilled start
- Positive instructions with reasons replace capitalised prohibition piles
- Prompt is iterated against an eval set and versioned
How do you choose few-shot examples, and when do examples hurt?
Model answer, written in a candidate's voice
- Start from the output contract and failure modes, then pick examples that are representative, diverse, edge-case-aware, and labelled consistently
- Show the desired format and reasoning, not just the final label
- Use dynamic few-shot retrieval from a curated bank per query, with diversity and label-balance constraints
- Watch for harm: surface-feature copying, label imbalance, recency bias, token cost, and zero-shot can beat examples for strong reasoning models
- Ablate presence, order, and selection on a held-out eval set before shipping
When does asking a model to reason step by step, or enabling a reasoning mode, help — and what does it cost?
Model answer, written in a candidate's voice
- Helps multi-step maths, planning, and complex instructions; little gain for simple extraction or classification
- Costs output tokens and latency, and can overthink or loop; use budgets and stop conditions
- Stated reasoning is not guaranteed to reflect the model’s actual computation, so do not treat it as proof
- Keep reasoning separate from the final answer via tags or structured output for robust parsing
- Measure accuracy vs latency with and without reasoning on the team’s own task before adopting it
You have finished this topic.
Reading
- Prompt Engineering (Lil'Log)Concise survey of zero/few-shot, instruction prompting, self-consistency and chain of thought.
- Prompting best practices (Claude documentation)Current vendor guidance: clarity, examples, XML structure, long-context placement, prefill migration.
- Effective context engineering for AI agentsWhy prompt design now means curating the whole context: system-prompt altitude, tools, examples and compaction.
- Introducing Structured Outputs in the APIHow grammar-constrained decoding guarantees schema adherence, and its limitations.
- Chain-of-Thought Prompting Elicits Reasoning in Large Language ModelsThe original chain-of-thought result and its dependence on model scale.
- Self-Consistency Improves Chain of Thought Reasoning in Language ModelsSampling and voting over reasoning paths; the baseline for test-time compute arguments.
- Let Me Speak Freely? A Study on the Impact of Format Restrictions on Performance of Large Language ModelsWhy strict output formats can cost reasoning quality, and how to design around it.
- GEPA: Reflective Prompt Evolution Can Outperform Reinforcement LearningAutomatic prompt optimisation by reflecting on traces; beats GRPO on average across six tasks with far fewer rollouts.
Practise this topic
- Write or critique a system prompt for a support assistant. How do you structure role, instructions, context, examples and output format, and where do long documents go?
- How do you choose few-shot examples, and when do examples hurt?
- When does asking a model to reason step by step, or enabling a reasoning mode, help — and what does it cost?
- Your pipeline needs JSON matching a schema on every call. Compare the options for guaranteeing it, and how you’d handle the failures that remain.
- You get a prompt, a dozen inputs and the model’s outputs, several of them wrong. In 30 minutes, diagnose the failure patterns, improve the prompt and explain how you’d verify the fix.
- In long chats, the assistant starts ignoring formatting and safety instructions from the system prompt. Why, and how do you fix it?
- About 2% of responses fail JSON parsing in production. Walk through finding and fixing the cause.
- You have a helper that returns token log-probabilities from an LLM for a batch of prompts. Build a binary classifier on top of it: write the prompt, turn log-probs into a calibrated score rather than a hard label, then improve it.
- You are migrating a production prompt suite to a newer Claude model that removes assistant prefill, rejects fixed thinking budgets in favour of adaptive thinking with an effort setting, and follows instructions more literally. What breaks, how do you find it, and how do you re-tune?
- GEPA, a reflective prompt optimiser in DSPy, reports beating GRPO fine-tuning with far fewer rollouts. When would you optimise prompts automatically instead of fine-tuning, and what could go wrong?
- An internal agent must follow about 40 specialised procedures (expense rules, incident runbooks, report formats). Compare one large system prompt with a skills-style design that loads procedures on demand. How do you keep the context small, make the right procedure trigger, and manage the risks?