Dashboard
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
51 small wins to finish your pathNext question →

Q31IntermediateConcept

How does constrained decoding guarantee structured outputs such as JSON?

30-second answerSay your answer out loud first, then reveal.

How it works

  1. Convert the JSON schema (or regex or grammar) into an automaton.
  2. Track the automaton's state as tokens are generated.
  3. Precompute, for each state, which vocabulary tokens are allowed (tricky, because tokens span multiple characters).
  4. Apply a mask to the logits, then sample normally among valid tokens.
Example. After {"status": ", with status an enum of ["open","closed"], only tokens that continue towards open or closed are allowed.

Benefits: a 100% syntactically valid, schema-conformant output; no retry loops for parse errors.

Caveats

  • Valid ≠ correct: the content can still be wrong or hallucinated within a valid structure.
  • Quality impact: forcing structure can push the model into low-probability tokens. Field order matters (put a reasoning field before the answer field so the model can think first).
  • Performance: grammar compilation and masking overhead (modern engines make this small).
  • Complex schemas (deep recursion, many optional fields) may not be fully supported.

Alternative: JSON mode (valid JSON, any shape) + schema validation + retry, which is simpler but not guaranteed.

Little by little, you're building something great.