Try it first
Before you read, pick what you think is right. It's fine to be wrong.
Why is it hard to get JSON in a fixed shape out of an LLM?
What is constrained decoding?
An LLM hands back a string. Your app needs JSON. This gap has stopped more production systems than model hallucination has. Structured output is the bridge between natural language and typed data. Build it well and the LLM becomes an API you can trust; build it badly and you end up at 3 a.m. picking free-form sentences apart with regular expressions.
Type: Build Language: Python (standard library only) Prerequisites: Stage 1 Prompt Engineering, Python dictionaries and JSON basics Time: about 90 minutes Next: Stage 3 Embeddings — turning meaning into numbers Run: Right in the browser (no installation). Model responses are fake (simulated) and no real API is called.
What You'll Learn
- Use the JSON mode and schema mode of the OpenAI, Anthropic, and Google APIs to receive output in a fixed shape.
- Build a validation layer that filters out malformed output and feeds the error details back to the model so it can try again.
- Explain how constrained decoding forces valid JSON at the token level, without any post-processing.
- Design extraction prompts that reliably turn running prose into typed data.
The Problem
You ask an LLM: "Pull the product name, price, and stock status out of this text." The answer comes back like this.
The product is the Sony WH-1000XM5 headphones, the price is $348.00, and it is currently in stock.
A perfectly correct answer. And completely useless to your app. Your inventory system needs {"product": "Sony WH-1000XM5", "price": 348.00, "in_stock": true}. It needs a JSON object with fixed keys, fixed types, and fixed value ranges, not a sentence.
The easy fix is to add "answer in JSON" to the prompt. Most of the time it works. The trouble is the rest of the time. The model wraps the JSON in a markdown code fence (```), adds a preamble such as "Here is the JSON:", or closes a bracket too early and produces JSON with broken syntax. The parser dies and the pipeline stops. You add try/except and retries. A retry sometimes returns different data. Now you have a consistency problem on top of the parsing problem.
This is not a prompt problem; it is a decoding problem. The model produces tokens one at a time, from left to right. At each position it picks the most plausible next token out of a vocabulary of more than 100,000. But at any given position, most of those tokens would break the JSON. If the model has just written {"price":, what can come next is a number, a quote (a string), null, true, false, or a minus sign. Everything else makes the JSON invalid. Without constraints, the model can pick a word that is perfectly fine in English and fatal for the grammar.
The Concept
The four levels of structured output
Ways of pinning down the output shape fall into four levels, and the further along you go, the more reliable they are.
- Prompt only'answer in JSON'no enforcement
- JSON modeJSON syntax guaranteedshape not guaranteed
- Schema modeJSON + schema shape guaranteed
- Constrained decodingenforced by blocking tokens(the mechanism inside schema mode)
Prompt only ("answer in valid JSON"): There is no mechanism that enforces anything. The model usually complies, but not always. Common failures are code fences, preambles, output cut off midway, and the wrong structure.
JSON mode: The API guarantees that the output is syntactically valid JSON. OpenAI's response_format: {"type": "json_object"} is this. Parsing is certain to succeed. But there is no guarantee that it matches the shape you wanted. There can be extra keys, wrong types, or missing fields.
Schema mode: The API takes a JSON schema and guarantees that the output matches it. As of November 2026, all the major companies offer it as a standard feature. OpenAI has Structured Outputs (the json_schema format with strict: true), Anthropic has structured outputs (output_config.format) and strict tool use (strict: true), and Google Gemini has the response schema (mime_type and schema in response_format). The output comes back with the keys, types, and constraints you defined.
XenLook note The "guarantee" has two gaps. First, if the model refuses to ans…
The "guarantee" has two gaps. First, if the model refuses to answer for safety reasons, you get a refusal message that does not match the schema (OpenAI has a refusal field; for Anthropic, stop_reason is "refusal"). Second, if the output hits the token limit and is cut off midway, the JSON arrives incomplete (Anthropic stop_reason: "max_tokens"; for OpenAI, a response that ended because the length limit was exceeded). So even in schema mode, always check the "reason it finished". This was confirmed against the official documentation of all three companies in November 2026.
Constrained decoding: While generating, at every token position, it masks out every token that would lead to invalid output. If the schema calls for a number and the model is about to emit a letter, that token's probability is set to 0. The model can only emit tokens that lead to valid output. This is the method OpenAI's Structured Outputs uses inside, and the libraries for open models, Outlines, Guidance, and XGrammar, use it too.
JSON Schema — the language for writing the promise
JSON Schema is a way of telling the model (or the validation layer) what shape the output must have. All the major structured output features use it.
{
"type": "object",
"properties": {
"product": { "type": "string" },
"price": { "type": "number", "minimum": 0 },
"in_stock": { "type": "boolean" },
"categories": {
"type": "array",
"items": { "type": "string" }
}
},
"required": ["product", "price", "in_stock"]
}This schema means the following. The output must be an object. It must have a string product, a number price of at least 0, and a boolean in_stock, and a string array categories may or may not be present. Output that does not match is rejected.
Schemas also handle harder cases. There are nested objects, arrays with typed items, enums (limiting a string to one of a fixed set of values), patterns (a regular expression on a string), and combinations (oneOf, anyOf, allOf, which pick one of several shapes).
XenLook note The keywords that schema mode accepts differ from company to com…
The keywords that schema mode accepts differ from company to company. OpenAI strict mode requires you to put every field in required and attach additionalProperties: false (a field that may be absent is imitated by allowing null, as in "type": ["string", "null"]), and it does not accept allOf, not, or if/then/else. Anthropic does not use range constraints such as minimum, maximum, and minLength in decoding. The official SDK moves such values into the description text and checks them separately after the response arrives. Gemini also ignores some keywords, so its documentation says "always validate received values in your app". The conclusion is one: even when you use schema mode, keep your own validation.
The Pydantic way
In Python you do not write JSON Schema by hand. You define a Pydantic model and the schema is generated.
from pydantic import BaseModel
class Product(BaseModel):
product: str
price: float
in_stock: bool
categories: list[str] = []This yields the same JSON schema as above. The Instructor library and each company's official SDK accept a Pydantic model as it is. Pass in the model class and a validated object comes back. Instructor retries on its own when the output does not match.
Function calling / tool use
This is a way to solve the same problem through a different door. Instead of making the model write JSON directly, you define a "tool" (a function) whose parameters have fixed types. The model produces a function call that carries structured arguments. OpenAI calls this "function calling" and Anthropic calls it "tool use". The result is the same: structured data.
- User: Pull the product infoout of this review
- Model processes the input
- Tool call:extract_product( product='Sony WH-1000XM5', price=348.00, in_stock=true)
- Validate againstthe function schema
- Structured result:{product, price, in_stock}
Tool use fits better when the model has to choose which function to call, not only fill in parameters. If you have 10 extraction schemas and the input decides which one is right, tool use gives you schema selection and structured output in one step. If instead the job is only to fix the shape of the answer, structured output (schema mode) is simpler.
XenLook note It used to be common to explain that "tool use is the only way t…
It used to be common to explain that "tool use is the only way to get structured output from Claude". That is no longer true. Anthropic also provides structured outputs (output_config.format) as an official feature, so use it when you only need to fix the shape of the answer, and use tool use when you want the model to choose a tool. The output_format parameter and beta header that appear in old examples on the internet are the old way.
Common failures
Even when you enforce a schema, structured output fails in ways that are hard to see.
Made-up values: The output matches the schema but the content is invented. The text says $348, but the model returns {"price": 299.99}. The type is right and the value is wrong, so schema validation cannot catch it. In "Build" part 4 below, you will build a check that compares against the input text.
Enum confusion: You limited a field to ["in_stock", "out_of_stock", "preorder"] and the model returns "available". The meaning is right, but it is not an allowed value. Constrained decoding prevents this; a prompt alone cannot.
Deep nesting: The deeper a schema is nested, the more errors appear. Each additional level of depth gives the model one more place to lose the structure.
Array length: The model may produce too many or too few array items. Schemas have minItems and maxItems, but not every company enforces them at the decoding stage.
Dropping optional fields: The model leaves out a field that is optional in form but important for your task. Even if the data is sometimes missing, make the field required in the schema and allow null instead. That makes the model say "none" explicitly as null.
Build It
XenLook note The Python names and output text are in English because real-wor…
The Python names and output text are in English because real-world code usually is too. It uses only the standard library (json, re), so it runs as it is in "Run the code" at the bottom of this page, with no installation. The model responses are not a real API; they are fakes that imitate mistakes real models often make.
1) A JSON schema validator
You build, from scratch, a validator that checks whether a Python object matches a JSON schema. This is the part on the output side that checks the schema was respected. It also handles the cases where a type allows several options, as in "type": ["string", "null"], and additionalProperties: false, which blocks fields not in the schema. Both are shapes that the OpenAI and Anthropic strict modes require.
import json
import re
def type_matches(data, expected):
if expected == "object":
return isinstance(data, dict)
if expected == "array":
return isinstance(data, list)
if expected == "string":
return isinstance(data, str)
if expected == "number":
return isinstance(data, (int, float)) and not isinstance(data, bool)
if expected == "integer":
return isinstance(data, int) and not isinstance(data, bool)
if expected == "boolean":
return isinstance(data, bool)
if expected == "null":
return data is None
return Truedef validate_schema(data, schema):
errors = []
_validate(data, schema, "", errors)
return errors
def _validate(data, schema, path, errors):
schema_type = schema.get("type")
# "type": ["string", "null"] means "a string, or an explicit null".
if isinstance(schema_type, list):
if data is None and "null" in schema_type:
return
matching = [t for t in schema_type if t != "null" and type_matches(data, t)]
if not matching:
errors.append(f"{path}: expected {' or '.join(schema_type)}, got {type(data).__name__}")
return
schema_type = matching[0]
if schema_type == "object":
if not isinstance(data, dict):
errors.append(f"{path}: expected object, got {type(data).__name__}")
return
for key in schema.get("required", []):
if key not in data:
errors.append(f"{path}.{key}: required field missing")
properties = schema.get("properties", {})
for key, value in data.items():
if key in properties:
_validate(value, properties[key], f"{path}.{key}", errors)
elif schema.get("additionalProperties") is False:
errors.append(f"{path}.{key}: field not allowed by schema")
elif schema_type == "array":
if not isinstance(data, list):
errors.append(f"{path}: expected array, got {type(data).__name__}")
return
min_items = schema.get("minItems", 0)
max_items = schema.get("maxItems", float("inf"))
if len(data) < min_items:
errors.append(f"{path}: array has {len(data)} items, minimum is {min_items}")
if len(data) > max_items:
errors.append(f"{path}: array has {len(data)} items, maximum is {max_items}")
items_schema = schema.get("items", {})
for i, item in enumerate(data):
_validate(item, items_schema, f"{path}[{i}]", errors)
elif schema_type == "string":
if not isinstance(data, str):
errors.append(f"{path}: expected string, got {type(data).__name__}")
return
enum_values = schema.get("enum")
if enum_values and data not in enum_values:
errors.append(f"{path}: '{data}' not in allowed values {enum_values}")
elif schema_type == "number":
if not type_matches(data, "number"):
errors.append(f"{path}: expected number, got {type(data).__name__}")
return
minimum = schema.get("minimum")
maximum = schema.get("maximum")
if minimum is not None and data < minimum:
errors.append(f"{path}: {data} is less than minimum {minimum}")
if maximum is not None and data > maximum:
errors.append(f"{path}: {data} is greater than maximum {maximum}")
elif schema_type == "boolean":
if not isinstance(data, bool):
errors.append(f"{path}: expected boolean, got {type(data).__name__}")
elif schema_type == "integer":
if not type_matches(data, "integer"):
errors.append(f"{path}: expected integer, got {type(data).__name__}")2) Generating a schema from a Python model
You imitate, in miniature, what Pydantic does. It generates a JSON schema from the field definitions and attaches additionalProperties: false to fit strict mode.
class SchemaField:
def __init__(self, field_type, required=True, default=None, enum=None, minimum=None, maximum=None):
self.field_type = field_type
self.required = required
self.default = default
self.enum = enum
self.minimum = minimum
self.maximum = maximum
def python_type_to_schema(field):
type_map = {
str: "string",
int: "integer",
float: "number",
bool: "boolean",
}
schema = {}
if field.field_type in type_map:
schema["type"] = type_map[field.field_type]
elif field.field_type == list:
schema["type"] = "array"
schema["items"] = {"type": "string"}
elif isinstance(field.field_type, dict):
schema = dict(field.field_type)
if field.enum:
schema["enum"] = field.enum
if field.minimum is not None:
schema["minimum"] = field.minimum
if field.maximum is not None:
schema["maximum"] = field.maximum
return schema
def model_to_schema(name, fields):
properties = {}
required = []
for field_name, field in fields.items():
properties[field_name] = python_type_to_schema(field)
if field.required:
required.append(field_name)
return {
"type": "object",
"properties": properties,
"required": required,
"additionalProperties": False,
}3) A constrained-token filter
Given JSON that is partway through generation, it tells you what kinds of token may come next. This is the heart of constrained decoding. A real engine handles the model's entire vocabulary, but here we follow the state character by character and report only token kinds. The key is remembering whether you are currently inside quotes, and whether the string that just closed was a key or a value. Looking only at the last character, you cannot tell that a colon (:) must follow {"product".
Give it the schema as well and it goes one step further. Grammar alone would allow any value after {"price":, but the schema allows only a number. It allows only keys not yet written, and it blocks } until all the required fields have appeared.
def scan_partial_json(text):
"""Walk a partial JSON string and return the parser state at its end."""
stack = [] # open containers: "{" or "["
expect = "value" # what the grammar allows next
in_string = False
string_is_key = False
escape = False
literal = "" # a number / true / false / null being typed
current = "" # characters of the string being typed
last_key = None # last key seen in the top-level object
keys_seen = [] # keys already written in the top-level object
for ch in text:
if in_string:
if escape:
escape = False
elif ch == "\\":
escape = True
elif ch == '"':
in_string = False
if string_is_key:
if len(stack) == 1:
last_key = current
keys_seen.append(current)
expect = "colon"
else:
expect = "after_value"
continue
current += ch
continue
if literal:
if ch.isalnum() or ch in ".-+":
literal += ch
continue
literal = ""
expect = "after_value"
if ch.isspace():
continue
if expect in ("value", "value_or_close"):
if ch == '"':
in_string, string_is_key, current = True, False, ""
elif ch == "{":
stack.append("{")
expect = "key_or_close"
elif ch == "[":
stack.append("[")
expect = "value_or_close"
elif ch == "]" and expect == "value_or_close":
stack.pop()
expect = "after_value"
else:
literal = ch
elif expect in ("key", "key_or_close"):
if ch == '"':
in_string, string_is_key, current = True, True, ""
elif ch == "}" and expect == "key_or_close":
stack.pop()
expect = "after_value"
elif expect == "colon":
if ch == ":":
expect = "value"
elif expect == "after_value":
if ch == ",":
expect = "key" if stack and stack[-1] == "{" else "value"
elif ch in "}]" and stack:
stack.pop()
expect = "after_value"
return {
"stack": stack, "expect": expect, "in_string": in_string,
"string_is_key": string_is_key, "literal": literal,
"last_key": last_key, "keys_seen": keys_seen,
}VALUE_TOKENS = ['"', "0-9", "-", "true", "false", "null", "[", "{"]SCHEMA_VALUE_TOKENS = {
"string": ['"'],
"number": ["0-9", "-"],
"integer": ["0-9", "-"],
"boolean": ["true", "false"],
"array": ["["],
"object": ["{"],
"null": ["null"],
}def next_valid_tokens(partial_json, schema=None):
"""Which kinds of token may come next.
With schema=None only JSON grammar is enforced. With a schema, the
top-level object is also held to its keys, types and required fields.
"""
if not partial_json.strip():
return ["{"]
st = scan_partial_json(partial_json)
top = schema if schema and schema.get("type") == "object" else None
at_top = len(st["stack"]) == 1 and st["stack"][0] == "{"
props = top.get("properties", {}) if top else {}
required = top.get("required", []) if top else []
if st["in_string"]:
if st["string_is_key"] and top and at_top:
return ["(rest of a schema key)", '"']
return ["any character", '"']
if st["literal"]:
lit = st["literal"]
for word in ("true", "false", "null"):
if word.startswith(lit) and lit != word:
return [word[len(lit):]]
closer = "}" if st["stack"] and st["stack"][-1] == "{" else "]"
return ["0-9", ".", ",", closer]
expect = st["expect"]
if expect == "colon":
return [":"]
if expect in ("value", "value_or_close"):
tokens = list(VALUE_TOKENS)
if top and at_top and st["last_key"] in props:
t = props[st["last_key"]].get("type")
types = t if isinstance(t, list) else [t]
tokens = []
for one in types:
tokens += SCHEMA_VALUE_TOKENS.get(one, VALUE_TOKENS)
if expect == "value_or_close":
tokens.append("]")
return tokens
if expect in ("key", "key_or_close"):
if top and at_top:
remaining = [k for k in props if k not in st["keys_seen"]]
tokens = [f'"{k}"' for k in remaining]
missing = [k for k in required if k not in st["keys_seen"]]
if expect == "key_or_close" and not missing:
tokens.append("}")
return tokens
return ['"', "}"] if expect == "key_or_close" else ['"']
# after a complete value
if not st["stack"]:
return ["<EOS>"]
if st["stack"][-1] == "[":
return [",", "]"]
if top and at_top:
missing = [k for k in required if k not in st["keys_seen"]]
remaining = [k for k in props if k not in st["keys_seen"]]
tokens = [","] if remaining else []
if not missing:
tokens.append("}")
return tokens
return [",", "}"]
def demonstrate_constrained_decoding(schema):
partial_states = [
"",
"{",
'{"product"',
'{"product":',
'{"product": "Sony"',
'{"product": "Sony",',
'{"product": "Sony", "price":',
'{"product": "Sony", "price": 348',
'{"product": "Sony", "price": 348,',
'{"product": "Sony", "price": 348, "in_stock": t',
'{"product": "Sony", "price": 348, "in_stock": true',
'{"product": "Sony", "price": 348, "in_stock": true}',
]
for state in partial_states:
display = state if state else "(empty)"
print(f"\n {display}")
print(f" grammar only : {next_valid_tokens(state)}")
print(f" with schema : {next_valid_tokens(state, schema)}")4) The extraction pipeline and retries
It pulls structured data out of text, validates it, and if that fails, tries again telling the model what was wrong. The fake model makes mistakes that real models often make. For the Sony text it adds a preamble and a code fence, and for the MacBook text it returns the price as a string like "$2,499". Only on the second attempt, having received the error details, does it fix them.
The last two cases are the important ones. For a text with no information, it returns null rather than making a value up. For the earbuds text, which gives no price, it makes up a plausible price. That passes the schema. So we add one more check (grounding_problems) that compares against the input text to see whether the value is really there.
def simulate_llm_extraction(text, schema, attempt=0, feedback=None):
t = text.lower()
if "sony" in t:
if not feedback:
# Common failure: a friendly preamble and a markdown fence.
return ("Here's the JSON:\n```json\n"
'{"product": "Sony WH-1000XM5", "price": 348.00, "in_stock": true}\n```')
return '{"product": "Sony WH-1000XM5", "price": 348.00, "in_stock": true, "categories": ["audio", "headphones"]}'
if "macbook" in t or "laptop" in t:
if not feedback:
# Common failure: the price copied as text, not as a number.
return '{"product": "MacBook Pro 16", "price": "$2,499", "in_stock": false}'
return '{"product": "MacBook Pro 16", "price": 2499.00, "in_stock": false, "categories": ["computers"]}'
if "keyboard" in t:
return '{"product": "Keychron Q1", "price": 169.00, "in_stock": true, "categories": ["peripherals"]}'
if "earbuds" in t:
# Schema-valid but invented: the text gives no price.
return '{"product": "Aurora X2", "price": 129.00, "in_stock": true, "categories": ["audio"]}'
# Nothing to extract: an honest model answers with explicit nulls.
return '{"product": null, "price": null, "in_stock": null, "categories": []}'
def extract_with_retry(text, schema, max_retries=3):
feedback = None
for attempt in range(max_retries):
raw = simulate_llm_extraction(text, schema, attempt, feedback)
try:
data = json.loads(raw)
except json.JSONDecodeError as e:
print(f" Attempt {attempt + 1}: JSON parse error -- {e}")
feedback = f"Your output was not valid JSON ({e}). Return only the JSON object."
continue
errors = validate_schema(data, schema)
if not errors:
return data, attempt + 1
print(f" Attempt {attempt + 1}: Schema validation errors -- {errors}")
feedback = "Fix these errors and return only the JSON object: " + "; ".join(errors)
return None, max_retries
def grounding_problems(data, text):
"""Schema checks cannot see invented values. Check them against the source."""
problems = []
price = data.get("price")
if isinstance(price, (int, float)):
numbers = [float(n.replace(",", "")) for n in re.findall(r"\d[\d,]*(?:\.\d+)?", text)]
if float(price) not in numbers:
problems.append(f"price {price} does not appear in the text")
name = data.get("product")
if isinstance(name, str) and name.split()[0].lower() not in text.lower():
problems.append(f"product '{name}' does not appear in the text")
return problemsNULLABLE_PRODUCT_SCHEMA = {
"type": "object",
"properties": {
"product": {"type": ["string", "null"]},
"price": {"type": ["number", "null"], "minimum": 0},
"in_stock": {"type": ["boolean", "null"]},
"categories": {"type": "array", "items": {"type": "string"}},
},
"required": ["product", "price", "in_stock", "categories"],
"additionalProperties": False,
}PRODUCT_SCHEMA = {
"type": "object",
"properties": {
"product": {"type": "string"},
"price": {"type": "number", "minimum": 0},
"in_stock": {"type": "boolean"},
"categories": {"type": "array", "items": {"type": "string"}},
},
"required": ["product", "price", "in_stock"],
"additionalProperties": False,
}5) Run it all
It runs the five demos in turn: schema validation, schema generation, constrained decoding, the extraction pipeline, and nested schema validation.
def run_schema_validation_demo():
print("=" * 60)
print(" STEP 1: JSON Schema Validation")
print("=" * 60)
test_cases = [
({"product": "Sony WH-1000XM5", "price": 348.0, "in_stock": True}, "Valid complete object"),
({"product": "Test", "price": 10.0, "in_stock": True, "categories": ["audio"]}, "Valid with optional array"),
({"product": "Test", "price": -5.0, "in_stock": True}, "Negative price"),
({"product": "Test", "in_stock": True}, "Missing required field (price)"),
({"product": "Test", "price": "ten", "in_stock": True}, "String as price"),
({"product": 123, "price": 10.0, "in_stock": True}, "Number as product name"),
("not an object", "String instead of object"),
({"product": "Test", "price": 10.0, "in_stock": "yes"}, "String as boolean"),
({"product": "Test", "price": 10.0, "in_stock": True, "color": "black"}, "Extra field not in schema"),
]
for data, label in test_cases:
errors = validate_schema(data, PRODUCT_SCHEMA)
status = "PASS" if not errors else f"FAIL: {errors}"
print(f"\n {label}:")
print(f" Data: {json.dumps(data) if isinstance(data, dict) else repr(data)}")
print(f" Result: {status}")
def run_schema_generation_demo():
print(f"\n{'=' * 60}")
print(" STEP 2: Model-to-Schema Generation")
print("=" * 60)
product_fields = {
"product": SchemaField(str),
"price": SchemaField(float, minimum=0),
"in_stock": SchemaField(bool),
"categories": SchemaField(list, required=False),
"rating": SchemaField(float, required=False, minimum=0, maximum=5),
}
schema = model_to_schema("Product", product_fields)
print(f"\n Generated schema from Python model:")
print(f" {json.dumps(schema, indent=2)}")
event_fields = {
"title": SchemaField(str),
"date": SchemaField(str),
"attendees": SchemaField(list),
"priority": SchemaField(str, enum=["low", "medium", "high"]),
"is_recurring": SchemaField(bool, required=False),
}
event_schema = model_to_schema("Event", event_fields)
print(f"\n Event schema:")
print(f" {json.dumps(event_schema, indent=2)}")
valid_event = {"title": "Standup", "date": "2026-01-15", "attendees": ["Alice", "Bob"], "priority": "high"}
invalid_event = {"title": "Standup", "date": "2026-01-15", "attendees": ["Alice"], "priority": "urgent"}
print(f"\n Validating against event schema:")
for data, label in [(valid_event, "Valid event"), (invalid_event, "Invalid priority enum")]:
errors = validate_schema(data, event_schema)
status = "PASS" if not errors else f"FAIL: {errors}"
print(f" {label}: {status}")
def run_constrained_decoding_demo():
print(f"\n{'=' * 60}")
print(" STEP 3: Constrained Decoding Simulation")
print("=" * 60)
demonstrate_constrained_decoding(PRODUCT_SCHEMA)
def run_extraction_pipeline_demo():
print(f"\n{'=' * 60}")
print(" STEP 4: Extraction Pipeline with Retry")
print("=" * 60)
texts = [
"The Sony WH-1000XM5 headphones are priced at $348 and currently available in stores.",
"The new MacBook Pro 16-inch laptop costs $2499 but is completely sold out everywhere.",
"I just bought a Keychron Q1 mechanical keyboard for $169 and it arrived today.",
"The Aurora X2 earbuds are in stock this week.",
"This sentence contains no product information at all.",
]
for text in texts:
print(f"\n Input: {text[:70]}")
result, attempts = extract_with_retry(text, NULLABLE_PRODUCT_SCHEMA)
if result is None:
print(f" Output: FAILED after {attempts} attempts")
continue
print(f" Output ({attempts} attempt{'s' if attempts > 1 else ''}): {json.dumps(result)}")
if result.get("product") is None:
print(" Check: nothing found -- fields are null, not invented")
continue
problems = grounding_problems(result, text)
if problems:
print(f" Check: schema OK but NOT grounded -- {problems}")
else:
print(" Check: grounded in the text")
def run_nested_schema_demo():
print(f"\n{'=' * 60}")
print(" STEP 5: Nested Schema Validation")
print("=" * 60)
order_schema = {
"type": "object",
"properties": {
"order_id": {"type": "string"},
"customer": {
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
},
"required": ["name", "email"],
},
"items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"product": {"type": "string"},
"quantity": {"type": "integer"},
"price": {"type": "number", "minimum": 0},
},
"required": ["product", "quantity", "price"],
},
"minItems": 1,
},
"total": {"type": "number", "minimum": 0},
},
"required": ["order_id", "customer", "items", "total"],
}
valid_order = {
"order_id": "ORD-001",
"customer": {"name": "Alice", "email": "alice@example.com"},
"items": [
{"product": "Widget", "quantity": 3, "price": 9.99},
{"product": "Gadget", "quantity": 1, "price": 24.99},
],
"total": 54.96,
}
invalid_order = {
"order_id": "ORD-002",
"customer": {"name": "Bob"},
"items": [],
"total": -10,
}
print(f"\n Order schema (nested objects + arrays):")
for data, label in [(valid_order, "Valid order"), (invalid_order, "Invalid order")]:
errors = validate_schema(data, order_schema)
status = "PASS" if not errors else "FAIL"
print(f"\n {label}: {status}")
if errors:
for e in errors:
print(f" - {e}")if __name__ == "__main__":
run_schema_validation_demo()
run_schema_generation_demo()
run_constrained_decoding_demo()
run_extraction_pipeline_demo()
run_nested_schema_demo()How to read the results
XenLook note This section is a guide added by XenLook.
This section is a guide added by XenLook.
When you run it in "Run the code" below, STEP 3 prints lines like these.
{"product"
grammar only : [':']
with schema : [':']
{"product":
grammar only : ['"', '0-9', '-', 'true', 'false', 'null', '[', '{']
with schema : ['"']
{"product": "Sony"
grammar only : [',', '}']
with schema : [',']grammar only shows the tokens that may come next when looking at JSON grammar alone, and with schema shows them when the schema is taken into account too. After a key is closed, only a colon can come. After the colon, grammar alone allows any value, but the schema allows only a quote, because product is a string. After the value "Sony" is closed, a comma or a closing brace comes. With the schema, the closing brace drops out, because the required fields price and in_stock have not appeared yet. Real constrained decoding sets the probability of any token not on this list to 0.
STEP 4 ends like this.
Input: The Aurora X2 earbuds are in stock this week.
Output (1 attempt): {"product": "Aurora X2", "price": 129.0, "in_stock": true, "categories": ["audio"]}
Check: schema OK but NOT grounded -- ['price 129.0 does not appear in the text']
Input: This sentence contains no product information at all.
Output (1 attempt): {"product": null, "price": null, "in_stock": null, "categories": []}
Check: nothing found -- fields are null, not inventedPassing the schema does not make an answer correct. The earbuds text has no price, but the fake model made up 129. The type was right, so schema validation passed, and only the check against the input text caught it. For the last text, which has no information at all, every value came back as null. If you fill in "Unknown" or 0, you can no longer tell it apart from real data.
| Output part | Meaning |
|---|---|
| STEP 1 | Checks 9 cases against the product schema — negative price, missing field, wrong type, and a field not in the schema (color) are FAIL |
| STEP 2 | Two schemas generated from Python field definitions, and the disallowed enum value "urgent" is FAIL |
| STEP 3 | For each partially generated JSON, the tokens that may come next — grammar alone versus grammar plus schema |
| STEP 4 | Extraction results for five texts — on which attempt each passed, and whether it matches the input text |
| STEP 5 | The nested order schema — 3 errors for the bad order (missing email, empty items array, negative total) |
Try It
XenLook note The code below is entirely commented out (#), so it does not r…
The code below is entirely commented out (#), so it does not run. To actually run it you need each company's API key. The model IDs and function names come from each company's official documentation as of November 2026, so when you run it yourself, check that day's documentation once more.
OpenAI: Structured Outputs
# from openai import OpenAI
# from pydantic import BaseModel
#
# client = OpenAI()
#
# class Product(BaseModel):
# product: str
# price: float
# in_stock: bool
#
# response = client.responses.parse(
# model="gpt-6.1-terra",
# input=[
# {"role": "system", "content": "Extract product information."},
# {"role": "user", "content": "Sony WH-1000XM5, $348, in stock"},
# ],
# text_format=Product,
# )
#
# product = response.output_parsed
# print(product.product, product.price, product.in_stock)OpenAI's Structured Outputs uses constrained decoding inside. That is why you almost never need to retry because of a wrongly shaped output. But the two gaps seen in "The Concept" above (refusal, and being cut off by the length limit) remain, so check that the response finished normally. The schema also does not check for you whether a value matches the input text. If your code uses the older Chat Completions style, you can do the same thing with client.chat.completions.parse(..., response_format=Product).
Anthropic: Structured Outputs and Strict Tool Use
# import anthropic
# from pydantic import BaseModel
#
# client = anthropic.Anthropic()
#
# class Product(BaseModel):
# product: str
# price: float
# in_stock: bool
#
# # 1) When you only need to fix the shape of the answer: structured outputs
# response = client.messages.parse(
# model="claude-opus-5-5",
# max_tokens=1024,
# messages=[{"role": "user", "content": "Extract: Sony WH-1000XM5, $348, in stock"}],
# output_format=Product,
# )
# product = response.parsed_output
#
# # 2) When you want the model to choose a tool: strict tool use
# response = client.messages.create(
# model="claude-opus-5-5",
# max_tokens=1024,
# tools=[{
# "name": "extract_product",
# "description": "Extract product information from text",
# "strict": True,
# "input_schema": {
# "type": "object",
# "properties": {
# "product": {"type": "string"},
# "price": {"type": "number"},
# "in_stock": {"type": "boolean"},
# },
# "required": ["product", "price", "in_stock"],
# "additionalProperties": False,
# },
# }],
# messages=[{"role": "user", "content": "Extract: Sony WH-1000XM5, $348, in stock"}],
# )
# tool_call = next(b for b in response.content if b.type == "tool_use")
# print(tool_call.input)In the first method, the SDK converts the Pydantic model into a JSON schema in output_config.format and sends it, then validates the answer it gets back and returns it as parsed_output. The second method guarantees that the arguments of the tool call the model chose match input_schema. Without strict: True, there is no guarantee and you only get "usually right". The first time a schema is sent it is a little slow because the grammar has to be compiled, and for the next 24 hours a cache is used.
Google: Gemini Response Schema
# from google import genai
# from pydantic import BaseModel
#
# client = genai.Client()
#
# class Product(BaseModel):
# product: str
# price: float
# in_stock: bool
#
# interaction = client.interactions.create(
# model="gemini-3.8-flash",
# input="Extract: Sony WH-1000XM5, $348, in stock",
# response_format={
# "type": "text",
# "mime_type": "application/json",
# "schema": Product.model_json_schema(),
# },
# )
# product = Product.model_validate_json(interaction.output_text)Gemini takes a JSON schema and fits the answer's shape to it. As in the last line, validating the received string once more with Pydantic is the approach Google's documentation recommends, because some schema keywords are ignored.
The Instructor library
# pip install instructor
# import instructor
# from pydantic import BaseModel
#
# client = instructor.from_provider("anthropic/claude-opus-5-5")
#
# class Product(BaseModel):
# product: str
# price: float
# in_stock: bool
#
# product = client.create(
# response_model=Product,
# max_tokens=1024,
# messages=[{"role": "user", "content": "Sony WH-1000XM5, $348, in stock"}],
# )Instructor wraps the clients of several companies and adds validation and automatic retries. If the first attempt fails validation, it feeds the error details back to the model as context and has it fix them. The extract_with_retry you built yourself in "Build It" part 4 does exactly this. Change only the front part, as in "openai/…" or "google/…", and the same code works with other companies' models.
Ship It
This lesson produces two deliverables.
A structured extraction prompt — a reusable prompt template that, given a JSON schema and running prose, returns only JSON that fits the schema. Values that are not in the text are not made up; they are left as null.
A skill for choosing a structured output method — a decision framework for choosing the right method depending on the company you use, the reliability you need, and the schema complexity.
The Python code (code/structured_outputs.py) is a practice tool that runs on its own. If you replace simulate_llm_extraction with a real API call, the validator, the retries, and the check against the input text keep working without changes.
XenLook note The two deliverables can be opened and read in English under "De…
The two deliverables can be opened and read in English under "Deliverables" at the bottom of this page. Just copy them as they are and paste them into an AI chat window or a coding agent.
Exercises
-
Make the schema validator handle
oneOf(the data must match exactly one of several schemas). That lets you handle multi-shape output where a field may be aProductobject or a differently shapedServiceobject. -
Build a "schema diff" tool that compares two schemas and sorts the changes into breaking changes (deleting a required field, changing a type) and non-breaking changes (adding an optional field, relaxing a constraint). You need this when you manage versions of extraction schemas in production.
-
Build a more realistic constrained decoding simulator. Give it a JSON schema and a 100-token vocabulary (letters, digits, punctuation, keywords), generate one step at a time, and mask the invalid tokens at each position. Measure what percentage of the vocabulary is allowed at each position. You may use
scan_partial_jsonfrom "Build It" part 3 as it is. -
Build an extraction evaluation set. Attach a human-written answer JSON to 50 product descriptions, run the pipeline on all of them, and measure the exact-match rate, per-field accuracy, and type compliance rate. Find which field is hardest to extract.
-
Add "confidence" to the extraction pipeline. Estimate how confident the model is for each field (by looking at token probabilities, or by running the same extraction 3 times and seeing how much the runs agree). Flag low-confidence fields for human review.
[옮긴이] In the XenLook course, we recommend using the check against the input text from "Build It" part 4 here as well. Even if all three runs gave the same value, a value that is not in the input text is made up. Consistency and fact are different problems.
Key Terms
| Term | What people say | What it actually means |
|---|---|---|
| JSON mode | "Returns JSON" | An API setting that guarantees the output is syntactically valid JSON. It does not enforce any particular schema |
| Structured output | "Typed JSON" | Output that matches the keys, types, and constraints of a given JSON schema |
| Constrained decoding | "Guided generation" | At each token position, masks tokens that would lead to invalid output so that only schema-conforming output comes out. Cases that end in a refusal or a length cutoff must be checked separately |
| JSON Schema | "A JSON template" | A declarative language for describing the structure, types, and constraints of JSON data (also used in OpenAPI, JSON Forms, and others) |
| Pydantic | "Python dataclasses, extended" | A Python library for defining data models with type validation. FastAPI, Instructor, and each company's SDK use it to build JSON schemas |
| Function calling | "Tool use" | The LLM produces a structured function call (a name plus typed arguments) instead of free-form sentences. OpenAI, Anthropic, and Google all support it |
| Instructor | "Pydantic for LLMs" | A Python library that wraps an LLM client, returns validated Pydantic objects, and retries automatically when validation fails |
| Token masking | "Vocabulary filtering" | Sets the probability of specific tokens to 0 during generation so the model cannot emit them |
| Schema compliance | "The shape is right" | All required fields are present, the types are right, values are within the constraints, and no disallowed fields appear |
| Retry loop | "Try again until it works" | Feeds the validation errors back to the model and has it fix them. Instructor does this automatically up to a set number of times |
| Grounding check | "Checking the evidence" | A check that the extracted value really appears in the input text. It catches made-up values that the schema cannot (a term added by the XenLook course) |
Further Reading
- OpenAI Structured Outputs guide — OpenAI's official documentation on JSON-schema-based structured outputs, the schema rules of strict mode, and refusal handling
- Anthropic structured outputs guide —
output_config.format, strict tool use, unsupported schema keywords, and how the SDK handles them - Gemini structured output guide — the response schema, supported keywords, and how it differs from function calling
- Willard & Louf, 2023 — "Efficient Guided Generation for Large Language Models" — The Outlines paper. How to turn a JSON schema into a finite state machine and constrain generation token by token
- Instructor documentation — A library for getting structured output from LLMs of many companies through Pydantic validation and retries
- JSON Schema specification — The full specification of the schema language that structured output features use
- Outlines library — An open library that turns regular expressions and JSON schemas into finite state machines to constrain generation
- Dong et al., "XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models" (MLSys 2025) — A grammar engine that compiles grammars with pushdown automata to mask tokens quickly
- Beurer-Kellner et al., "Prompting Is Programming: A Query Language for Large Language Models" (LMQL) — A paper that treats constrained decoding as a query language with type and value constraints
- Microsoft Guidance — A template-based constrained generation library. It is not tied to any one company and is used alongside Outlines and XGrammar
This lesson is an English edition, translated by XenLook from its corrected Korean edition, of Rohit Ghumare's AI Engineering from Scratch (MIT License).
Run it yourself
structured_outputs.py
This is the code of this lesson. Press the button and Python runs only inside this browser. Your code and results are never sent to XenLook servers.
Not run yet.
Check your understanding
When you've read it all, try these. You see the answer and the explanation as soon as you choose.
What is the benefit of validating LLM output with a Pydantic model?
What should you do when an LLM returns wrong JSON even though you instructed it not to?
When should you use the structured output an API provides natively, and when the approach of only asking for JSON in the prompt?
What you take away
These are the things you build in this lesson and keep. Tap to open.
PromptStructured Extraction PromptGiven a JSON schema and running prose, an extraction prompt that returns one schema-conforming JSON object built only from what the text says
You are a structured data extractor. I will give you a JSON schema and some running prose. Extract the data from the text and produce JSON that matches the schema exactly.
Extraction procedure
1. Study the schema
Before extracting, study the schema.
- Check the required fields and the type of each
- Check enums, minimum and maximum values, and format conditions
- Check the nested object and array structure
- Check which fields allow null
- Note in advance which fields will be ambiguous or hard to extract from the text
2. Extraction rules
Use only what is in the text: Every value must be written in the text or follow directly from it. Do not make up a value just because it seems plausible. Prices, dates, quantities, and names in particular must be exactly as they appear in the text.
Information not in the text: Even for a required field, do not fill it with an invented default value.
- If the schema allows null, write
null - If it is an array, write an empty array
[] - If it is a required field that does not allow null and the text has no information for it, do not make up a value; write that field in the "extraction notes" below. If the schema has no place for notes, return
{"error": "missing_required", "fields": ["field name"]}instead of JSON - Do not fill the gap with values such as "unknown", "no information", 0, or false. You would no longer be able to tell them apart from real values
Follow types exactly: Every value must match the schema's type exactly.
- For "price" of type number: 348.00, not "$348" or "three hundred forty-eight dollars"
- For "in_stock" of type boolean: true/false, not "yes" or "available"
- For "categories" of type array: ["audio", "headphones"], not "audio, headphones"
Enum fields: The value must be one of the allowed values. If the text uses a similar word, map it to the closest allowed value (for example, "available" → "in_stock"). If it clearly matches none of the values, write null when null is allowed; otherwise, write it in the extraction notes.
Nested objects: Extract each nested level separately, and fit inner objects to their own sub-schemas.
Fields not in the schema: Do not create keys that are not in the schema. If the schema has additionalProperties: false, always obey it.
3. Check confidence
For each extracted field, gauge your confidence in your head.
- High: It is clearly written in the text
- Medium: It is hinted at in the text or needs a little inference
- Low: The text alone gives weak grounds — do not write such a value; leave it as null or put it in the notes
If any field has low confidence or any required field is empty, write a short note in an _extraction_notes field, but only when the schema allows additional fields (for example, "price: the text gives no price"). If the schema does not allow additional fields, do not include notes.
4. Output format
Return only one JSON object. Do not add markdown code fences, preambles, or explanations. The output must be readable directly by JSON.parse() or json.loads().
Input format
Schema:
{schema}Text to extract from:
{text}
Output
One JSON object that matches the schema exactly.
How to use: replace
{schema}and{text}, then paste it into an AI chat window. If you use it together with an API's schema mode (structured outputs), the API guarantees the shape and this prompt takes care of the content rule "only what is in the text, null if absent". To check whether a received value really appears in the text, check once more in code, as in the input-text check in "Build It" part 4 of the lesson.
SkillChoosing a Structured Output MethodA decision framework for choosing the right structured output method based on the company you use, the reliability you need, and the schema complexity
Use this decision framework when you build an LLM app that needs data in a fixed shape.
When to use each method
Prompt only ("answer in JSON"): Use it only for prototypes and internal tools where an occasional parsing failure is acceptable. Always add validation and a retry with an upper limit on attempts. Do not use it in production pipelines.
JSON mode (API setting): When syntactically valid JSON is a must but the schema is simple or flexible. The assumption is that your app checks the shape. OpenAI's json_object format is the typical example.
Schema mode (structured outputs): Production systems where every output must match a fixed schema. Use it as the default for production extraction and classification work. There are OpenAI and Anthropic structured outputs, the Gemini response schema, and Outlines, Guidance, and XGrammar for open models. The shape is guaranteed, but responses that ended in a refusal or a length cutoff, and made-up values, still have to be checked on your side.
Function calling / tool use: When the model has to choose which function to call, not only fill in parameters. Use it when there are several schemas and you want the model to pick the right one, or when attaching to an existing tool setup. Strict mode (strict: true) must be on for the arguments to be guaranteed to match the schema.
The Instructor library: When you want Pydantic validation and automatic retries with any company's model. It is the most convenient in Python projects. It wraps OpenAI, Anthropic, Google, and open models.
Company-specific guidance (per official documentation, November 2026)
OpenAI: Use Structured Outputs (the json_schema format, strict: true). Pass a Pydantic model directly to the SDK's responses.parse(..., text_format=Model). Strict mode puts every field in required and demands additionalProperties: false. A field that may be absent is expressed by allowing null. Check the response's refusal.
Anthropic: To fix only the shape of the answer, use structured outputs (output_config.format, SDK messages.parse(..., output_format=Model)). To have the model choose a tool, use strict tool use (strict: true). Range constraints (minimum, maxLength, and so on) and recursive schemas are not enforced in decoding, so validate after receiving, as the SDK does. If stop_reason is "refusal" or "max_tokens", the output may not match the schema.
Google Gemini: Give response_format a mime_type: "application/json" and a JSON schema. Some keywords are ignored, so validate the received string again with Pydantic.
Open models (vLLM, SGLang, Ollama, and others): Use the serving engine's structured output feature (which usually uses a grammar engine such as XGrammar or Outlines), or use Outlines or Guidance. They convert the JSON schema into a state machine or grammar and mask invalid tokens during generation. You have to run the inference server yourself.
Schema design principles
- Keep it as flat as you can. The deeper the nesting, the more extraction errors appear.
- Use enums for categorical fields. Do not expect the model to invent the right string.
- For ambiguous fields, do not make them optional; make them required but allow null. The model will then say "none" explicitly.
- Attach a description (
description) to each field. The model reads descriptions as instructions. - Avoid multi-shape types (
oneOf,anyOf) unless they are truly needed. They complicate decoding and validation, and support differs from company to company. - Give numbers a minimum and a maximum. This catches absurd made-up values. Some companies do not enforce them in decoding, so check in your validator too.
- Give arrays
minItemsandmaxItemsto block empty or endless arrays. Likewise, whether they are enforced differs from company to company.
Common failures and fixes
- JSON wrapped in a markdown code fence: move from the prompt-only method to JSON mode or schema mode
- Matches the schema but the content is wrong: compare in code whether the extracted values really appear in the input text (prices, dates, names). For content that is hard to check in code, add an LLM evaluation step or have a person review it
- Enum values come out inconsistent: move to constrained decoding (schema mode), or snap to the allowed values in post-processing
- Optional fields keep getting dropped: change to required + allow null. Do not fill in made-up defaults in your app code
- Extraction is too slow: the first time a schema is used, it can be slow because the grammar is being compiled (usually cached afterward). If latency matters, reuse the same schema, simplify the schema, and judge by measuring the real latency
- A large array of uneven items: split the input, extract from each piece, and merge
- The response is cut off midway: check the reason it finished (length exceeded), then raise the output token limit or split the input
Reliability ladder
| Method | Parsing guaranteed | Schema shape guaranteed | Checks that remain |
|---|---|---|---|
| Prompt only | No | No | Parsing, shape, and content, all of them — validation + retry required |
| JSON mode | Yes | No | Shape and content — schema validation in the app |
| Schema mode / strict tool use | Yes* | Yes* (within supported keywords) | Refusals and cutoffs, unsupported constraints, content |
| Open model + grammar engine | Yes* | Yes* | Cutoffs, content |
| Instructor + retries | Confirmed by validation | Confirmed by validation | Content, retry count and cost |
* Responses that ended in a refusal or a length cutoff are the exception. No method guarantees that the values are true, so the "content" check on the last line is always your job.
This course is XenLook's English translation and revision of Rohit Ghumare's AI Engineering from Scratch (MIT License), based on the Korean edition we corrected against the original. Source commit: 8fec9cc19e.
Full MIT License text
MIT License
Copyright (c) 2026 Rohit Ghumare
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.Source lesson: phases/11-llm-engineering/03-structured-outputs