Real Studios

Structured LLM Outputs: DCCD, XGrammar and StructEval for AI Engineers

Structured LLM outputs editorial title card

Reliable structured output from LLMs comes from two proven approaches: schema-constrained generation, which masks illegal tokens at each decoding step, and draft-then-constrain methods, which draft freely before enforcing structure. Structured outputs are text or data formats that a program can parse without manual correction: JSON, XML, SQL, or code. This guide covers the benchmarks, research and implementation patterns that separate genuine syntactic guarantees from prompting tricks that often reduce errors without guarantees.


TL;DR:

  • Schema enforcement features in provider APIs guarantee both syntax and schema conformance, reducing manual validation and parsing bugs.
  • Constrained decoding offers a true guarantee of well-formed outputs but incurs higher computational costs and potential semantic distortion.
  • Draft-then-constrain approaches improve semantic accuracy by separating reasoning from formatting, significantly boosting structured correctness on benchmarks.
  • Regular validation, logging failure rates, and testing prompt and model updates prevent schema drift and production errors.
  • Start with provider-managed enforcement and only move to self-hosted solutions when specific, measurable issues justify the added complexity.

Table of Contents

Why structured outputs matter for software pipelines and agentic systems

A single malformed field breaks a pipeline. When an LLM returns a JSON object with a trailing comma, a missing bracket, or a string where a number belongs; the parser throws an exception and the workflow stops. In agentic systems, this failure compounds: a tool call with the wrong argument type does not just fail once, it can cascade through a chain of dependent calls, corrupt state, or trigger a retry loop that burns tokens and latency.

Syntactic validity and semantic correctness are separate problems, and conflating them is a common source of production bugs. A JSON object can be perfectly well-formed and still contain the wrong customer ID, an impossible date, or a category that does not exist in your lookup table. Guaranteeing structure solves parsing; it does not solve correctness.

The consequences show up across common integration points:

  • Function calls: an agent invoking a tool with a malformed argument object causes a runtime error rather than a graceful fallback.
  • Config files: generated YAML or JSON configuration with an invalid key breaks deployment scripts silently until runtime.
  • UI code: LLM-generated HTML or SVG that is not renderable fails to display, with no clear error message for the end user.
  • Data extraction: a structured extraction from an invoice or contract that drops a required field corrupts downstream reporting.

Each of these failure modes has a different tolerance for error. A chatbot that occasionally returns malformed markdown is an annoyance. An automation that writes directly to a database or triggers a payment is a different category of risk, and the cost of a single bad output can outweigh months of otherwise correct runs. This is why teams building agentic or automation-heavy systems increasingly treat structured output reliability as a design requirement, not an afterthought bolted on after a prototype works.

Common approaches: prompting, provider features and tool calling

Most teams start with prompting, and for good reason: it costs nothing extra to try. Asking a model to "respond only in valid JSON matching this schema" reduces malformed output significantly, particularly with larger, well-instruction-tuned models. But prompting alone gives no guarantee. The model can drift, add commentary before the JSON block, or produce a field type mismatch, and there is no mechanism forcing it to comply. Prompting is a first line of defence, not a contract.

Provider SDKs raise the bar considerably. OpenAI's response_format with a JSON Schema and Anthropic's tool_use both integrate schema enforcement directly into the API contract rather than leaving it to instruction-following. These features can guarantee schema conformance at the API level and typically ship with parsing helpers that return validated objects rather than raw strings, which removes an entire class of manual parsing bugs from application code.

Function or tool calling is the dominant pattern for action-driven agents. Rather than asking the model to describe what it wants to do in prose, you define a set of callable functions with typed arguments, and the model selects one and populates the arguments against that schema. This pattern separates reasoning (choosing what to do) from execution (calling code with validated inputs), which is a cleaner boundary than trying to parse intent out of free text.

JSON mode is worth distinguishing from full schema enforcement. Many providers offer a simple flag that guarantees syntactically valid JSON without guaranteeing it matches any particular schema. That is enough for a use case where you just need parseable output and will validate structure yourself. It is not enough when downstream code assumes specific fields exist with specific types.

  • Prompting only: fastest to implement, no guarantees, best for low-stakes or human-reviewed outputs.
  • JSON mode: guarantees valid JSON syntax, not schema conformance.
  • Schema-enforced response formats: guarantees both syntax and schema, the strongest provider-managed option.
  • Tool/function calling: best for agents that need to take typed actions rather than return typed data.

One well-documented finding: draft-then-constrain decoding raised a 1B model's strict structured accuracy on a maths benchmark from 15.24% to 39.0% when a JSON constraint was applied, according to the Draft-Conditioned Constrained Decoding paper. That gap between constrained and unconstrained baselines is the practical argument for moving past prompting alone once correctness matters.

Choosing between these options is largely a question of how much control you need versus how much you are willing to build. Provider-managed schema enforcement covers the majority of production cases without any custom decoding infrastructure. Self-hosted or highly specific grammars, covered next, exist for the cases that provider features cannot express.

Constrained decoding and grammar-driven generation explained

Constrained decoding works by intervening at the token level, before a token is ever sampled. At each generation step, the decoder computes which tokens would keep the output valid against a grammar, sets the logits of every illegal token to negative infinity, and renormalises the remaining probability mass before sampling. The model can only ever choose a token that keeps the output well-formed, which is why this approach offers a genuine guarantee rather than a strong tendency.

Illustration of grammar filtering generated tokens

The grammars themselves borrow directly from formal language theory. Context-free grammars (CFGs) can express nested structures like JSON objects and arrays. Finite-state automata handle simpler, flatter formats such as enumerations or fixed-pattern strings. Pushdown automata, which track a stack, are what make nested and recursive structures like deeply nested JSON tractable to constrain, since they can remember how many brackets are still open.

The cost of this guarantee is computational. Recomputing which tokens are legal at every single decoding step, potentially across a vocabulary of over 100,000 tokens, is expensive if done naively. Doing this on CPU while the GPU sits idle waiting for the mask, or vice versa, introduces latency that can dominate total generation time for short outputs. This is the orchestration problem that recent grammar engines exist to solve.

There is also a subtler cost: distortion. Forcing a model down a narrow set of legal tokens at every step can push it toward technically valid but semantically awkward completions, particularly when the constraint is very tight relative to what the model would naturally produce. A model constrained to fill a numeric field might satisfy the type requirement with a plausible-looking but wrong number, because the constraint controls form, not content.

ApproachGuaranteeTypical cost
Prompting onlyNoneNegligible
JSON modeValid syntax onlyNegligible
Schema-enforced API (response_format, tool_use)Syntax plus schemaLow, provider-managed
Naive token-level constrained decodingSyntax plus schemaHigh, per-token mask cost
Optimised grammar engine (XGrammar-style)Syntax plus schemaLow, near-zero overhead

Pro Tip: Test constrained decoding against your actual schema complexity before committing infrastructure to it: shallow schemas rarely justify the engineering cost, while deeply nested ones often do.

Research advances: DCCD and XGrammar explained

Two recent lines of research address the two biggest weaknesses of constrained decoding: semantic distortion and latency.

Draft-Conditioned Constrained Decoding, described in the DCCD paper, tackles distortion. Instead of constraining generation from the first token, DCCD lets the model draft an unconstrained response first, reasoning freely without any grammar restricting its token choices. It then runs a second, constrained pass conditioned on that draft, projecting the free-form reasoning into the required structure. This preserves the model's planning process rather than forcing it to plan and format simultaneously, which is where naive constrained decoding tends to produce awkward or shallow answers. The authors report structured accuracy improvements of up to 24 percentage points on strict benchmarks, and reproducible code is available in the DCCD repository, which includes two-stage decoding examples built on vLLM and similar backends.

XGrammar, detailed in the XGrammar paper, tackles latency. Its central idea is splitting tokens into two categories: context-independent tokens, whose legality never depends on where you are in the grammar and can therefore be checked once and cached, and context-dependent tokens, which need runtime checking against a persistent stack that tracks the current parse state.

The practical split for engineering teams:

  • Reach for draft-then-constrain when semantic quality inside the structure matters as much as the structure itself, such as reasoning-heavy tasks squeezed into a typed output.
  • Reach for an optimised grammar engine when you are self-hosting models and latency at scale is the binding constraint, not semantic depth.
  • Combine both for demanding production agents: draft freely, constrain efficiently, and validate semantically afterwards.
  • Skip both for simple, shallow schemas where provider-managed schema enforcement already clears the bar.

Neither technique replaces validation. Both improve the odds that what comes out of the model is both well-formed and closer to what you actually meant.

Benchmarks and evaluation: what StructEval measures

StructEval is the benchmark to know if you want to compare models on structured generation rather than trust marketing claims. It covers more than 18 formats across 44 task types, and it deliberately separates two different jobs: generation, where the model produces structured output from a natural-language instruction, and conversion, where it transforms one structured format into another. It also separates renderable formats, such as HTML and SVG, from non-renderable ones like JSON or YAML.

That distinction matters because it exposes gaps that text-only metrics miss entirely. A model can produce syntactically perfect SVG markup that renders as a broken or empty image, an error invisible to a JSON-schema validator but obvious the moment you look at the rendered output. StructEval's findings bear this out: generation tasks are consistently harder than conversion tasks, and renderable output formats are harder than text-only ones.

Interpreting a StructEval-style score means looking at three separate layers rather than one composite number:

  • Syntactic correctness: does the output parse against its format's grammar at all.
  • Render fidelity: for renderable formats, does the parsed output actually display as intended.
  • Semantic fidelity: does the content match what was asked for, independent of format.

A model can score well on the first layer and poorly on the second or third, and treating a single pass/fail metric as the whole story hides exactly where a pipeline will break.

For development teams, the practical takeaway is to mirror this layered approach in your own test suite rather than inventing a bespoke one. Run syntactic validation as a fast, cheap gate. Add render checks if your outputs include HTML, SVG or similar formats. Reserve semantic assertions, value ranges, lookups against known-good data, for a separate test layer, since they are slower and more brittle to write but catch the errors that matter most in production.

Implementation patterns and libraries for production systems

Turning these concepts into working code follows a fairly consistent pattern across teams building structured-output pipelines, regardless of which provider or model sits underneath.

  1. Define the schema first, in code. Pydantic is the dominant pattern in Python pipelines: a schema is a class definition, versioned in the same repository as the code that consumes it, rather than a string embedded in a prompt.
  2. Use provider SDK parsing where it exists. Both OpenAI's response_format and Anthropic's tool_use can return parsed objects directly, which removes a manual json.loads and validation step and the bugs that come with it.
  3. Validate in application code regardless. Provider-side schema enforcement covers syntax and structure, not business logic, so a validation layer in your own code should still check value ranges, foreign key existence and cross-field consistency.
  4. Evaluate self-hosted constrained decoding for open models. Libraries such as Outlines implement grammar-constrained generation for locally hosted models, useful when you cannot rely on a provider's managed schema feature.
  5. Instrument everything. Track schema validation failure rate as a first-class metric, add regression tests that run whenever a prompt or model version changes, and define a fallback path (retry with a stricter prompt, fall back to a smaller deterministic parser) for when validation fails.

Real-studios' own integration work follows a version of this pattern: the integration services that connect LLM outputs to downstream systems typically add a validation hook at the boundary, so a malformed or semantically wrong output never reaches a production database or triggers an action untested.

Pro Tip: Version your Pydantic schemas alongside your prompts, not separately: a prompt change that silently drifts from the schema it is meant to produce is one of the most common causes of production incidents.

Libraries such as Outlines and grammar engines like XGrammar sit at the infrastructure layer beneath this pattern. Most teams will not need to build a grammar engine themselves; adopting one, or relying on a provider's managed equivalent, is usually the more efficient choice.

Common pitfalls, debugging checklist and best practices

Most structured-output failures in production trace back to a small set of recurring mistakes.

  • Over-constraining the schema. A rigid schema with too many required fields or overly strict types can force the model into semantically poor completions just to satisfy the type checker; loosen fields that genuinely vary and validate them separately.
  • Truncation in nested responses. Long, deeply nested JSON is prone to being cut off mid-object when a token limit is reached, producing output that fails parsing even though the model "knew" the right answer; set generous token limits for nested schemas and detect truncation explicitly.
  • Treating syntactic validity as the finish line. A parseable object can still contain the wrong data; run semantic assertions (value ranges, lookups against known-good tables) as a separate check even after schema validation passes.
  • Not logging validation failures as a health metric. Schema validation failure rate is one of the most useful production signals for structured-output systems and is frequently left unmonitored until a downstream system breaks.
  • Skipping schema regression tests on prompt or model changes. A prompt tweak or a model version bump can silently shift output structure; run a fixed regression suite against schema conformance whenever either changes.

Treat these as the minimum checklist before shipping any pipeline that depends on structured output, not as a one-time setup task. Models, prompts and provider APIs all change over time, and each change is a fresh opportunity for a schema to drift out from under the code that assumes it still holds.

How Real-studios applies these patterns in client projects

Clients bringing AI agents, RAG systems or automations into production consistently run into the same problem: outputs need to be both correct and immediately usable by existing software, whether that is a CRM, a booking system or an internal dashboard. A customer service agent that extracts a booking date correctly but returns it in an unparseable format is functionally broken, even though the reasoning behind it was right.

The approach to this problem generally follows the same structure: early prototypes are built with looser prompting to establish that the underlying reasoning and data extraction work as intended. Once validated, schema enforcement is introduced, typically through provider-managed structured outputs or tool calling, so the same logic returns typed, predictable objects. Production rollout adds validation and monitoring at the integration boundary, catching malformed and semantically incorrect outputs before they reach live systems.

This progression—from prototype to enforcement to production rollout—is important because skipping straight to rigid schema enforcement before the underlying task is proven tends to bake early mistakes into a structure that is harder to change later. Ongoing support after launch keeps schema regression tests and validation metrics in place as models and prompts are updated, rather than treating them as a one-off setup step.

Choosing provider-managed versus self-hosted enforcement

Provider-managed structured outputs are the right default for most teams. OpenAI's response_format and Anthropic's tool_use cover the majority of production schemas without any custom decoding infrastructure, and they get faster and more reliable as providers invest in them, at no engineering cost to you.

Self-hosted constrained decoding earns its complexity in narrower cases: when you are running open models for cost, latency or data residency reasons, when your grammar is genuinely unusual (a domain-specific format no provider schema tool expresses well), or when you need draft-then-constrain's semantic benefits and no managed equivalent exists.

My rule of thumb: start with provider-managed enforcement always, and only invest in a grammar engine or self-hosted constrained decoding once you have a specific, measured failure mode that managed tools cannot fix. Building constrained decoding infrastructure before you have evidence you need it is a common way teams over-engineer a problem that a schema-enforced API call would have solved in an afternoon.

— Oded

Get help building reliable structured-output systems

Services offered include AI agents such as RAG, voice, chat and email agents built with schema enforcement from the start; automation and integration connecting LLM outputs directly to CRMs, databases and internal tools; rapid MVPs delivering working, schema-validated prototypes quickly; and AI engine optimisation to help businesses remain visible as search shifts toward AI-driven answers.

A typical engagement moves from prototype to schema validation to a production rollout with ongoing support after launch. Visit the services overview to discuss a project, or look at rapid MVPs if a fast proof of concept is the immediate need.

Sources

FAQ

What is the difference between JSON mode and schema-constrained output?

JSON mode guarantees that output is valid JSON syntax but not that it matches any particular structure. Schema-constrained output, available through features like OpenAI's response_format or self-hosted grammar engines, guarantees both valid syntax and conformance to a defined schema.

Does constrained decoding guarantee correct answers, not just valid formatting?

No. Constrained decoding, which masks illegal tokens by setting their probability to zero, guarantees syntactic validity, meaning the output always parses correctly. It does not guarantee semantic correctness, so downstream validation of values and logic is still required.

What is draft-then-constrain decoding and why does it help?

Draft-then-constrain decoding, studied in the DCCD research, lets a model draft a response without constraints first, then applies constrained decoding conditioned on that draft.

Which library should I use for constrained generation with open-source models?

Outlines is a widely used library for constrained generation with self-hosted open models, and grammar engines such as XGrammar are designed to make token-level constraints fast enough for production use. Pydantic is the standard choice for defining and validating the schemas these tools enforce.

How should I evaluate a model's structured output ability before choosing it?

Use a layered evaluation similar to StructEval: check syntactic correctness first, then render fidelity for any visual formats, then semantic fidelity against the actual task. StructEval's findings show generation tasks are harder than conversion tasks and renderable formats are harder than text-only ones, so test both dimensions rather than relying on a single pass rate.

Recommended

All guides