Topic 2 of 5 · 4 min read
Forcing valid JSON with grammars and schemas
Goal: Configure a local runner to return output that always matches a given JSON schema.
Constrained decoding forces a local model to emit only tokens that fit a JSON schema or grammar, so the output is valid by construction instead of by request.
Check yourself · 1 of 3
What does constrained decoding do differently from asking a model to "return only JSON"?
Why it matters
Asking a model for "valid JSON, no extra text" works most of the time and fails at the worst moment: a missing brace, a trailing comment, or a polite sentence before the object. Small local models fail this way more often than large hosted ones. With constrained decoding, the runner masks every token that would break the format at each step, so a parse error cannot happen.
How to do it
- Write a JSON schema for the object you need. Keep it small: required fields, simple types,
enumfor fixed choices. - Pass the schema to the runner. The route differs by tool:
- Ollama takes the schema in the
formatfield of its native API, orresponse_formaton its OpenAI-style route. - llama-server accepts a
json_schemain its completion request,response_formaton chat, or a raw GBNF grammar (a text format for describing allowed strings). - vLLM supports structured outputs through
response_formatand a structured-output option, using a schema, regex or grammar.
- Ollama takes the schema in the
- Still tell the model what you want in the prompt. The mask forces the shape, but the model reads the prompt to choose the content.
- Validate the result in your own code anyway.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="local")
schema = {
"type": "object",
"properties": {
"sentiment": {"type": "string", "enum": ["positive", "neutral", "negative"]},
"confidence": {"type": "number"},
},
"required": ["sentiment", "confidence"],
}
res = client.chat.completions.create(
model="qwen3:8b",
messages=[{"role": "user", "content": "Classify: 'The update broke my login.' Return sentiment and confidence."}],
response_format={"type": "json_schema", "json_schema": {"name": "review", "schema": schema}},
)
Before and after
Before: The prompt says "Return only JSON." One reply in twenty starts with "Sure! Here is the JSON:" and the parser throws.
After: The schema is passed to the runner. Every reply parses. The remaining checks are about meaning, such as whether the sentiment is right.
What goes wrong
- Valid does not mean correct. The model can return a well-formed object with a wrong or invented value. Schema checks catch shape, not truth.
- A very large or deeply nested schema slows generation and can make a small model produce worse content.
- Support differs by version and route. A field accepted on one endpoint may be ignored on another, so test with a deliberately hard input and see whether the shape holds.
- A schema with no room to think can hurt reasoning tasks. If accuracy drops, let the model write a short free-text step first, then the structured answer.
Examples
A fixed set of labels
A support tool needs one of billing, bug or other. A schema with an enum makes any other word impossible, so the router never receives "Billing issue, I think". The prompt still includes a short definition of each label.
A grammar for a custom line format
root ::= "CMD:" ws verb " " target
verb ::= "start" | "stop" | "restart"
target ::= [a-z0-9-]+
ws ::= " "?
This GBNF grammar allows only lines such as CMD: restart api-2. A schema cannot describe it, but a grammar can.
Key points
- Constrained decoding masks tokens that would break the schema, so the output parses by construction.
- Ollama, llama-server and vLLM each accept a JSON schema, though the field and route differ.
- A GBNF grammar describes allowed strings and is useful for formats a JSON schema cannot express.
- The prompt must still describe the task, because the constraint fixes the shape, not the content.
- Valid output can still be wrong, so validate meaning and keep tests with hard inputs.
Common mistakes
- Relying on "return only JSON" in the prompt and parsing with a bare
JSON.parse. - Passing a schema and dropping the task description from the prompt.
- Treating schema-valid output as correct output.
- Building a huge schema with many optional nested fields for a small model.
Check yourself · 2 of 3
A local model with a schema always returns well-formed objects, but some sentiment values are plainly wrong. What does that show?
Check yourself · 3 of 3
You need output lines like CMD: restart api-2, which a JSON schema cannot express. What fits best in llama.cpp?
Practice items, not counted towards your mastery.
Start here
- Ollama: OpenAI compatibility (opens in a new tab)DocsFree
Lists the endpoints and request fields Ollama accepts through its OpenAI-style API, and what is not supported.
- llama.cpp server README (opens in a new tab)DocsFree
Flags and endpoints of llama-server, including its OpenAI-compatible routes and JSON schema options.
- vLLM: structured outputs (opens in a new tab)DocsFree
How vLLM constrains output to a JSON schema, regex or grammar.
More for this topic
- Ollama: structured outputs (opens in a new tab)DocsFree
Passing a JSON schema in the format field and validating the reply.
- llama.cpp grammars (GBNF) (opens in a new tab)DocsFree
The GBNF grammar syntax llama.cpp uses to restrict generated tokens.