Skip to main content
Module 1 · Lesson 4 of 44/48 in the course~20 min
Module lessons (4/4)

Structured Outputs: JSON Schema & Constrained Decoding

The Challenge of Unconstrained LLM Generation

Foundation models are generative sequence predictors trained on natural language. When prompted to "Return a JSON object with name and age", an unconstrained model might emit:

Text
Sure! Here is the JSON you requested:
```json
{
  "name": "Alice",
  "age": 28,
}
```

I hope this helps!

This output immediately breaks standard json.loads() parsers due to:

  1. Conversational preamble ("Sure! Here is...")
  2. Markdown code block fences (```json)
  3. Trailing conversational postamble ("I hope this...")
  4. Invalid syntax (such as trailing commas before closing braces)

How Constrained Decoding Guarantees Valid JSON

Modern production engines (such as OpenAI Structured Outputs, vLLM Guided Decoding, and llama.cpp BNF grammars) do not rely on post-hoc prompt begging. Instead, they enforce JSON syntax at the sampling step through Logit Masking:

Text

Model predicts next token
│
▼
Grammar State Machine (e.g. JSON DFA)
Checks: "Is token valid given current syntax state?"
│
├── YES: Keep logit as-is
└── NO: Set logit to -Infinity (mask completely)
│
▼
Softmax & Sample
(Result is mathematically guaranteed to follow the JSON Schema)

If the JSON grammar is expecting a closing quote or comma, the logits for alphabetical letters are masked with -∞, making syntactic violations mathematically impossible.

ApproachMechanismSyntactic ReliabilityLatency Overhead
Prompt EngineeringSystem prompt ("Respond in JSON")~85 - 92% (Unreliable)Zero
Post-hoc Regex ExtractionPython regex cleanup + retry~95 - 98%10 - 20ms
Constrained Logit MaskingEngine-level BNF Grammar / DFA100% Guaranteed~2 - 5ms

Parsing & Cleaning Raw Model Responses in Python

When constrained decoding is unavailable (e.g. on legacy third-party endpoints), engineers use resilient extraction routines:

Python
import json
import re

def extract_json(raw_completion: str) -> dict:
    """Extracts and parses the first JSON object found inside raw text."""
    # Strip markdown fences if present
    match = re.search(r'```(?:json)?\s*(\{[\s\S]*?\})\s*```', raw_completion)
    if match:
        return json.loads(match.group(1))

    # Fallback to finding outermost curly braces
    start = raw_completion.find('{')
    end = raw_completion.rfind('}')
    if start != -1 and end != -1 and end > start:
        return json.loads(raw_completion[start:end+1])

    raise ValueError("No valid JSON payload detected in completion.")

Check Your Understanding

Quiz#ai-engineering.m1.l4.q1

How does logit masking in constrained decoding prevent invalid JSON generation?

Answer options

Practice: Sanitization, Extraction & Schema Validation

Practice Stage

Warmup — Markdown fence stripping

Exercise#ai-engineering.m1.l4.e1
Attempts: 0Loading…

Write strip_markdown_fence(text) that extracts the JSON string contained between ``json and `` fences. If no fences exist, return the stripped text.

Loading editor…
Show hint

Use a regular expression or split on chr(96)*3.

Solution available after 3 attempts

Practice Stage

Practice — Safe JSON extraction

Exercise#ai-engineering.m1.l4.e2
Attempts: 0Loading…

Write safe_parse_json(payload, default_val=None) that loads a JSON string into a dict. If json.loads fails with an error, return default_val.

Loading editor…
Show hint

Wrap json.loads(payload) in a try/except block returning default_val on exception.

Solution available after 3 attempts

Practice Stage

Mastery — Schema validator with type checking

Exercise#ai-engineering.m1.l4.e3
Attempts: 0Loading…

Write validate_schema(data, required_schema) where required_schema is a dict mapping field names to expected types (e.g. {'name': str, 'age': int}). Return True if data contains all keys with matching types, else False.

Loading editor…
Show hint

Iterate over required_schema items, verify key in data and isinstance(data[key], expected_type).

Solution available after 3 attempts