Foundations to Frontier
Tests
F. NLP and Large Language Models › F9 Prompting and In-Context Learning

Structured output

Programs need model output they can parse: JSON matching a schema, a fixed set of labels, function-call arguments. Asking politely in the prompt works most of the time but not always. Validation with retries is exact but costs extra calls. Constrained (grammar-guided) decoding masks, at each step, every token that could not lead to valid output, so the result is always valid. Masking has a subtle cost, though: it renormalises locally. When the model was heading towards an invalid answer, it is forced into whatever valid continuation shares the prefix, which can distort the answers. This page covers JSON mode and schema-based structured outputs, grammar engines, validation and repair, and schema design (including putting reasoning before the answer). In the exercises you validate outputs against a schema and build an enum token mask. You then take a model that puts 30% of its belief on out-of-range three-digit values for a field limited to 0–99. Prompt-only output was valid 72% of the time, and retrying needed 1.4 attempts on average while keeping the model's own valid distribution. Masked decoding was always valid, but it turned would-be 1xx answers into 10–19: their share rose from 0.5% to 26%, and the mean answer fell from 62 to 48.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Getting answers a program can read

When software uses a model’s answer, it needs a precise format, like a form with fixed boxes. You can ask for the format, check it and ask again if it is wrong, or force the model, word by word, to only write things that fit the form. Forcing guarantees the format, but if the model wanted to write something that doesn’t fit, it gets squeezed into the nearest thing that does, which can quietly change the answer. The demo shows this squeeze.

Prompting lab
Share of answers 10–19: retry-until-valid 0.5% (green, the model's own valid distribution, about 1.43 tries each); masked decoding 30.3% (red): always valid, but distorted.
Why engineers care

Structured outputs connect models to software (databases, control systems, dashboards); validate every field and check that constraints do not silently change the values.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Constrained decoding guarantees…
  2. 2. Retrying until valid costs…
  3. 3. Forcing a format can…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Prompting: describe the format and give an example; parse robustly (models wrap JSON in prose or code fences). Validity is high but not guaranteed.
  • JSON mode / structured outputs (provider APIs): the server constrains decoding to valid JSON or to a supplied JSON schema.
  • Grammar engines: Outlines, XGrammar, llguidance, llama.cpp GBNF grammars and vLLM guided decoding compile a schema or regex into a token-level automaton and mask invalid tokens at each step.
  • Validate and repair: check against the schema (Pydantic, jsonschema), send errors back to the model, retry; exact with respect to the model’s distribution given validity, at a cost of 1/P(valid) calls on average.
  • Distortion: masking samples each token from the model’s renormalised local distribution, which is not the model’s distribution conditioned on the whole output being valid.
  • Schema design: order fields so that reasoning comes before the answer; use enums for labels; keep schemas small; allow ‘unknown’ values so the model is not forced to invent data.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Grammar engines work by…
  2. 2. Validate-and-retry is exact with respect to…
  3. 3. Put a reasoning field…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Structured output in practice

Exercise 1.

  • Validate an object against a small schema (types, ranges, enums).
  • Extract the first JSON object from a reply.

Practice.

  • Use the provider’s structured-output mode with a JSON schema (or Pydantic model) when available.
  • Self-hosted: vLLM guided_json / guided_choice, Outlines, or llama.cpp grammars.
  • Always validate server-side as well; check semantic ranges, not only types.
  • Compare constrained and unconstrained answers on a sample to detect distortion, and give fields an escape value such as null.
from pydantic import BaseModel, Field
class Reading(BaseModel):
    reasoning: str
    count: int = Field(ge=0, le=99)
    unit: str = Field(pattern="^(m|km|ft)$")
r = client.chat.completions.parse(model=MODEL, messages=msgs, response_format=Reading)   # schema-constrained
reading = r.choices[0].message.parsed
🐍 Exercise 1: validating structured output
Implement a minimal schema validator and robust JSON extraction.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A Python library for schema models:
  2. 2. vLLM option for JSON-schema decoding:
  3. 3. Give fields an escape value so the model…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Local renormalisation vs conditioning. Let p(y) be the model’s distribution over complete outputs and V the valid set. The ideal constrained output follows p(y | y ∈ V) = p(y)/p(V). Masked decoding instead samples token by token from p(t | prefix) restricted to tokens that keep the prefix completable. Its probability of y is Π_i p(t_i | prefix)/Z_i, where each Z_i is the mass of allowed tokens at step i. The Z_i depend on the path, so prefixes that lead mostly to invalid continuations are not down-weighted as they should be. Their mass is pushed into whichever valid completion remains.

Example. If the model wants 120 but values must be ≤ 99, the prefix ‘1’ is still valid, ‘12’ is still valid, and then only END is allowed, so the answer becomes 12. Every would-be 1xx answer turns into 1x.

Fixes. Rejection sampling (retry) gives exact conditioning; resampling-based methods (sequential Monte Carlo) approximate it at lower cost; good prompting raises p(V) so constraints rarely bind; and schemas that allow ‘unknown’ or wider ranges reduce forced choices.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Exact constrained sampling follows…
  2. 2. Masking fails to down-weight…
  3. 3. Exact conditioning is achieved by…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Does constrained decoding preserve the model’s answers, or only their format?

History.

  • Grammar-constrained decoding in parsing and code generation (for example PICARD, 2021); B. Willard and R. Louf, “Outlines” (2023).
  • OpenAI JSON mode (2023) and structured outputs (2024); XGrammar (2024).
  • Z. Tam et al., “Let me speak freely? A study on the impact of format restrictions” (2024); work on grammar-aligned decoding and SMC (2024).

Exercise 2.

  • Field: an integer from 0 to 99.
  • The model’s belief: most mass on two-digit values around 60, but 30% on three-digit values (for example it misreads units). It writes numbers digit by digit, then an end token.
  • Three approaches: prompt-only (accept anything), retry until valid (rejection sampling), and masked decoding (exact output distribution computed by enumerating the prefix tree).
approach validity attempts distance from the model’s valid distribution (TV) share of 10–19 mean value
model, given validity (target) — — 0 0.005 62.2
prompt only 0.719 1 (invalid outputs) — —
retry until valid 1.000 1.40 0 (exact) 0.005 62.2
masked decoding 1.000 1 0.273 0.263 48.4
  • Prompting is not enough: 28% of outputs violated the range.
  • Retrying is exact but costs: 1.4 generations on average, more when the model often violates the schema.
  • Masking is always valid but distorts: would-be 1xx answers were cut to 1x, so 10–19 rose from 0.5% to 26% of answers and the mean fell by 14. A downstream system would see plausible, valid, wrong numbers.
  • Seeds 1 and 2: TV 0.29 and 0.29; validity 0.70 and 0.70.
  • Lesson: constraints guarantee format, not meaning; when the model often wants to violate a constraint, fix the prompt or the schema rather than relying on the mask.
🐍 Exercise 2 (research): does constrained decoding preserve the model's answers, or only their format?
Compare prompt-only output, retry-until-valid and masked constrained decoding for a range-limited integer field; measure validity, cost and distortion.

Structured output in AI, robotics and aerospace

  • Information extraction: turning reports and logs into database rows with schema-checked fields.
  • Robotics: language-model planners emit actions as structured commands checked against an allowed action set.
  • Safety-relevant values: numbers extracted by models (limits, readings) should be range-checked and compared with unconstrained outputs to catch forced values.

References

  1. B. T. Willard and R. Louf (2023). “Efficient guided generation for large language models.” arXiv:2307.09702 (Outlines).
  2. Y. Dong et al. (2024). “XGrammar: flexible and efficient structured generation engine for large language models.” arXiv:2411.15100.
  3. Z. R. Tam et al. (2024). “Let me speak freely? A study on the impact of format restrictions on performance of large language models.” EMNLP Industry.
  4. K. Park et al. (2024). “Grammar-aligned decoding.” NeurIPS.