Sub topic 6
Getting reliable structured output and validating it
This chapter assumes you can read basic Python and JSON, and that you know what a prompted language model does. It covers the step between "the model returned some text" and "the system holds a trustworthy record". A prompted extractor can be right about the content and still break your pipeline, because the output is not parseable or does not match your schema. A validation layer turns those problems into events you can count and handle.
Why free text is not a result
The schema from the earlier chapters defines the fields, their types, and when a field is empty. A language model only produces text that is likely to follow your instructions. It does not guarantee that it will. Four kinds of failure appear in practice:
- Syntax failures. The output has a polite preamble ("Sure! Here is the JSON"), is wrapped in a Markdown code fence, has a trailing comma, or is cut off at the token limit.
- Shape failures. A key is missing, renamed, or added. A list appears where you expected a string.
- Type failures.
"total": "120.50 EUR"instead of120.5. In Python,Truealso passesisinstance(x, int), so booleans slip through naive checks. - Content failures. The JSON is perfect, but the vendor name is not in the document. Schema checks cannot catch this. It needs a grounding check against the source text.
A validator addresses the first three directly. A grounding check addresses the fourth. Both give you something you can measure: the share of outputs that were rejected, and why.
Make the prompt state the contract
Validation works best when the prompt and the validator describe the same contract. The prompt should state three things: the exact keys, the allowed types, and what to do when a value is missing. The null rule matters because a model that is told to fill every field will fill them, often with invented values.
import json
PROMPT = """Extract the invoice fields from the text.
Return only a JSON object with keys "vendor" (string or null), "total" (number or null), "currency" (string or null).
Use null when a field is not stated. Do not guess.
Text: {text}
JSON:"""
def parse_extraction(raw):
try:
data = json.loads(raw)
except json.JSONDecodeError:
return None
if not isinstance(data, dict) or set(data) != {"vendor", "total", "currency"}:
return None
if data["total"] is not None and not isinstance(data["total"], (int, float)):
return None
return data
print(parse_extraction('{"vendor": "Acme", "total": 120.5, "currency": "EUR"}'))
print(parse_extraction('Sure! {"vendor": "Acme"}'))The first call returns the dictionary. The second returns None because the text before the brace is not valid JSON. Note what this parser does not do. It does not check the vendor or currency types, it accepts True as a total, and it reports nothing about why it failed. The next sections fix each gap.
Validate with reasons, not just a yes or no
A validator that returns a list of error messages is more useful than one that returns None. You can log the messages, group them by type for error analysis, and send them back to the model in a retry.
import json
KEYS = {"vendor": str, "total": (int, float), "currency": str}
def validate(raw):
"""Return (data, errors). data is None when errors is not empty."""
try:
data = json.loads(raw)
except (json.JSONDecodeError, TypeError):
return None, ["output is not valid JSON"]
if not isinstance(data, dict):
return None, ["top level must be a JSON object"]
errors = []
missing = sorted(set(KEYS) - set(data))
extra = sorted(set(data) - set(KEYS))
if missing:
errors.append(f"missing keys: {missing}")
if extra:
errors.append(f"unexpected keys: {extra}")
for key, types in KEYS.items():
value = data.get(key)
if value is None:
continue
if isinstance(value, bool) or not isinstance(value, types):
errors.append(f"{key} has wrong type: {type(value).__name__}")
currency = data.get("currency")
if isinstance(currency, str) and len(currency) != 3:
errors.append("currency must be a 3-letter code")
return (data if not errors else None), errors
print(validate('{"vendor": "Acme", "total": "120.50", "currency": "EUR"}'))
print(validate('{"vendor": "Acme", "total": 120.5, "currency": "EUR"}'))The first call returns (None, ['total has wrong type: str']). The second returns the data with an empty error list. Two details are worth copying. The isinstance(value, bool) test closes the boolean loophole. A missing key and an explicit null are treated differently: a missing key is an error, but null is a legitimate answer under the null rule.
Where to put the checks
Put cheap checks first and expensive ones last. The order below is the usual one, and each stage can reject an output on its own.
| Stage | What it checks | Catches |
|---|---|---|
| Parse | The text is valid JSON | Preambles, fences, truncation |
| Shape | Keys match the schema exactly | Missing or invented fields |
| Type and range | Each value has the right type and a plausible value | Strings for numbers, negative totals |
| Format | Dates, currency codes and similar values follow a pattern | Free-text answers in typed fields |
| Grounding | The value appears in or follows from the source text | Hallucinated values |
Check that values come from the document
Schema validation cannot tell a correct vendor from an invented one. For span-like fields such as names, dates, and identifiers, a grounding check is cheap: the extracted string should occur in the source. For normalized fields, such as a total that you asked the model to convert to a number, compare the normalized value against numbers found in the text.
A strict substring test will reject legitimate answers when whitespace or case differs. Normalize both sides before comparing, and decide per field whether a failure means "reject" or "flag for review". The retry loop below uses the strict version for vendor.
import json
PROMPT = """Extract the invoice fields from the text.
Return only a JSON object with keys "vendor" (string or null), "total" (number or null), "currency" (string or null).
Use null when a field is not stated. Do not guess.
Text: {text}
JSON:"""
KEYS = {"vendor": str, "total": (int, float), "currency": str}
def validate(raw):
try:
data = json.loads(raw)
except (json.JSONDecodeError, TypeError):
return None, ["output is not valid JSON"]
if not isinstance(data, dict):
return None, ["top level must be a JSON object"]
errors = []
if set(data) != set(KEYS):
errors.append(f"keys must be exactly {sorted(KEYS)}")
else:
for key, types in KEYS.items():
value = data[key]
if value is not None and (isinstance(value, bool) or not isinstance(value, types)):
errors.append(f"{key} has wrong type: {type(value).__name__}")
return (data if not errors else None), errors
def check_grounding(data, text):
vendor = data["vendor"]
if vendor is not None and vendor.lower() not in text.lower():
return [f"vendor {vendor!r} does not appear in the text"]
return []
def extract(text, call_model, max_attempts=3):
base = PROMPT.format(text=text)
prompt = base
for attempt in range(1, max_attempts + 1):
raw = call_model(prompt)
data, errors = validate(raw)
if data is not None:
errors = check_grounding(data, text)
if not errors:
return data, attempt
prompt = base + "\n\nYour previous answer was rejected: " + "; ".join(errors) + ". Fix these problems."
return None, max_attempts
replies = iter([
'Sure! {"vendor": "Acme Ltd"}',
'{"vendor": "Globex", "total": 120.5, "currency": "EUR"}',
'{"vendor": "Acme Ltd", "total": 120.5, "currency": "EUR"}',
])
def fake_model(prompt):
return next(replies)
text = "Invoice from Acme Ltd. Total due: 120.50 EUR"
print(extract(text, fake_model))The script prints ({'vendor': 'Acme Ltd', 'total': 120.5, 'currency': 'EUR'}, 3). The first reply fails to parse, the second parses but names a vendor that is not in the text, and the third passes. Replace fake_model with a function that calls your model API to use it for real.
Reducing failures before they happen
Retries cost money and latency, so lower the failure rate first.
- Show the format. One or two examples of correct output in the prompt reduce shape and type errors more than extra prose instructions do.
- Ask for JSON only, and parse defensively. Some models still add a fence or a sentence. Stripping a fence is safe. Searching for the first
{and last}is more lenient but can hide a real problem, so count how often you need it. - Use the provider's structured-output feature if one exists. Many APIs can constrain decoding to a JSON schema or force a tool call with typed arguments. This removes most syntax and shape failures. It does not remove content failures, because a constrained model can still put a wrong value in a valid slot.
- Set a low temperature. Extraction rarely benefits from varied wording, and lower randomness makes format drift less common.
- Leave room for the answer. A
max_tokenslimit that is too small truncates long outputs, and the JSON ends mid-string. Treat a parse error on an output that ends abruptly as a limit problem.
Handle the failures that remain
Decide up front what happens when all attempts fail. Silently dropping the document biases your evaluation, because the hardest documents disappear from the results. Three options are common:
- Failure queue. Store the document, the last raw output, and the error messages for later review.
- Fallback extractor. Route the document to a different model or a rule-based extractor. The hybrid chapter returns to this idea.
- Partial acceptance. Keep the fields that passed and mark the others as missing. Only do this if downstream consumers can handle missing fields.
Retries should be limited, usually to two or three. Beyond that, the model tends to repeat the same mistake, and each attempt adds latency. Keep the error text you send back short and specific, as in the loop above. A message such as "total has wrong type: str" helps. "Try again" does not.
Count what the validator tells you
Log every rejection with its category. The share of outputs that fail at each stage is a first-class metric next to span-level F1. Be careful reading it:
- A high parse-failure rate points to prompt or format problems, and is cheap to fix.
- A high grounding-failure rate points to hallucination, and may need examples with explicit nulls or a different model.
- A low rejection rate does not mean high accuracy. An output can pass every check and still be wrong. Only comparison against the gold data measures correctness.
When you compute precision and recall, decide how rejected documents count. The usual choice is to treat a document with no accepted output as having predicted nothing, so its gold fields count as misses. That keeps reliability problems visible in the score.
Exercise
A model returns {"vendor": "Acme", "total": true, "currency": "EUR"} for a document that has no total. The original parser from this chapter, which checks only isinstance(data["total"], (int, float)), accepts it. Explain why it passes, name the fix, and say what the prompt should also change so the model is less likely to produce it.
Show answer
In Python, bool is a subclass of int, so True passes isinstance(True, (int, float)). The fix is to reject booleans explicitly: check isinstance(value, bool) before the type test, as validate() does. The prompt should state that total is a number or null and that null must be used when the total is not stated, ideally with one example that shows a null total. A model that thinks it must fill the field may produce a boolean or an invented number.
Exercise
Your pipeline has a 99% schema-valid rate, but span-level F1 against the gold set is low. Which kind of failure does that point to, and which stage of the validator would you add or tighten?
Show answer
It points to content failures: the outputs have the right shape and types but wrong values. Add or tighten the grounding stage, which checks that extracted values occur in, or follow from, the source text. Then run error analysis on the grounded failures that remain, because a value can appear in the document and still be the wrong one, for example a ship-to company instead of the vendor.