Sub topic 7
Validating structured output
This chapter assumes you can write basic Python, read and write JSON, and call a model through an API or SDK. It also assumes you have seen deterministic checks such as length limits and regular expressions from the earlier chapters.
Why structured output needs its own check
Many applications do not show the model's answer to a person. They pass it to other code: a ticketing system, a database insert, or a function call. That code expects a specific shape. If the model returns prose, a missing field, or a value outside the allowed set, the downstream code fails, or worse, it silently stores bad data.
Structured output validation is an output guardrail. It sits after the model call and before anything else uses the result. It answers two questions:
- Is the text parseable in the format you asked for, such as JSON?
- Does the parsed data match the schema you expect: the right fields, types, and values?
These two questions fail in different ways, so it helps to keep them separate.
Where validation sits
The check runs on every response, and a failure can send control back to the model.
Layer 1: parsing
json.loads turns a string into Python objects. It raises json.JSONDecodeError if the text is not valid JSON. Typical causes of parse failures:
- The model wraps the JSON in a Markdown code fence.
- The model adds a sentence before or after the JSON, such as "Here is your ticket:".
- The output is cut off because it hit the token limit, leaving an unclosed brace.
- Single quotes, trailing commas, or comments, which JSON does not allow.
You can reduce these with a clear prompt ("Reply with a single JSON object and nothing else") and, where your provider supports it, a JSON mode or schema-constrained decoding. Do not rely on either alone. Constrained decoding can guarantee syntax, but it does not guarantee that the content is sensible. A valid JSON object can still hold a wrong priority or an empty summary.
Layer 2: schema checks
After parsing, check the data against your expectations. The checks you usually need are:
- The top-level value has the right type (an object, not a list or a string).
- Required fields are present.
- Each field has the right type.
- Enumerated fields hold one of the allowed values.
- Strings are non-empty and within a length limit.
- Numbers are within a range.
Note that json.loads("null"), json.loads("[1, 2]") and json.loads("42") all succeed. A parse that succeeds tells you nothing about shape, which is why the type check on the top-level value comes first.
A hand-written validator
The following function checks a support ticket. It requires a priority from a fixed set and a non-empty string summary.
import json
def parse_ticket(raw: str) -> dict:
data = json.loads(raw)
if not isinstance(data, dict):
raise ValueError("expected a JSON object")
if data.get("priority") not in ("low", "medium", "high"):
raise ValueError("priority must be low, medium or high")
if not isinstance(data.get("summary"), str) or not data["summary"]:
raise ValueError("summary must be a non-empty string")
return dataEvery failure raises ValueError. This is deliberate. json.JSONDecodeError is a subclass of ValueError, so a caller can catch one exception type for both parse and schema failures. The error messages are also written to be read by the model, which matters in the next section.
A few details are worth noticing:
data.get("priority")returnsNonewhen the field is missing, andNoneis not in the allowed tuple, so one check covers both "missing" and "wrong value".- The
summarycheck tests the type before the truthiness. Without theisinstancetest, a list like["x"]would pass thenot data["summary"]test. - The function ignores extra fields. Whether that is acceptable depends on the consumer. If you write the dictionary straight into a database, build a new dictionary from only the fields you know instead of passing
datathrough.
Layer 3: retry with feedback
Models are not deterministic, and many failures are transient. Asking again often works, and it works better when you tell the model what went wrong. This function retries up to a fixed limit and appends the last error to the prompt.
import json
def parse_ticket(raw: str) -> dict:
data = json.loads(raw)
if not isinstance(data, dict):
raise ValueError("expected a JSON object")
if data.get("priority") not in ("low", "medium", "high"):
raise ValueError("priority must be low, medium or high")
if not isinstance(data.get("summary"), str) or not data["summary"]:
raise ValueError("summary must be a non-empty string")
return data
def get_ticket(prompt: str, call_model, max_attempts: int = 3) -> dict:
last_error = ""
for _ in range(max_attempts):
suffix = f"\nPrevious attempt failed: {last_error}" if last_error else ""
raw = call_model(prompt + suffix)
try:
return parse_ticket(raw)
except ValueError as err: # json.JSONDecodeError is a ValueError
last_error = str(err)
raise RuntimeError(f"No valid output after {max_attempts} attempts: {last_error}")You can try it without a real model by passing a fake call_model that fails first and succeeds second:
replies = iter([
"Here is your ticket: {}",
'{"priority": "high", "summary": "Login page returns 500"}',
])
def fake_model(prompt: str) -> str:
return next(replies)
print(get_ticket("Create a ticket for the login outage.", fake_model))The first reply fails at json.loads because of the leading sentence. The second call receives the prompt plus the decode error message, and the second reply passes. The call prints the dictionary with priority set to high.
Design points for the retry loop
- A fixed limit is required. Without
max_attempts, a prompt the model cannot satisfy loops forever and burns tokens. Two or three attempts is a common range. - Retries cost money and time. Each attempt is a full model call. Track how often retries happen. A high retry rate means the prompt or schema needs work, not that you need more attempts.
- Feedback can be stale. The loop above sends only the latest error. For a failing response you may also want to include the previous output, so the model can correct it instead of starting over.
- Retry on validation errors, not on every error. Network errors and rate limits need their own handling, usually with backoff. Do not mix them into the same
exceptclause. - The final failure must be handled.
RuntimeErroris raised after the last attempt. The caller must decide what happens next, which is the subject of the failure handling chapter.
Validation libraries
Hand-written checks are clear for two fields. They get tedious and error-prone for nested objects, lists, and many fields. Schema libraries such as Pydantic or the jsonschema package describe the shape once and generate the checks and error messages for you.
| Approach | Strength | Weakness |
|---|---|---|
| Hand-written checks | No dependency, full control, easy to read for small shapes | Grows messy, easy to miss a case |
| JSON Schema (`jsonschema`) | Language-neutral, can be shared with other services and with the model provider | Error messages can be hard for a model to use |
| Pydantic models | Typed Python objects, coercion, good error detail | Coercion can hide problems if you leave it on by default |
Whichever you choose, keep the same retry structure: parse, validate, feed the error back, stop after a limit.
What schema validation does not catch
Passing validation means the output has the right shape. It does not mean the content is correct.
- A ticket with
"priority": "low"for a total outage is valid and wrong. - A summary can contain personal data, an injected instruction, or an invented fact.
- A field that holds a free-text string can carry any content the model chooses.
Treat validated output as untrusted data. If a field will be used in a SQL query, a shell command, or an HTML page, escape or parameterize it the same way you would for user input. Apply the other output guardrails to the string fields too, such as the PII redaction and secret checks from earlier chapters. For content-level questions, such as whether a summary matches the source, use a grounding check or a judge.
Common errors
- Catching too broadly.
except Exceptionhides bugs in your own validator. CatchValueErrorfor validation and let other exceptions surface. - Forgetting the top-level type check.
data.get(...)on a list raisesAttributeError, notValueError, and escapes the retry loop. - Accepting booleans as numbers. In Python,
Trueis an instance ofint. If a field must be an integer count, test forboolexplicitly. - Unbounded retries. Always cap attempts, and log each failure.
- Silent coercion. Turning
"3"into3may be fine, or may mask a model that ignores the schema. Decide deliberately. - Stripping code fences blindly. Removing a leading fence is a reasonable tolerance step, but do it narrowly and still validate the result.
Exercise
The function parse_ticket is given the raw model reply ["high", "Login fails"]. Which line of the function rejects it, and why does the order of the checks matter?
Show answer
The isinstance(data, dict) check rejects it with "expected a JSON object", because json.loads parses the text successfully into a Python list. The order matters because the later checks call data.get(...), which does not exist on a list. If the type check came last, the function would raise AttributeError. That is not a ValueError, so it would escape the retry loop's except ValueError clause and crash the caller instead of triggering a retry.
Exercise
A teammate sets max_attempts to 10 because "the model usually gets it right eventually". Give two reasons to keep the limit low, and one change to make instead if the first attempt often fails.
Show answer
Each attempt is a full model call, so a high limit multiplies latency and cost for every request that fails, and a prompt the model cannot satisfy will spend all 10 attempts before failing anyway. Instead of raising the limit, improve the prompt: state the exact schema with an example, enable JSON mode or schema-constrained output if the provider supports it, and track the retry rate to confirm the change helped.