Sub topic 12
Getting structured output and validating it
This chapter assumes you can already send a chat request and read the response, as covered in the earlier chapters. You should also be comfortable with Python and JSON.
Why free text is a problem
A model returns text. Your program usually needs fields it can use: a number, a category, a list. If you parse prose with string tricks, the code breaks whenever the wording changes. The fix has two parts. You ask for JSON, then you check what comes back before you use it.
Asking for JSON
There are three levels of control, from weakest to strongest:
| Approach | What it gives you | What it does not guarantee |
|---|---|---|
| Describe the format in the prompt | Usually valid JSON | Anything. The model may add prose or code fences. |
| JSON mode (`response_format` set to `json_object`) | Output that parses as JSON | The right keys or types |
| Schema-constrained output (`response_format` of type `json_schema`) | Output that follows your schema | Correct values. A well-formed answer can still be wrong. |
JSON mode on the chat-completions shape usually requires the word "JSON" to appear somewhere in your messages. Parameter names and support differ between providers and models, so check your provider's documentation. Whatever the mode, treat the reply as untrusted input.
Validate every reply
Validation has three steps:
- Parse the text with
json.loads. - Check the shape: required keys, types and allowed values.
- Check
finish_reason. A value oflengthmeans the output was cut off and the JSON is probably incomplete.
If a check fails, send the error back to the model and ask for a correction. Cap the number of attempts.
Worked example
This program extracts a task from a sentence. It sets temperature to 0 to reduce variation.
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",
}
PRIORITIES = {"low", "medium", "high"}
def validate(data):
if not isinstance(data, dict):
raise ValueError("top level must be a JSON object")
if not isinstance(data.get("title"), str) or not data["title"]:
raise ValueError("'title' must be a non-empty string")
hours = data.get("hours")
if isinstance(hours, bool) or not isinstance(hours, int) or hours < 0:
raise ValueError("'hours' must be a non-negative integer")
if data.get("priority") not in PRIORITIES:
raise ValueError("'priority' must be one of low, medium, high")
def extract_task(text, max_attempts=3):
messages = [
{"role": "system", "content": (
"Return only a JSON object with keys title (string), "
"hours (integer) and priority (low, medium or high)."
)},
{"role": "user", "content": text},
]
for _ in range(max_attempts):
resp = requests.post(
URL,
headers=HEADERS,
json={
"model": os.environ["LLM_MODEL"],
"messages": messages,
"response_format": {"type": "json_object"},
"temperature": 0,
},
timeout=30,
)
resp.raise_for_status()
choice = resp.json()["choices"][0]
raw = choice["message"]["content"]
try:
if choice["finish_reason"] == "length":
raise ValueError("reply was cut off; it is not complete JSON")
data = json.loads(raw)
validate(data)
return data
except ValueError as err:
messages.append({"role": "assistant", "content": raw})
messages.append({
"role": "user",
"content": f"Invalid: {err}. Return only the corrected JSON.",
})
raise RuntimeError("no valid JSON after retries")
print(extract_task("Fix the login bug today, about 3 hours, it is urgent."))json.JSONDecodeError is a subclass of ValueError, so one except clause handles both parse errors and validation errors. A failed attempt is appended to the history, so the model sees its own mistake.
Common errors
- Trusting JSON mode to enforce your keys. It only guarantees valid syntax.
- Skipping the
finish_reasoncheck. A lowmax_tokensvalue produces truncated JSON. - Passing the parsed data straight into a database query, a shell command or a file path. Validate values, and use parameterized queries.
- Retrying forever. Every repair attempt costs tokens and time.
Exercise
A reply parses with json.loads, but finish_reason is "length". Should you use the data? Why or why not?
Show answer
No. The output hit the token limit, so it may be cut off. A truncated reply that happens to parse can still be missing fields. Treat it as invalid, then raise max_tokens or ask for a shorter answer, and retry.