All posts

LLM structured output in production: how to get reliable JSON without a retry loop eating your budget

LLM structured output guarantees valid JSON, not correct JSON. What schema-constrained decoding does and doesn't cover, the failure modes left over, and a validation layer that holds up in production.

CodeKrypt 6 min read

Your product needs a model's answer to land in a database column, an API call or a workflow step. That means JSON your code can trust. LLM structured output features now make that far easier than the prompt-and-pray era, but they solve a narrower problem than most teams assume. This post covers what they guarantee, what they quietly don't, and the validation layer that closes the gap.

What does LLM structured output actually guarantee?

There are three levels, and teams often mix them up.

ApproachValid JSON?Matches your schema?Correct values?
Prompt only ("reply in JSON")UsuallySometimesNot guaranteed
JSON modeYesNoNot guaranteed
Schema-constrained structured outputsYesYes, for supported schemasNot guaranteed

OpenAI's structured outputs guide is explicit that both JSON mode and Structured Outputs ensure valid JSON, but "only Structured Outputs ensure schema adherence", and it recommends using them over JSON mode when possible. Anthropic's structured outputs docs describe the same idea: constrain the response to a schema, either as a JSON output format or as strict tool use.

The last column is the important one. A schema constrains shape. It cannot know that an invoice total should equal the sum of its line items, or that a date should not be in the past. That part is still your job.

When does structured output still fail?

Three documented cases, all of which return a normal-looking response.

1. Refusals. Anthropic's docs say a refusal comes back with stop_reason: "refusal" and a 200 status, you are billed for the tokens, and "the output might not match your schema because the refusal message takes precedence over schema constraints." OpenAI similarly says a refusal does not necessarily follow the schema and exposes a refusal field to check.

2. Truncation. If the model hits the token limit, the output can be cut off. Anthropic's docs say that with stop_reason: "max_tokens" the output "might be incomplete and not match your schema". OpenAI's guide shows the same check against an incomplete status.

3. Schema features the provider doesn't support. Both providers accept a subset of JSON Schema. Anthropic lists recursive schemas, numerical constraints such as minimum and maximum, string constraints such as minLength, and additionalProperties other than false as unsupported, and an unsupported feature returns a 400 error. So a constraint you wrote in the schema may not be enforced by the decoder at all.

The practical rule: read the stop reason before you parse. A 200 is not a success signal.

Why a valid object can still be wrong

Schema-valid output fails in ways that look fine to a parser:

This is the same gap that sits behind most agent failures in production: the output looks right, so nothing flags it.

What schema design makes failures less likely?

Design the schema for the model as well as for your database.

What does a production validation layer look like?

A reliable pipeline has four steps after the model call:

  1. Check the stop reason. Branch on refusal, truncation and normal completion before touching the payload.
  2. Parse and validate against the schema locally. Zod in TypeScript or Pydantic in Python. Anthropic's SDK helpers do this: they can transform schemas that use unsupported features and then enforce the original constraints locally.
  3. Run business-rule checks. Totals add up, dates are plausible, IDs exist in your system, enum values are in your allowed set.
  4. Route failures by type. This is where cost control happens.
FailureRight responseWrong response
Truncated outputRetry once with a higher token limitRetry with the same limit
RefusalSurface to a human or a fallback pathLoop retries
Schema violation (unsupported constraint)Fix the schema or validate locallyRetry the same call
Business-rule violationRetry once, passing the specific error backRetry with no feedback
Repeated failureQueue for human reviewRetry forever

Every retry is a full paid call, so unbounded loops show up directly in your bill. If you are already working on spend, the same discipline applies as in reducing LLM API costs: cap attempts, and measure.

What should you measure?

Track these separately from overall error rate:

These feed naturally into an evaluation framework: keep a fixed set of real inputs with expected outputs, and re-run it whenever you change a model, prompt or schema. If you route between providers, remember that schema support differs between them, as covered in LLM API fallback for outages and rate limits. A fallback model needs the same validation layer, and possibly a schema it supports.

What should you do next?

  1. Switch from prompt-only or JSON mode to schema-constrained structured outputs on every path where code consumes the result.
  2. Read the stop reason before parsing, and handle refusal and truncation explicitly.
  3. Add local validation with Zod or Pydantic, plus business-rule checks the schema can't express.
  4. Make "unknown" a valid value in your schema.
  5. Cap retries, route failures by type, and log every failure with its category.
  6. Build a small regression set from real inputs before your next prompt or model change.

If you are building an AI product where model output feeds billing, records or customer-facing workflows, this validation layer is part of the architecture, not an afterthought. Our AI SaaS page covers how we approach it.

CodeKrypt avatar

CodeKrypt

Drafted by CodeKrypt's AI writing pipeline, built and maintained by our engineers, under fixed rules on sources and claims. How we write

Frequently asked questions

What is the difference between JSON mode and structured outputs?
JSON mode guarantees the response is valid JSON. Structured outputs additionally enforce your schema, so required fields and types are present. OpenAI's guide states that only Structured Outputs ensure schema adherence and recommends them over JSON mode where possible.
Does structured output guarantee the data is correct?
No. It guarantees shape, not truth. A model can return a perfectly valid object with a wrong amount, a wrong date or an invented value. You still need validation against your own business rules.
When can structured output still fail to match the schema?
When the model refuses, or when it hits the token limit mid-response. Both OpenAI and Anthropic document these cases, and both return a normal-looking response, so check the stop reason before parsing.
Should I still retry on failure?
Yes, but narrowly. Retry on truncation with a higher token limit, and on semantic validation failures with the error fed back to the model. Do not blindly retry refusals.

Related reading

Chat on WhatsApp