LearnTopic guide

Prompting, few-shot and structured output

Prompting is still the cheapest lever on LLM behaviour, and applied LLM interviews test it as engineering rather than folklore: how a system prompt is structured, how examples are chosen and when they hurt, when reasoning helps and what it costs, how to guarantee schema-valid output, and how prompts are versioned and regression-tested. Expect a live exercise: diagnose failures from a dozen outputs, fix the prompt and say how you would prove the fix. Current practice has shifted: reasoning models need less hand-holding and are steered with an effort setting rather than hand-written reasoning steps, structured outputs replace parsing hacks, some providers no longer accept assistant prefill, and ‘prompt engineering’ has widened into context engineering: deciding which instructions, tools, examples and retrieved data enter the window at each step of an agent.

Applied LLM · ML engineering8 key concepts11 questions

Start: Key concepts 6 lessons · about 17 min
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

Anatomy of a production promptA left-to-right flow of the production prompt. Stable components come first: role and audience, task and success criteria, rules with reasons, examples and output format. Variable context and data sit in marked blocks after the stable prefix, and the assembled prompt reaches the model.Role and audiencewho the model isTask and success criteriawhat success looks likeRules with reasonswhy each rule existsExamplessteer format and toneOutput formatschema-valid outputContext and datadelimited in marked blocksModelprefix-cached stable prefixstable first12345Stable prefixVariableModel
  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.

The anatomy components, with the stable parts first for prefix caching and variable data in marked blocks.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Set role and taskState the role and audience, then the task and success criteria.
2Add rules with reasonsGive each rule the reason behind it, so models generalise from the purpose.
3Add examples and formatAdd examples and the output format; examples are the strongest steer for format and tone.
4Mark variable dataKeep variable context and data in marked blocks (XML tags or headings) after the stable prefix.
5Send to modelThe stable prefix is cached for prefix caching; the variable block is appended per request.

Source: This page's text

Boxes
BoxGroupDetail
Role and audienceStable prefixwho the model is
Task and success criteriaStable prefixwhat success looks like
Rules with reasonsStable prefixwhy each rule exists
ExamplesStable prefixsteer format and tone
Output formatStable prefixschema-valid output
Context and dataVariabledelimited in marked blocks
ModelModelprefix-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 = 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

Gain over single sample = (Majority accuracy − Single-sample accuracy) × 100

Worked cases
CaseSingle-sample accuracyMajority accuracyGain over single sample
p = 0.70.783.7%13.7 points
p = 0.40.431.7%−8.3 points
Assuming independent samples, majority vote over 5 samples lifts 70% single-sample accuracy to 0.837, but correlated samples and 5× output tokens mean real gains are smaller.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.

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

  1. Instructions and examples are the weakest option.

  2. JSON mode gives valid JSON, any shape.

  3. Schema-constrained decoding masks invalid tokens using a grammar compiled from the JSON Schema.

  4. 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.

The ladder moves from instructions and examples to JSON mode, schema-constrained decoding and typed tool calls, with validation still required.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.

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.

Next: Worked examples Lesson 3 of 6 · about 3 min

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

Diagnosing JSON parse failuresThe flow starts with 1,000,000 calls a day and 2% JSON parse failures. A single retry fixes only 30%, so failures are bucketed as truncation, refusals, unescaped text or markdown fences, then fixed in order and added to the regression suite.Pipeline calls1,000,000 calls/dayJSON parse failures2% of callsRetry observationone retry fixes 30%Failure bucketstruncation, refusals, unescapedtext, fencesFixes in orderstructured output, max tokens,refusals, retryRegression suitetrack rate per release2% failone retryinput-dependentbucketadd failing inputs12345InputDiagnoseFixTrack
  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.

A 2% JSON parse failure rate is traced from a daily pipeline to input-dependent buckets, ordered fixes and a regression suite.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1Failures appearA pipeline makes 1,000,000 calls a day; 2% fail JSON parsing.
2Retry is weakOne retry fixes only 30%, so failures are input-dependent, not random.
3Bucket failuresBucket the failures: truncation at max_tokens, refusals, unescaped quotes or newlines, markdown fences.
4Fix in orderApply fixes in order: schema-constrained structured output or a tool call, raise max tokens, handle refusals, retry once with the validator's message.
5Track per releaseAdd the failing inputs to the regression suite so the rate is tracked per release.

Source: This page's text

Boxes
BoxGroupDetail
Pipeline callsInput1,000,000 calls/day
JSON parse failuresInput2% of calls
Retry observationDiagnoseone retry fixes 30%
Failure bucketsDiagnosetruncation, refusals, unescaped text, fences
Fixes in orderFixstructured output, max tokens, refusals, retry
Regression suiteTracktrack 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.

Next: What changed Lesson 4 of 6 · about 3 min

What changed recently

  1. 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.

    Source

  2. 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.

    Source

  3. 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.

    Source

  4. 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.

    Source

  5. 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.

    Source

Next: Pitfalls and interview angles Lesson 5 of 6 · about 2 min

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?
Next: Quiz Lesson 6 of 6 · about 3 min

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.

  1. Question 1 of 3 · Applied LLM · Technical · Easy

    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?

  2. Question 2 of 3 · Applied LLM · Technical · Easy

    How do you choose few-shot examples, and when do examples hurt?

  3. Question 3 of 3 · Applied LLM · Technical · Medium

    When does asking a model to reason step by step, or enabling a reasoning mode, help — and what does it cost?

Reading

Practise this topic

  1. 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?Applied LLM · Technical · Easy
  2. How do you choose few-shot examples, and when do examples hurt?Applied LLM · Technical · Easy
  3. When does asking a model to reason step by step, or enabling a reasoning mode, help — and what does it cost?Applied LLM · Technical · Medium
  4. 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.Applied LLM · Technical · Easy
  5. 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.Applied LLM · Technical · Medium
  6. In long chats, the assistant starts ignoring formatting and safety instructions from the system prompt. Why, and how do you fix it?Applied LLM · Technical · Medium
  7. About 2% of responses fail JSON parsing in production. Walk through finding and fixing the cause.Applied LLM · Technical · Easy
  8. 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.Applied LLM · Coding · Medium
  9. 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?Applied LLM · Technical · Medium
  10. 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?Applied LLM · Technical · Hard
  11. 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?Applied LLM · System design · Medium

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.