Sub topic 12
Getting structured output and validating it
This chapter assumes you can send a chat-completions request and read the response (see the earlier chapters on the request and response objects). You should also be comfortable with JSON and with basic Python exceptions.
A model returns text. Your program usually needs data: a dictionary with known keys and types. This chapter covers how to ask for JSON, how to parse it, and why you must validate it before trusting it.
Why free text is a poor interface
Suppose you ask a model to classify a support ticket. A reply like "I'd say this is probably a billing issue, high priority" is readable to a person. Code cannot reliably extract the category from it. The wording changes between calls, and a regex that works today breaks tomorrow.
You want output like this:
{"category": "billing", "priority": "high", "summary": "Customer was charged twice."}There are three common ways to get it, listed from weakest to strongest guarantee:
- Ask in the prompt and parse the reply yourself.
- Turn on JSON mode, which constrains the output to be syntactically valid JSON.
- Supply a JSON Schema and use structured outputs, which constrains the output to match that schema.
Parameter names and availability differ between providers and models. The examples here use the chat-completions shape. Check your provider's documentation for the exact fields.
Level 1: prompt for JSON and parse it
The simplest approach needs no special API feature. You describe the shape in the system message and lower the temperature so the output is more consistent.
import json
import os
import requests
URL = "https://api.openai.com/v1/chat/completions"
HEADERS = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "application/json",
}
SYSTEM = (
"Classify the support ticket. Reply with only a JSON object with keys "
'"category" (one of "billing", "bug", "other"), '
'"priority" (one of "low", "high") and "summary" (a short string). '
"Do not add any text outside the JSON."
)
def classify(ticket_text):
payload = {
"model": os.environ["LLM_MODEL"],
"temperature": 0,
"messages": [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": ticket_text},
],
}
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=30)
resp.raise_for_status()
choice = resp.json()["choices"][0]
return choice["message"]["content"], choice["finish_reason"]
text, reason = classify("I was charged twice for my March invoice.")
print(reason)
print(text)This usually works. It is not a guarantee. The model may wrap the JSON in a Markdown fence, add a sentence before it, or leave out a key. Your parser has to expect that.
Common parsing failures
| Symptom | Cause | Response |
|---|---|---|
| `json.JSONDecodeError` on the first character | Reply starts with prose or a code fence | Strip the fence, or switch to JSON mode |
| `json.JSONDecodeError` near the end | Output was cut off, and `finish_reason` is `length` | Raise the length limit or shorten the output |
| Parsed fine but a key is missing | The model ignored part of the instruction | Validate and retry |
| Parsed fine but `priority` is `"urgent"` | The value is outside your allowed set | Validate and retry |
The second row matters. Always check finish_reason before parsing. A reply that stopped because it hit the token limit is truncated JSON, and no parser can repair it reliably.
Level 2: JSON mode
Many providers offer a JSON mode. In the chat-completions format you set response_format to {"type": "json_object"}.
payload = {
"model": os.environ["LLM_MODEL"],
"response_format": {"type": "json_object"},
"messages": [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": "I was charged twice for my March invoice."},
],
}JSON mode guarantees that the reply is syntactically valid JSON, provided it finishes. It does not guarantee your keys, your types, or your allowed values. Some providers also require the word "JSON" to appear in the messages when you enable it, so keep the instruction in the prompt.
Level 3: structured outputs with a JSON Schema
Structured outputs let you pass a JSON Schema, a formal description of the allowed shape. Where supported, the provider constrains generation so the reply conforms to the schema.
schema = {
"type": "object",
"properties": {
"category": {"type": "string", "enum": ["billing", "bug", "other"]},
"priority": {"type": "string", "enum": ["low", "high"]},
"summary": {"type": "string"},
},
"required": ["category", "priority", "summary"],
"additionalProperties": False,
}
payload = {
"model": os.environ["LLM_MODEL"],
"response_format": {
"type": "json_schema",
"json_schema": {"name": "ticket", "strict": True, "schema": schema},
},
"messages": [
{"role": "system", "content": "Classify the support ticket."},
{"role": "user", "content": "I was charged twice for my March invoice."},
],
}Schema support has limits. Providers typically accept only a subset of JSON Schema. In strict mode, for example, every property usually must be listed in required, and additionalProperties must be false. Some keywords for string length or numeric ranges may be ignored or rejected. Read your provider's list of supported keywords.
Constrained output can also still fail in two ways:
- The model may refuse a request for safety reasons. The response then contains a refusal instead of schema-shaped content.
- Generation can still be cut off by the length limit, which leaves incomplete JSON.
A schema also guarantees only the shape. A summary can be well-formed and wrong.
Validate everything
Whatever level you use, treat the model's reply as untrusted input. It crosses a trust boundary in the same way as a form field submitted by a user. Parse it, then check it against your own definition of valid.
You can validate by hand for small cases. For anything larger, use a validation library. This example uses pydantic, which you install with pip install pydantic.
import json
from typing import Literal
from pydantic import BaseModel, ValidationError
class Ticket(BaseModel):
category: Literal["billing", "bug", "other"]
priority: Literal["low", "high"]
summary: str
def parse_ticket(text, finish_reason):
if finish_reason != "stop":
raise ValueError(f"Reply incomplete, finish_reason={finish_reason}")
try:
return Ticket.model_validate_json(text)
except ValidationError as err:
raise ValueError(f"Reply failed validation: {err}") from err
good = '{"category": "billing", "priority": "high", "summary": "Charged twice."}'
print(parse_ticket(good, "stop"))
bad = '{"category": "billing", "priority": "urgent", "summary": "Charged twice."}'
try:
parse_ticket(bad, "stop")
except ValueError as err:
print("rejected:", err)model_validate_json handles both steps: it parses the text and checks every field. A bad JSON string and a bad value both raise ValidationError, so one handler covers both.
Keep the schema you send to the model and the model you validate against in sync. With pydantic you can generate the schema from the class with Ticket.model_json_schema(), which avoids two definitions drifting apart. Check that the result meets your provider's strict-mode rules before you send it.
Retry on validation failure
Because validation can fail even with good prompts, build a bounded retry loop. A common technique is to send the invalid reply back with the error message so the model can correct itself. This uses the conversation-state pattern from the multi-turn chapter.
def classify_validated(ticket_text, max_attempts=3):
messages = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": ticket_text},
]
last_error = None
for _ in range(max_attempts):
payload = {
"model": os.environ["LLM_MODEL"],
"temperature": 0,
"response_format": {"type": "json_object"},
"messages": messages,
}
resp = requests.post(URL, headers=HEADERS, json=payload, timeout=30)
resp.raise_for_status()
choice = resp.json()["choices"][0]
text = choice["message"]["content"] or ""
try:
return parse_ticket(text, choice["finish_reason"])
except ValueError as err:
last_error = err
messages.append({"role": "assistant", "content": text})
messages.append(
{
"role": "user",
"content": f"That reply was invalid: {err}. Return corrected JSON only.",
}
)
raise RuntimeError(f"No valid reply after {max_attempts} attempts: {last_error}")Each retry costs tokens and adds latency, so keep the cap small. If a request fails the same way repeatedly, the cause is usually the prompt or schema, not bad luck. Retries here are separate from the network retries covered earlier. Those handle HTTP failures, while this loop handles replies that arrived but were wrong.
The overall flow
Edge cases and gotchas
- Content can be null. If the model refuses or calls a tool,
message["content"]may benull. Useor ""or check for it before parsing. - Code fences. Without JSON mode, replies are often wrapped in a Markdown fence. Strip it before parsing, but treat this as a workaround.
- Streaming. A streamed JSON reply is only valid once the final chunk arrives. Accumulate the fragments and parse at the end.
- Large numbers and dates. JSON has no date type. Ask for ISO 8601 strings and validate them. Integers beyond your language's safe range need care.
- Injection through content. If a field's text comes from user input, such as a ticket body, the model may follow instructions hidden in it. Validation confirms shape, not honesty. Do not pass a field straight into a shell command, SQL query, or HTML page.
- Lower temperature helps, not guarantees. Temperature 0 reduces variation but does not remove it.
Choosing a level
| Need | Use |
|---|---|
| Quick prototype, tolerant parser | Prompt for JSON |
| Always parseable JSON, flexible keys | JSON mode plus validation |
| Fixed keys, types and allowed values | Structured outputs plus validation |
In every case, keep your own validation. The schema constrains the model, and validation protects your program.
Exercise
A model reply parses as JSON in your tests, but in production you sometimes get a JSONDecodeError at the end of a long reply. What do you check first, and why?
Show answer
Check finish_reason. If it is "length", the reply hit the token limit and the JSON is truncated. Raise the max-token setting or ask for shorter output. Parsing cannot fix a truncated reply.
Exercise
You enable JSON mode and get valid JSON, but the "priority" field sometimes contains "urgent", which your code does not handle. Name two ways to fix this.
Show answer
Use structured outputs with an enum for priority so generation is constrained to allowed values, and validate the parsed reply in your own code (for example with a pydantic Literal). If validation fails, retry with the error message, up to a small attempt limit.