Skip to main content
llama.cpp enforces structure at decode time: tokens that would break the schema get zero probability, so the output is guaranteed to parse. You can supply a JSON Schema (converted to a grammar automatically) or a hand-written GBNF grammar. Both work in llama-server, the CLI tools, and the C API.

JSON schema with llama-server

Pass an OpenAI-style response_format. llama-server converts the schema to a grammar for that request.
{"type": "json_object"} (any valid JSON) is also accepted, and the non-OpenAI /completion endpoint takes the schema directly in a json_schema field.
The grammar constrains which tokens can be produced; it does not tell the model what to produce. Describe the fields in the system prompt (as above) so the model fills them meaningfully instead of emitting the shortest string that satisfies the schema.
Supported schema features include object / array / string / number / integer / boolean / null, enum, const, required, additionalProperties, minItems / maxItems, minLength / maxLength, pattern, anyOf / oneOf, $ref and $defs. Unsupported keywords are ignored rather than rejected, so validate the parsed object in your code as well.

GBNF grammars

For non-JSON formats (a fixed set of labels, a date, a command line), write a small grammar in llama.cpp’s GBNF syntax:
Use it per request (grammar field on /completion or /v1/chat/completions) or globally with --grammar-file on llama-server / llama-cli:
To see the grammar llama.cpp generates for a schema, or to ship a pre-converted grammar with your app:

In-process bindings

Add a grammar sampler to the chain before the final dist sampler. Convert JSON schemas ahead of time with json_schema_to_grammar.py, or at runtime with json_schema_to_grammar() from the common library.
The grammar sampler is stateful: call llama_sampler_reset(smpl) (or rebuild the chain) before each new generation.

Best practices

  • Keep schemas small. Every optional field and nested object enlarges the grammar and the model’s decision space. Split large extractions into several focused calls.
  • Describe fields in the prompt. The schema is invisible to the model; field names and a one-line description per field in the system prompt are what steer content.
  • Use low temperature. 0.1 (the LFM2.5 default) is right for structured output.
  • Validate anyway. Grammar guarantees syntax, not semantics β€” check ranges, enums, and referential consistency in application code and retry on failure.
  • Avoid open-ended strings at the end. A final unbounded string field can run until max_tokens; set maxLength or put bounded fields last.