Sub topic 6
Getting Reliable Structured Output and Validating It
Assume you know basic Python and JSON, and you understand precision, recall, and F1. This chapter focuses on a practical boundary: an LLM produces text, but your application needs trustworthy structured data.
Why valid JSON is not enough
An extraction prompt can request a JSON object, but the model may return:
- JSON with extra commentary
- Missing keys
- Wrong value types
- Invented values for information absent from the source
- A valid value in the wrong format, such as
"120.50"instead of120.5
JSON syntax answers only one question: “Can a JSON parser read this?” Your application must also answer:
- Does the object have exactly the expected fields?
- Does every field have the expected type?
- Are missing values represented consistently?
- Are values allowed by the business rules?
- Can the result be traced back to the input text?
A schema is the contract between the model and the rest of the system.
Write the schema into the prompt
Suppose an invoice extractor must return a vendor, a total, and a currency. The schema should state both the keys and the null rule. A null rule says when the model must return null instead of guessing.
import json
PROMPT = """Extract the invoice fields from the text.
Return only a JSON object with exactly these 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
expected = {"vendor", "total", "currency"}
if not isinstance(data, dict) or set(data) != expected:
return None
if data["vendor"] is not None and not isinstance(data["vendor"], str):
return None
if data["currency"] is not None and not isinstance(data["currency"], str):
return None
total = data["total"]
if total is not None and (
isinstance(total, bool) or not isinstance(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 result is a dictionary. The second result is None because it is not valid JSON and does not contain the complete schema.
The bool check matters because Python treats True and False as subclasses of int. Without that check, a boolean could pass a numeric validation.
Add semantic validation
Type checks do not prove that a value makes sense. Add rules that reflect the domain:
totalmust be zero or greater.currencymust be a known three-letter code.vendormust not be an empty string.- A currency should be present when a total is present.
You can reject an invalid result, send it for review, or retry with a correction prompt. Do not silently repair uncertain model output unless the repair rule is deterministic and tested.
| Validation layer | Example failure | Typical response |
|---|---|---|
| Syntax | Trailing text after the JSON object | Reject or retry |
| Shape | Missing `currency` key | Reject |
| Type | `"total": "120.5"` | Reject or normalize by an explicit rule |
| Semantic | Negative invoice total | Reject or review |
| Provenance | Value has no supporting text span | Review or reject |
Use provider features, but keep a validator
Some model APIs offer structured-output modes, JSON mode, or a JSON Schema parameter. These features can reduce syntax and shape errors. They do not guarantee that the extracted value is true, relevant, or supported by the source text.
A reliable pipeline keeps application-level validation after the API response:
Handle failures explicitly
A retry can help when the failure is formatting-related. For example, a second prompt can include the validation error and ask for only the corrected object. Limit retries because they increase latency and cost.
Log enough information to diagnose failures, including:
- The model and prompt version
- The validation category
- A request identifier
- The raw response, subject to privacy and retention rules
Do not log sensitive invoice text by default. Redact or restrict access where necessary.
For evaluation, measure both extraction quality and contract failures. A response that is valid JSON but contains a wrong vendor should count as an extraction error. A response that cannot be parsed should count as a system failure and should not disappear from your measurements.
Exercise
The model returns {"vendor": "Acme", "total": "120.5", "currency": "EUR"}. Should a validator accept it for the schema in this chapter?
Show answer
No. The total is a string, but the schema requires a number or null. Reject it or apply a separately specified, tested normalization rule.