# Structured outputs and few-shot examples: getting reliable data from LLMs

> Source: <https://flaviocopes.com/structured-outputs-few-shot/>
> Published: 2026-11-28 08:00:00+00:00

**Recommendation:** Constrain decoding to a JSON Schema instead of relying on prompt-only JSON, and add boundary few-shot examples for ambiguous cases; the source saw 0% raw parse success without constraints and a 37% token cut with four examples.
More in the playbook "Verifying model output": <https://wpnews.pro/playbooks/output-verification>

# Structured outputs and few-shot examples: getting reliable data from LLMs

By [Flavio](https://flaviocopes.com/about/)

Tagged: [AI](https://flaviocopes.com/tags/ai/)

How constrained decoding, JSON Schema design, field order, nullable fields, and boundary few-shot examples work across 150 release-note runs.

Getting plain English out of a language model is easy. Getting clean, typed JSON that your application can trust without waking you up at 3 a.m. is a different engineering problem.

Most teams start by adding “Respond only with valid JSON” to the system prompt. That works in a quick prototype. Then real traffic arrives, the model wraps the JSON in triple backticks, invents a key you never asked for, writes `"N/A"` into a field your database expects to be null, or labels a harmless CI refactor as a production bug fix.

You are dealing with two separate layers here. The first layer is syntax and shape: can your code parse the response into the exact fields and types you declared? The second layer is semantic policy: did the model apply your actual business rules to an ambiguous input?

Constrained decoding solves the first layer by locking the model to a JSON Schema at token-generation time. Field ordering, nullable types, and boundary few-shot examples solve the second layer.

To see how both layers interact in practice, I ran a 150-call benchmark across 30 nuanced release-note entries, testing five configurations on live models, plus a 10-entry missing-field test. The numbers turned up a few surprises, including a case where adding four few-shot examples actually made the pipeline faster and cut output tokens by 37%, and another case where a strict schema still returned an empty string that broke `JSON.parse()`.

## Prompt-only JSON, JSON mode, and schema-constrained outputs

When you ask a model for structured data over an API, you have four mechanisms to choose from. Developers often blur them together, even though they enforce very different guarantees on the server.

Prompt-only JSON is the baseline. You describe the JSON shape in natural language inside the system or user message and hope the model obeys. Nothing on the inference server stops the model from writing `"Here is the JSON you requested:"` before the opening brace, wrapping the payload in a Markdown code fence, or trailing off with a friendly note after the closing brace.

In our 30-entry release-note benchmark, prompt-only JSON on `gpt-4.1-mini` scored **0% on raw `JSON.parse()`**. Every single one of the 30 responses came back wrapped in Markdown code fences. Here is the exact raw output returned for the entry `"Dropped Node.js 18 support; minimum runtime is now Node 20.11."`:

json
{
  "category": "breaking",
  "breaking": true,
  "needs_migration": true
}
You might be tempted to write a helper that strips leading and trailing triple backticks with a regular expression and call it a day. That hack fixes the cleanest failure mode while leaving the nastier ones open. A model running without decoding constraints can still put a Markdown comment inside the object, use single quotes, escape a string improperly, omit a required boolean, or rename `needs_migration` to `requiresMigration` on a Tuesday afternoon when the provider updates a model snapshot.

Even worse, look at what the same prompt-only run returned for `"Changed default cookie SameSite attribute from None to Lax for all session middleware."`:

json
{
  "category": "feature",
  "breaking": false,
  "needs_migration": false
}
Stripping the fences would have parsed that object without throwing an error, and then silently shipped the wrong classification for a breaking session-middleware change.

JSON mode (`response_format: { type: 'json_object' }`) is the second mechanism. On the server side, JSON mode prevents syntax errors and Markdown fences so the output is always parseable JSON, assuming the response finishes before hitting the output token limit. What JSON mode still ignores is your contract. It accepts `{"type": "bug"}` just as happily as `{"category": "fix", "breaking": false, "needs_migration": false}`. Every missing field, extra key, wrong primitive type, or out-of-range enum string still reaches your application code.

Schema-constrained structured outputs (`response_format: { type: 'json_schema', json_schema: { strict: true, ... } }`) close that gap. Instead of checking only generic JSON grammar, the inference engine compiles your exact JSON Schema into a grammar that restricts every token the model is allowed to emit. If your schema says `category` must be one of five enum strings and `breaking` must be a boolean, the model cannot emit `"bugfix"` or `"yes"` at those positions. For a quick reference on the flags across tools and APIs, see the [structured outputs](https://flaviocopes.com/ai-glossary/structured-outputs/) glossary entry.

Tool calling (function calling) with `strict: true` uses the same constrained-decoding engine under the hood, targeted at the tool's `arguments` JSON object instead of the assistant's top-level message content. Use tool calling when the model needs to choose among several actions or loop with your code. Use `response_format` structured outputs when the API call itself represents a single typed extraction, classification, or transformation.

| Mechanism | Prevents Markdown fences | Enforces exact keys and types | Supports strict enums | Handles multi-action routing | Typical failure mode |
| --- | --- | --- | --- | --- | --- |
| Prompt-only JSON | No | No | No | No | Fences, prose preambles, renamed keys, invalid JSON |
| JSON mode (`json_object`) | Yes | No | No | No | Valid JSON with missing fields, wrong types, extra keys |
| Structured outputs (`json_schema`, `strict: true`) | Yes | Yes | Yes | No | Truncation at `max_tokens`, refusals, empty strings, wrong semantics |
| Strict tool calling (`strict: true`) | Yes | Yes | Yes | Yes | Wrong tool picked, extra tool-call turn overhead |

Notice the last column. Moving from prompt-only JSON to strict structured outputs wipes out malformed syntax and unknown keys, yet it leaves truncation, refusals, and semantic mistakes intact. We will build explicit defenses for every one of those.

## How constrained decoding works under the hood

Understanding what happens inside the inference server explains why strict schemas behave the way they do, why the first call with a new schema is slower, and why field ordering changes accuracy.

At each decoding step, a transformer language model does not pick a single word directly. It runs a forward pass over the prompt plus all tokens generated so far, and outputs a vector of raw scores called **logits**, one score for every token in the model's vocabulary (often 100,000 to 200,000 tokens). Normally, the server applies softmax to turn those logits into probabilities, applies temperature and `top_p` filtering, and samples the next token.

Constrained decoding inserts a deterministic filter right before softmax.

Before the first token is sampled, the server compiles your JSON Schema into a formal grammar, typically a **finite-state machine (FSM)** for flat schemas or a **context-free grammar (CFG)** backed by a pushdown automaton when schemas involve nested objects, arrays, or recursive references. Modern serving stacks like Outlines, XGrammar, and llama.cpp's GBNF engines precompute an index mapping each grammar state to the exact subset of vocabulary tokens that keep the output on a valid path.

That token-level mapping is trickier than it looks because BPE tokenizers do not align cleanly with JSON punctuation. A single token in the vocabulary might be `{"cat`, another might be `egory":"`, and another might be `breaking",`. The grammar engine handles this by stepping through a character-level state machine over the vocabulary trie, checking whether appending a token's characters transitions the parser into a live state or a dead end.

Once the grammar index is ready, the decode loop adds one tiny step per token:

1. The model computes the full logit vector for the current prefix.
2. The server asks the grammar state machine for the bitmask of valid next tokens from the current state.
3. Every disallowed token has its logit overwritten with $-\infty$ (negative infinity).
4. Softmax converts $-\infty$ to an exact probability of `0.0`, renormalizing the remaining valid tokens so their probabilities sum to `1.0`.
5. The sampler picks from the surviving valid tokens, appends the token to the sequence, and advances the grammar state.

``` mermaid steps
flowchart TD
  accTitle: Step 1: Compile JSON Schema into grammar states
  accDescr: The inference server compiles the JSON Schema into a finite-state machine or context-free grammar before decoding starts.
  A["JSON Schema (strict: true)"] --> B["Grammar compiler (FSM / CFG)"]
  B --> C["Valid token mask per state"]
%% step
flowchart TD
  accTitle: Step 2: Model produces raw logits over the vocabulary
  accDescr: Given the prefix so far, the model computes raw logit scores for every token in its vocabulary, including invalid tokens like markdown fences.
  A["Prefix: {'category':"] --> B["Transformer forward pass"]
  B --> C["Raw logits for all tokens"]
  C --> D["Allowed: 'breaking', 'fix', 'deprecation'"]
  C --> E["Disallowed: ``` json, 'bugfix', newline prose"]
%% step
flowchart TD
  accTitle: Step 3: Grammar mask sets invalid logits to negative infinity
  accDescr: Before softmax, the grammar bitmask forces every invalid token logit to negative infinity so only schema-valid tokens survive sampling.
  A["Raw logits"] --> B["Apply grammar bitmask"]
  B --> C["Disallowed tokens -> -Infinity (prob = 0)"]
  B --> D["Allowed tokens -> Softmax & sample"]
  D --> E["Emit valid token and advance grammar state"]
```

This mechanism has two immediate engineering consequences you will feel in production.

First, **grammar compilation has a cold-start cost**. Turning a complex JSON Schema with deep nesting, large enums, or `anyOf` unions into token bitmasks over a 128k+ vocabulary takes measurable CPU time on the very first request. Providers cache compiled grammars by schema hash, so subsequent requests with the exact same schema skip compilation and run with negligible per-token masking overhead (often microseconds per step). If your code dynamically injects timestamps, user IDs, or random enum lists into the JSON Schema itself on every request, you bust that grammar cache on every call and pay the cold-start penalty over and over. Keep your schemas static and pass dynamic options inside the prompt when you can, or keep a small bounded set of reusable schemas.

Second, **logit masking cannot undo a decision the model already made**. Because decoding is strictly left-to-right (autoregressive), the grammar can only force the next token to be syntactically legal given the tokens already printed. If the schema puts `"category"` first, the model has to pick between `"breaking"`, `"deprecation"`, `"fix"`, `"feature"`, and `"internal"` on token number four, with zero scratchpad tokens to inspect the nuance of the changelog line. Once `"fix"` is emitted, it sits permanently in the attention context, and every field after it is conditioned on defending that choice. We will see how dramatically that matters when we look at our benchmark numbers.

There is also a subtle statistical effect called **tokenization bias** or probability distortion. When a grammar blocks tokens that would have been high-probability continuations (like leading whitespace, comments, or a slightly different phrasing), the remaining probability mass shifts onto whichever allowed tokens happen to share a legal prefix. Keeping your enum labels short, lowercase, distinct, and natural English words (like `breaking`, `deprecation`, `fix`, `feature`, `internal` instead of cryptic numeric codes like `CAT_01`, `CAT_02`) aligns with the model’s pretrained token probabilities and reduces friction with the mask.

## Building a production Node.js and Zod pipeline

Writing raw JSON Schema objects by hand gets tedious fast, and it splits your source of truth in two: one schema for the API request and a separate TypeScript type or runtime validator in your codebase. If you rename a field in one place and forget the other, your pipeline silently breaks.

The cleaner pattern in Node.js is to define the contract once with Zod, convert it to a strict JSON Schema for the API request, and run `safeParse()` on the decoded JSON after the call finishes.

Let’s build the exact release-note classifier schema we used for the benchmark. We want every entry classified into one of five categories, paired with two booleans (`breaking` and `needs_migration`), an optional GitHub issue reference that explicitly allows `null`, and a concise `rationale` placed first so the model reasons before committing to the labels.

First, define the Zod schema and derive the strict JSON Schema. Note how every property is required and optional data uses `.nullable()`, matching strict mode’s rules.

``` js
import { z } from 'zod'

export const ReleaseNoteClassification = z.object({
  rationale: z
    .string()
    .describe('One short sentence explaining whether consumers are impacted today'),
  category: z.enum([
    'breaking',
    'deprecation',
    'fix',
    'feature',
    'internal',
  ]),
  breaking: z
    .boolean()
    .describe('True only if existing callers can fail or change behavior after upgrading'),
  needs_migration: z
    .boolean()
    .describe('True only if users must change code, config, or data for THIS release'),
  issue_id: z
    .string()
    .nullable()
    .describe('Referenced issue or PR identifier like "#412", or null if none is mentioned'),
})

export const releaseNoteJsonSchema = z.toJSONSchema(ReleaseNoteClassification, {
  target: 'draft-2020-12',
})
```

Before sending `releaseNoteJsonSchema` to an API with `strict: true`, check one detail that trips up almost every first-time Zod-to-JSON-Schema integration: `additionalProperties: false` must be present on every object node, and every property in `properties` must appear in `required`. Zod v4’s `z.toJSONSchema()` emits `additionalProperties: false` automatically when you declare `z.strictObject(...)`, or you can enforce it with a small recursive normalizer so nested objects never slip through.

Here is a small normalizer that guarantees strict-mode compliance on any nested object schema without mutating the original object:

``` js
export const toStrictSchema = (schema) => {
  if (!schema || typeof schema !== 'object') return schema
  const copy = Array.isArray(schema)
    ? schema.map(toStrictSchema)
    : Object.fromEntries(
        Object.entries(schema).map(([key, value]) => [key, toStrictSchema(value)])
      )

  if (!Array.isArray(copy) && copy.type === 'object' && copy.properties) {
    copy.additionalProperties = false
    copy.required = Object.keys(copy.properties)
  }

  return copy
}
```

Now look at the API wrapper. A naive wrapper grabs `choices[0].message.content`, runs `JSON.parse()`, and returns the result. In production, a strict structured-output call has four distinct non-happy outcomes you need to separate cleanly in code:

1. **HTTP or transport errors** (429 rate limits, 5xx upstream errors, timeouts): retryable with exponential backoff and jitter.
2. **Model refusals** (`message.refusal` is non-empty): when safety filters trigger, the API deliberately bypasses the JSON Schema and puts an explanation in`message.refusal` with`content: null` . Retrying the exact same prompt usually fails again; route to an explicit refusal handler.
3. **Token-limit truncation or empty output** (`finish_reason === 'length'` or`!content?.trim()` ): constrained decoding stops mid-object the moment`max_tokens` runs out, leaving invalid partial JSON like`{"rationale": "Changed default...` or an empty string if internal reasoning tokens consumed the budget. Never feed truncated output to`JSON.parse()` blindly.
4. **Post-parse validation failures** (`safeParse()` fails): catches any constraint the provider’s grammar engine ignored (like regex patterns, numeric bounds, or cross-field invariants you validate with`.refine()` ).

Here is a complete production-ready caller in plain Node.js using `fetch`, with explicit handling for all four paths and zero third-party SDK lock-in:

``` js
const SYSTEM_POLICY = [
  'Classify a single software release-note entry into JSON.',
  'Rules:',
  '- breaking: removes APIs, raises minimum runtime, or changes defaults that alter existing behavior. breaking=true, needs_migration=true.',
  '- deprecation: adds a warning for a FUTURE version while current code keeps working. breaking=false, needs_migration=false.',
  '- fix: fixes a bug or security vulnerability without breaking backwards compatibility. breaking=false, needs_migration=false.',
  '- feature: adds backwards-compatible capability. breaking=false, needs_migration=false.',
  '- internal: CI, devDependencies, test fixtures, or repo tooling with no runtime effect on package consumers. breaking=false, needs_migration=false.',
  'Keep rationale to one short sentence.',
].join('\n')

const FEW_SHOT_EXAMPLES = [
  {
    role: 'user',
    content: 'Soft-deprecated legacy CSV parser; logs warning and will be removed in v6.',
  },
  {
    role: 'assistant',
    content: JSON.stringify({
      rationale: 'Logs a warning for a future major version while current callers still work.',
      category: 'deprecation',
      breaking: false,
      needs_migration: false,
      issue_id: null,
    }),
  },
  {
    role: 'user',
    content: 'Bumped devDependency eslint from 9.10 to 9.14 and tightened CI lint config.',
  },
  {
    role: 'assistant',
    content: JSON.stringify({
      rationale: 'Affects only repository CI and dev tooling with no consumer impact.',
      category: 'internal',
      breaking: false,
      needs_migration: false,
      issue_id: null,
    }),
  },
  {
    role: 'user',
    content: 'Changed default request timeout from 30s to 5s across HTTP clients (#814).',
  },
  {
    role: 'assistant',
    content: JSON.stringify({
      rationale: 'Tightening a default timeout can break existing callers that rely on slower responses.',
      category: 'breaking',
      breaking: true,
      needs_migration: true,
      issue_id: '#814',
    }),
  },
  {
    role: 'user',
    content: 'Patched header injection vulnerability in redirect helper without changing public signatures.',
  },
  {
    role: 'assistant',
    content: JSON.stringify({
      rationale: 'Fixes a security bug while keeping the public API backwards compatible.',
      category: 'fix',
      breaking: false,
      needs_migration: false,
      issue_id: null,
    }),
  },
]

export const classifyReleaseNote = async (entry, { apiKey, model = 'gpt-4.1-mini' }) => {
  const response = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${apiKey}`,
    },
    body: JSON.stringify({
      model,
      temperature: 0,
      max_tokens: 256,
      messages: [
        { role: 'system', content: SYSTEM_POLICY },
        ...FEW_SHOT_EXAMPLES,
        { role: 'user', content: entry },
      ],
      response_format: {
        type: 'json_schema',
        json_schema: {
          name: 'release_note_classification',
          strict: true,
          schema: toStrictSchema(releaseNoteJsonSchema),
        },
      },
    }),
  })

  if (!response.ok) {
    const body = await response.text()
    return { ok: false, kind: 'http_error', status: response.status, detail: body }
  }

  const payload = await response.json()
  const choice = payload.choices?.[0]
  if (!choice) {
    return { ok: false, kind: 'empty_choices', payload }
  }

  if (choice.message?.refusal) {
    return { ok: false, kind: 'refusal', reason: choice.message.refusal }
  }

  if (choice.finish_reason === 'length') {
    return { ok: false, kind: 'truncated', raw: choice.message?.content ?? '' }
  }

  const raw = choice.message?.content
  if (typeof raw !== 'string' || raw.trim() === '') {
    return {
      ok: false,
      kind: 'empty_content',
      finishReason: choice.finish_reason,
    }
  }

  let parsedJson
  try {
    parsedJson = JSON.parse(raw)
  } catch (error) {
    return { ok: false, kind: 'invalid_json', raw, error: error.message }
  }

  const validated = ReleaseNoteClassification.safeParse(parsedJson)
  if (!validated.success) {
    return { ok: false, kind: 'schema_mismatch', raw, issues: validated.error.issues }
  }

  return { ok: true, data: validated.data, usage: payload.usage }
}
```

Look closely at the return shape: every failure mode comes back as a tagged discriminated union (`http_error`, `refusal`, `truncated`, `empty_content`, `invalid_json`, `schema_mismatch`). That separation pays off immediately in monitoring. If `truncated` spikes, raise `max_tokens` or shorten the `rationale` instructions. A spike in `empty_content` on a reasoning model tells you hidden reasoning tokens ate the completion budget. And `schema_mismatch` flags a cross-field rule or unsupported JSON Schema constraint violation.

## Schema design traps that quietly ruin quality

Most guides treat the JSON Schema as a passive data container: pick your fields, turn on `strict: true`, and move on. In practice, the shape of your schema directly changes how well the model reasons and how often it fabricates data.

### Field order: put reasoning before the verdict

JSON objects are technically unordered maps in the JSON specification, yet an LLM generates JSON sequentially from left to right. Strict structured-output engines enforce the property order declared in your schema’s `properties` object so the grammar stays compact and deterministic.

That means **key order in your schema determines thought order inside the model**.

If your schema lists `category`, `breaking`, and `needs_migration` first, and puts `rationale` at the bottom (or omits `rationale` entirely), the model has to emit the category token immediately after `{"category":"`. Any subtle reasoning about whether a deprecation warning requires migration right now happens too late, or never happens at all. Worse, if `rationale` comes *after* the wrong label, the model will happily write a plausible-sounding justification explaining why its wrong label was correct.

Putting `rationale` first flips the dynamic. Before emitting `"category"`, the model spends 15 to 25 tokens stating the facts in the entry: “Logs a warning for a future major version while current callers still work.” Once those tokens are in the generated prefix, attention attends straight back to “future major version” and “current callers still work”, making `"deprecation"` and `"needs_migration": false` the highest-probability continuation.

In our 30-entry release-note benchmark on `gpt-4.1-mini`:

- Strict schema with verdict first (no rationale) hit **86.7% exact match (26/30)** with 15 average output tokens.
- Moving to a clear policy with `rationale` first jumped to**100% exact match (30/30)** .

You do not need a long chain-of-thought essay. One short sentence in the first field is enough for classification and extraction tasks, and you can strip the `rationale` field before saving to your database if downstream consumers do not need it (though keeping it in your audit logs makes debugging bad predictions ten times faster).

### Nullable fields vs forced required strings

Strict JSON Schema mode on OpenAI-compatible APIs requires every property in `properties` to appear in `required`. Developers migrating an existing schema often mark every field as `type: "string"` and leave it there.

That creates a subtle hallucination trap. What happens when the source document simply does not contain the field?

Suppose your schema extracts `issue_id` from a release note, and the release note says `"Fixed memory leak in WebSocket reconnect timer under high packet loss."` with no GitHub issue number anywhere in the text. If `issue_id` is `type: "string"` and required, the grammar literally forbids the model from omitting the field or emitting `null`. The model’s only legal escape is to invent a string. Depending on the model and prompt, you get `""`, `"none"`, `"N/A"`, `"unknown"`, or worst of all, a plausible fabricated value like `"#123"`.

To measure this directly, we ran 10 release notes with no GitHub issue number through both schemas:

- With required `type: "string"` , the model emitted empty-string placeholders`""` on**10 out of 10** entries (`["", "", "", "", "", "", "", "", "", ""]` ).
- With nullable `type: ["string", "null"]` , the model returned clean JSON`null` on**10 out of 10** entries.

Empty strings might look harmless until a downstream template renders `https://github.com/org/repo/issues/` or a database `NOT NULL` check treats `""` as a valid ticket reference and joins every unrelated changelog item together on an empty key. Any field that might legitimately be absent from the input should be explicitly nullable (`z.string().nullable()` in Zod, emitting `type: ["string", "null"]` or `anyOf: [{ type: "string" }, { type: "null" }]`).

### Unsupported and silently ignored JSON Schema keywords

JSON Schema is a massive specification, and constrained-decoding compilers only support a practical subset of it. Many validation keywords are either rejected with a `400 Bad Request` when strict mode is enabled, or silently dropped by gateways and model adapters before compilation.

| JSON Schema feature | Typical strict-mode support | Practical risk if you rely on it | Safe engineering pattern | 
|---|---|---|---|
| `type` ,`properties` ,`required` ,`additionalProperties: false` | Universal | Rejected if `additionalProperties: false` is omitted | Always set `additionalProperties: false` and list all keys in`required` | 
| `enum` and`const` | Universal | Very large enums (hundreds of values) slow grammar compilation | Keep enums compact (under ~30 values); use retrieval or 2-stage classification for large taxonomies | 
| Nullable unions ( `["string", "null"]` or`anyOf` ) | Wide | Some providers prefer `anyOf` over type arrays; avoid`oneOf` | Test your target provider; normalize with a helper | 
| `minimum` ,`maximum` ,`minLength` ,`maxLength` | Partial or ignored | Some engines reject them in strict mode; others ignore them silently | Enforce numeric bounds and string lengths in Zod `safeParse()` after the call | 
| `pattern` (regular expressions) | Partial | Backreferences and lookarounds fail compilation; complex regexes spike latency | Use simple character classes if supported, and always re-validate in app code | 
| `minItems` ,`maxItems` ,`uniqueItems` | Often unsupported | Model can emit 0 items or duplicates even if declared | Check array bounds and deduplicate in application code | 
| Deeply nested recursive `$ref` | Strictly capped | Exceeding provider nesting depth or total property count triggers 400 errors | Flatten deeply nested trees into flat arrays with parent IDs | 

Treat the provider’s JSON Schema as your **wire-shape guardrail** and your local Zod `safeParse()` (plus `.refine()` rules) as your **application invariant checker**. For example, our release-note policy states that `category === 'breaking'` must always pair with `breaking: true`. JSON Schema cannot express cross-field boolean invariants cleanly inside strict mode, whereas a three-line Zod `.superRefine()` catches any contradiction immediately after parsing.

### Overly wide enums and tangled booleans

When a classification schema grows to 20 or 30 overlapping enum categories (`bug`, `bugfix`, `patch`, `security_fix`, `regression`, `hotfix`), accuracy degrades even with strict decoding. Every extra synonym splits probability mass across near-identical tokens.

Split orthogonal questions into separate fields instead of multiplying enum combinations. Rather than an enum with `"breaking_feature"`, `"non_breaking_feature"`, `"breaking_fix"`, `"security_breaking"`, and `"soft_deprecation"`, keep `category` to five mutually exclusive buckets and track `breaking` and `needs_migration` as separate booleans with crisp one-line definitions.

Also include an explicit escape hatch whenever inputs can fall outside your known classes. In an open-world feed where marketing copy or empty merge commits occasionally show up, adding `"other"` or `"unknown"` keeps the model from forcing junk text into `"fix"`.

## Why 100% schema compliance still ships wrong answers

The biggest mistake teams make after turning on `strict: true` is celebrating when JSON parse errors drop to zero and stopping there.

A strict schema enforces the container, not the judgment inside it. In Setup 2 of our benchmark (`gpt-4.1-mini`, strict schema, 0-shot, verdict first), the pipeline achieved **100% valid JSON** and **100% schema compliance** across all 30 release notes. Not a single exception was thrown. Yet **4 out of 30 entries (13.3%) were classified wrong**.

Look at the exact four mistakes Setup 2 made:

1. `"Added deprecation warning when passing a string to createClient(); object options will be required in v4."` Expected:`category: "deprecation", breaking: false, needs_migration: false` .
Got:`category: "deprecation", breaking: false, needs_migration: true` .
2. `"Soft-deprecated XML export adapter; prints warning on startup and will be removed in v5."` Expected:`category: "deprecation", breaking: false, needs_migration: false` .
Got:`category: "deprecation", breaking: false, needs_migration: true` .
3. `"Upgraded devDependency vitest from 2.0 to 2.1 in repo CI."` Expected:`category: "internal", breaking: false, needs_migration: false` .
Got:`category: "fix", breaking: false, needs_migration: false` .
4. `"Rewrote unit test fixtures to avoid hitting live DNS during npm test."` Expected:`category: "internal", breaking: false, needs_migration: false` .
Got:`category: "fix", breaking: false, needs_migration: false` .

Look at the pattern in those four misses. The model was not being careless or random. It made two completely reasonable interpretations that happened to clash with our team’s policy:

- Does a deprecation warning mean `needs_migration: true` ? If your release bot uses`needs_migration` to block automated Dependabot upgrades today, a soft warning for a future major version must be`false` . Without that policy boundary spelled out, the model reasonably thought “users will have to migrate eventually, so`true` .”
- Is fixing flaky unit test fixtures or bumping `vitest` in CI a`fix` or`internal` ? In everyday English, fixing live DNS lookups in tests sounds like a fix. Under a consumer-facing changelog policy, anything that does not ship in the published package belongs in`internal` .

No amount of JSON Schema tightening can resolve those two questions. Both outputs are 100% valid against the schema. This is where clear policy instructions and **boundary few-shot examples** do the heavy lifting.

### Boundary few-shot examples beat easy examples

When people add few-shot examples to a prompt, their first instinct is to pick clean textbook examples: `"Added dark mode"` -> `feature`, `"Fixed crash on startup"` -> `fix`, `"Removed v1 endpoint"` -> `breaking`.

Those examples waste input tokens. Any modern LLM already gets obvious entries right zero-shot.

The most useful few-shot examples live right on the **decision fences** where two categories almost touch:

- A soft deprecation warning that prints a message today and breaks in a future major version (`deprecation` ,`breaking: false` ,`needs_migration: false` ).
- A test-suite or `devDependency` update that uses bug-fix phrasing like “avoid hitting live DNS” or “fixed flaky CI runner” (`internal` , not`fix` ).
- A silent default change like switching cookie `SameSite` from`None` to`Lax` or tightening a default timeout (`breaking: true` ,`needs_migration: true` , even though no function was removed).
- A backwards-compatible security patch (`fix` ,`breaking: false` ,`needs_migration: false` , so the model does not over-trigger`breaking` whenever it sees security keywords).

Notice two critical details about formatting few-shot examples with structured outputs:

1. **Format every example as exact assistant/user turns matching your live JSON Schema.** Putting JSON examples inside a Markdown prose block inside the system prompt works less reliably than passing real`{ role: 'user', content: ... }` and`{ role: 'assistant', content: JSON.stringify(...) }` message pairs. Real message turns match the model’s post-training conversation template and show the exact serialized JSON shape, key order, and null formatting.
2. **Never include an example that violates your own schema.** If you add a new field like`issue_id` to your Zod schema later, update every few-shot example object too. A few-shot example missing a field or using`"N/A"` instead of`null` fights the grammar and pulls the model toward inconsistent behavior.

### The hidden speedup: few-shot examples calibrate output length too

Before running the benchmark, I expected Setup 4 (strict schema + rationale + 4 boundary few-shot examples) to be slightly *slower* than Setup 3 (strict schema + rationale, 0-shot) because Setup 4 sends more input tokens on every call (460 input tokens vs 255).

In practice, the opposite happened: Setup 3 and Setup 4 both hit **100% exact match (30/30)**, yet Setup 4 was **111ms faster at median latency** (827ms vs 938ms) and cut average output tokens from **60 down to 38**, a **37% reduction in generated tokens**.

Why did sending *more* input tokens make the request *faster*?

Because prefill (processing input tokens) runs in parallel across GPU tensor cores, so adding 205 input tokens takes only a few milliseconds, and when the system prompt plus few-shot prefix stays static across calls, provider prompt caching cuts both the prefill time and the input token cost even further. Decoding (generating output tokens) runs strictly one token at a time, so every extra output token adds a full sequential forward pass and bills at 3x to 5x the input token rate.

Without examples, Setup 3 obeyed `"Keep rationale to one short sentence"` loosely and averaged 60 output tokens per call, writing wordier explanations inside `rationale`. In Setup 4, the four boundary examples each had a tight 10-to-14-word rationale. The model immediately matched that length and cadence, dropping output volume from 60 tokens to 38 tokens while keeping 30/30 accuracy.

Few-shot examples do two jobs at once: they pin down your semantic boundaries, and they act as a concrete style ruler that keeps free-text fields like `rationale` short and predictable.

### Static few-shot vs dynamic retrieval-selected few-shot

For a 5-category release-note classifier, 3 to 5 static boundary examples in the prompt are usually the sweet spot. Pushing to 15 or 20 static examples rarely improves accuracy further on a narrow task, burns context tokens, and can dilute attention across conflicting edge cases.

The calculus changes when your taxonomy grows to 30+ categories, hundreds of product SKUs, or complex domain policies where no five examples can cover every boundary. In that regime, **dynamic few-shot selection** works better:

1. Maintain a curated bank of labeled boundary cases (say, 100 to 500 reviewed examples from real production edge cases) stored with embeddings or BM25 keywords.
2. When a new input arrives, retrieve the top 3 to 5 most similar labeled examples from that bank.
3. Inject those retrieved examples into the prompt right before the live user input, keeping the system prompt and JSON Schema identical.

There is a real cost tradeoff to weigh before switching to dynamic few-shot selection. Static few-shot examples live inside the fixed prompt prefix, which means provider prompt caching hits on almost every request after the first one. Dynamic few-shot examples change per request, which invalidates the cached prefix right after the system prompt. Keep static boundary examples whenever 3 to 5 cases cover your policy edges; reach for retrieval-selected examples only when a large taxonomy forces you to pick relevant cases per input.

## Walkthrough of the 150-call benchmark and real failure analysis

To test these mechanics on real data instead of synthetic one-liners, I assembled 30 realistic open-source release-note entries spanning five tricky buckets:

- Explicit and implicit breaking changes (dropped Node.js 18 support, cookie `SameSite` default switched from`None` to`Lax` , SQLite default journal mode switched from`DELETE` to`WAL` requiring manual migration).
- Soft deprecations that log warnings today and schedule removal for a future major release.
- Backwards-compatible bug fixes and security patches (WebSocket memory leaks, header sanitization without API changes).
- New backwards-compatible features.
- Internal repository work that often sounds like a fix (`vitest` devDependency upgrades, test fixture rewrites, CI adjustments).

Every setup ran all 30 entries end-to-end (150 live classification calls total), measuring raw JSON parse rate, schema compliance rate, exact 3-field match (`category`, `breaking`, and `needs_migration` all matching the labeled ground truth), median latency (`p50`), average input tokens, and average output tokens. Separately, 10 entries containing no GitHub issue number ran through the missing-field test comparing required `type: "string"` against nullable `type: ["string", "null"]`.

Here are the full measured results across all five setups:

| Setup | Model | Valid JSON | Valid Schema | Exact Match | p50 Latency | Avg In Tokens | Avg Out Tokens | 
|---|---|---|---|---|---|---|---|
| 1. Prompt-only JSON (0-shot) | `gpt-4.1-mini` | 0% (0/30) | 0% (0/30) | 0% (0/30) | 807ms | 59 | 27 | 
| 2. Strict schema (0-shot, verdict first) | `gpt-4.1-mini` | 100% (30/30) | 100% (30/30) | 86.7% (26/30) | 650ms | 93 | 15 | 
| 3. Strict schema (0-shot, rationale first) | `gpt-4.1-mini` | 100% (30/30) | 100% (30/30) | 100% (30/30) | 938ms | 255 | 60 | 
| 4. Strict schema + rationale + 4-shot | `gpt-4.1-mini` | 100% (30/30) | 100% (30/30) | 100% (30/30) | 827ms | 460 | 38 | 
| 5. Strict + rationale + 4-shot | `gpt-6-luna` | 96.7% (29/30) | 96.7% (29/30) | 96.7% (29/30) | 1408ms | 454 | 69 | 

Plotting schema validity next to exact semantic accuracy makes the gap obvious at a glance:

Four concrete lessons jump straight out of the raw logs.

### 1. Prompt-only JSON fails at both layers

In Setup 1, raw `JSON.parse()` failed on all 30 entries because `gpt-4.1-mini` wrapped every response in ```` ``` json ... ``` ````. That alone took 27 average output tokens (nearly double Setup 2’s 15 tokens) and slowed median latency to 807ms compared to Setup 2’s 650ms. Strict JSON Schema decoding was actually **faster and cheaper on output tokens** than prompt-only JSON because the grammar blocked the Markdown fence tokens, indentation whitespace, and extra newlines.

Even if you had stripped the Markdown fences in Setup 1, the payload inside still missed subtle breaking changes (calling the `SameSite=None` to `Lax` default change a non-breaking `feature`) and flagged soft deprecations as `needs_migration: true`.

### 2. Strict schema alone fixes syntax, not policy

Setup 2 was the fastest configuration overall at 650ms p50 and 15 average output tokens, with 30/30 valid JSON and 30/30 valid schema. If you only monitored parse exceptions in production, Setup 2 would look completely healthy while misrouting 13.3% of your changelog entries (every soft deprecation and every internal CI/test entry in the sample).

### 3. Rationale-first plus 4 boundary shots hits the production sweet spot

Adding the written policy and moving `rationale` ahead of the classification fields in Setup 3 eliminated all four errors (30/30 exact match), at the cost of jumping from 15 to 60 average output tokens and 650ms to 938ms p50 latency.

Adding four compact boundary few-shot examples in Setup 4 kept the exact same 30/30 accuracy while pulling output tokens down from 60 to 38 (-37%) and cutting p50 latency from 938ms to 827ms. At typical API pricing where output tokens cost 4x input tokens and static prefixes get cached at a steep discount, Setup 4 beats Setup 3 on both speed and unit economics once you run more than a handful of requests.

### 4. Strict mode on a different model still needs runtime guards

Look at Setup 5 (`gpt-6-luna`, strict schema + rationale + 4-shot). It classified 29 out of 30 entries accurately, at 1408ms p50 and 69 average output tokens. The single miss was striking:

- Entry: `"Default SQLite journal mode changed from DELETE to WAL on new databases; existing files require manual PRAGMA or migration."`
- Expected: `{ "category": "breaking", "breaking": true, "needs_migration": true }`
- Raw output received: `""` (empty string)

Even with `strict: true` enabled on the API request, one call out of 30 came back as an empty content string! That happens in real production systems when a model spends its completion budget on internal reasoning tokens, trips an upstream content or stop condition, or returns an incomplete response before emitting the opening `{`.

That single failure out of 150 calls is worth its weight in gold as a reminder: strict structured outputs make malformed JSON rare, yet your production client still has to guard against empty strings, `finish_reason === 'length'`, refusals, and retries.

## Production validation, error handling, and eval loops

Once your schema and boundary examples work on 30 entries, the next job is keeping them working six months later when prompts get edited, models rotate, or new kinds of inputs arrive.

Start by separating the request pipeline into crisp deterministic stages. Your application code should never assume a 200 HTTP status means you have a usable object.

Notice the final box before committing state: **deterministic business rules**. Even after `Zod.safeParse()` succeeds, put cross-field checks and action gates in ordinary code. For example, if a classifier returns `category: 'breaking'` alongside `breaking: false`, reject it as an inconsistent prediction and route it for review (or enforce that rule directly inside a Zod `.superRefine()`).

Here is how you can enforce cross-field invariants right inside the Zod schema so inconsistent combinations never sneak past validation:

``` js
export const CheckedReleaseNote = ReleaseNoteClassification.superRefine((value, ctx) => {
  if (value.category === 'breaking' && !value.breaking) {
    ctx.addIssue({
      code: 'custom',
      path: ['breaking'],
      message: 'Entries categorized as breaking must set breaking to true',
    })
  }

  if (value.category === 'internal' && (value.breaking || value.needs_migration)) {
    ctx.addIssue({
      code: 'custom',
      path: ['category'],
      message: 'Internal repo changes cannot be breaking or require migration',
    })
  }
})
```

Next, build a tiny regression harness around a checked-in `evals.jsonl` file. Every time a user or reviewer spots a misclassified record in production, append that exact raw input and its corrected expected JSON to your eval file.

Keep one ironclad rule as your eval set grows: **never put your test cases into your few-shot prompt**. Maintain two separate files: `few-shot-examples.json` (your 3 to 5 crisp boundary examples that ship in the prompt) and `held-out-evals.jsonl` (30 to 200 real labeled inputs that the prompt never sees). Whenever you tweak a field description, upgrade a model from `gpt-4.1-mini` to a newer snapshot, or try a cheaper model, run the held-out eval script and compare four numbers before deploying:

- **Parse and schema rate:** Should sit at 99.5% to 100%, with every empty or truncated call logged separately so you see whether`max_tokens` needs headroom.
- **Exact match rate:** The share of entries where every single field matches ground truth.
- **High-cost field recall:** In release-note triage, missing a real`breaking: true` change causes an outage, whereas calling a test refactor`fix` instead of`internal` is mildly annoying. Track recall on your highest-stakes fields separately from overall exact match.
- **Output tokens and p50/p95 latency:** A model swap that improves accuracy by 1% while doubling p95 latency and tripling output tokens might be a bad trade if a smaller model with one better boundary example hits the same mark.

If you want to retry a failed `safeParse()` or `superRefine()` call automatically, cap it at **one repair retry**, passing the exact Zod error message back to the model in a follow-up user turn (`"Your previous JSON failed validation: Entries categorized as breaking must set breaking to true. Return corrected JSON."`). If the single retry still fails, stop retrying and drop the item into a dead-letter or human-review queue. Unbounded repair loops burn tokens on genuinely ambiguous inputs that no retry will fix.

## How I would use it

If I were wiring a structured extraction or triage pipeline into one of my own apps today, here is the exact progression I would follow.

I would start with a single call to a fast, inexpensive model (`gpt-4.1-mini` class) using strict JSON Schema decoding generated from a Zod schema. I would put a short one-sentence `rationale` field first, make every potentially absent field explicitly nullable (`type: ["string", "null"]`), write a crisp 5-to-10-line policy in the system prompt, and include 3 to 5 boundary few-shot examples as real user/assistant message pairs. That exact setup (Setup 4 in our benchmark) hit 30/30 exact match at 827ms median latency and 38 average output tokens, with a static prefix that caches cleanly across requests.

For most developer tools and SaaS workflows, such as release-note triage, invoice or receipt metadata extraction, tagging user feedback, or normalizing messy webhook payloads where the model is already reading the text, that single pass is enough. Keeping everything in one typed call avoids extra network hops and keeps maintenance low.

I would add a **second verification pass** only when a wrong label triggers an irreversible or expensive action, like automatically blocking a production deploy pipeline, issuing a refund, or sending an automated compliance notice. In that case, I would first check whether a deterministic rule can catch the risk (for example, flagging any changelog entry mentioning `DROP`, `minimum`, or `default` for review if the model said `breaking: false`). If deterministic checks aren’t enough, a second pass with a stronger model or an independent prompt can audit only the high-stakes slice rather than doubling latency on every request.

There are also clear cases where I would skip LLM structured outputs altogether:

- **High-volume narrow routing with calibrated probabilities.** If an app needs to classify hundreds of thousands of short messages a day into a small fixed set of buckets and act differently on 0.95 confidence versus 0.55 uncertainty, a dedicated decision model or a small fine-tuned classifier is faster, cheaper, and gives real probability distributions instead of generated confidence guesses. I compared that tradeoff in detail in[Jev vs structured outputs](https://flaviocopes.com/jev-structured-outputs/) .
- **Strict sub-50ms latency budgets.** Constrained decoding over an HTTP LLM API sits in the hundreds of milliseconds to low seconds (650ms to 1,408ms p50 in our runs). Real-time autocomplete, inline request middleware, or high-frequency fraud scoring belongs in local heuristics, SQL, or a small specialized model.
- **Deterministic structured inputs.** Never send a Git diff header, HTML table, CSV export, or log line with a fixed syntax to an LLM just to pull out JSON fields. A 20-line parser or AST walker is free, instant, and 100% reproducible.
- **Long-form creative writing.** Cramming multi-paragraph prose, tone-sensitive replies, or exploratory brainstorming into rigid nested JSON schemas degrades writing quality because the model spends capacity juggling escaping and structure. When you need both prose and metadata, keep the schema flat (one`body` string and a couple of small metadata fields), or generate the prose freely and run a cheap structured extractor on top.

Schema-constrained decoding gets your JSON into the right shape. Field order, nullable types, runtime checks on refusals and empty responses, and a handful of sharp boundary examples are what turn that clean JSON into data your application can actually rely on.

Want me to talk about your product? You can [sponsor this site](https://flaviocopes.com/sponsor/).
