← All writing

LLM engineering· March 29, 2026 · 11 min

Structured Outputs Without Tears: Schemas, Retries, and Recovery

Getting JSON out of an LLM is easy at toy scale and ruinous at production scale. The fix is not a better prompt; it is a worse schema.

Three Eras, One Problem

Every team that ships LLM features rediscovers the same arc.

  1. Prompt-and-pray — "respond in JSON." Works most of the time. Fails on the worst possible inputs.
  2. JSON mode — provider-side guarantee that the output parses. Doesn't guarantee it matches your schema.
  3. Constrained decoding — provider masks the logits so only schema-valid tokens can be sampled. Output is correct by construction, but you pay for it.

Most production systems I've seen are still in era 1, sometimes with a Zod parser bolted on, sometimes not. They run fine until they don't.

Why "Respond in JSON" Still Works (And Why That's a Trap)

A modern model, prompted with a clear schema and a couple of examples, will produce valid JSON on something like 95% of inputs. That number is good enough to demo, good enough to ship the MVP, and exactly bad enough to be a load-bearing problem at scale.

5% failure means at 1M calls a day, you have 50,000 broken responses. Most of them are interesting in production-incident ways: a trailing comma, a markdown fence, a missing closing brace, an unprompted "Here is the JSON you requested:" preamble, an unescaped quote inside a string field.

The 5% is also adversarial-shaped. Failures cluster on the inputs that matter: long inputs, ambiguous inputs, inputs containing JSON-looking strings the model wants to echo. The thing that fails is the thing you most needed to work.

How Constrained Decoding Actually Works

Constrained decoding sounds magical until you look at it. It is not magical. It is a finite-state machine over the schema, applied to the model's logits at every step.

At each token, the decoder asks: given the JSON I've emitted so far, which tokens are legal next? It builds a mask over the vocabulary — 1 for legal tokens, 0 for everything else — multiplies the logits by the mask (or adds -inf to the masked positions), then samples. The model literally cannot emit invalid JSON because the invalid tokens have zero probability.

This is what's under the hood of Claude's tool use, OpenAI's structured outputs, Outlines, and the schema mode in Instructor. The implementations differ in how the grammar is compiled and cached, but the principle is the same.

The cost is real:

  • First-token latency goes up 10-30% for complex schemas. The grammar has to be compiled before sampling can start.
  • Throughput drops on high-QPS endpoints because the mask computation is not free.
  • Schema complexity matters more than you think. A deeply nested schema with unions can blow up the FSM state space.

For most production paths, the latency cost is worth it. Stop debugging unparseable JSON in your error logs.

Schemas the Model Actually Gets Right

Constrained decoding will give you syntactically valid output. It will not give you semantically correct output. Those are different things, and the schema design controls both.

What the model handles well:

  • Shallow, flat objects.
  • Required fields with defaults.
  • Enums with a handful of lowercase string options.
  • Arrays of a single type.

What the model handles badly:

  • Deeply nested arrays of unions. The model loses track of which branch it's in.
  • Optional fields. The model omits them unpredictably, usually when you most wanted them.
  • Numeric fields with implicit semantics. ("Score 0 to 100" — you'll get 0.8.)
  • Free-form additionalProperties: true. The model invents fields you didn't ask for.

A rule that has paid off across multiple projects: if your schema is more than two levels deep, flatten it. Trade a slightly more annoying parsing step for an output the model can produce reliably.

The Discriminated Union Trap

This is the most common bug I review.

You define a union like Action = Refund | Cancel | Reschedule. Each variant has different required fields. The model, helpfully, produces something like:

{
  "type": "refund",
  "amount": 49.99,
  "reason": "duplicate charge",
  "new_date": "2026-04-12"   // why is this here
}

new_date belongs to Reschedule. The model mixed variants because the schema let it. Constrained decoding usually catches this — but only if you actually use a discriminator.

The fix:

const ActionSchema = z.discriminatedUnion('type', [
  z.object({
    type: z.literal('refund'),
    amount: z.number(),
    reason: z.string(),
  }),
  z.object({
    type: z.literal('cancel'),
    reason: z.string(),
  }),
  z.object({
    type: z.literal('reschedule'),
    new_date: z.string().datetime(),
  }),
])

Three rules that compound: use a literal type field. Use lowercase strings. Make type the first field in the JSON ordering. The model leans heavily on the first field to commit to a variant, and then the constrained decoder forbids the wrong sibling fields.

Recovery: Send the Validation Error Back

Even with constrained decoding, you'll have validation errors at the Zod layer — semantic ones the FSM can't catch. (amount is negative. new_date is in the past. Enum value was right syntactically but wrong contextually.)

The pattern that works is treating Zod errors as a feedback signal, not an exception:

async function callWithRetry<T extends z.ZodTypeAny>(
  prompt: string,
  schema: T,
  maxRetries = 2,
): Promise<z.infer<T>> {
  const messages: Message[] = [{ role: 'user', content: prompt }]

  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    const raw = await llm.complete({ messages, schema })
    const parsed = schema.safeParse(raw)

    if (parsed.success) return parsed.data

    messages.push({ role: 'assistant', content: JSON.stringify(raw) })
    messages.push({
      role: 'user',
      content:
        'Your previous response failed validation:\n' +
        parsed.error.issues.map(i => `- ${i.path.join('.')}: ${i.message}`).join('\n') +
        '\nReturn a corrected response.',
    })
  }

  throw new Error('schema validation failed after retries')
}

Two things matter. Pass the structured Zod issues, not the stringified error blob — the model parses path: message more reliably than a stack trace. Cap retries at 2 or 3. If it didn't fix it by then, it's not going to, and you're burning tokens.

Streaming Is Harder Than It Looks

Everyone wants streamed structured outputs for the UX. The problem: you cannot validate a JSON object until the closing brace arrives. Until then, every prefix is technically incomplete.

The naive approach — buffer until the stream ends, then parse — defeats the point of streaming. The working approach is a partial JSON parser that knows how to close open structures and emit a best-effort object on every chunk.

json5, partial-json, and json-stream all do versions of this. The shape of the API:

import { parse } from 'partial-json'

let buffer = ''
for await (const chunk of stream) {
  buffer += chunk
  try {
    const partial = parse(buffer, Allow.ALL)
    render(partial)  // partial may have undefined leaves
  } catch {
    // not yet parseable, keep buffering
  }
}

The renderer has to tolerate fields being undefined and arrays being shorter than their final length. Build the UI around that constraint from the start. Retrofitting streaming into a UI that assumed complete objects is more painful than rewriting from scratch.

Function Call vs. JSON Field: When to Pick Which

There are two ways to get structured data out of a modern model.

MechanismWhen it winsCost
Tool/function callThe output is an action with parameters. Provider does the constraining. Most reliable.Burns prompt budget on tool definitions. Heavier in token count.
JSON in a response fieldThe output is data, not an action. Lighter on prompt budget.Slightly less reliable, especially for unions. Needs JSON mode or explicit grammar.

My default: tool calls for anything the agent will do something with (route a ticket, file a refund, schedule a job). JSON fields for anything the agent is returning to the user (a classification, a summary, a list).

If you need both — a tool call where the tool's result is itself structured — define both, separately. Don't try to smuggle data through tool arguments. The model will get confused about whether the tool call is a real action or just a return-value transport.

Optional Fields Are Evil for LLMs

This deserves its own section because it's the trap I see most often.

You define a schema where notes is optional. You expect: filled in when relevant, omitted otherwise. What you get: omitted ~70% of the time, including when it would have been useful, because the model has no clear signal about when "relevant" is.

Make it required. Give it a sentinel:

const Schema = z.object({
  category: z.enum(['billing', 'technical', 'account']),
  priority: z.enum(['p0', 'p1', 'p2', 'p3']).default('p2'),
  notes: z.string().default(''),    // required, defaults to empty
  needs_human: z.boolean().default(false),
})

notes: "" carries the same semantic load as omitting the field and lets your downstream code stop checking if (output.notes !== undefined) everywhere. The model also fills the field more often when it has to put something there — usually with useful text, occasionally with "", almost never with garbage.

A Concrete Example: classify_ticket

Putting it together. A real classifier I've shipped variants of:

import { z } from 'zod'
import Anthropic from '@anthropic-ai/sdk'

const ClassifyTicket = z.object({
  category: z.enum(['billing', 'technical', 'account', 'other']),
  priority: z.enum(['p0', 'p1', 'p2', 'p3']),
  sentiment: z.enum(['angry', 'frustrated', 'neutral', 'positive']),
  needs_human: z.boolean(),
  reason: z.string().min(10).max(200),
})

const tool = {
  name: 'classify_ticket',
  description: 'Classify a support ticket along four axes.',
  input_schema: {
    type: 'object',
    properties: {
      category: { type: 'string', enum: ['billing', 'technical', 'account', 'other'] },
      priority: { type: 'string', enum: ['p0', 'p1', 'p2', 'p3'] },
      sentiment: { type: 'string', enum: ['angry', 'frustrated', 'neutral', 'positive'] },
      needs_human: { type: 'boolean' },
      reason: { type: 'string', minLength: 10, maxLength: 200 },
    },
    required: ['category', 'priority', 'sentiment', 'needs_human', 'reason'],
  },
}

async function classify(ticket: string) {
  const client = new Anthropic()
  const res = await client.messages.create({
    model: 'claude-opus-4-7',
    max_tokens: 1024,
    tools: [tool],
    tool_choice: { type: 'tool', name: 'classify_ticket' },
    messages: [{ role: 'user', content: ticket }],
  })

  const block = res.content.find(b => b.type === 'tool_use')
  if (!block || block.type !== 'tool_use') throw new Error('no tool call')

  return ClassifyTicket.parse(block.input)
}

The Zod schema is the source of truth. The tool's input_schema is derived from it (in real code, via zod-to-json-schema). The provider does the constrained decoding. Zod re-validates on receipt — belt and suspenders, because the provider's idea of "valid against schema" occasionally drifts from yours, particularly around string length bounds.

What Didn't Work

The first time I built this kind of classifier, I tried to be efficient. One schema, one call, returns the classification and a follow-up action and a draft reply. Three things at once, nested.

The classification fields were fine. The draft reply was usually fine. The follow-up action — a discriminated union over five possible actions — was wrong about 20% of the time. Wrong variant, wrong fields, occasionally an action for a ticket that didn't warrant any action at all.

The fix was unglamorous: split into two calls. First call classifies. Second call, conditional on the classification, generates the action with a much smaller schema scoped to that category. Total latency went up by ~40%. Error rate on the action dropped from 20% to under 2%.

Lesson: schema complexity has superlinear cost to model accuracy. Two simple schemas beat one elegant one almost every time.

A Sharper Takeaway

The model isn't bad at structured output. Your schema is bad at being produced. Flatten it, require everything, use a discriminator, validate twice, and recover from errors by sending the errors back. Get the schema right and the model will get the data right.