Designing a Schema for an Extraction Task
Design a Pydantic v2 schema for invoice extraction step by step: exact money types, nullable fields, an enum with an explicit OTHER value, a 'cannot answer' status, a totals check, and the changes strict modes need before a provider accepts the schema.
Contentsand lesson path
On this page
- The task
- Step 1: Name fields for the model, not just for your code
- Step 2: Pick types that cannot lose information
- Step 3: Give the model a way to say "no invoice here"
- Step 4: Check the schema against strict-mode rules
- Check your understanding
- Apply it
- Review prompt
Lessons of Structured Outputs
- Why Free Text Breaks Pipelines Concept · 10 min
- Designing a Schema for an Extraction Task Worked example · 20 min
- Constrained Decoding and Its Limits Concept · 15 min
- Lab: Enforced Schemas Across Two Providers Lab · 25 min
- Validation, Repair and Retry Budgets Worked example · 20 min
- Check: Schema and Failure Scenarios Knowledge check · 6 questions
What you will learn
- Design a JSON Schema or Pydantic model for an extraction or decision task, including enums, optional fields and an explicit 'cannot answer' path.
Prerequisites: LLM API Integration
01. The task
An accounts-payable team receives invoices as text from many suppliers. They want each one turned into a record their payment system can load: vendor, invoice number, invoice date, due date, currency, line items, tax and total. Some documents that arrive are not invoices at all, some are too damaged to read, and suppliers bill in currencies the payment system does not support.
Your job in this lesson is the schema: the contract the model must fill and your code will check. You will make five decisions, write the result as a Pydantic v2 model, and then test it against the rules that providers' strict modes enforce. You need Python 3.12 or later and Pydantic (pip install pydantic==2.14.1, the version these examples were run with). No API key is needed: nothing here calls a model.
02. Step 1: Name fields for the model, not just for your code
The model reads the schema as part of its instructions, so names and descriptions steer what it extracts. Three habits help:
- Plain, specific names.
vendor_nameandinvoice_datesay what to look for;vord1do not. - Descriptions for rules a type cannot express. "Billing company as printed", "Negative for discounts and credits" and "null if the document has none" each prevent a specific mistake.
- Evidence before conclusions. Output follows the schema's property order (Claude places required properties before optional ones), so put line items before totals, and any short justification field before a verdict that depends on it.
Keep the schema as small as the downstream system needs. Every extra field is one more value the model can get wrong, and both providers cap the size and complexity of a strict schema.
03. Step 2: Pick types that cannot lose information
Money is not a float. Binary floating point cannot store most decimal fractions exactly, so sums drift and an equality check between line items and the total fails on correct data. The schema below carries amounts as strings such as "1250.00", constrained by a regular expression, and Pydantic turns them into exact Decimal values. WithJsonSchema sets what the provider sees; the Python type stays Decimal.
Dates are dates. invoice_date: date becomes a string with format: date in the schema, and Pydantic rejects 14/09/2026.
Absent means null. due_date: date | None with no default is required but nullable: the key must be present, and null is a legal value. That is the form strict modes want (step 4).
Enums need an honest exit. The payment system handles four currencies. A closed enum of exactly those four would force a Canadian invoice into one of them. Adding OTHER (printed, but not supported) and allowing null (not printed) gives the model a truthful choice, and gives your code a value to route to a person.
"""Extraction contract shared by every provider (Pydantic v2)."""
from datetime import date
from decimal import Decimal
from typing import Annotated, Literal
from pydantic import BaseModel, ConfigDict, Field, WithJsonSchema, model_validator
# Money travels as a string such as "1250.00" and becomes an exact Decimal.
Money = Annotated[
Decimal,
WithJsonSchema({"type": "string", "pattern": "^-?[0-9]+[.][0-9]{2}$"}),
]
# Quantities travel as JSON numbers; Pydantic reads the digits exactly.
Quantity = Annotated[Decimal, WithJsonSchema({"type": "number"})]
class Strict(BaseModel):
model_config = ConfigDict(extra="forbid") # -> "additionalProperties": false
class LineItem(Strict):
description: str
quantity: Quantity = Field(description="Units billed, as printed")
unit_price: Money
line_total: Money = Field(description="Negative for discounts and credits")
class Invoice(Strict):
vendor_name: str = Field(description="Billing company as printed")
invoice_number: str
invoice_date: date
due_date: date | None = Field(description="null if the document has none")
currency: Literal["USD", "EUR", "GBP", "JPY", "OTHER"] | None = Field(
description="ISO 4217 code; OTHER if another currency; null if not stated"
)
line_items: list[LineItem]
tax_amount: Money | None = Field(description="null if no tax line")
total_amount: Money = Field(description="Amount due, as printed")
@model_validator(mode="after")
def totals_add_up(self) -> "Invoice":
expected = sum(i.line_total for i in self.line_items) + (self.tax_amount or 0)
if expected != self.total_amount:
raise ValueError(
f"line items + tax = {expected}, total_amount = {self.total_amount}"
)
return self
class Extraction(Strict):
"""The root object: an invoice, or an explicit reason why there is none."""
status: Literal["ok", "not_an_invoice", "unreadable"]
reason: str | None = Field(description="Why status is not ok; else null")
invoice: Invoice | None = Field(description="null unless status is ok")
@model_validator(mode="after")
def invoice_matches_status(self) -> "Extraction":
if (self.status == "ok") != (self.invoice is not None):
raise ValueError("invoice must be set exactly when status is ok")
return selfTwo more things in this file are deliberate. ConfigDict(extra="forbid") on every model makes Pydantic emit additionalProperties: false, which strict modes require, and makes validation reject unknown keys. And the two model_validator methods hold rules that span several fields, which a JSON Schema for these providers cannot express: the line items plus tax must equal the total, and an invoice must be present exactly when the status is ok.
04. Step 3: Give the model a way to say "no invoice here"
The root object is Extraction, not Invoice. It has a status of ok, not_an_invoice or unreadable, a reason that explains any status other than ok, and an invoice that is null unless the status is ok. Without this wrapper, a delivery note or a scan full of OCR noise would come back as a confident, invented invoice.
Why a wrapper object rather than "either an invoice or an error" at the top level? OpenAI's strict mode requires the root of the schema to be an object, not an anyOf. A wrapper works on both providers, and code that consumes it can branch on one field: store the invoice when the status is ok; record the status and reason, and skip payment, otherwise. Inside the wrapper you can still use unions, for example a list whose items are either a product line or a discount line, told apart by a kind field.
05. Step 4: Check the schema against strict-mode rules
Pydantic generates JSON Schema with model_json_schema(), but a schema generated from an ordinary model is not automatically one a strict mode accepts. The rules differ by provider and are documented as a subset of JSON Schema:
- OpenAI strict mode: every object needs
additionalProperties: false; every property must be listed inrequired(optional values are written as a union withnull); the root must be an object; keywords such asallOf,notandif/thenare rejected. - Claude structured outputs: every object needs
additionalProperties: false; numeric bounds (minimum,maximum), string lengths and recursive schemas are not supported; there are limits on optional and union-typed parameters across the request.
The script compares a naive model with the one from step 2, using a small checker for the two rules that trip people up most. It then shows the float problem and the validators at work.
from decimal import Decimal
from pydantic import BaseModel, ValidationError
from invoice_schema import Extraction
def strict_problems(node, path: str = "$") -> list[str]:
"""Closed objects (both providers) and every key required (OpenAI strict)."""
found = []
if isinstance(node, dict):
if node.get("type") == "object":
if node.get("additionalProperties") is not False:
found.append(f"{path}: additionalProperties is not false")
optional = set(node["properties"]) - set(node.get("required", []))
found += [f"{path}.{name}: not in required" for name in sorted(optional)]
for key, value in node.items():
found += strict_problems(value, f"{path}.{key}")
elif isinstance(node, list):
for i, value in enumerate(node):
found += strict_problems(value, f"{path}[{i}]")
return found
class NaiveInvoice(BaseModel):
vendor_name: str
due_date: str | None = None
total_amount: float
print("naive :", strict_problems(NaiveInvoice.model_json_schema()))
print("strict:", strict_problems(Extraction.model_json_schema()) or "no problems")
currency = Extraction.model_json_schema()["$defs"]["Invoice"]["properties"]["currency"]
print("currency:", [option.get("enum", "null") for option in currency["anyOf"]])
print("float :", 0.1 + 0.2, "| Decimal:", Decimal("0.1") + Decimal("0.2"))
line = {"description": "Toner", "quantity": 2, "unit_price": "64.00",
"line_total": "128.00"}
invoice = {"vendor_name": "Northwind", "invoice_number": "INV-7",
"invoice_date": "2026-09-14", "due_date": None, "currency": "CAD",
"line_items": [line], "tax_amount": "25.60", "total_amount": "150.00"}
for change in ({"currency": "CAD"}, {"currency": "OTHER"}):
attempt = {"status": "ok", "reason": None, "invoice": invoice | change}
try:
Extraction.model_validate(attempt)
except ValidationError as err:
for e in err.errors():
print("error :", ".".join(map(str, e["loc"])), "->", e["msg"])
nothing = Extraction.model_validate(
{"status": "not_an_invoice", "reason": "A delivery note", "invoice": None})
print("cannot answer:", nothing.status, "|", nothing.reason)python schema_demo.pynaive : ['$: additionalProperties is not false', '$.due_date: not in required']
strict: no problems
currency: [['USD', 'EUR', 'GBP', 'JPY', 'OTHER'], 'null']
float : 0.30000000000000004 | Decimal: 0.3
error : invoice.currency -> Input should be 'USD', 'EUR', 'GBP', 'JPY' or 'OTHER'
error : invoice -> Value error, line items + tax = 153.60, total_amount = 150.00
cannot answer: not_an_invoice | A delivery noteRead the output line by line:
- The naive model fails both rules: Pydantic leaves
additionalPropertiesunset, anddue_date: str | None = Nonehas a default, so it is not required. Sent raw withstrict: true, OpenAI rejects it with a 400. - The step-2 model passes, because every object forbids extra keys and every nullable field has no default.
currencyallows the five codes ornull, nothing else.0.1 + 0.2shows why money isDecimal.CADis rejected by the enum, so a provider enforcing the schema could only have producedOTHERornull. WithOTHER, the totals rule catches an invoice whose items and tax do not add up to the total.- A
not_an_invoiceresult validates with no invoice at all.
You do not always have to make these changes by hand. The SDK helpers, OpenAI's client.responses.parse(text_format=Model) and Anthropic's client.messages.parse(output_format=Model), convert a Pydantic model to their provider's subset and validate the reply against your original model. Anthropic's helper, for example, adds additionalProperties: false and moves unsupported constraints into field descriptions. Designing the model to be strict-ready anyway means the same schema works through raw HTTP, either SDK and your own validation, which lesson 4 relies on.
06. Check your understanding
07. Apply it
For the skill project, write your own invoice_schema.py, or adapt this one, and test it before you call any model:
- run the strict-rule checker on its schema and fix every problem;
- write five hand-made dictionaries: a correct invoice, one with a wrong total, one in an unsupported currency, a delivery note and an unreadable scan, and confirm each validates or fails the way you expect;
- write down which statuses go to a person and which are stored as they are.
08. Review prompt
From memory: list the five schema decisions from this lesson and the mistake each one prevents. Explain why Optional[str] = None and str | None without a default produce different schemas, and why the root of the schema is a wrapper with a status instead of the invoice itself.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.