You have a pile of vendor invoices, and someone types them into a spreadsheet every week.
The goal: drop the PDFs in a folder, run one script, and get a spreadsheet with every line item. The AI does the reading, and plain Python checks its work, so a misread invoice never lands in your books unnoticed.
What you'll do:
- Install uv, the tool that runs it.
- Copy one Python file and see what each part does.
- Run it on a sample invoice, then on yours.
At the end you'll have invoices.csv, plus a short list of any invoice that didn't add up, for a person to check.
Get the code: the project, with a sample invoice, is on GitHub. Free to use, MIT licensed.
1. Install uv
uv installs Python and the right package versions for you, so there's no virtual environment to set up.
curl -LsSf https://astral.sh/uv/install.sh | shOn Windows, or with Homebrew, use the other install options.
2. The code
Save this as extract.py:
# /// script
# requires-python = ">=3.12"
# dependencies = ["pydantic-ai-slim[anthropic]==2.78.0", "liteparse==2.21.5"]
# ///
import csv
from datetime import date
from decimal import Decimal
from pathlib import Path
from liteparse import LiteParse
from pydantic import BaseModel, Field, model_validator
from pydantic_ai import Agent, UnexpectedModelBehavior
class LineItem(BaseModel):
description: str
amount: Decimal
class Invoice(BaseModel):
vendor: str
invoice_number: str
invoice_date: date
line_items: list[LineItem] = Field(min_length=1)
tax: Decimal
total: Decimal
@model_validator(mode='after')
def check_the_math(self):
lines = sum(item.amount for item in self.line_items)
if lines + self.tax != self.total:
raise ValueError(
f'Lines {lines} plus tax {self.tax} is not the total '
f'{self.total}. Read the invoice again for a missed line.'
)
return self
agent = Agent(
'anthropic:claude-sonnet-5-5',
output_type=Invoice,
instructions=(
'Copy the invoice exactly as printed. Shipping, fees, discounts and '
'credits are line items, and discounts and credits are negative. '
'Tax is 0 if there is none. Never change or invent a number.'
),
)
parser = LiteParse(quiet=True)
pdfs = sorted(Path('invoices').glob('*.pdf', case_sensitive=False))
if not pdfs:
raise SystemExit('No PDFs found in the invoices folder.')
csv_file = f'invoices-{date.today()}.csv'
with open(csv_file, 'w', newline='') as f:
rows = csv.writer(f)
rows.writerow(['file', 'vendor', 'invoice', 'date', 'item', 'amount'])
for pdf in pdfs:
try:
text = parser.parse(pdf).text
invoice = agent.run_sync(text).output
except UnexpectedModelBehavior:
print('CHECK BY HAND', pdf.name)
continue
except Exception as error:
print('SKIPPED', pdf.name, error)
continue
items = [(item.description, item.amount) for item in invoice.line_items]
if invoice.tax:
items.append(('Tax', invoice.tax))
for description, amount in items:
rows.writerow([pdf.name, invoice.vendor, invoice.invoice_number,
invoice.invoice_date, description, f'{amount:.2f}'])
print('OK', pdf.name, f'{invoice.total:.2f}')
print('Saved', csv_file)The comment block at the top lists the two packages uv installs: Pydantic AI talks to the model, and LiteParse turns each PDF into text on your machine, free, with OCR for scans. Tested on 2026-12-03 with the latest releases that day, including a live run with Claude Sonnet 5.5 on the sample invoice.
Then three parts:
Invoiceis a Pydantic class listing what you want back. Money isDecimal, so cents stay exact.check_the_mathadds up the lines. The model copies, Python adds, because code adds exactly and a model only usually does.- The loop reads each PDF in
invoices/and writes one CSV row per line item, plus aTaxrow, so the amount column adds up to the total. A PDF that can't be read, or a rate limit, printsSKIPPEDand the run carries on.
The trick is that you never write retry code. When check_the_math fails, Pydantic AI sends the error back and the model reads the invoice again, now told what was off. If the second read still doesn't add up, you get CHECK BY HAND and nothing is saved for that file.
3. Run it
Put your PDFs in a folder called invoices/ next to extract.py, or start with the sample from the demo repo. It's a produce invoice with a credit line, the kind a first read misses:

Get a key from the Claude Platform, then:
export ANTHROPIC_API_KEY=your-key
uv run extract.pyAfter Pydantic AI's startup banner, you'll see:
OK invoice-88412.pdf 140.30
Saved invoices-2026-12-03.csvEach run writes a new dated CSV from everything in the folder, so move PDFs out once they're done, or you pay to read them again.
To use another provider, change the model string and swap anthropic for that provider in the dependencies line, for example pydantic-ai-slim[openai]. For one key across several providers with spending caps, the Pydantic AI Gateway takes 'gateway/anthropic:claude-sonnet-5-5'. Setting it up gets a guide of its own.
What it won't catch
Only mistakes that break the math. A wrong date, invoice number or vendor still adds up. Scans show it: run through OCR, the sample invoice came back with invoice number 88412 as "8a412". So check a few rows against the paper each month.
A passing check also doesn't prove every line was read right. A model told the lines are $38.40 short could, in principle, make up a line to close the gap, which is why the instructions forbid it and why the spot check matters.
Some correct invoices will land in CHECK BY HAND: a deposit already paid, or a "balance due" that isn't the invoice total. That's the right place for them.
My rule: trust checks your code can run, not the model's confidence in itself.
Before you rely on it
- Run 20 of last month's invoices and compare them with what was typed by hand.
- Then point it at new ones.
- If one vendor keeps landing in
CHECK BY HAND, ask them for a CSV instead.
Step 1 is a small eval. Keep those 20 invoices and their hand-typed answers, and rerun them whenever you change the prompt or try a new model. Report it as "wrong on X of 20," not pass or fail. For how to build evals that don't mislead you, see how to choose an AI model.