Workflow recipe
Extract structured data from PDFs
Turn a folder of PDF invoices into validated JSON with Docling, a Pydantic schema and structured outputs, plus a review file for every one that fails a check.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
To extract structured data from PDFs with AI, hand-check a small golden set, convert each PDF to Markdown with Docling, define the fields in a Pydantic schema and have the model fill it through structured outputs. Plain Python then checks rules the schema cannot, such as totals that must add up, and every failure goes to a review file.
Pasting a PDF into a chatbot and asking for “the invoice details as JSON” works once. For two hundred invoices a month it falls apart: tables come out jumbled, totals get invented when they are hard to read, and nobody notices the one that was wrong.
This recipe splits the job into parts you can check. Docling, an open-source converter, turns each PDF into clean Markdown with its tables intact. A Pydantic schema says exactly which fields you want, and the model fills it through structured outputs. Plain Python then checks the numbers add up, and anything that fails goes into a review file instead of your accounts. The example uses invoices, but the same pattern works for purchase orders, lab reports or contracts.
FolderAbout 30 min
1. Hand-check a small golden set first
Pick ten PDFs that cover the variety you get: different suppliers, a multi-page one, one with a discount line, one scanned. For each, write the correct answer by hand as JSON in a golden/ folder, named after the PDF.
{
"supplier_name": "Northwind Supplies Ltd",
"invoice_number": "INV-20931",
"issue_date": "2026-11-03",
"due_date": "2026-12-03",
"currency": "GBP",
"purchase_order": null,
"total": "252.60"
}This takes half an hour and is the most useful half hour in the project. Without it you cannot tell whether a change to the prompt or schema made things better or worse.
TerminalAbout 15 min
2. Install Docling and look at what it produces
python -m venv .venv && source .venv/bin/activate
pip install docling "pydantic-ai-slim[anthropic]"
docling pdfs/northwind-0931.pdf --to md --output converted/The first run downloads Docling’s layout and table models, so it is slow. Open the Markdown file and compare it with the PDF. Check three things: tables are real Markdown tables with the right columns, numbers are intact, and nothing is missing from page two.
Docling runs OCR by default for pages without a text layer, which handles most scans. If a scan still comes out empty or garbled, the image quality is the problem, and no prompt will fix it.
EditorAbout 20 min
3. Define the schema, with nulls for what may be missing
from datetime import date
from decimal import Decimal
from typing import Literal
from pydantic import BaseModel, Field
class LineItem(BaseModel):
description: str
quantity: Decimal = Field(gt=0)
unit_price: Decimal = Field(ge=0, description="Price per unit as printed, without currency symbol")
line_total: Decimal | None = Field(None, description="Line total as printed, or null if not shown")
class Invoice(BaseModel):
supplier_name: str
invoice_number: str
issue_date: date
due_date: date | None = Field(None, description="Null if the invoice shows no due date")
currency: Literal["GBP", "EUR", "USD", "OTHER"]
purchase_order: str | None = Field(None, description="PO number if printed, otherwise null. Never guess.")
items: list[LineItem] = Field(min_length=1)
subtotal: Decimal | None = Field(None, description="Subtotal before tax as printed, or null")
tax: Decimal | None = Field(None, description="Total tax as printed, or null")
total: Decimal = Field(description="Total amount due as printed")Three choices here prevent most bad data. Fields that may be absent, like the PO number, are nullable, so the model is not pushed to invent one. Currency is a closed list with an OTHER escape. And the descriptions, which are sent to the model, say “as printed”, because you want to read numbers, not have the model calculate them.
EditorAbout 15 min
4. Write the checks the schema cannot express
A schema guarantees shape. It cannot tell you the total is right. Put the arithmetic in code:
from decimal import Decimal
from schema import Invoice
TOLERANCE = Decimal("0.02")
def problems(inv: Invoice) -> list[str]:
"""Checks the schema cannot express. An empty list means the invoice adds up."""
found = []
items_sum = sum((i.quantity * i.unit_price for i in inv.items), Decimal("0"))
for n, item in enumerate(inv.items, start=1):
if item.line_total is not None and abs(item.quantity * item.unit_price - item.line_total) > TOLERANCE:
found.append(f"line {n}: quantity x unit price does not match line total")
if inv.subtotal is not None and abs(items_sum - inv.subtotal) > TOLERANCE:
found.append(f"items add up to {items_sum}, subtotal says {inv.subtotal}")
expected = (inv.subtotal if inv.subtotal is not None else items_sum) + (inv.tax or Decimal("0"))
if abs(expected - inv.total) > TOLERANCE:
found.append(f"subtotal plus tax is {expected}, total says {inv.total}")
if inv.due_date and inv.due_date < inv.issue_date:
found.append("due date is before issue date")
if inv.currency == "OTHER":
found.append("currency is not GBP, EUR or USD")
return foundAdd your own rules: known supplier names, invoice number formats per supplier, a maximum plausible total. Each rule turns a silent error into a line in the review file.
EditorAbout 25 min
5. Convert, extract and route failures to review
import csv
import json
import sys
from pathlib import Path
from docling.document_converter import DocumentConverter
from pydantic_ai import Agent
from pydantic_ai.exceptions import UnexpectedModelBehavior
from checks import problems
from schema import Invoice
agent = Agent(
"anthropic:claude-opus-5-5",
output_type=Invoice,
retries=2,
instructions=(
"Extract the invoice fields from the Markdown below, which was converted from a PDF. "
"Copy numbers and identifiers exactly as printed. "
"If a field is not in the document, return null. Do not calculate or guess values."
),
)
def main(pdf_dir: str, out_dir: str) -> None:
out = Path(out_dir)
out.mkdir(parents=True, exist_ok=True)
converter = DocumentConverter()
passed, review = 0, []
for pdf in sorted(Path(pdf_dir).glob("*.pdf")):
markdown = converter.convert(pdf).document.export_to_markdown()
(out / f"{pdf.stem}.md").write_text(markdown, encoding="utf-8")
if len(markdown.strip()) < 50:
review.append({"file": pdf.name, "reason": "almost no text extracted: scanned PDF?"})
continue
try:
invoice = agent.run_sync(markdown).output
except UnexpectedModelBehavior as err:
review.append({"file": pdf.name, "reason": f"output failed the schema: {err}"})
continue
record = {"file": pdf.name, **invoice.model_dump(mode="json")}
(out / f"{pdf.stem}.json").write_text(json.dumps(record, indent=2), encoding="utf-8")
issues = problems(invoice)
if issues:
review.append({"file": pdf.name, "reason": "; ".join(issues)})
else:
passed += 1
with (out / "review.csv").open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["file", "reason"])
writer.writeheader()
writer.writerows(review)
print(f"{passed} passed all checks, {len(review)} need review: see {out / 'review.csv'}")
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])Run it on the golden-set PDFs:
export ANTHROPIC_API_KEY="your-key"
python extract.py golden-pdfs/ out/Pydantic AI sends the schema to the model, validates what comes back, and on a validation error asks the model to try again (here up to twice). The converted Markdown is saved next to each result, so when a record is wrong you can see whether conversion or extraction caused it.
TerminalAbout 20 min
6. Score against the golden set
import json
import sys
from pathlib import Path
FIELDS = ["supplier_name", "invoice_number", "issue_date", "due_date", "currency", "purchase_order", "total"]
def main(golden_dir: str, out_dir: str) -> None:
right = {f: 0 for f in FIELDS}
count = 0
for expected_file in sorted(Path(golden_dir).glob("*.json")):
got_file = Path(out_dir) / expected_file.name
if not got_file.exists():
print(f"{expected_file.name}: no output")
continue
expected = json.loads(expected_file.read_text())
got = json.loads(got_file.read_text())
count += 1
for field in FIELDS:
if str(expected.get(field)) == str(got.get(field)):
right[field] += 1
else:
print(f"{expected_file.name}: {field} expected {expected.get(field)!r}, got {got.get(field)!r}")
for field in FIELDS:
print(f"{field:16} {right[field]}/{count}")
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])python score.py golden/ out/Read every mismatch next to its Markdown file. If the Markdown is wrong, fix conversion (better scans, a different table setting). If the Markdown is right and the field is wrong, improve the field description in the schema. Re-run both scripts after each change and keep a note of the scores, so you know a change helped.
SpreadsheetAbout 25 min
7. Run the batch and work the review file
Once the golden set scores well, run the full folder. Load the passing JSON into your spreadsheet or database, and give review.csv to the person who used to type invoices in by hand. Their job becomes checking the flagged ones instead of all of them.
Add every reviewed failure to the golden set, with the correct answer. Over a few weeks you collect the awkward cases your suppliers actually send, and the score tells you whether a model or prompt change is safe.
Check it worked
Verification checklist
0 of 7 done
When it goes wrong
If many records fail the total check, look at the Markdown first. Merged table cells and totals printed outside the table are the usual cause. Docling’s table export can help: each table in result.document.tables has export_to_dataframe() so you can inspect it as rows and columns.
If the model returns plausible values that are not in the PDF, the field is required when it should be nullable, or the description invites calculation. Make it nullable and say “as printed”.
If extraction is slow or costly, check the Markdown length. Long terms-and-conditions pages are sent to the model with every invoice. Trim pages you never need before extraction, for example by converting only the first two pages.
If dates come out in the wrong format or order (3/11 versus 11/3), add the supplier’s country to the instructions, or extract the date as printed into a string field and parse it in code with a known format.
Variations
To keep documents on your machine, point Pydantic AI at a local model served by Ollama through its OpenAI-compatible endpoint. Expect lower accuracy on messy tables, which the golden set will show you.
For one-off jobs without code, a coding agent with the pdf skill can extract text and tables from a handful of files, and the xlsx skill can write the results into a spreadsheet. Check the numbers against the source as carefully as you would here.
If you need a reader-ready summary of a long PDF rather than fields in a table, summarise a long report with AI keeps a page reference on every claim instead.
For other document types, only the schema and checks change. A purchase order has the same line-item pattern; a lab report needs units and reference ranges; a contract needs dates, parties and notice periods with the clause they came from.
Related document AI guides
Structured outputs explains how the model is held to a schema, and the document parsing entry defines the conversion step. For questions over documents rather than fields, build a RAG pipeline in a day or chat with private documents locally. If the output ends up in a spreadsheet, clean and check it with AI. More recipes are in the AI workflow examples hub.
Outcome and tools
- Outcome
- A script that converts PDFs to typed records, checks each one against business rules, measures accuracy on a hand-checked set, and lists failures for review.
- For
- Developers, Data analysts
- Variants for
- Claude Code
- Agent Skills
Related
- Get reliable JSON from an LLM with structured outputs
Describe the output as a schema, let the provider enforce it, validate it with Pydantic AI or the AI SDK, and handle failures.
- Clean and analyse a messy spreadsheet with AI
Clean a messy spreadsheet with ChatGPT or Claude without losing rows: profile it, agree the rules, keep a cleaning log and reconcile totals before any chart.
- Evaluate RAG answers with a golden dataset
Set up RAG evaluation with a golden dataset and promptfoo: score retrieval, correctness and grounding for every question, and fail CI when answer quality drops.
- Docling
Converts PDFs and office documents into structured output for LLM pipelines.
- Structured outputs
Constraining or validating model output so it matches a schema, usually JSON Schema, and can be parsed reliably by your code.