Sub topic 9
Validating output with a typed model
A model can return text that looks like your JSON but is wrong in small ways. A date might be written as 15/03/2024. A total might be "1,234.50" as a string. A key might be misspelled, or the whole answer might be wrapped in a Markdown fence. This chapter shows how to catch these problems with a typed model, so only data that matches your schema reaches the rest of your code.
This chapter assumes you can call an LLM API and read its response, you know basic Python and JSON, and you have the Invoice schema idea from the earlier chapter on schema design. Examples use Pydantic v2 (pip install pydantic).
Why validation is a separate step
The prompt asks for a shape, and structured-output features can push the model toward it. Neither guarantees the result. Validation is the check that sits after the model call. It turns an untrusted string into either a typed object or a precise list of what is wrong.
Three things make this worth doing:
- Failure is explicit. Bad data raises an exception instead of flowing into your database.
- Errors are specific. Pydantic reports which field failed and why. That message can be shown to a person or fed back to the model.
- Types are usable. After validation,
invoice.invoice_dateis a realdate, andinvoice.totalis a realfloat.
A schema with real constraints
The schema in the earlier chapter used str and float for most fields. You can tighten it. Use date for dates, a pattern for currency codes, and a lower bound for the total. Setting extra="forbid" makes the model reject keys you did not ask for. That catches renamed keys such as invoice_no instead of invoice_number.
from datetime import date
from typing import Optional
from pydantic import (
BaseModel,
ConfigDict,
Field,
ValidationError,
field_validator,
model_validator,
)
class Invoice(BaseModel):
model_config = ConfigDict(extra="forbid")
vendor: str = Field(min_length=1, description="Name of the company issuing the invoice")
invoice_number: str = Field(min_length=1)
invoice_date: Optional[date] = Field(default=None, description="ISO 8601 date, or null if absent")
currency: Optional[str] = Field(default=None, pattern=r"^[A-Z]{3}$")
total: Optional[float] = Field(default=None, ge=0)
@field_validator("currency", mode="before")
@classmethod
def normalize_currency(cls, value):
# Runs before the pattern check, so "usd " becomes "USD".
if isinstance(value, str):
return value.strip().upper()
return value
@model_validator(mode="after")
def total_needs_currency(self):
if self.total is not None and self.currency is None:
raise ValueError("total is present but currency is missing")
return selfEach piece does a different job:
- Constraints such as
min_length,pattern, andgereject values that have the right type but a wrong shape. - A
beforevalidator repairs harmless formatting differences. Use it only for fixes you would accept from a human typist. Do not use it to guess missing data. - An
aftermodel validator checks rules that involve several fields at once.
The cross-field rule above is a design choice. Some of your invoices may leave the currency implied. Write rules that match your documents, and keep them few.
Parsing and validating in one call
Invoice.model_validate_json(raw) parses the JSON and validates it in a single step. If the text is not valid JSON, it raises the same ValidationError as a schema failure, so you need only one except clause.
Models often wrap JSON in a Markdown fence even when told not to. A small cleanup function handles that case before validation:
def parse_model_output(raw: str) -> Invoice:
cleaned = raw.strip()
if cleaned.startswith("```"):
cleaned = cleaned.strip("`").strip()
if cleaned.lower().startswith("json"):
cleaned = cleaned[4:]
return Invoice.model_validate_json(cleaned)
def summarize_errors(exc: ValidationError) -> str:
parts = []
for err in exc.errors():
location = ".".join(str(p) for p in err["loc"]) or "(whole document)"
parts.append(f"{location}: {err['msg']}")
return "; ".join(parts)exc.errors() returns a list of dictionaries. Each has loc (the path to the field), msg (a readable message), type (a stable code such as missing), and input (the offending value). The type code is the better choice if your program needs to branch on the kind of error. The msg text can change between Pydantic versions.
Now run it on three kinds of model output:
good = '{"vendor": "Acme Ltd", "invoice_number": "INV-1042", "invoice_date": "2024-03-15", "currency": "usd", "total": 1234.5}'
fenced = "```json\n" + good + "\n```"
bad = '{"vendor": "Acme Ltd", "invoice_number": "INV-1042", "invoice_date": "15/03/2024", "currency": "US Dollar", "total": "1,234.50", "tax": 10}'
for label, raw in [("good", good), ("fenced", fenced), ("bad", bad)]:
try:
invoice = parse_model_output(raw)
print(label, "->", invoice.model_dump())
except ValidationError as exc:
print(label, "-> INVALID:", summarize_errors(exc))The first two cases succeed. In both, "usd" has become "USD", and the date string is now a date object. The third case fails on four fields at once: invoice_date, currency, total, and the forbidden extra key tax. Pydantic reports all of them in one pass rather than stopping at the first.
Lax versus strict conversion
By default, Pydantic converts values when the conversion is unambiguous. The string "1234.5" becomes the float 1234.5, and "2024-03-15" becomes a date. This is usually what you want for JSON from a model. It does not accept "1,234.50", because the comma makes the conversion ambiguous.
If you need exact types, enable strict mode on a field with Field(strict=True) or on the whole model with ConfigDict(strict=True). Be aware of one catch. In JSON, a date is always a string, so strict mode on a date field can reject valid input. Test strict settings against real model output before relying on them.
What validation cannot tell you
A passing result means the data has the right shape. It does not mean the data is true. A model can invent "vendor": "Acme Ltd" when the document never names a vendor, and every check above will pass. Three habits reduce this risk:
- Make fields
Optionalwhere the document may not contain them. A required field pushes the model to fabricate a value. - Keep constraints about format. Do not use them to catch wrong facts.
- Follow validation with the grounding check, covered later in this tutorial, which compares values against the source text.
Also watch for constraints that are too tight. A pattern that rejects real-world values, such as a vendor name containing an unusual character, produces false failures. Those failures waste retries and send good documents to review. Log every validation failure with its type codes. If one field fails often, the constraint or the prompt probably needs adjusting.
What to do with a failure
The result of a failed validation is a list of field-level errors, and the next step depends on your pipeline:
- Retry the call with
summarize_errors(exc)appended to the prompt. The next chapter covers this loop. - Keep any fields that passed and re-ask only for the failed ones, if your schema allows partial results.
- Route the document to a person when retries run out.
Whichever you choose, do not silently replace a failed field with a default value. A missing total that is quietly stored as 0.0 is harder to find later than an exception.
Exercise
A model returns {"vendor": "Acme Ltd", "invoice_number": "INV-7", "total": 99.0} for the Invoice model in this chapter. Does it validate? If not, which rule fails, and what are two ways to fix the problem?
Show answer
It does not validate. The modelvalidator totalneeds_currency raises an error because total is present but currency is None (it was omitted, so it takes the default). Fix 1: change the prompt so the model returns the currency when the document shows it, and return null only when it does not appear. Fix 2: relax or remove the cross-field rule if your documents often leave the currency implied. Fixing it by inserting a made-up default such as "USD" would hide missing data, so avoid it.
Exercise
Why does summarize_errors use err["loc"] and not only err["msg"], and why is branching on err["type"] safer than matching message text?
Show answer
loc says which field failed, so a retry prompt or a review screen can point at exactly that field. The msg text alone may not name it. The type value, such as "missing" or "json_invalid", is a stable code. msg wording can change between Pydantic versions, which would silently break code that matches it.