Structured output and validation
medium 6 minA structured response passes through several gates.
Read the receipt, stamp the form, match the total.
A clerk reads a receipt, checks its fields against a form and compares the total with the original slip before filing.
Video lesson · Chapter 1 of 4
Forty-two fits the form
Theory
Read or listen first. About 2 min.
What it is
A structured response passes through several gates. The decoder produces text or constrained tokens, the parser constructs a value, and validators check field types and cross-field invariants. A final evidence or business check tests whether this particular value is correct for this particular record.
Why it exists
A system that accepts perfectly shaped but incorrect amounts is still unsafe to automate. Give extraction, validation and evidence mismatches distinct outcomes so recovery can target the actual cause.
A valid refund object can still be wrong
Inside this chapter
Chapter sources- JSON Mode & Structured Outputs
- JSON mode targets parseable JSON. Schema-constrained output further restricts the shapes and values the generator may return. Parsing and schema validation still cannot verify truth or authorization. A valid amount of 42 is an error if the receipt says 24.
JSON mode makes the output parseable; schema-constrained output additionally restricts it to the fields, types and allowed values you declared. Both operate on the shape of text, so neither can know whether a digit was swapped or a field copied from the wrong line. Keep a separate comparison against the source of record whenever the value drives money or actions.
Example. The object {"amount":42,"currency":"USD"} can pass syntax and schema checks while failing a comparison to a 24-dollar receipt.
Three gates, three different questions
Gate Asks {"amount":42,"currency":"USD"}JSON mode does it parse? pass Schema constraint right fields, types and enums? pass Evidence check does the receipt say 42? fail: receipt says 24 Each gate is necessary. None of the first two can see the receipt. - Pydantic Models for LLM Output
- A Pydantic model describes fields and validates a decoded object, with configurable coercion and strictness. Express domain invariants as validators where appropriate. Test a string amount, a missing currency and a negative refund explicitly so you know which cases the model rejects and which it normalizes.
By default Pydantic runs in lax mode, converting compatible inputs such as the string '3' into the integer 3. Strict mode refuses that conversion. Either can be right, but you should choose deliberately and pin the choice with tests at the boundaries (0, 1, 5, 6) and with wrong types. Cross-field rules, such as a refund not exceeding the original charge, belong in model validators.
Example. Test a field constrained to 1 through 5 using 0, 1 and 6. Then test the string “3” under strict and coercing settings.
Another example. A refund model with
amount: Decimal = Field(gt=0)and a validator checkingamount <= original_chargerejects a negative refund and a refund larger than the purchase before either reaches the payments queue.Pythonfrom pydantic import BaseModel, ConfigDict, Fieldclass Rating(BaseModel): model_config = ConfigDict(strict=True) score: int = Field(ge=1, le=5)Rating(score=1) # acceptedRating(score=0) # ValidationError: below 1Rating(score=6) # ValidationError: above 5Rating(score="3") # strict: ValidationError (lax mode would coerce to 3)Pydantic v2. Decide on purpose whether "3"should be rejected or normalised, then test it. - Schema Design Best Practices
- Design schemas to express the distinctions the application needs. Missing, unknown and zero often mean different things. Prefer constrained types and an explicit absent state over free-form strings. Include a schema version so producers and consumers can change without silently assigning different meanings to a field.
A schema is where you decide which distinctions the business cares about. Use enums instead of free text where the set is known, an explicit null or 'unknown' state where absence is possible, and a version field so consumers know which rules a payload follows. Most silent data bugs in extraction pipelines come from two different situations being encoded the same way.
Example. Distinguish {"discount":0} from {"discount":null}. The former states no discount; the latter may represent a missing fact.
Three ways to say discount
Payload Means Downstream action {"discount": 0}invoice states no discount post as zero {"discount": null}fact not found in the document flag for review field missing, schema_version: 1producer predates the field treat as unknown, not zero If all three collapse into 0, the ledger cannot tell a real zero from a gap. - Output Parsing Strategies
- Keep the raw response, parsing outcome and validation outcome distinct. A parser can recover JSON syntax while leaving incorrect field names or values intact. Unbounded attempts to repair malformed output make latency unpredictable. Retain the original evidence and return a clear validation result.
Lenient parsers can close a dangling bracket or quote, which is handy for syntax but dangerous for content: closing a truncated string turns half a name into a confident value. Treat a response that ended early as incomplete and re-run extraction from the source. Cap repair attempts so a pathological response cannot stall a request for a minute.
Example. A response ends halfway through a quoted name. Mark it incomplete and recover from the original source instead of inventing the missing characters.
Keep raw, parsed and validated apart
Store the raw text at every step so a later investigation can see what the model actually returned. - Validation & Error Recovery
- Classify failures before retrying. Invalid syntax, a missing fact and an upstream timeout require different responses. A targeted repair may fix syntax; an absent fact needs a null value or review. Record attempts under one operation ID and apply a finite retry budget.
Retries are only useful when something could change between attempts. Syntax slips are often random and a single retry with the error message fixes them; a timeout may clear on its own; but a field that is absent from the source will stay absent. Logging attempts under one operation ID lets you see which failure types consume the retry budget.
Example. A blank due-date field remains blank after a retry. Treat it as missing evidence rather than spending the entire retry budget seeking a date.
Classify first, then choose the recovery
Retrying a missing fact rarely conjures it. It only spends budget or invites a guess.
How it works
Step through the idea, or press Play.
Candidate record. amount = 42 · USD
Understand it
Worked example
A valid refund object can still be wrong
- 1
amount = 42 · USD
The model returns an object in the requested shape. Syntax is only the first boundary.
- 2
Number and currency accepted
Types and permitted currencies pass. Domain rules can also reject negative amounts or invalid combinations.
- 3
Receipt says 24 USD
Compare the extracted value with the referenced receipt. A schema-valid result is withheld or corrected when the source disagrees.
Follow the handoffs
- 1Candidateamount 42, USD
- 2Parsedvalid JSON object
- 3Schema passesnumber, allowed currency
- 4Receipt checkreceipt says 24 USD
- 5Withheldevidence_mismatch logged
The object was well formed at every step until it met the source of record.
Give each failure its own outcome
| Outcome | Cause | Recovery |
|---|---|---|
extraction_error | no parseable object | bounded re-run |
validation_error | wrong type or broken invariant | targeted repair or review |
evidence_mismatch | valid value disagrees with the receipt | withhold, correct from source |
accepted | all checks pass | write the refund |
Summary
The whole topic in one minute.
Validation can establish a legal shape or range. The relationship between this value and this receipt is an independent evidence check.
A system that accepts perfectly shaped but incorrect amounts is still unsafe to automate. Give extraction, validation and evidence mismatches distinct outcomes so recovery can target the actual cause.