llama-server, the CLI tools, and the C API.
JSON schema with llama-server
Pass an OpenAI-styleresponse_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.
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:grammar field on /completion or /v1/chat/completions) or globally with --grammar-file on llama-server / llama-cli:
In-process bindings
- C API (mobile, embedded)
- Python (llama-cpp-python)
- Node.js (node-llama-cpp)
Add a grammar sampler to the chain before the final The grammar sampler is stateful: call
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.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
stringfield can run untilmax_tokens; setmaxLengthor put bounded fields last.