Structured Outputs in Production, How to Get JSON Your Code Can Trust

Diagram of prompt only output against schema constrained output, missing fields and drifting types on one side, guaranteed fields and types on the other

A support inbox holds 400 tickets on a Monday morning. Your script asks a model to sort each one into billing, technical or account, and to pull out the order number. By ticket 30 the replies stop matching the shape your code expects.

One answer wraps the JSON in code fences. One returns the priority as the word high instead of a number. One drops the order number field entirely. The model was asked to guess a shape, and guessing is what it did.

Structured outputs let you hand an LLM a JSON Schema with your request, and the API then constrains generation so the reply matches that schema. Required fields arrive, types hold, and enum values stay legal. You still handle refusals and cut-off replies in code, but the shape of a completed answer is guaranteed.

If your team is wiring a model into a product and the parsing layer keeps growing, our AI chatbot development team builds these flows schema-first, so the data your code receives is a contract from day one.

What structured output is, and what it is not

Structured output is a reply whose shape is fixed before generation starts. You declare the shape as a JSON Schema, a description of which keys exist, what type each value takes, which values an enum allows and which fields are required. The API enforces that description while the model writes.

It is not a formatting instruction inside a prompt. A prompt asks the model to behave, and the model can drift on a long or unusual input. It is also not the same as JSON mode, which only promises that the reply parses as JSON. Parsing is the floor, not the contract.

ApproachValid JSONMatches your schemaRetry logic needed
Prompt onlyUsually, not alwaysNoYes, forever
JSON modeYes, unless cut offNoSometimes
Schema constrainedYes, unless cut off or refusedYesOnly for refusals and limits

The boundary matters because code treats the three rows very differently. Prompt-only output needs a defensive parser for the life of the product. Schema-constrained output needs a validator and a refusal check, a much smaller surface.

How constrained decoding enforces the schema

The guarantee behind structured outputs is constrained decoding. A model writes one token at a time, choosing from a probability spread over its whole vocabulary. Constrained decoding puts a grammar engine between that spread and the choice the model makes.

Before generation, the provider compiles your schema into a grammar. At each step the engine works out which tokens keep the reply inside the grammar and masks out every token that would break it. The model picks only from what remains, so a malformed reply is never a candidate.

Anthropic describes its implementation in exactly these terms, a compiled grammar that limits sampling to valid tokens. OpenAI documents the same promise from the other side, schema adherence for completed replies. On open models the grammar work is usually done by XGrammar, the default backend in vLLM since version 0.7.0, as the DevToolLab guide records.

The three surfaces that return structured data

Every major API offers the same idea through three surfaces, and picking the wrong one is a common first error. The first is the response format, where the schema shapes the answer the user sees. In the OpenAI Responses API it sits under text.format with type json_schema and strict set to true. In the Anthropic Messages API it sits under output_config.format.

The second surface is the tool call. Each tool declares an input schema, and strict mode holds the arguments to it, set with strict to true on the function or tool definition. The third surface is JSON mode, the older flag that forces valid JSON and nothing more.

OpenAI states the rule of thumb in its own guide. Connect the model to tools and data with function calling. Structure how the model responds to the user with the response format.

Picking the right surface for the job

The decision turns on one question. Who consumes the JSON, a screen or a system.

If the JSON feedsUseWhy
A screen or a stored recordResponse formatThe answer itself is the product, so its shape is the contract
A system that acts on itStrict tool callsYour code executes the arguments, so they must be right
An older model with no schema supportJSON mode plus validationIt is the only option, so the validator carries the load

Teams often need both surfaces at once. An agent can call tools with strict arguments while it works and still return its answer through a response format, in a single request.

Diagram of the three surfaces, response format, strict tool calls and JSON mode, with the guarantee each one gives

One portable schema that passes all three APIs

The schema below is written to the intersection of the three big APIs. It classifies a support ticket, and every keyword in it is one all three providers enforce. The example is fictional, a help desk that exists only on this page, and you can copy it as a starting point.

{
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "category": {
      "type": "string",
      "enum": ["billing", "technical", "account"]
    },
    "priority": {
      "type": "integer",
      "enum": [1, 2, 3]
    },
    "order_number": {
      "type": ["string", "null"]
    },
    "summary": {
      "type": "string"
    },
    "needs_human": {
      "type": "boolean"
    }
  },
  "required": ["category", "priority", "order_number", "summary", "needs_human"]
}

Three choices in this schema do the heavy lifting. Every field is required, which OpenAI strict mode demands. The one field that can be empty, order_number, takes a null union instead of going optional. And additionalProperties is false, so no provider can invent a key your code has never seen.

The keyword intersection across OpenAI, Claude and Gemini

Providers accept different slices of JSON Schema, and the differences are where portable schemas go to die. The matrix below is drawn from the official documentation of each provider, as compared by Metarix and 9io in November 2026.

Keyword or ruleOpenAIClaudeGemini
Every field in requiredDemandedOptional allowed, cappedOptional allowed
minimum and maximumEnforcedRejected with a 400 errorEnforced
minLength and maxLengthNot in the supported listRejected with a 400 errorAccepted, then ignored
Recursive schemasSupportedNot supportedSupported
Enum value casingEnforced as writtenNot guaranteedEnforced as written

The dangerous rows are the quiet ones. A schema that Gemini accepts can still return a two-character summary, because the length limit you wrote was dropped without an error. Anything a provider ignores has to be checked again in your own code.

Diagram of the safe keyword set shared by OpenAI, Claude and Gemini, the keywords to check per provider, and the ones to leave out

OpenAI rules that break schemas in production

OpenAI strict mode pairs the widest supported keyword set with the strictest shape rules. The root of the schema must be an object. Every object must set additionalProperties to false, including nested ones. Every field must appear in required, so optional data travels as a null union.

The published size limits are generous. A schema may hold up to 5,000 object properties, 10 levels of nesting and 1,000 enum values across all enum properties, figures from the OpenAI documentation, read 24 November 2026. Most production schemas come nowhere near those ceilings.

Two behaviours catch teams out. The first request with a new schema carries extra latency while the API processes it, later requests do not. And a safety refusal arrives outside the schema, in its own field, so code that never checks for one will try to parse the refusal text as data.

Claude rules that break schemas in production

Anthropic made its structured output feature generally available on 4 February 2026, the last of the big three to ship it natively, a date the DevToolLab guide records from the Anthropic documentation. It runs on the Messages API for JSON replies and on tool definitions for strict tool use.

The grammar caps are the tightest of the three. One request may hold 20 strict tools, 24 optional parameters and 16 parameters with union types. Numeric bounds and string length limits return a 400 error. Recursive schemas are not supported.

Compilation is the other cost. Anthropic compiles each schema into a grammar under a 180-second timeout, then caches it for 24 hours from last use. A schema that changes on every request pays that compile again and again, so keep schemas stable.

Gemini rules that break schemas in production

Google exposes schema-shaped replies through responseMimeType and responseJsonSchema on generateContent, and through the response format on the newer Interactions API. Its keyword support is the loosest of the three.

The trap is silence. Gemini accepts minLength, maxLength and uniqueItems, then ignores them, as the Google documentation itself lists. A schema can pass every request and still let through values your code assumed were impossible.

The working rule for Gemini is plain. Treat the schema as a shape guarantee only, and run every length, range and uniqueness rule again in your validator.

What a schema cannot promise

A completed, non-refused reply matches the schema. That sentence carries three conditions, and each one is a failure mode your code has to own.

FailureWhat you receiveThe check that catches it
RefusalA refusal instead of the objectRead the refusal field or stop reason first
TruncationJSON cut off at the token limitCheck the finish reason before parsing
Valid shape, wrong valuesA legal enum on the wrong ticketValidate business rules after parsing

The third row is the one teams forget. A schema can promise that priority is 1, 2 or 3. It cannot promise the model picked the right one, or check a total against an invoice. OpenAI states this plainly, applications still need to validate rules a schema cannot express.

Validate anyway, the checks your code still owns

The wrapper around a structured call has four steps, none of them optional in production. Parse the reply. Validate it against the same schema on your side. Run the business rules the schema cannot hold. Then route each failure by type instead of retrying blindly.

Routing matters because the failures have different cures. A refusal should never be retried as it stands, the request has to change or a human takes the ticket. A truncation wants a higher token limit. A business-rule failure wants one more call with the error fed back, capped at a single retry so a bad input cannot loop.

This wrapper is small, usually under a hundred lines, and it is the difference between a demo and a system. Teams scoping an AI feature can cost it as part of the first build, the way we set out in our guide to building an AI MVP for a startup.

A worked example, ticket triage from prompt to parsed object

Take the Monday inbox again, now with the schema from earlier in place. The example is fictional, a composite of the triage flows our team builds, with numbers invented for this page.

The ticket says the customer was charged twice for March, with no order reference on the second charge. The model returns the object below, through the response format, with strict mode on.

{
  "category": "billing",
  "priority": 2,
  "order_number": null,
  "summary": "Customer reports a duplicate March charge with no order reference on the second charge.",
  "needs_human": true
}

Every field the code needs is present and typed. The order number is null because the customer never gave one, which the null union allows and the validator accepts. The summary stays prose, so a human reads it before any refund moves.

The cost and latency math of doing this right

The money argument rests on retries. With prompt-only output, every malformed reply costs a second call. The worked figures here are illustrative, built on round numbers so you can swap in your own.

Say a pipeline sorts 10,000 tickets a day and 8 in every 100 prompt-only replies fail validation. That is 800 retries a day. At an illustrative 900 tokens per retry, the pipeline burns 720,000 tokens a day, about 21.6 million tokens a month, on answers it already paid for.

Schema-constrained calls remove the format failures from that bill. What remains is the refusal and truncation rate, which for most internal pipelines runs far below the format failure rate. The limit on this maths is that your failure rate is yours, so measure it for a week before quoting the saving.

Where the model runs changes the bill again. Our vLLM vs TGI benchmarks compare the two main open inference servers on throughput and latency, the maths that decides whether self-hosting pays.

Structured output on models you host yourself

Open weights models can play the same game. vLLM takes a structured_outputs block holding a JSON schema, a regex, a choice list or a grammar. Ollama takes a schema in its format field. Both run grammar-constrained decoding locally, with XGrammar doing the masking in most stacks.

The trade is operational. A hosted API compiles and caches grammars for you. A self-hosted stack gives the same shape guarantee with no per-call API bill, and hands you version pinning, grammar bugs and capacity planning instead.

Mistakes that still ship broken JSON

These are the errors our team sees most when a structured pipeline reaches production and fails in ways the demo never showed.

  • Trusting the schema and deleting the validator, then learning that a truncated reply parses as nothing at all
  • Marking fields optional on OpenAI and reading the 400 error as a model failure
  • Putting numeric bounds in a Claude schema, which the API rejects before the model ever runs
  • Writing length limits for Gemini and never checking them in code, because the API never checks them either
  • Changing the schema on every request and paying the grammar compile cost on every call
  • Comparing enum values case-sensitively on Claude, whose documentation warns the casing is not guaranteed

Every item here passes a demo. Each one fails on real inputs, which is why the checklist follows.

The readiness checklist before production

Before a schema-shaped feature ships, walk this list once with the code open.

  • The schema sits in version control and changes by pull request, not by prompt edit
  • Every field is required, with null unions where a value can be absent
  • The wrapper checks the refusal field and the finish reason before it parses
  • Business rules run after validation, with one capped retry
  • Enum comparisons are case-insensitive where the provider asks for it
  • A week of failure rates is logged, split by refusal, truncation and rule failure

How Denebly builds schema-first AI features

At Denebly, a schema is where an AI feature stops being a demo. Our chatbot and automation builds start from the data contract, the exact object each workflow consumes, and the prompt is written last, around the schema.

The build order is fixed. Define the schema with the client, wire the wrapper with its refusal and truncation checks, then tune the model against a week of real inputs. A first build typically runs two to four weeks.

If your feature lives or dies on machine-readable answers, our AI automation services team can scope the schema and the wrapper with you. Or start with a conversation about your project, and we will tell you plainly whether a schema is the right tool.

Frequently asked questions

What are structured outputs

A way of calling an LLM where you attach a JSON Schema to the request and the API constrains the reply to match it. Required fields, types and enum values are enforced during generation, not requested in the prompt and hoped for.

What is the difference between JSON mode and a schema-constrained reply

JSON mode guarantees that a reply parses as JSON. It does not guarantee your fields, your types or your enum values. A schema-constrained reply guarantees the shape as well, for completed replies that were not refused.

Which API should a small team start with

Start where your stack already lives. OpenAI has the widest documented schema subset, Claude the tightest grammar caps, and Gemini needs the most validation in your own code. All three enforce a plain schema of types, required fields and enums.

Can one schema serve OpenAI, Claude and Gemini at the same time

Yes, if you write to the intersection. Keep every field required, use null unions for empty values, set additionalProperties to false, and leave out numeric bounds and length limits. Check anything outside that set in your own validator.

What still breaks even with a schema in place

Three things. A safety refusal arrives outside the schema. A reply cut off at the token limit arrives incomplete. And a reply can match the schema perfectly while holding the wrong values, which only business-rule validation catches.

Do structured replies cost more than plain replies

The call is priced like any other call on the same model. The saving sits in the retries you stop making, and the cost sits in schema processing on the first request with a new schema. Stable schemas keep that cost near zero.

Sources

  • OpenAI, developer documentation, the structured output guide and the supported schemas pages, schema limits and refusal handling, read 24 November 2026.
  • Anthropic, developer documentation, JSON outputs, strict tool use, grammar caps and caching, read 24 November 2026.
  • Google, Gemini structured output documentation, supported keywords and the constraints it lists as ignored, read 24 November 2026.
  • JSON Schema, the specification and vocabulary pages, the neutral standard each provider subset is drawn from. JSON Schema specification
  • Posix AI, competitor explainer on OpenAI and Claude schema guarantees, read in full on 24 November 2026.
  • DevToolLab, LLM structured output guide, 2026, read 24 November 2026.
  • Metarix and 9io, provider comparison guides, November 2026, read 24 November 2026.
Arslan Mushtaq, Founder of Denebly

WRITTEN BY

Arslan Mushtaq

Founder, Denebly

Arslan founded Denebly in 2018 and leads its AI development work for startups and mid-size businesses, across AI chatbots, agentic workflows, RAG systems, machine learning and automation. Denebly has delivered 100+ projects from Dallas, Texas.

Connect on LinkedIn More about Arslan

Ready to Solve Your Business Problems With AI?

Tell us what you are trying to build, automate or fix. You will get an honest assessment within one business day, not a sales pitch.

Custom AI development for startups and growing businesses. Chatbots, agents, machine learning and automation that deliver measurable results.

sales@denebly.com
Dallas, Texas, USA

Get Started Free Consultation AI Readiness Audit Pricing Response within 24 hours You own the code & data