Constrained decoding — explanation
What is this about?
A language model writes one token at a time, each sampled from a probability distribution over its whole vocabulary. Asking it nicely for JSON works most of the time; "most of the time" is not enough for a program that parses the answer. Structured output (response_format) and forced tool calls (tool_choice: required) are therefore guaranteed by razorbill, not requested: at each step, the tokens that would break the expected format are removed before sampling. This page explains how, where it stops, and the lessons learnt while building it.
How the guarantee works
razorbill uses XGrammar, the grammar engine bundled with mlx-swift-lm. A JSON Schema (or a tool-call format) is compiled into a grammar for the model's tokenizer. During generation, a logit processor asks the grammar, at each step, which tokens may come next, and gives every other token a probability of zero. Whatever the model "wants", it can only write a valid continuation; when the grammar is complete, generation ends.
The processor sits inside mlx-swift-lm's normal generation loop. Temperature, top-p, penalties, the thinking budget, streaming and tool-call parsing all keep working: the constraint only narrows the choice of tokens.
Reasoning models think first. The processor stays inactive until the model closes its reasoning (</think>): the reasoning is free text, then the answer is constrained. Constraining the reasoning too would turn it into JSON, and the model would lose the benefit of thinking.
The grammar is not enough: telling the model
The first version only constrained. Measured with Qwen3-4B, it worked well when the model answered directly, but with reasoning on, the answers were valid JSON with absurd content: a paragraph of prose in a "country" field, a population written as an endless string of digits. The cause is plain once seen: nothing in the prompt said JSON was expected, so the model planned a prose answer while thinking, and the grammar then forced that prose into the fields.
razorbill therefore also tells the model: with response_format, one sentence is appended to the system message, carrying the schema for json_schema. With it, the same test went from prose in the fields to three correct answers out of three, with reasoning half as long. The grammar guarantees the form; the instruction makes the content sensible. OpenAI's models are trained for structured output and do not need this; local models do.
Key order
A grammar generated from a schema writes an object's properties in the order the schema lists them. That order matters to clients: putting a reasoning field before answer is a known way to let a model think before it commits. razorbill's first version lost it: Swift's JSON decoder does not keep the order of object keys, so schemas reached the grammar sorted alphabetically. The request's schemas are now read with an order-preserving parser.
What cannot be guaranteed
Some JSON Schema keywords are accepted by XGrammar but not enforced: not, if / then / else, dependentRequired, dependentSchemas, multipleOf, uniqueItems, contains, minContains, maxContains. With "strict": true, the client asked for a guarantee, so razorbill refuses such a schema with a 400 naming the keyword rather than silently returning output that might break it. Without strict, they are ignored.
Forced tool calls depend on the model family. Each family writes tool calls in its own syntax: <tool_call>{"name": …, "arguments": …}</tool_call> for Qwen and Hermes, <|python_tag|> and other forms for Llama, [TOOL_CALLS] for Mistral… razorbill builds forcing grammars (XGrammar "structural tags") for the <tool_call> JSON syntax only, which covers the most common tool-capable local models. For the other families, tool_choice: required, a named function, or a strict tool is refused with a 400, and auto still works through mlx-swift-lm's parsers.
Content. A grammar guarantees that population is an integer, not that it is the right one. Small models (below about 1B parameters) follow schemas reliably and fill them poorly; at temperature 0 they can also loop inside a long string until max_tokens. Prefer a 4B model or larger for extraction.
Small-model pitfalls the server handles
- Whitespace loops. JSON allows any amount of whitespace between tokens, and the bundled XGrammar version does not restrict it. Qwen3-0.6B, constrained, would sometimes write newlines forever. razorbill penalises long runs of whitespace tokens while a constraint is active.
- Repeated calls. Under
tool_choice: required, a small model may call the same tool again and again untilmax_tokens, and the truncated last call is lost. A forced call therefore produces one call unless the client explicitly sendsparallel_tool_calls: true. - JSON answers streamed in one piece. mlx-swift-lm's tool-call parser holds back any answer starting with
{in case it is a bare JSON tool call. Without tools in the request, razorbill switches to a parser without that fallback, so JSON streams token by token.
Costs
The grammar is compiled for each request (about 0.2 s): the bundled XGrammar cannot copy a compiled grammar, so caching it would mean sharing mutable state between requests. Masking the vocabulary at each step also slows generation; measured on a small model in a debug build, about 90 tokens/s free against about 49 constrained.
Rejected alternatives
- Validate after generation and retry: no guarantee, unbounded cost, and streaming would show invalid output.
- Only the instruction, no grammar: what models do without help is exactly what the guarantee is for.
- Forcing tool calls for every family with hand-written grammars: each syntax is a maintenance burden; refusing clearly is honest until a real need appears.
How it relates to the rest
- How to use it: get structured output and use function calling.
- The exact fields and refusals: HTTP API reference.
- How reasoning is separated before the constraint applies: reasoning models.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
|