---
title: Prompting, few-shot and structured output
url: https://gurkanozkan.ai/learn/topics/prompting/
markdown: https://gurkanozkan.ai/learn/topics/prompting.md
kind: topic
tracks:
  - Applied LLM
  - ML engineering
json: https://gurkanozkan.ai/api/learn/topics/prompting.json
---

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

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

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

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

### 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?

**Solution**

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?

**Solution**

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


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

**Solution**

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

- **Nov 2026: 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](https://developers.openai.com/api/docs/guides/latest-model)
- **Feb 2026: 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](https://www.anthropic.com/news/claude-opus-4-6)
- **Oct 2025: 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](https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills)
- **Sep 2025: 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](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents)
- **Jul 2025: 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](https://arxiv.org/abs/2507.19457)

## 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?

## Reading

- [Prompt Engineering (Lil'Log)](https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/) (Blog, 40 min, Intro): Concise survey of zero/few-shot, instruction prompting, self-consistency and chain of thought.
- [Prompting best practices (Claude documentation)](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices) (Docs, 60 min, Core): Current vendor guidance: clarity, examples, XML structure, long-context placement, prefill migration.
- [Effective context engineering for AI agents](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents) (Blog, 25 min, Core): Why prompt design now means curating the whole context: system-prompt altitude, tools, examples and compaction.
- [Introducing Structured Outputs in the API](https://openai.com/index/introducing-structured-outputs-in-the-api/) (Blog, 15 min, Core): How grammar-constrained decoding guarantees schema adherence, and its limitations.
- [Chain-of-Thought Prompting Elicits Reasoning in Large Language Models](https://arxiv.org/abs/2201.11903) (Paper, 40 min, Core): The original chain-of-thought result and its dependence on model scale.
- [Self-Consistency Improves Chain of Thought Reasoning in Language Models](https://arxiv.org/abs/2203.11171) (Paper, 35 min, Deep): Sampling 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 Models](https://arxiv.org/abs/2408.02442) (Paper, 30 min, Deep): Why strict output formats can cost reasoning quality, and how to design around it.
- [GEPA: Reflective Prompt Evolution Can Outperform Reinforcement Learning](https://arxiv.org/abs/2507.19457) (Paper, 40 min, Deep): Automatic 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…](https://gurkanozkan.ai/learn/questions/applied-llm-prm-01.md)
- [How do you choose few-shot examples, and when do examples hurt?](https://gurkanozkan.ai/learn/questions/applied-llm-prm-02.md)
- [When does asking a model to reason step by step, or enabling a reasoning mode, help — and what does it cost?](https://gurkanozkan.ai/learn/questions/applied-llm-prm-03.md)
- [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.](https://gurkanozkan.ai/learn/questions/applied-llm-prm-04.md)
- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-prm-05.md)
- [In long chats, the assistant starts ignoring formatting and safety instructions from the system prompt. Why, and how do you fix it?](https://gurkanozkan.ai/learn/questions/applied-llm-dbg-03.md)
- [About 2% of responses fail JSON parsing in production. Walk through finding and fixing the cause.](https://gurkanozkan.ai/learn/questions/applied-llm-dbg-04.md)
- [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…](https://gurkanozkan.ai/learn/questions/applied-llm-cod-04.md)
- [You are migrating a production prompt suite to a newer Claude model that removes assistant prefill, rejects fixed thinking budgets in favour of adaptive…](https://gurkanozkan.ai/learn/questions/recent-b-prompting-01.md)
- [GEPA, a reflective prompt optimiser in DSPy, reports beating GRPO fine-tuning with far fewer rollouts. When would you optimise prompts automatically instead of…](https://gurkanozkan.ai/learn/questions/recent-b-prompting-02.md)
- [An internal agent must follow about 40 specialised procedures (expense rules, incident runbooks, report formats). Compare one large system prompt with a…](https://gurkanozkan.ai/learn/questions/recent-b-prompting-03.md)
---

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