Delve · Field guide
Reliable JSON from LLMs: constrain the decoder, verify the values
Grammar-level enforcement kills malformed JSON; schema design and semantic checks are what stop wrong-but-well-shaped data.
Delve Editorial · AI Engineering · 9 min
#structured-output #constrained-decoding #json-schema #validation #reliability #evaluation
The short answer
Make the invalid output impossible, then check what remains: compile your schema into a grammar that masks disallowed tokens at every decoding step, validate the result into typed objects, retry with the specific validation error, and measure field-level accuracy because a structurally perfect object can still hold the wrong value.
Constrained decoding removes one whole class of failure — syntax — and that class is the easiest to over-value. Once structure is enforced, the residual errors are semantic: a plausible enum-adjacent category, a wrong severity, an empty list where the model should have asked a question instead. Those need schema design, validation, labeled evaluation, and routing, not a stronger prompt.
- Schema-valid, pilot 1.000 in all structured conditions
- Free-form baseline 0.000 JSON and schema validity
- Dominant residual failure False confidence, then category mismatch
01 · The mechanism
JSON is a pattern the model imitates, not a rule it obeys
An LLM picks each token from a probability distribution over its vocabulary. Nothing in that distribution encodes a grammar; JSON is a pattern the model has seen often enough to imitate, and imitation is probabilistic. The arithmetic compounds fast: a model that gets a field right 99% of the time produces a fully correct twenty-field record only about 82% of the time. That compounding, not insufficient sternness in the prompt, is why instruction-hardening plateaus.
The failures are several distinct problems, each with a different fix:
- Truncation — the token budget expires mid-object. Fix by sizing the budget from the schema and by masking end-of-sequence until the document closes. - Wrapping — a preamble or fenced code block around the object. Fix with a tolerant extractor or decoder-level enforcement. - Type drift — the string "3" where an integer belongs. Fix in the validator, with coercion rules you chose on purpose. - Enum drift — a plausible synonym where the schema wanted a closed value. Fix by enforcing enum membership at decode time. - Escaping errors — an unescaped quote inside a string value. Fix with grammar masking.
Prompt instructions nudge the distribution; masking removes options from it entirely. That difference is why one approach converges and the other asymptotes.
A model that is right 99% of the time per field is wrong on a fifth of its twenty-field records.
02 · The enforcement layer
Constrained decoding: tokens that cannot be sampled
Constrained decoding compiles the schema into an automaton and edits the model's choices in flight. The JSON Schema becomes a context-free grammar or finite-state machine; at every decode step each vocabulary token is tested — does appending its bytes keep the output a valid prefix? Tokens that fail get their logits set to negative infinity, so the sampler can never select them . The end-of-sequence token stays masked until the output is a complete document, which removes mid-structure truncation structurally rather than statistically .
Not all "structured output" is the same guarantee. A JSON mode that only promises the text will parse still lets required keys vanish and enums drift. A strict schema mode that constrains required properties and allowed values closes those holes. Read the provider's contract for what is actually enforced, not the feature's name.
The mechanism is not free. Building the mask means checking the whole vocabulary against the grammar at every step, and naive engines pay for it in latency . Earley-based pruning with state caching cuts that overhead substantially — one engine reports up to 2× speedup over prior implementations while preserving compliant output . Two practical boundaries: providers support only a subset of JSON Schema keywords, and the tokenizer matters, because masking operates on the byte strings that tokens represent .
Enforcement converts a probabilistic failure into an impossible one — but only for the property you actually encoded. Unsupported schema keywords silently fall back to best effort.
03 · The interface
Schema design and the validation-repair loop
A schema is an interface: it shapes both what the model can emit and what your code must handle. Four decisions move failure rates most. Flatten before you nest; every extra level is another place for an object to be abandoned mid-way. Use enums instead of free strings for closed sets, so drift becomes unrepresentable rather than merely discouraged. Make optionality explicit — a nullable field that is always present beats a key that sometimes disappears, because downstream code stops needing two code paths. Keep reasoning fields short and put them before the answer field if you want the model to commit to a category after stating evidence; this ordering effect is widely practiced but thinly evidenced, so treat it as a hypothesis to test on your own schema.
At runtime, parse into typed objects — Pydantic, Zod, a Go struct — and log the exact failing path. On failure, re-prompt with the concrete validation error and the offending fragment rather than "try again"; a generic retry resamples the same distribution and often reproduces the same defect. Bound the loop at two or three attempts, then fall through to a dead-letter path or a human. Whether error-fed repair converges faster than blind retry is not well established in the retrieved evidence; the bounded fallback is what makes the choice safe either way.
The schema is not documentation of the output. It is the output's operating conditions.
04 · The gap
Schema validity saturates; correctness does not follow
Every layer so far guarantees shape. A 50-task ticket-triage pilot using gpt-4o-mini shows exactly where that stops: free-form output scored 0.000 on JSON and schema validity, while every structured condition — JSON-only prompting, schema validation, validation retry, validation repair, and the full reliability configuration — scored 1.000 on both . Once structure is enforced, parse errors stop discriminating between pipelines. What remained were semantic failures, with false confidence most frequent, followed by priority mismatch, customer-impact mismatch, and human-review mismatch .
Constrained decoding can make this worse in a subtle way. The grammar forces the model to emit some enum value; it cannot emit "unclear" unless you gave it that token. A forced choice looks like a decision, and a decision looks like confidence. The same mechanism can silently shorten a list, because ending the array is always grammatically legal.
So track four numbers, not one: schema-valid rate as a floor, field-level precision and recall against a labeled set, abstention calibration (does high stated confidence track correctness?), and human-review mismatch rate. The pilot is 50 synthetic tasks on one provider — a directional signal, not a law.
Monitoring only parse failures is how teams ship confidently wrong data: the dashboard goes green the moment the grammar works.
05 · The assembly
One pipeline, five layers, from ticket text to typed record
Concrete application: turn free-text support tickets into a record with a closed-enum category, a closed-enum severity, a nullable affected-customer field, a shallow list of extracted entities, and a one-line summary.
Layer one is the schema: enums for both classifications, required for the fields your downstream code cannot do without, explicit null for the customer, nesting no deeper than two. Layer two is enforcement: a strict schema mode where the provider actually constrains required keys and enums, with the token budget sized from the schema's worst case. Layer three is a typed validator that returns structured errors, not a boolean. Layer four is a bounded repair loop that feeds the failing path and fragment back to the model, capped at two attempts before routing to human review. Layer five is an evaluation gate: a labeled sample scored for field-level accuracy and abstention calibration on every schema or model change.
The strongest caveat is that the hardest residual failures live above the token level. A grammar cannot encode whether "severity: high" is true. And when a model would benefit from deliberating before answering, forcing it to emit structure first can suppress that reasoning — plausible from how constrained decoding narrows the distribution, but not something the retrieved evidence settles. Where accuracy matters most, let the model reason in free text or a scratch field, then emit the typed record in a second constrained pass.
Constrained decoding makes the output well-formed. Only evaluation makes it trustworthy.
What each layer buys you
Layers stack; each one closes a failure class the previous one cannot see.
| Layer | What it guarantees | What it cannot stop | Cost |
|---|---|---|---|
| Prompt instruction only | Nothing enforced; compliance varies by model and schema | Fences, truncation, type and enum drift | Zero infrastructure, highest variance |
| Provider JSON mode | Text parses as valid JSON | Missing required keys, wrong enums, wrong types | One configuration flag |
| Strict schema / constrained decoding | Structure, required properties, and allowed values conform | Wrong values, bad abstention, silently short lists | Grammar compilation and per-step mask overhead |
| Typed validator plus error-fed retry | Malformed shapes are caught before downstream use | Errors the validator has no rule for | Extra latency on the failure path |
| Semantic eval gate plus human routing | Field-level accuracy is measured; low-confidence rows are held | Novel error types outside the labeled set | Labeled data and ongoing eval maintenance |
Common misconceptions
- If the output validates against the schema, the extraction was correct. Validation proves shape. In the ticket-triage pilot, every structured condition hit 1.000 schema validity while priority, customer-impact, and confidence errors persisted [S2][S3].
- Turning on JSON mode enforces my schema. Some JSON modes only guarantee the text parses. Required keys and enum membership are separate guarantees that only strict schema modes provide.
- Lowering temperature is the fix for malformed JSON. Temperature reduces sampling variance; it does not remove the possibility of an invalid token or a missing key. Grammar masking removes it.
- Retrying the same request until it parses is a reliability strategy. Blind retries resample the same distribution and can reproduce the same defect, while adding latency. Feed back the specific validation error and cap the attempts.
Build the stack in one afternoon
Order matters: enforcement first, then design, then measurement.
Freeze a narrow schema
Use closed enums for every set you can enumerate, mark must-have fields required, make optionality explicit as nullable rather than absent, and keep nesting at two levels or fewer.
Verify what your provider actually enforces
Confirm that the strict mode constrains required properties and enum values, not just JSON syntax. Check which JSON Schema keywords are supported and size the token budget from the schema's worst case.
Validate into typed objects
Parse with Pydantic, Zod, or a struct unmarshal and log the exact failing field path plus the offending fragment, so the failure is diagnosable rather than just visible.
Feed errors back, then stop
Send the concrete validation error on the first retry. Cap at two attempts, then route to a dead-letter queue or human review instead of looping.
Gate deploys on field-level accuracy
Maintain a labeled sample; score per-field precision and recall plus abstention calibration whenever the model, prompt, or schema changes. Block the deploy on regression.
What would change my mind: A controlled benchmark showing that grammar-constrained decoding matches unconstrained generation on field-level accuracy across several models and schemas would weaken the case for keeping a separate reasoning pass before the structured emission.
Recall check
A team enables strict schema enforcement. Parse errors drop to zero, but downstream reports still contain wrong severity values. What best explains this?
- The validator is coercing strings into integers incorrectly
- The model is still emitting markdown fences outside the object
- Token-level masking guarantees shape, not the truth of the value chosen
- The sampling temperature is too high for classification tasks
Grammar masking removes invalid tokens, so structure becomes deterministic. Which allowed value gets sampled is still a model judgment, and that is where semantic errors live.
Which failure does masking the end-of-sequence token until the grammar accepts a complete document most directly prevent?
- The model stopping before the object is structurally complete
- A value drawn from the wrong category
- A schema keyword the grammar compiler does not support
- A tokenizer that maps one token to an unusual byte string
Holding end-of-sequence open until the document parses means generation cannot terminate mid-structure. Wrong values and unsupported keywords are separate problems.
Your extraction schema nests entities three levels deep and the model keeps dropping inner items. Which change should you try first?
- Lower the temperature
- Add an instruction telling the model not to omit items
- Retry the entire request up to five times
- Flatten the nesting and move the list to a required top-level field
Deep nesting multiplies the points where a structure can be abandoned, and ending a list early is always grammatically legal. Flattening removes both risks before any sampling or retry tuning.
Open questions
- Does forcing structure before a model reasons degrade extraction accuracy? If it does, the correct architecture is a free-text reasoning pass followed by a constrained formatting pass, which changes latency, cost, and prompt design.
- How much of the residual semantic error is schema design versus model capability? Design fixes are cheap and local; capability fixes mean changing models or adding human review, with very different cost profiles.
- Do grammar constraints interact with sampling temperature in ways that affect confidence calibration? Sampling settings tuned on free generation may be miscalibrated under masking, which would make stated confidence systematically misleading.
Sources
- Earley-driven dynamic pruning for efficient structured decoding | Proceedings of the 42nd International Conference on Machine Learning — ACM Digital Library
- Structured Output Reliability in Enterprise LLM Workflow Systems: A 50-Task OpenAI Pilot Study of Schema Validation, Recovery Po... — Zenodo
- Structured Output Reliability in Enterprise LLM Workflow Systems: A Study of Schema Validation, Recovery Policies, and Human Review — Zenodo
- constrain — Go Packages
- constrain - constrain — Go Packages