Sub topic 9
Validating output with a typed model
This chapter assumes you can call an LLM API, read JSON, and write basic Python. You should also have a schema in mind, such as the Invoice model from the schema chapter. The model's reply is text. Before your code uses it, you need to confirm that it is valid JSON and that it matches your schema.
Why validate
A model can return JSON that parses but is still wrong for your code. Common failures:
- A key is missing or misspelled, such as
invoice_noinstead ofinvoice_number. - A number arrives as a string, such as
"1,250.00". - The JSON is wrapped in prose or a Markdown fence.
- A required field is
null.
A typed model catches all of these at one boundary. Code after that boundary can trust the data.
Define the model
Pydantic is a Python library that checks data against type hints. You write the schema once as a class.
from typing import Optional
from pydantic import BaseModel, Field
class Invoice(BaseModel):
vendor: str = Field(description="Name of the company issuing the invoice")
invoice_number: str
invoice_date: Optional[str] = Field(default=None, description="ISO 8601 date, or null if absent")
currency: Optional[str] = Field(default=None, description="Three-letter currency code, or null if absent")
total: Optional[float] = Field(default=None, description="Grand total as a number, or null if absent")vendor and invoice_number are required. The other three are optional, so the model can return null instead of inventing a value.
Validate the reply
model_validate_json parses the text and checks every field in one step. It raises ValidationError if either step fails.
from pydantic import ValidationError
raw = '{"vendor": "Acme Ltd", "invoice_number": "INV-42", "total": "oops"}'
try:
invoice = Invoice.model_validate_json(raw)
except ValidationError as exc:
print(exc)Here total is not a number, so Pydantic reports the field name and the problem. This message is useful input for the retry step in the next chapter.
What validation does and does not check
By default, Pydantic converts compatible values. The string "1250.5" becomes the float 1250.5. This is convenient, but it can hide sloppy output. If you want strict behavior, set model_config = ConfigDict(strict=True) on the class.
Validation checks the shape and types. It cannot tell you that the value is correct. A model can return a well-formed invoice number that appears nowhere in the document. Grounding checks, covered later, address that.
You can add rules for the values themselves:
from pydantic import BaseModel, field_validator
from typing import Optional
class CheckedInvoice(BaseModel):
vendor: str
invoice_number: str
currency: Optional[str] = None
@field_validator("currency")
@classmethod
def currency_is_three_letters(cls, value):
if value is not None and not (len(value) == 3 and value.isalpha()):
raise ValueError("currency must be a three-letter code")
return valueWhere validation sits
Common errors
- Catching a broad
Exception. This hides bugs. CatchValidationError. - Making every field required. The model then guesses to satisfy the schema. Use
Optionalfor values that may be absent. - Treating a passed validation as proof of accuracy.
Exercise
A model returns {"vendor": "Acme", "invoicenumber": "A-1", "total": "12.50"}. With default Pydantic settings, does Invoice.modelvalidate_json succeed, and what is the type of total? What changes if you enable strict mode?
Show answer
It succeeds, and total becomes the float 12.5, because Pydantic coerces the numeric string. In strict mode, validation fails with a ValidationError because a string is not accepted for a float field in JSON input.