Sub topic 6
Schema-constrained structured outputs
This chapter assumes you can read a JSON Schema and a Pydantic model (covered earlier in this tutorial), and that you have called a chat-completion API before. The code uses the OpenAI Python SDK because its structured-output feature is widely copied. Other providers use different parameter names for the same idea.
What constrained decoding is
Prompting and JSON mode ask the model to behave. Schema-constrained decoding makes it behave. The provider compiles your JSON Schema into a grammar, and at every generation step it blocks any token that would break that grammar.
A language model generates text one token at a time. At each step it scores every token in its vocabulary and samples one. With constrained decoding, an extra step sits between scoring and sampling. The decoder works out which tokens are legal at the current position, sets the scores of all other tokens to negative infinity, and samples from what remains.
Suppose the schema says category must be one of billing, bug, feature_request, other. After the decoder has written "category": ", only tokens that begin one of those four strings are allowed. The model cannot write "Billing issue". It can still pick the wrong allowed value, because the grammar controls form, not meaning.
What you get and what you do not
Constrained decoding guarantees these things, as long as generation finishes normally:
- The output is syntactically valid JSON.
- Every key listed in
requiredis present. - No keys outside
propertiesappear, whenadditionalPropertiesisfalse. - Each value has the declared type.
- Enum fields contain one of the listed values.
It does not guarantee these:
- That the values are correct. A ticket about a crash can still be labelled
billing. - That keyword limits such as
minimum,maximum,maxLength, orpatternare enforced. Many providers reject or ignore some of these keywords. - That generation finishes. If the token limit is reached, the JSON is cut off mid-object.
- That the model answers at all. It can refuse, and a refusal is not shaped like your schema.
Making a request
Here is a complete call that asks for the ticket triage object from earlier chapters. The schema is hand-written and stays within the subset that strict mode accepts. Limits such as the 1 to 3 range for priority are left to Pydantic validation after the call.
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel, Field, ValidationError
client = OpenAI() # reads OPENAI_API_KEY from the environment
TRIAGE_SCHEMA = {
"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,
}
class TicketTriage(BaseModel):
category: Literal["billing", "bug", "feature_request", "other"]
priority: int = Field(ge=1, le=3)
summary: str = Field(max_length=200)
def triage(ticket_text: str) -> TicketTriage:
response = client.chat.completions.create(
model="gpt-4o-mini",
max_tokens=300,
messages=[
{"role": "system", "content": "Triage the support ticket."},
{"role": "user", "content": ticket_text},
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "ticket_triage",
"strict": True,
"schema": TRIAGE_SCHEMA,
},
},
)
choice = response.choices[0]
if choice.message.refusal:
raise RuntimeError(f"Model refused: {choice.message.refusal}")
if choice.finish_reason == "length":
raise RuntimeError("Output was truncated by max_tokens")
return TicketTriage.model_validate_json(choice.message.content)
if __name__ == "__main__":
print(triage("I was charged twice for my March invoice. Please fix this today."))Three parts of this code matter.
"strict": Trueturns on constrained decoding. Without it, the provider treats the schema as a hint, and you are closer to JSON mode.- The code checks
refusalandfinish_reasonbefore parsing. A truncated reply or a refusal would otherwise surface as a confusingValidationErrororJSONDecodeError. model_validate_jsonruns last. The schema constraint and your own validation are two layers, not substitutes.
Strict-mode schema rules
Providers support only a subset of JSON Schema in strict mode, because each construct has to compile into a grammar. The exact subset differs by provider and changes over time, so read the current documentation before relying on a keyword. The following restrictions are common in OpenAI-style strict mode:
| Rule | Why it exists | What to do |
|---|---|---|
| Every property must be listed in `required` | The grammar needs a fixed key order and set | Make an optional field nullable instead |
| `additionalProperties` must be `false` on every object | Open objects have no finite grammar | Set it on nested objects too |
| Some validation keywords are rejected or ignored (for example string length or numeric ranges, depending on the provider) | They are hard to express as token masks | Enforce them in Pydantic after the call |
| Root must be an object | Simplifies the output envelope | Wrap a list as `{"items": [...]}` |
| Limits on nesting depth, total properties, and enum size | Grammar compile cost | Flatten the schema or split the task |
To express an optional field under the "all required" rule, allow null:
{
"type": "object",
"properties": {
"due_date": {
"type": ["string", "null"],
"description": "Due date as YYYY-MM-DD, or null if the ticket gives none"
}
},
"required": ["due_date"],
"additionalProperties": false
}The model must now emit the key every time, and it writes null when it has nothing to put there. Say in the description when null is the right answer. Otherwise the model may invent a date to fill the slot.
Letting the SDK build the schema
Writing a schema by hand and a Pydantic model for the same shape means two sources of truth. Some SDKs accept the Pydantic class directly, convert it to a strict-compatible schema, and parse the reply for you. In the OpenAI SDK this is client.beta.chat.completions.parse(..., response_format=TicketTriage), and the parsed object appears on message.parsed.
Check what the converter does with your constraints. If you declared Field(ge=1, le=3), the SDK may drop the range from the schema it sends, and it may or may not enforce it on the way back. Treat the SDK's guarantee as covering types and enums only, unless the documentation says otherwise. The beta namespace has also moved between SDK versions, so confirm the current method name.
Costs and side effects
Constrained decoding has costs that prompt-only approaches do not.
- First-request latency. The provider compiles your schema into a grammar. Some providers add noticeable latency the first time they see a new schema, then cache it. Changing the schema on every request defeats the cache.
- Field order is generation order. Keys come out in the order the schema lists them. If
summarycomes beforecategory, the model writes the summary first and can use it as reasoning for the category. If you want the model to reason before deciding, put a free-textreasoningfield earlier in the schema than the decision fields. - Constraint can distort answers. When the only legal tokens are all poor choices, the model still has to pick one. A schema with no
otheroption forces a category even for a ticket that fits none. Always give the model an exit value. - Schema size uses tokens. Providers inject the schema into the prompt in some form. Long enum lists and long descriptions count against your context and cost.
When to use it
Choose constrained decoding when your provider offers it and the schema fits the supported subset. It removes the retry loop for malformed JSON, which is the most common failure with prompt-only output. Prefer it to JSON mode whenever the output shape is fixed, because JSON mode guarantees only that the output parses.
Fall back to other techniques in these cases:
- The model or provider has no strict mode. Use prompting plus validation plus retry.
- Your schema needs features outside the supported subset, such as recursive structures beyond the allowed depth or complex
oneOfcombinations. Simplify the schema or validate after the call. - You are already using tool calling for an agent loop. Strict function parameters give you the same constraint through the tool interface, covered in a later chapter.
Even with strict mode, keep the validation step and the bounded retry from the earlier chapters. A retry now targets semantic errors, such as a priority outside 1 to 3, rather than syntax errors.
Common mistakes
- Forgetting
strict. The schema is accepted, replies look fine in testing, and then occasional malformed output appears in production. Confirm in the request that strict mode is on. - Parsing before checking
finish_reason. Alengthstop produces cut-off JSON. Raisemax_tokens, shorten the output, or split the task. - Treating
refusalas data. On a refusal the content may be empty or absent. Branch on it explicitly. - Relying on schema limits. A
maximumthe provider ignores gives you a value of 7 where you wanted 3. Validate after the call. - No exit enum value. The model is forced to mislabel unusual inputs, and your error rate looks like model quality when it is schema design.
- Streaming and partial parsing. Streamed output is valid JSON only once complete. Do not feed partial chunks to a strict parser.
Exercise
A strict-mode request returns HTTP 200 and the response has finishreason "length". Your code calls modelvalidate_json on the content and it raises a ValidationError. Does constrained decoding mean the JSON must have matched the schema, and what should the code do instead?
Show answer
No. The schema guarantee holds only when generation ends normally. A "length" stop means maxtokens cut the output off mid-object, so the JSON is incomplete. The code should check finishreason before parsing, and on "length" it should raise or retry with a higher max_tokens or a smaller task, not treat it as a validation problem. It should also check for a refusal before parsing.
Exercise
Your schema has a priority field typed as an integer with minimum 1 and maximum 3, sent in strict mode. The model returns priority 5 and the request succeeds. Give two possible explanations and the fix that works in both cases.
Show answer
The provider either rejected-then-stripped or silently ignored the minimum and maximum keywords, because strict mode supports only a subset of JSON Schema, or the SDK removed them when converting the model. Either way the decoder enforced only the integer type. The fix is to validate with Pydantic (Field(ge=1, le=3)) after the call, and optionally to retry with the validation error. You can also make priority an enum of the integers 1, 2 and 3 if the provider supports integer enums.