Sub topic 6
Schema-constrained structured outputs
This chapter assumes you know basic Python, can read JSON, and have called an LLM API before. It also assumes you have seen JSON mode, which guarantees syntactically valid JSON but not your fields.
What constrained decoding does
A language model produces text one token at a time. At each step it scores every token in its vocabulary and picks one. In schema-constrained decoding, the provider converts your JSON Schema into a grammar. Before each pick, it masks out every token that would break that grammar. The model can only choose tokens that keep the output valid.
The result is a guarantee about shape. The reply parses as JSON, contains every required key, uses the right types, and uses only values from your enums. Prompting and JSON mode cannot promise this.
Writing a schema providers accept
Here is a hand-written schema for the ticket triage task.
{
"type": "object",
"properties": {
"category": {
"type": "string",
"enum": ["billing", "bug", "feature_request", "other"]
},
"priority": {
"type": "integer",
"description": "1 is most urgent, 3 is least urgent"
},
"summary": {
"type": "string",
"description": "One-sentence summary of the ticket"
}
},
"required": ["category", "priority", "summary"],
"additionalProperties": false
}Two lines matter most. required lists every key, so none can be omitted. "additionalProperties": false forbids extra keys. Many providers require both in strict mode.
Notice what is missing. The Pydantic model from the earlier chapter limits priority to 1 through 3 and summary to 200 characters. This schema has no minimum, maximum, or maxLength.
Supported subset
Providers support only a subset of JSON Schema. Grammar compilation is hard for some features, so providers reject or ignore them. The exact list changes by provider and over time, so check your provider's documentation. Typical restrictions are:
- Keywords such as
minimum,maximum,minLength, andmaxLengthmay be unsupported or not enforced. - Every property must be listed in
required. Optional fields are often written as a type that also allowsnull. - Recursive schemas, deeply nested objects, and very large enums may hit limits.
- The first request with a new schema can be slower, because the grammar is compiled and then cached.
Calling the API
Most providers accept a schema in a request field for the response format. The field name and nesting differ between providers. The sketch below follows the shape of OpenAI's Python SDK. Verify names against your provider's current documentation.
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel, Field
class TicketTriage(BaseModel):
category: Literal["billing", "bug", "feature_request", "other"]
priority: int = Field(description="1 is most urgent, 3 is least urgent")
summary: str = Field(description="One-sentence summary of the ticket")
client = OpenAI()
completion = client.beta.chat.completions.parse(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "Triage the support ticket."},
{"role": "user", "content": "I was charged twice this month."},
],
response_format=TicketTriage,
)
message = completion.choices[0].message
if message.refusal:
print("Model refused:", message.refusal)
else:
print(message.parsed)The SDK converts the Pydantic class to a schema, sends it, and parses the reply back into a TicketTriage object. Check refusal before reading parsed, because a refusal does not follow your schema.
What the guarantee does not cover
Constrained decoding fixes syntax and structure. It does not fix three other problems.
- Wrong values. The model can return
"category": "bug"for a billing complaint. The shape is valid and the content is wrong. - Truncation. If generation hits the token limit mid-object, the output is cut off and does not parse. Check the stop reason, such as
length, before trusting the reply. - Unenforced limits. If your provider ignores
maximum, the model may returnpriority: 7.
For these reasons you still validate after decoding. Keep your Pydantic model with its limits, and run validation on every reply. The next chapters cover validation and retries.
Choosing between techniques
| Technique | Valid JSON | Matches your schema | Typical use |
|---|---|---|---|
| Prompt only | Usually | Not guaranteed | Any model, quick prototypes |
| JSON mode | Yes | No | Older models, loose shapes |
| Schema-constrained | Yes | Yes, within the supported subset | Production extraction |
Use schema-constrained output when your provider and model support it and your schema fits the supported subset. Otherwise fall back to prompting with validation and retries.
Exercise
Your schema sets "maximum": 3 on priority, and your provider's strict mode does not enforce maximum. The reply parses as JSON and has all required keys, but priority is 7. What went wrong, and what should your code do?
Show answer
Constrained decoding only guarantees what the grammar can express, and this provider's grammar ignores maximum. The reply is structurally valid but semantically out of range. Your code should still validate the reply, for example with a Pydantic model that has Field(ge=1, le=3). On failure it should retry with the error message or reject the reply.
Exercise
A constrained request returns text that ends mid-object and fails to parse. Name the likely cause and one check that detects it.
Show answer
The generation likely hit the maximum token limit. Check the response's stop or finish reason (for example length) before parsing, and raise the token limit or shorten the schema or input if it appears.