GOAT EngineerPreparing your learning space…

AI Engineering · Concept Library · Free article

Structured Outputs

Structured outputs make a model return data that matches a schema you defined, by blocking every off-schema token before it can be sampled. Every major provider ships that guarantee now. What none of them promise is that the values inside the perfect shape are right.

An LLM emits text, so when you need machine-readable data, an intent, a refund amount, a priority, you're asking a plausibility engine to produce something a parser will accept, which it has no built-in reason to do. There's a ladder of techniques ending in constrained decoding, which masks any off-schema token before sampling and so guarantees the structure; every major provider ships it now. But guaranteeing the shape is not guaranteeing the answer: a model will hand you flawlessly-formatted, dangerously wrong values. The engineering is a schema to enforce structure, a second layer to check meaning, and a bounded loop to recover what slips through.

Wrenlet's drafter writes replies for humans to approve. But you want to do more: automatically tag each ticket with an intent, pull out any refund amount, set a priority, and flag whether it needs a human. That means the model cannot just write prose: it has to return data your code can read: { "intent": "refund", "refund_amount": 50, "priority": "normal", "needs_human": false }. So you add “respond in JSON” to the prompt, wire up JSON.parse, and ship.

It works most of the time, which is exactly the problem. Roughly one ticket in seven comes back as something JSON.parse will not take, and another one in eight parses cleanly into the wrong shape, so about a quarter of the queue is mis-routed or stuck. The model wrapped the JSON in a markdown code fence. Or opened with “Sure! Here's the JSON:”. Or added a trailing comma, or used single quotes, or wrote $50 instead of 50, or invented a reason field you never asked for. Each of these is a production incident waiting to happen: a ticket that silently fails to route. To fix it for real, you have to understand why a language model is bad at this by default, and what actually makes it reliable.

Prompt, JSON mode, tool calling or strict mode: which one guarantees your schema?

Only the last two. A prompt asking for JSON guarantees nothing, and JSON mode guarantees only that the bytes parse, so both can hand you the wrong fields and the wrong types. A forced tool call with strict mode on, and constrained decoding against your schema, are the same mechanism underneath and are the only rungs that make off-schema output impossible. There are four levels of reliability, and knowing which one you're on is most of the skill.

Each rung buys a stronger guarantee
ApproachWhat it doesWhat it guarantees
Prompt and parseAsk for JSON in the prompt; parse and catch errors.Nothing. Works most of the time, fails unpredictably: the markdown fences and preambles above.
JSON modeA provider flag that forces syntactically valid JSON.It will parse. It does not have to match your schema, so you can still get the wrong fields or types.
Function / tool callingDefine a tool whose parameters are a JSON Schema; force the model to “call” it.The arguments conform to the schema (guaranteed once strict mode is on). This is literally how providers implement structured output.
Constrained decoding (strict)Compile the schema to a grammar and enforce it token-by-token during generation.The output physically cannot leave the schema. This is the only real structural guarantee.

Climb the rungs and watch the failure rate collapse, the same batch of extractions, scored at each level.

The failure rates here are illustrative. They are picked so each failure mode shows up in a handful of tickets instead of a thousand, and the real rate for your model against your schema is something only your own logs can tell you. What transfers is which failures each rung removes, and which one it leaves standing:

The interactive version of this example is available when JavaScript loads.

How does constrained decoding guarantee valid JSON?

How can anything force a probabilistic model to stay valid? The trick is to constrain it at the only place that matters: the moment it picks each token. Compile your schema into a grammar, a little state machine that knows, at every point in the output, which characters are legal next. (After "refund_amount": the grammar knows the next thing must be a number or null, so a quoted string or a bare word like about is not available to it.) At each generation step, you look at the grammar's current state, build the set of legal next tokens, and set the probability of every illegal token to zero before sampling. The model draws only from what's allowed.

That's the whole idea, and it's powerful: the output cannot wander off-schema, because the off-schema tokens were never on the table. Play one decision point below, the model is about to write the refund amount. Flip the constraint on and off and sample:

The interactive version of this example is available when JavaScript loads.

Tool calling is structured output

If you've done function/tool calling, you have already done structured output. You just called it something else. A tool definition is a name plus a JSON Schema for its arguments. When you force the model to call that tool, it must produce arguments that fit the schema, which is exactly a structured output. The everyday idiom is “extraction via a single forced tool”: define one tool whose schema is the object you want, force it, and the arguments the model returns are your parsed data. You never even run a function.

The interactive version of this example is available when JavaScript loads.

The trap: a valid shape is not a correct answer

Here is the mistake that constrained decoding invites: relief. The JSON always parses now, the schema always matches, the green light is on, so you trust it. But structure and truth are two different guarantees, and you only bought the first one. A constrained model will hand you { "refund_amount": 500 } for a $50 charge without blinking, perfectly formatted, schema-valid, and about to refund ten times too much. The grammar forced the shape. It has nothing to say about the value.

This is the single most important idea on this page. Every output below is 100% schema-valid, the badge never wavers, and some of them would do real damage. Click through them:

The interactive version of this example is available when JavaScript loads.

Validation is three layers, not one

“Did it validate?” is really three questions stacked, and each one catches a different class of failure. The first two you get almost free from a schema library (Pydantic, Zod); the third is yours to write.

Three validity classes, each needs its own check
LayerQuestionExample failure it catches
ParseIs it valid JSON at all?Model wrapped the object in a code fence and a sentence, JSON.parse throws.
StructuralDoes it match the schema, fields, types, enums?priority: "urgent!" when the enum is low | normal | high; refund_amount as a string.
SemanticAre the values actually right for this context?refund_amount: 999999 on a $40 order; an order_id that doesn’t exist; a refund tagged billing_question.

When it breaks: repair or reask?

Even with strict mode you'll recover from failures, a truncated object, a semantic rule that rejected a value, a model without strict mode at all. You have two moves, and they cost very different amounts.

Two recoveries, two bills
MoveHow it worksCostFixes
RepairDeterministically fix the bytes, strip the markdown fence, close a dangling brace, coerce "50" to 50.Nearly free; no model call.Structural damage only. It can’t recover a wrong or missing value.
ReaskFeed the validation error back to the model and let it try again.A full extra generation, more tokens, more latency, and it can loop.Structural AND semantic errors: the model can add the field it forgot. But it might fail again.

Watch how each move plays out, and where each dead-ends:

The interactive version of this example is available when JavaScript loads.

So the rule of thumb is simple. If the bytes are just messy, a stray code fence, a cut-off tail, a "50" that should be 50, repair them; it costs nothing. If the model got the content wrong, reask it and let it think again. When one reask isn't enough, climb one rung at a time: reask with the error attached, then reask with more context, then throw the attempt out and regenerate fresh (maybe a little hotter, or on a different model), and if it still won't come out right, stop and hand it to a human. Two rules keep this from spiralling. First, constrain from the start whenever you can, so most breaks never happen at all. Second, cap the retries: an uncapped reask loop is its own outage. Stop at two or three; if you routinely need more, the schema or the model is the problem, not your loop. (A library like Instructor automates exactly this: validate the object, and on failure re-ask with the error appended, up to a set limit.)

It helps to see the whole pipeline, because the two paths are fixed by different actors. Walk one broken output through, stage by stage, on each path: notice who catches the error, who decides it's repairable, and who actually applies the fix, your own deterministic code on the repair path, versus the model re-prompted with its own mistake on the reask path.

The interactive version of this example is available when JavaScript loads.

Does forcing structured output make the model worse?

On reasoning-heavy tasks it can, and the evidence is genuinely contested. There's a subtle cost to clamping the output into a rigid shape. If you force the model to start emitting schema tokens immediately, you deny it the room to think. For a plain extraction that's fine, there's nothing to reason about. But for a task that needs working-through, “read this thread, decide if it's actually a billing dispute or a cancellation, and set the priority”, making it commit to a structured field before it has reasoned can lower accuracy. One well-known 2024 study, “Let Me Speak Freely?” by Tam and colleagues, reported real drops on reasoning-heavy tasks under tight formatting.

It's genuinely contested. A rebuttal from the Outlines team argued the hit was mostly a prompt mismatch rather than the constraint itself, and under matched prompting structured generation held its own or won. A 2025 benchmark, JSONSchemaBench, found a small gain under constraints, though you have to read past the abstract for it. So the honest summary is it depends on the task, the model, and how you prompt it. But the move that wins under either reading is the same: let it reason first, then extract. Give the model a free-text scratchpad (or a reasoning field the schema fills first), let it think, then run a tight, constrained extraction over that reasoning. You keep open-generation quality and a guaranteed schema instead of trading one for the other.

Can you stream a structured output?

The tokens stream, and a validated object does not exist until the last one lands. The reliability you gain from structure collides with the responsiveness you gain from streaming. Because every prefix of a JSON object is invalid until it closes, you can't hand your code a guaranteed-valid object mid-stream: a validated result only exists at the final token. There are three honest patterns, and you pick by who's consuming the output:

How teams reconcile the two

  • Stream, then validate at the end. Simplest and safest: let the tokens stream for latency, but only parse and schema-check once the object closes. The consumer is code that needs a whole, valid object.
  • Partial / best-effort parsing. A tolerant parser closes open braces and quotes so a UI can fill fields as they arrive (a live form populating field by field). The catch: those intermediate objects are unvalidated and still mutating, fine to render, dangerous to act on.
  • Stream a list, validate each item as it closes. When the output is a collection, emit and validate each element the moment its } arrives, you get progressive delivery and a validated object per item.

Constrained decoding composes with all three: the tokens still stream, and because masking guarantees the object conforms as far as it gets, the retry loop shrinks to one case: the reply that was cut off at the token limit. You just can't fully validate mid-flight, partial JSON is still partial. Decide per call which you're optimizing: a streamed answer for a human, or structured data for a machine.

The tools you’ll actually reach for

Two shelves: the providers' built-in modes, and the libraries that wrap or replace them. The split that matters is whether you can touch the model's logits. Hosted APIs do the masking for you; over an open model you bring your own engine.

Provider modes and libraries, honestly
ToolWhat it isReach for it when
OpenAI Structured Outputsjson_schema + strict: true (and per-tool strict), constrained decoding on a JSON-Schema subset.You’re on OpenAI and want a hard schema guarantee, not just JSON mode.
Anthropic strict tool use / output_configGrammar-constrained tool inputs (strict: true) and Structured Outputs (output_config.format).You’re on Claude and need the arguments or final object schema-guaranteed.
Google Gemini responseSchemaresponseMimeType: "application/json" + responseSchema (an OpenAPI-3.0 subset).You’re on Gemini; note it keeps function-calling and responseSchema as separate paths.
InstructorPydantic/Zod extraction that patches the client, adds a response_model, and does the validate-and-reask loop.You want typed data + automatic bounded retries over a hosted API.
Outlines / XGrammar / llguidanceConstrained-decoding engines (FSM / pushdown grammar) that mask logits directly.You run open models (vLLM/SGLang/local) and need the guarantee yourself.
Pydantic / ZodSchema definition + structural and (via validators/refinements) semantic validation.Always: this is the substrate the rest build on.
BAMLA DSL whose parser coerces messy model output to your schema instead of constraining generation.Open/local models without native strict mode, or to avoid provider lock-in.

The four calls, and what each one is for

Four minimal shapes cover almost everything you'll write. Field names are accurate to each provider.

Structured output, four ways

  • OpenAI, ask for the schema, strict. Write your object as a schema class (a RefundRequest in Pydantic or Zod) and make the call with strict mode turned on (response_format → a json_schema with strict: true). You get a ready-to-use, typed object back on message.parsed. One thing to handle first: if the model refused on safety grounds, that refusal isn’t shaped like your object, so check message.refusal and branch before you read the data.
  • Anthropic, force one tool, read its input. Define a single tool whose input is your object, and force the model to call it (tool_choice: { type: "tool", name: "record_refund_request" }, plus disable_parallel_tool_use: true so you get exactly one). Its answer comes back with your object already filled in and already parsed, read it straight off the tool_use block’s input; no JSON.parse needed.
  • No strict mode? Validate, then ask again. Check the output against your schema (Schema.safeParse(raw)). If it fails, tell the model exactly what was wrong, append the errors as a short corrective turn (“your last output failed validation: … return only valid JSON”), and let it retry. Cap it at a few tries; after that, stop and hand off to a human. Never loop forever.
  • Add the one rule a schema can’t express. The schema promises refund_amount is a number; it can’t promise the number is sane. Add a single check, “a refund can’t exceed the order total”, as a Zod .refine(v => v.refund_amount <= v.order_total, …) or a Pydantic @model_validator. That one line is the only thing standing between you and a refund ten times too big.

How do you measure structured-output reliability?

With four numbers rather than one: parse success, schema conformance, semantic correctness, and the average retries per successful result. A dashboard that shows only the first will happily hide a real regression, because the first two are the ones constrained decoding pins near perfect while the third is free to fall.

The metrics that matter

  • Parse success rate, does it yield valid JSON at all? Unenforced prompting fails a meaningful slice (roughly ~5 to 15%, model- and schema-dependent); JSON mode or strict decoding drives parse failure to near-zero.
  • Schema-conformance rate, does it match your schema? JSON mode still mismatches a meaningful slice, often low double digits; strict/native constrained decoding pins this near 100%.
  • Semantic-correctness rate, are the values right? The number that actually matters and the hardest to get: it needs rules or an LLM judge, and it can sit far below your schema-conformance rate.
  • Retry rate, average retries per successful result. Healthy is well under one; a rising average (past ~2) means the model or schema is wrong, not the loop.

What still goes wrong, and the habit that answers it

Two of these are genuinely outside what a schema can promise, and they are the ones worth memorising: a reply that ran out of tokens, and a refusal, which is not shaped like your object at all.

Each row is a failure strict mode leaves you, and the habit that covers it
What still happensWhat to do about it
Truncation. The object was valid so far, then hit the token limit and stopped mid-value. Valid-so-far is not complete.Read the finish reason before you parse, and treat a truncated response as its own outcome rather than a parse error to retry blindly.
A refusal. The model declines on safety grounds, and that answer does not fit your object.Handle it as its own branch. OpenAI exposes a refusal field precisely so you do not have to force it into a string field.
A schema-valid value that is wrong. The right shape, the wrong enum member, or a refund of $500 against a $50 charge.A semantic layer in the same place you parse, every time: business rules, cross-field invariants, allow-lists. The schema guarantees the shape and nothing else.
Judgement compressed out of the answer, because the first token had to be schema.Reason first, then extract. Give the model a free-text scratchpad or a first reasoning field, then run the tight extraction over it.
An unbounded recovery loop, quietly costing more than the failure did.Repair the cheap structural breaks for free, reask the meaningful ones with the error fed back, cap retries at two or three, and hand over to a human on exhaustion.
A request that will not run, because your schema used a keyword the provider does not enforce.Design to the enforced subset: no extra fields, every field required with optionality expressed as nullable, and every other check in your own layer.
A green dashboard over a wrong answer, because it measured validity.Put a semantic-correctness metric beside parse rate and schema conformance, or the constraint tax and the valid-but-wrong values have nowhere to show up.

Interview cheat-sheet, intern to principal

Why does an LLM return invalid JSON if you just ask for JSON in the prompt?
Because it samples plausible tokens and nothing in that process enforces JSON grammar, validity is a learned tendency, not a guarantee. So you get markdown fences, prose preambles, trailing commas, wrong types, and extra fields. And mid-generation, every partial state is invalid anyway; validity only (maybe) appears at the last token.
What is the difference between JSON mode and constrained/structured outputs?
JSON mode guarantees the output parses as JSON, syntactic validity, but not that it matches your schema; you can still get missing fields, wrong types, or extra keys. Constrained (strict) decoding compiles your schema to a grammar and masks off-schema tokens during generation, so the output cannot leave the schema. One guarantees syntax; the other guarantees your contract.
How does constrained decoding actually guarantee valid structure?
It compiles the schema into a grammar/state machine that knows the legal next tokens at each point in the output, and because JSON nests arbitrarily, that machine needs a stack (a pushdown automaton), not just a flat FSM. Before sampling each token, it sets the probability of every illegal token to zero and renormalizes, so the model can only draw a legal one. Off-schema output is impossible because those tokens were never available.
How is tool/function calling related to structured output?
They're the same mechanism. A tool definition is a name plus a JSON Schema for its arguments; forcing the model to call it makes it emit arguments that fit the schema: a structured output. “Extraction via a single forced tool” is the common idiom, and per-tool strict mode uses the very same constrained-decoding engine as response-format structured outputs. The only gotcha is unwrapping: Anthropic's input is a parsed object, OpenAI's arguments is a JSON string.
A structured output is 100% schema-valid. Can you trust it?
Only for its shape. Valid ≠ correct: a constrained model will happily emit a well-formed but wrong value, a hallucinated refund amount, the wrong intent, a non-existent ID. The schema guarantees parseability; correctness needs a separate semantic layer (business rules, cross-field invariants, allow-lists) and often review. Schema-valid is the floor, not the finish line.
Walk me through your validation architecture for structured output.
Three layers: parse (is it JSON?), structural (does it match the schema, fields, types, enums?), and semantic (are the values right for this context, in range, referentially valid, the correct enum?). A schema library gives you parse + structural almost free; the semantic layer is custom (validators, rules, a DB lookup, or an LLM judge). On failure, a bounded recovery loop: repair cheap byte damage, reask meaningful errors with the error fed back, cap retries, escalate to a human.
The JSON came back broken and you have no strict mode. Repair or reask?
Repair for cheap structural damage (strip fences, close braces, coerce obvious types), a near-free deterministic fix that only touches bytes, not meaning. Reask when the content is wrong and the model needs to reconsider: a full extra call that can fix semantics but costs tokens/latency and can loop, so always cap it. Best of all, constrain from the start so most failures never occur.
When can forcing structured output hurt quality, and what do you do about it?
On reasoning-heavy tasks, forcing the model to emit schema tokens before it has worked through the problem can lower accuracy, the “Let Me Speak Freely?” finding, though it's contested (a rebuttal pinned much of it on prompt mismatch, and other benchmarks show a small gain). The robust fix under either reading is reason-first-then-extract: let the model think in free text (or a first scratchpad field), then run a tight constrained extraction over that reasoning.
Why do multi-step LLM systems need strict outputs more than single calls?
Because per-step reliability compounds: a 95%-valid step chained ten times is 0.95¹⁰ ≈ 60% end-to-end. Parse-and-pray is survivable for one call and a coin-flip for a pipeline. A near-100% structural guarantee per step is what keeps a long chain or an agent from breaking somewhere in the middle.
How would you measure structured-output reliability in production?
Three numbers, not one: parse success rate, schema-conformance rate, and, the one that matters most and hides the easiest, semantic-correctness rate (via rules or a judge), plus the average retry rate as a health signal. The trap is that constrained decoding can show 100% validity while value accuracy drops (the constraint tax), so a dashboard that only tracks validity will miss real regressions.

By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.