This is the companion to the grammar guide, for the common case where the format you want is JSON with a known shape. Instead of writing GBNF by hand, you describe the shape as a JSON Schema and llama.cpp converts it to a grammar for you. The server README lists schema-constrained JSON response format as a feature and documents a json_schema request field for grammar-based sampling.
Related guide: Related Local AI guide
Send a schema with the chat request
Start the server normally, then call the OpenAI-compatible endpoint with response_format:
curl http://localhost:8080/v1/chat/completions -H "Content-Type: application/json" -d '{
"model": "model",
"messages": [{"role": "user", "content": "List three lighthouse keepers with their years of service."}],
"response_format": {"type": "json_schema", "json_schema": {"name": "keepers", "schema": {"type": "object", "properties": {"keepers": {"type": "array", "items": {"type": "string"}}}, "required": ["keepers"]}}}}
}'
The schema only constrains the output — it is not injected into the prompt — so still ask for what you want in plain words. A test of llama-server reported that response_format with json_schema blocked a value outside the schema’s enum even when the prompt asked for it, which is the behaviour to expect.
Verify it parses
Pipe every reply through a JSON parser before your program trusts it. If parsing fails, check that you sent the schema to the /v1/chat/completions endpoint and that the model field matches the server’s alias — the server ignores the model name for generation but still needs the request to be well formed. Keep the schema strict: an empty schema {} means any JSON, which is barely a constraint at all.
Expected result. We checked the llama.cpp server README for the schema-constrained JSON feature and the json_schema field, and the linked test report for the enum-blocking behaviour. We did not run this software ourselves for this guide, so no output here is a recorded result; steps marked UNTESTED were checked against the sources below, not run.
Limits
A schema guarantees shape, not content: the model can return valid JSON with invented facts. Very long contexts with grammar sampling are reported to be slow in some versions. We did not run llama-server, so no reply here is a recorded result.
Sources
- llama.cpp server README — Schema-constrained JSON response format feature; json_schema request field for grammar-based sampling; OpenAI API compatible chat completions routes
- llama-server OpenAI-compatible API test — response_format with json_schema does constrain the output: the schema blocked a value outside the enum even though the prompt asked for it
- llama.cpp reference — grammars and JSON schema: llama.cpp constrains generation with GBNF grammars and converts JSON Schemas to grammars; on the OpenAI endpoint use response_format
Checked 2026-11-28.
