Skip to content
AI.info

Generative AI

Structured Outputs and Constrained Generation

Design schema-constrained generation pipelines that distinguish syntax, semantic validity, completeness, and downstream safety.

By the end you can

Comparison

Four validity layers must be checked independently

Passing one layer does not mean passing the next. The gap opens at the very first one, and the JSON standard documents it.

RFC 8259, the specification of JSON, published in December 2017, says the names in an object SHOULD be unique. Then it says what follows when they are not: “An object whose names are all unique is interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings. When the names within an object are not unique, the behavior of software that receives such an object is unpredictable.”

Unpredictable how? The same section lists the divergence in the field. Many implementations report only the last name/value pair. Others report an error, or fail to parse the object at all. Some report all of the duplicates, the repeats included. An object that carries the same name twice is fully valid JSON, accepted by the parser, and worth three different meanings to three different receivers.

That is the syntactic layer failing on its own terms. Nobody has yet asked about schema conformance, evidence or authorization.

FigureComparison · 4 columns

Syntactic validity

The output can be parsed as JSON or another target format.

  • Quotes and delimiters are valid
  • Parser accepts the document
  • No guarantee about required fields
  • No guarantee about meaning

Schema conformance

Fields, types, enums, and nesting match the declared schema.

  • Supports deterministic integration
  • Can constrain decoding or validate afterward
  • May still contain invented values
  • Does not establish completeness

Semantic validity

Values agree with source evidence and field definitions.

  • Requires grounding or domain checks
  • Dates and units must be interpreted correctly
  • Contradictions need handling
  • Often requires tools or review

Business validity

The object satisfies current permissions, policies, and workflow invariants.

  • Authorization remains external
  • Cross-field rules may apply
  • Consequences determine review
  • Valid data can still be unsafe to execute

Constrained decoding prunes invalid continuations

A schema-aware generator can restrict token choices so the output stays compatible with a grammar or a type definition. That reduces formatting errors and simplifies parsing downstream. It cannot tell whether a value is present in the source, current, or authorized. The model can produce a perfectly shaped falsehood.

That sentence has been measured, by Geng and colleagues in 2023. Constituency parsing, Penn Treebank, eight shots: an input-dependent grammar raised LLaMA-33B's parse-tree validity from 64.2% to 100.0%. Every single output was a well-formed tree. Bracketing F1 rose only from 42.9 to 54.6, against the supervised parsers the paper lists at 92.1–95.7 (Kitaev and Klein 95.6, Zhang et al. 95.7). Total structural success. Roughly half the linguistic content wrong.

Their own summary says as much: “In conclusion, GCD substantially improves the performance of LLMs on constituency parsing, but performance still falls short of the F1-scores achieved by supervised methods (95% and above).”

The vendors say the same thing about their own products. OpenAI's Structured Outputs guide says of its own coverage that “While Structured Outputs supports much of JSON Schema, some features are unavailable either for performance or technical reasons”, and it warns, where it handles edge cases: “The model will always try to adhere to the provided schema, which can result in hallucinations if the input is completely unrelated to the schema.” The constraint is a pressure to fill the fields. It is not a source of the values that fill them.

Structure controls the language of possible outputs; it does not validate the world described by those outputs.

Case

A public draft standard, and decoding held to a grammar

The grammar side of this is standardised. The standard is a public draft — strictly, an expired one.

The dialect that structured-output tooling targets is 2020-12, and it exists only as IETF Internet-Drafts. draft-bhutton-json-schema-00, "JSON Schema: A Media Type for Describing JSON Documents", is dated 8 December 2020 and expired on 11 June 2021. Its successor, draft-bhutton-json-schema-01, is dated 10 June 2022 and expired on 12 December 2022. The JSON Schema project dates the corresponding "Draft 2020-12" release 16 June 2022. Neither draft ever became an RFC.

The document's own Status of This Memo tells you not to lean on it: “Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress."”

A production integration layer is built on a document that expired five years ago and forbids being cited as anything but work in progress.

Held to a grammar, decoding nevertheless earns its place, and the size of the gain is on record. Closed information extraction, SynthIE-text-small, four shots: LLaMA-33B scored 17.5 micro-F1 unconstrained (14.1 precision / 23.1 recall) and 36.0 constrained (39.3 / 33.2). That overtook GenIE T5-base — the supervised, task-specific model — at 34.8 F1 (49.6 / 26.8). The abstract claims the pattern: “Our results indicate that grammar-constrained LMs substantially outperform unconstrained LMs or even beat task-specific finetuned models.”

Doubling F1 without finetuning is a real result. And 36.0 is still 36.0. Shape is guaranteed by construction. Content is not.

Example

A useful schema represents uncertainty instead of hiding it

Fields should capture what the workflow needs to know, including absence and evidence status. So should the order they are declared in, which is a semantic decision rather than a matter of taste.

Format restriction has been measured on GSM8K. Adding an explicit schema to a JSON prompt cut claude-3-haiku from 86.99% to 23.44% accuracy, and gpt-3.5-turbo from 74.70% to 49.25%. For gpt-4o-mini-2024-07-18, natural language scored 94.57%, against 86.95% in JSON-mode and 91.71% under JSON-Schema.

On the Last Letter Concatenation task, Tam and colleagues traced the shortfall to key order. 100% of GPT-3.5-Turbo JSON-mode responses placed the "answer" key before the "reason" key. Zero-shot chain-of-thought had quietly become zero-shot direct answering. Their finding: “However in reasoning related task, JSON-mode failed to adhere to the order of reasoning first followed by answer causing a large drop in final performance.”

OpenAI's guide confirms the mechanism is structural: “outputs will be produced in the same order as the ordering of keys in the schema”. Whoever writes the schema decides where the reasoning happens. A sixty-point accuracy drop can be entirely a consequence of which field was listed first.

  • Nullable fact: Distinguish “not present” from an empty string or a guessed value. This is often forced rather than chosen. OpenAI's Structured Outputs requires that every field be marked required, so optionality has to be emulated with a union type with null; Azure's documentation of the same feature shows the worked ["string", "null"] example and also requires additionalProperties: false.
  • Evidence pointer: Store source ID, span, page, timestamp, or tool result linked to the field, so a value can be checked against the document rather than trusted because it parsed.
  • Validation state: Record whether a value is proposed, verified, rejected, or requires review. Put the reasoning field before the conclusion field, since the model answers in the order you declared.
  • Units and timezone: Keep numerical interpretation explicit rather than embedded in prose, and keep it in your own validator. Azure's list of keywords unsupported by structured outputs includes minLength, maxLength, pattern, format, minimum, maximum, multipleOf, patternProperties, unevaluatedProperties, propertyNames, minProperties, maxProperties, unevaluatedItems, contains, minContains, maxContains, minItems, maxItems and uniqueItems, which OpenAI's current page scopes to fine-tuned models only.
  • Schema version: Preserve compatibility and explain how older records were produced, including which subset of the dialect they were generated under. The composition keywords allOf, not, dependentRequired, dependentSchemas, if, then and else are excluded from OpenAI's subset, so cross-field logic lives in application code and moves between releases.

Visual

A structured-generation pipeline still needs several gates

Treat model output as a candidate object. Treat the generator as an engine with declared limits, not as a guarantee.

JSONSchemaBench, released in January 2025, put numbers on those limits: 10,000 real-world JSON schemas plus the official JSON Schema Test Suite, run against six constrained-decoding engines. On the GitHub-Easy split, OpenAI's structured-output API declared support for only 30% of the schemas and Gemini for 8%, against 90% for Guidance. On GitHub-Medium OpenAI fell to 13%. Among the schemas they did accept, compliance was 0.97 and 0.88. Geng and colleagues read that as a deliberate trade: “While closed-source implementations have low empirical coverage, they have very high compliance rates, indicating that their providers have taken a more conservative strategy, implementing only a subset of JSON Schema features that they can reliably support.”

So the "Generate under constraints" gate may simply decline most of the schemas you actually hold. Acceptance is not conformance either. On the test suite, XGrammar was under-constrained — it accepted instances it should have rejected — in 38 feature categories, against 1 for Guidance.

"Parse and validate" is not redundant with the generator. It is the only step that has read your schema, rather than the subset of it the engine implements.

FigureProcess · 6 steps
  1. 1

    Define the schema

    Specify fields, types, allowed values, and uncertainty representation.

  2. 2

    Generate under constraints

    Use schema-aware output or a tightly specified format.

  3. 3

    Parse and validate

    Reject malformed or nonconforming objects deterministically.

  4. 4

    Check semantics

    Compare values with sources, tools, calculations, and cross-field rules.

  5. 5

    Authorize consequences

    Apply current identity, policy, limits, and confirmation.

  6. 6

    Record and monitor

    Store traces, schema version, failures, repairs, and downstream outcomes.

Key idea

Automatic repair can conceal a model failure

A parser or a second model can often repair malformed JSON. Silent repair makes the pipeline look reliable while it changes fields or invents defaults the original output never supplied. A repairer that quietly keeps the last of two duplicate names is making exactly the undocumented choice RFC 8259 warns about — only now inside your own pipeline, under your own logo. Repairs should be deterministic where possible, logged, and evaluated separately. High-risk fields should trigger regeneration, clarification, or review rather than invisible patching.

A repaired object needs provenance showing what the model produced and what the application changed.

Steps

Design a safe extraction object

Choose a source-dependent task and make missing evidence explicit. Design the field order deliberately: reasoning before conclusion. Then test against the two failure modes this lesson measured. A document that parses perfectly and means different things to different parsers. An output that is 100.0% well-formed while its content scores 54.6.

FigureProcess · 6 steps
  1. 1. Define each field

    Write its meaning, type, unit, and allowed absence.

  2. 2. Add evidence fields

    Link claims to spans, documents, or tool results.

  3. 3. Express uncertainty

    Use status and reason codes rather than fabricated defaults.

  4. 4. Add cross-field rules

    Validate dates, totals, identities, and logical dependencies.

  5. 5. Separate authorization

    Keep execution permissions outside the generated object.

  6. 6. Test malformed and plausible errors

    Include both syntax failures and well-shaped false values.

Structured generation creates a clean software boundary

Schemas make model output easier to parse, test, log, and route. Designed carefully, they also show which fields may be absent and what evidence stands behind each one. What they do not do is settle anything about the world. The constraint that produced 100.0% valid parse trees produced 54.6 bracketing F1 in the same run, and OpenAI's own guide warns that forcing adherence to a schema can itself induce fabrication.

The next lesson uses structured arguments for tool calls. Once generated data can cause an external action, authorization and idempotency become central.

Key takeaways