New Tool Radar

Local AI

How to Constrain llama.cpp Output with a Grammar

Give llama-server a GBNF grammar file with --grammar-file so every reply follows the format you need, instead of hoping the model cooperates.

Schematic diagram with three steps: write a GBNF grammar file, start llama-server with --grammar-file, and check that every reply matches the grammar.

A prompt can ask for JSON, but only a grammar can guarantee it. llama.cpp constrains generation with GBNF grammars: at each step the sampler is restricted to tokens that keep the output valid, so the reply cannot wander out of the format. The server README documents --grammar GRAMMAR for a BNF-like grammar and --grammar-file FNAME for reading one from a file.

Related guide: How to Serve a Local Model with an OpenAI-Compatible API Using llama-server

Apply a grammar to the server

Write your grammar to a file — the llama.cpp repository ships samples in its grammars/ directory — then start the server with it:

llama-server -m model.gguf --grammar-file ./grammars/json.gbnf

Every completion from that server now follows the grammar. You can also send a grammar per request: the server README documents a grammar field on the completion endpoints, so one server can serve a strict format for one client and free text for another. Keep grammars small and test them with short prompts first — a grammar that can never match what the model wants to say will produce empty or stalled output.

Check the output

Ask for ten replies and check each one against the format with a parser (for JSON, python -m json.tool). If a reply fails to parse, the grammar was not applied — check that you passed --grammar-file to the server that actually served the request, not to a different process. The server README also documents the error when an invalid grammar is sent to the /completion endpoint: it answers that it failed to parse the grammar.

Expected result. We checked the llama.cpp server README for the –grammar and –grammar-file flags and the per-request grammar field, and the llama.cpp README for the GBNF grammars documentation link. 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 grammar constrains the shape of the output, not its truth: a perfectly valid JSON reply can still contain wrong values. Grammar sampling also adds work to each decoding step. We did not run llama-server, so no reply here is a recorded result.

Sources

Checked 2026-11-28.

See all