Example

Separate validating JSON from constraining decoding

Validate a good, incomplete and malformed record, then apply a token mask and see why a post-hoc check is not constrained generation.

There are two different guarantees hiding under “structured output”. A validator checks text after the model has produced it and may reject or repair it. A constrained decoder changes the next-token distribution during generation so that invalid tokens cannot be chosen. The first can fail after paying for the whole generation; the second needs a schema compiler and a token mask.

This example demonstrates both primitives at a small scale. validate_json accepts a complete record, rejects a record missing value, and rejects malformed JSON. FiniteStateDecoder filters a candidate list down to allowed tokens. The filter is a mask primitive, not a model loop: the page does not claim that a model was constrained. The chapter’s structured_lab.py is where the schema compiler is wired into a real model, and it is optional here.

Run it

From the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch35/structured.py --json

Python 3.11 or later with jsonschema. No model, network, GPU or credentials. It finishes immediately. The real-model constrained-decoding experiment requires Qwen3-0.6B and CUDA and is not the default path.

Implementation

The schema requires an object with answer and value and forbids additional properties. The decoder keeps only tokens in its allowed set and raises if the set becomes empty. The two mechanisms are deliberately adjacent so their different scope is visible.

SCHEMA = {
    "type": "object",
    "properties": {
        "answer": {"type": "string"},
        "value": {"type": "number"},
    },
    "required": ["answer", "value"],
    "additionalProperties": False,
}


def validate_json(text: str, schema: dict = SCHEMA) -> ValidationResult:
    try:
        data = json.loads(text)
    except json.JSONDecodeError as exc:
        return ValidationResult(valid=False, errors=[str(exc)])
    errors = []
    try:
        jsonschema.validate(instance=data, schema=schema)
    except jsonschema.ValidationError as exc:
        errors.append(exc.message)
    return ValidationResult(valid=len(errors) == 0, errors=errors, metadata={"data": data})


class FiniteStateDecoder:
    def __init__(self, allowed_tokens: List[str]) -> None:
        self.allowed = set(allowed_tokens)

    def filter(self, candidates: List[str]) -> List[str]:
        return [c for c in candidates if c in self.allowed]

    def decode_step(self, candidates: List[str]) -> str:
        filtered = self.filter(candidates)
        if not filtered:
            raise ValueError("no allowed tokens")
        return filtered[0]

Expected outcome

Observed with the command above (exit 0):

{
  "good": {
    "valid": true,
    "errors": [],
    "metadata": {
      "data": {
        "answer": "yes",
        "value": 42
      }
    }
  },
  "bad": {
    "valid": false,
    "errors": [
      "'value' is a required property"
    ],
    "metadata": {
      "data": {
        "answer": "yes"
      }
    }
  },
  "invalid": {
    "valid": false,
    "errors": [
      "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"
    ],
    "metadata": {}
  },
  "filtered": [
    "a",
    "b"
  ]
}

The good record passes. The incomplete record is valid JSON but violates the schema. The malformed record fails before schema validation. The token filter drops x and keeps a and b; it has no notion of the JSON grammar, so this is a mask demonstration, not a proof that a model can only emit valid JSON.

Mechanism and limitations

Documented: validate_json returns a ValidationResult with a valid flag, error messages and parsed data when available. FiniteStateDecoder filters a candidate list and raises when no candidate is allowed. The tests check a valid record, a missing field, malformed JSON, filtering, the empty-allowed error, the demo and JSON serialisation.

Observed: the command exited 0 with the four results above. The targeted tests.test_ch35_structured is part of the canonical suite; no independent test count is claimed here.

Not shown: constrained generation, a schema-to-automaton compiler, tokeniser boundaries, a model, or a guarantee that a generated record says the right thing. The filter operates on strings, not token ids, and is not integrated with a decoder. The chapter’s structured_lab.py and schema_core.py contain the real compiler and masking experiment; this page does not quote their measurements.

Challenge this result

Add a third property to the schema and omit it from the good record; the validator should reject it. Then add a token that would start an invalid JSON string to the allowed set and explain why the filter still cannot guarantee valid JSON without a grammar state. Finally, state the difference between a schema validator, a repair pass, a validate-and-retry loop, and a decoding constraint. Only one of them prevents an invalid token from being generated.

Source and verification

Canonical source: examples/ch35/structured.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch35_structured.py . Chapter: Structured Outputs and Constrained Decoding . The run above is a fresh local execution on Windows 11 with Python 3.13.15; it validates text and filters strings, and does not run a model.

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.