New Tool Radar

Local AI

Constrain llama-server Output to JSON with a Grammar File

Force llama-server to return valid JSON with response_format json_schema, or limit it further with a GBNF grammar.

Schematic with three steps: Ask for schema-constrained JSON; Check the constraint holds; Use a GBNF grammar for tighter limits.

When a program consumes model output, free text is a parsing risk. llama-server turns a JSON schema into a grammar and constrains sampling, so the model cannot emit a token that breaks the schema, and a GBNF grammar can restrict output even further.

What you need

  • llama-server running with a chat model loaded
  • curl or the OpenAI Python SDK
  • A JSON schema for the answer you need

Step 1: Ask for schema-constrained JSON

Send a chat completion to /v1/chat/completions with response_format set to type json_schema and a schema object, for example an object with a name string and a date string, both required. The server converts the schema into a grammar before sampling.

Step 2: Check the constraint holds

Ask in the prompt for a value outside the schema, such as an enum value that is not listed. The schema should win: in the cited test, a three-value enum blocked the forbidden value even though the prompt asked for it, while the reasoning text stayed free.

Step 3: Use a GBNF grammar for tighter limits

For rules a schema cannot express, pass a GBNF grammar in the grammar field, for example root ::= (si | no). The model then answers with only one of those words. Use response_format type json_object when you want JSON without a schema.

Worked example: extract a name, a label, and ports

The table below is a synthetic example. The schema test and its result come from the cited llama-server guide; the values are its documented test case.

Field Schema Returned value
nombre string nginx
etiqueta string 1.29-alpine
puertos list of integers 80, 443

Expected result (UNTESTED). the reply parses as JSON, matches the schema exactly, and a forbidden enum value is refused. This check was not run live; the schema behaviour comes from the cited llama-server guide.

Limits

  • The constraint applies to the final answer; a reasoning model may still reason freely first.
  • A schema cannot express every rule; use GBNF for those cases.
  • Tool calls need the Jinja template engine, which is on by default in current builds.
  • Some less-used OpenAI parameters are silently ignored by the server.

Sources

See all