Why a language model does not emit JSON
An instruction-tuned model predicts the next token from a probability distribution. Nothing in that process knows what a brace is. The model has learned from training data that answers to extraction prompts often look like JSON, so it produces something JSON-shaped most of the time. Most of the time is not a contract.
The failures are consistent enough to enumerate. A preamble before the object, such as Here is the JSON you requested. A markdown fence wrapped around it because the training data was full of chat transcripts. Single quotes instead of double. A trailing comma after the last property. An unescaped newline inside a string. The word undefined, or NaN, or a Python None where null belongs. A comment. A second object appended after the first. A key that the schema never mentioned, invented because it seemed plausible.
Then there is truncation, which is the most common failure in production and the least often handled. The model is halfway through a nested object when it hits the max_tokens limit, and the response ends mid-string. The JSON is not malformed because the model made a mistake; it is malformed because you cut it off. Any parser will reject it, and any retry that does not raise the limit will fail the same way.
Prompting reduces the frequency of all of these. It cannot reduce any of them to zero, because a sampled distribution always has mass on other tokens. If your pipeline needs a guarantee, you need a mechanism that removes the invalid tokens from the distribution. That is what constrained decoding does.
Layer one: make the contract explicit
Before reaching for machinery, write the request so that a competent human would produce the right shape. That means naming the fields, their types, and what to do when a value is unknown. Vague instructions produce vague structure.
A good contract has four parts. It states that the response must be a single JSON object, with no prose before or after and no markdown fence. It gives the schema, either as a compact JSON Schema document or as a short field list with types. It gives one minimal example of a valid response, small enough that the model cannot copy its content instead of answering. And it defines the null policy: which fields may be null, and that missing data must be null rather than an empty string or a guess.
Two details matter more than they look. First, put the schema in the system message and repeat the shape requirement at the end of the user message, because the most recent tokens carry the most weight. Second, forbid the fence explicitly. Models fence JSON because humans fence JSON in markdown, and an instruction that says raw JSON only, no code fences is a cheap and reliable fix.
Set the sampler for the job too. Temperature near zero for extraction, top_p at 1.0 or close, and no repetition penalty, because penalising repeated tokens punishes the braces, quotes and commas that JSON is made of. A repetition penalty of 1.1 on a JSON task is a self-inflicted wound: the model starts avoiding the second occurrence of a key it needs to repeat across array items.
All of this raises the hit rate. On a modern instruct model with a clean schema, you might go from eighty per cent parseable to ninety-eight per cent. The remaining two per cent is why the rest of this article exists.
Layer two: prefill the opening brace
If the API lets you supply a partial assistant message, use it. Send the conversation with a final assistant turn containing a single opening brace, and ask the server to continue from there instead of starting a new turn. The model's first token is now a key, a whitespace token or a closing brace, not the word Certainly. The preamble failure disappears entirely, because there is no room for a preamble.
In transformers this is a template call with add_generation_prompt=False after appending the assistant message, which leaves the model inside the assistant turn. In vLLM it is continue_final_message in the chat request. Mistral's API exposes it directly; OpenAI's does not, which is one reason the same prompt behaves differently across providers.
Prefill composes well with stop sequences. Add the model's end-of-turn token and any wrapper the template uses, so a model that tries to emit a second object after the first is cut off. It also composes with a closing-brace check: if the response does not end with a brace, treat it as truncated rather than attempting a repair.
There is one sharp edge. Prefilling a character that is part of a multi-token sequence can split a token, and some serving stacks handle that boundary badly. A brace is usually its own token in modern vocabularies, so the risk is low, but verify the first generated token looks sane rather than assuming. Prefill is a strong nudge, not a guarantee: the model can still produce a trailing comma three fields later.
Layer three: constrained decoding
Constrained decoding changes the sampling step itself. At each position, a parser tracks which tokens would keep the output on a path to a valid document. Tokens that would break the grammar are masked by setting their logits to negative infinity. The model still chooses among the survivors according to its own probabilities, so the output stays fluent in content while being structurally impossible to corrupt.
The parser is a finite state machine compiled from a grammar or a JSON Schema. Libraries such as outlines and xgrammar compile the schema once, build an index from parser states to allowed token ids, and then apply a mask at every decode step. vLLM ships both as backends and exposes them through guided decoding; SGLang does the same with its own EBNF engine; llama.cpp implements GBNF grammars natively.
The guarantee is exact and narrow. The output will parse as JSON and will satisfy the structural parts of the schema: required keys present, types correct, enums respected, arrays shaped as declared. It will not be semantically correct. A grammar that says a field is a string will happily accept the string not-a-date for a field named date. A grammar that says an amount is a number will accept negative values unless the schema sets a minimum and the backend honours it. Constrained decoding solves syntax; your validator solves meaning.
Support varies by backend and schema feature. Basic types, objects, arrays, enums, required fields and additionalProperties false are broadly supported. Numeric bounds, string patterns, minItems and maxItems, and deeply recursive schemas are supported unevenly or silently ignored. If a constraint matters, test it: send a request designed to violate it and see whether the server allows the violation.
Using it through vLLM
vLLM accepts a schema in the OpenAI-compatible request body under response_format with type json_schema, or through the older guided_json parameter. The newer structured_outputs field is the forward-looking spelling. The server compiles the schema, caches the compiled form keyed by schema hash, and applies the mask during generation.
In practice you define the shape once, as a Pydantic model, and derive the schema from it. model_json_schema() gives you a dict you can attach to the request. That keeps one source of truth: the same class validates the response later, so a field you forgot to describe shows up as a validation error rather than a silent omission.
The first request with a new schema pays a compilation cost that can run into hundreds of milliseconds for a large schema. Later requests hit the cache. If you generate schemas dynamically, for example one per customer, you will pay that cost constantly and the cache will thrash. Prefer a small set of stable schemas with optional fields over a schema factory.
Two server options are worth knowing. The guided decoding backend selects xgrammar or outlines; xgrammar is generally faster to compile and is the default in recent releases. There is also a switch that stops the grammar from permitting arbitrary whitespace, which keeps output compact instead of letting the model wander through spaces until it hits the token limit. Whichever you choose, run constrained and unconstrained requests against the same eval before rolling it out.
JSON mode is not schema mode
Many servers expose a response_format of type json_object, sometimes called JSON mode. It guarantees that the output parses as JSON. That is all it guarantees. No schema is applied, so the keys, types and nesting are whatever the model chose to produce. It is a useful floor and a poor contract.
JSON mode is also weaker than it sounds on some stacks, because it is implemented as a grammar that permits any valid JSON document, including a bare number, a string, or an empty object. A model asked an ambiguous question may return {} and satisfy the mode perfectly. If a downstream consumer expects a specific object, json_object will not protect it.
Treat JSON mode as a migration step for prompts that already work. If you have a schema you care about, send the schema. If your server only offers json_object, put the schema in the prompt and validate on the way out, because the mode is doing much less than its name suggests.
Using it through llama.cpp and GBNF
llama.cpp predates JSON Schema support and exposes a grammar language called GBNF. A GBNF file is a set of rules with alternations, character classes and repetition, close to a regular expression grammar with named productions. A JSON grammar is about thirty lines: a value rule that alternates between object, array, string, number, true, false and null, plus rules for whitespace and escapes. llama.cpp ships a converter that turns a JSON Schema into GBNF, and recent builds accept a JSON schema directly in the request.
The GBNF path is the right one when you are running quantised models locally, because it needs no server-side support beyond the binary you already have. It is also the most transparent: you can read the grammar and know exactly what is permitted. The trade-off is that GBNF gives you no schema semantics. Required keys, types and enums have to be encoded by hand in the rules, and every schema change is a grammar change you must review.
Watch for whitespace rules. A grammar that does not permit spaces between tokens produces minified JSON, which is fine for a parser and miserable for a human reading logs. A grammar that permits unlimited whitespace can let the model ramble through spaces until it hits the token limit. Constrain whitespace explicitly rather than leaving it as a wildcard.
Validate, then repair deliberately
Even with constrained decoding, validate. Parse the string with a real JSON parser, then validate against the schema with Pydantic, jsonschema, or the equivalent in your language. Parsing catches truncation and transport corruption; schema validation catches the semantic gaps grammar cannot see.
When validation fails, do not silently patch the string with a regular expression. A regex that fixes a trailing comma today will corrupt a legitimate string containing a comma tomorrow. Either retry or fail loudly.
The retry that works is a repair turn. Send the original request, the invalid output, and the validator's error message, and ask for a corrected object that satisfies the schema. Models are good at this: the error text tells them exactly which field is wrong. Bound it to one or two attempts, because a model that failed twice on the same schema is usually failing for a structural reason that another attempt will not fix.
Make the retry safe. If the call has side effects, validate before executing, and make the execution idempotent with a request key. Log every validation failure with the raw output, the schema hash, and the finish reason. That log is how you find out that a schema change broke a downstream consumer, or that a particular model revision has started emitting numbers as strings.
Finally, check finish_reason. A response that ended because of the length limit is truncated regardless of how valid its prefix looks. Treat length as a failure even if the JSON happens to parse, because a truncated array is still a wrong answer.
Designing schemas the model can satisfy
Schema design is prompt engineering with a type system. A shape that is easy to generate is also a shape that is easy to validate.
- Prefer flat objects with a handful of fields over deeply nested trees. Every level of nesting is another place to run out of tokens and another chance for the grammar to confuse the model.
- Use enums rather than free strings for categorical fields. An enum both constrains decoding and tells the model the label space.
- Use nullable fields with an explicit null for unknown data, rather than optional fields that may be absent. Absence and null mean different things to a consumer, and models handle an explicit null more reliably.
- Avoid anyOf and oneOf where a nullable field or a discriminator would do. Union schemas expand the grammar and make compilation slow.
- Set additionalProperties false so invented keys are rejected at validation time instead of silently reaching your database.
- Add descriptions to every field. They cost tokens and they are the only place the model learns what a field means.
- Keep arrays bounded with maxItems, and say in the prompt what to do when there are more items than the bound.
- Put the discriminator first in each variant so the model commits to a shape before filling it in.
A decision guide
Match the mechanism to the consequence of a bad response.
- Prototype, human reads the output: prompt contract plus prefill is enough.
- Batch job that can retry: prompt contract, prefill, validation, one repair attempt.
- Production API with a database behind it: constrained decoding, strict schema, validation, bounded retry, and a hard failure path.
- Local quantised model: GBNF or the server's JSON schema support, whichever your build offers.
- Anything where a wrong value is worse than no answer: add semantic checks after parsing, because no grammar knows that a date must be in the future or that an account id must exist.