Sub topic 6
Designing the extraction schema
This chapter assumes you can write basic Python, read and write JSON, and have called an LLM API with a prompt. It also assumes you know what a PDF is. You do not need to have used Pydantic before, but the examples use it.
The extraction schema is the contract between your document and your code. It lists the fields you want, their types, and what a field should contain when the document does not provide it. Most extraction bugs trace back to a schema that was too loose, too strict, or ambiguous. This chapter covers how to design one.
What a schema does
A schema serves three purposes at once.
- It tells the model what to look for. Field names and descriptions become part of the prompt.
- It tells your code what shape to expect, so downstream code can rely on the types.
- It gives validation something to check, which is the basis for the retry and review steps in later chapters.
Because the schema does all three jobs, a field you add "just in case" costs you in each place. It adds prompt tokens, adds a way for validation to fail, and adds a value someone has to evaluate.
Start from the decision, not the document
Begin by asking what your system does with the data. An accounts-payable system needs a vendor, an invoice number, a date, a currency and a total. It probably does not need the vendor's fax number, even though the invoice shows it.
A practical approach:
- List the downstream uses of the data.
- Collect five to ten real documents, including messy ones.
- For each use, mark where the value appears in the documents.
- Keep only the fields that a use requires.
Adding fields later is easy. Removing a field that other code depends on is not.
A minimal schema in Pydantic
Pydantic is a Python library that defines data shapes as classes and validates data against them. Here is the invoice schema used throughout this tutorial.
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")Notice the split between required and optional fields. vendor and invoice_number have no default, so validation fails if they are missing. The other three are Optional with a default of None, so the model may return null for them.
Required versus optional fields
This is the most consequential choice in the schema. Consider what happens in each direction.
| Choice | What the model does when the value is missing | Risk |
|---|---|---|
| Field is required | It must produce something, so it may invent a plausible value | Hallucinated data that passes validation |
| Field is optional | It can return `null` | Real values may be reported as `null` if the model is cautious |
A required field pressures the model to fill it. A made-up invoice number is worse than a missing one, because the made-up value looks valid and flows into your system. So the usual rule is: make a field optional unless a record without it is useless to you.
The required fields in the example (vendor and invoice_number) are the ones the business cannot process without. If they are absent, a failure is the right outcome. It sends the document to a human instead of storing a guess.
Choosing types
Pick the narrowest type that matches how the value will be used.
- Use
floatorDecimalfor money, not a string like "$1,234.50". Tell the prompt to return a plain number. For exact currency arithmetic,Decimalavoids floating-point rounding, but the JSON still carries a number. - Use ISO 8601 strings (
YYYY-MM-DD) for dates. Ambiguous formats such as03/04/2025mean different dates in different countries, so ask the model to normalize and say so in the description. - Use
Literalor anEnumfor fields with a fixed set of values, such as a document status. - Use
listof a nested model for repeating items such as line items.
Here is a schema extended with an enum and nested line items.
from enum import Enum
from typing import Optional
from pydantic import BaseModel, Field
class PaymentTerms(str, Enum):
net_15 = "net_15"
net_30 = "net_30"
net_60 = "net_60"
due_on_receipt = "due_on_receipt"
other = "other"
class LineItem(BaseModel):
description: str
quantity: Optional[float] = None
unit_price: Optional[float] = None
amount: Optional[float] = None
class DetailedInvoice(BaseModel):
vendor: str = Field(description="Name of the company issuing the invoice")
invoice_number: str
total: Optional[float] = Field(default=None, description="Grand total as a number, or null if absent")
payment_terms: Optional[PaymentTerms] = Field(
default=None,
description="One of the allowed values, or null if the document states no terms",
)
line_items: list[LineItem] = Field(default_factory=list)
example = DetailedInvoice(vendor="Acme Ltd", invoice_number="A-100", payment_terms="net_30")
print(example.model_dump_json(indent=2))The enum includes an other value. Without it, a document with terms such as "net 45" would force the model to pick a wrong category or fail validation. An escape value keeps the field honest.
Handling missing values and ambiguity
A document can leave a value out in several ways, and the schema should distinguish what matters to you.
- Absent: the invoice has no currency printed. Return
null. - Ambiguous: two totals appear, such as a subtotal and a grand total. Define which one you want in the field description.
- Unreadable: OCR damaged the number. Returning
nullis safer than a guess. - Not applicable: a credit note has no due date.
nullis correct here too.
All of these map to null, which loses the reason. If the reason matters, add a companion field, for example a short notes string, or a per-field confidence. Do this only when a downstream step uses it, since each addition grows the schema.
Descriptions are the main tool for resolving ambiguity. Compare two descriptions for the same field:
- Weak:
total: Total amount - Better:
total: Grand total including tax, as a number without currency symbols, or null if absent
The second removes three questions the model would otherwise answer by guessing.
Keep the schema small and flat
Each additional field raises the chance of an error somewhere in the record. Deeply nested structures are harder for models to produce and harder for you to evaluate. Prefer a flat set of fields, and use nesting only for genuinely repeating groups such as line items.
If a document needs many fields, consider several smaller schemas for different parts of it, such as header, line items and totals. That fits well with the long-document techniques later in the tutorial.
Common mistakes
- Everything required. The model fills gaps with inventions. Make fields optional by default.
- Vague names. A field called
datecould be the invoice date, due date or delivery date. Name itinvoice_dateand describe it. - Free-text values for fixed sets. A string where an enum belongs leads to "Net 30", "net30" and "30 days" in your database.
- No description on ambiguous fields. The model chooses a meaning silently.
- Schema drift. The prompt lists one set of keys and the Pydantic class another. Generate the prompt's key list from the model with
Invoice.model_fields.keys()so they cannot diverge.
from pydantic import BaseModel
from typing import Optional
class Invoice(BaseModel):
vendor: str
invoice_number: str
total: Optional[float] = None
keys = ", ".join(Invoice.model_fields.keys())
print(f"Return only a JSON object with these keys: {keys}")How the schema flows through the pipeline
Test the schema before you build around it
Before wiring up the full pipeline, check the schema by hand against your sample documents. For each one, fill in the schema yourself. Note every place you hesitated, because the model will hesitate there too. Each hesitation points to a missing description, a missing enum value, or a field that should be optional.
Then check that your validation behaves as intended on bad input.
from typing import Optional
from pydantic import BaseModel, ValidationError
class Invoice(BaseModel):
vendor: str
invoice_number: str
total: Optional[float] = None
good = '{"vendor": "Acme Ltd", "invoice_number": "A-100", "total": null}'
bad = '{"vendor": "Acme Ltd", "total": "about 50"}'
print(Invoice.model_validate_json(good))
try:
Invoice.model_validate_json(bad)
except ValidationError as exc:
print(exc.error_count(), "errors")The bad input fails twice: invoice_number is missing and total is not a number. Those are the errors the retry loop will feed back to the model.
Summary of design rules
- Include only fields that a downstream use needs.
- Make fields optional unless a record is useless without them.
- Use narrow types: numbers for money, ISO strings for dates, enums for fixed sets.
- Add an escape value such as
otherto enums. - Write descriptions that settle ambiguity.
- Keep the structure flat, and nest only repeating groups.
- Generate prompt keys from the schema.
Exercise
A schema marks invoice_number as required and currency as optional. A scanned invoice has a smudged invoice number. What is likely to happen with a required field, and what would you change if a missing number should not block processing?
Show answer
The model may invent a plausible invoice number to satisfy the required field, and the invented value would pass validation. If a missing number should not block processing, make invoice_number optional with a default of None, and add a grounding check. If the record is useless without it, keep it required, but then route documents where validation fails or the value is not found in the source text to human review.
Exercise
You add a payment_terms string field and find values such as "Net 30", "net30" and "30 days" in your database. Which schema change fixes this, and what value should you add to avoid forcing wrong answers?
Show answer
Replace the string with an Enum or Literal listing the allowed values (for example net15, net30, net60, dueon_receipt). Add an other value for terms that fit none of the categories, and keep the field optional so the model can return null when no terms are stated.