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:
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:
- Conversational preamble ("Sure! Here is...")
- Markdown code block fences (
```json) - Trailing conversational postamble ("I hope this...")
- 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:
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.
| Approach | Mechanism | Syntactic Reliability | Latency Overhead |
|---|---|---|---|
| Prompt Engineering | System prompt ("Respond in JSON") | ~85 - 92% (Unreliable) | Zero |
| Post-hoc Regex Extraction | Python regex cleanup + retry | ~95 - 98% | 10 - 20ms |
| Constrained Logit Masking | Engine-level BNF Grammar / DFA | 100% 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:
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
How does logit masking in constrained decoding prevent invalid JSON generation?
Practice: Sanitization, Extraction & Schema Validation
Warmup — Markdown fence stripping
Write strip_markdown_fence(text) that extracts the JSON string contained between ``json and `` fences. If no fences exist, return the stripped text.
Show hint
Use a regular expression or split on chr(96)*3.
Solution available after 3 attempts
Practice — Safe JSON extraction
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.
Show hint
Wrap json.loads(payload) in a try/except block returning default_val on exception.
Solution available after 3 attempts
Mastery — Schema validator with type checking
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.
Show hint
Iterate over required_schema items, verify key in data and isinstance(data[key], expected_type).
Solution available after 3 attempts