All guides

Pull invoice data out of PDFs with Pydantic AI, in one short file

To extract invoice data with Pydantic AI, give the agent a Pydantic Invoice class with a validator that checks the lines add up to the total. When they don't, Pydantic AI sends the error back and the model reads it again. No retry code.

Gabriel MongaloDecember 3, 20263 min read

Gabriel Mongalo is an AI engineer in Phoenix with 10+ years shipping production software. He runs Southern Sun, an AI consulting practice serving Phoenix-area businesses in person and US businesses remotely.

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:

  1. Install uv, the tool that runs it.
  2. Copy one Python file and see what each part does.
  3. 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.

Terminal
curl -LsSf https://astral.sh/uv/install.sh | sh

On Windows, or with Homebrew, use the other install options.

2. The code

Save this as extract.py:

extract.pyPython
# /// 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:

  • Invoice is a Pydantic class listing what you want back. Money is Decimal, so cents stay exact.
  • check_the_math adds 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 a Tax row, so the amount column adds up to the total. A PDF that can't be read, or a rate limit, prints SKIPPED and 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:

A wholesale produce invoice from Tres Arroyos Produce Co., invoice 88412 dated 11/18/2026: Roma tomatoes 2 at 31.75 for 63.50, romaine hearts 3 at 38.40 for 115.20, then under Credits / adjustments a credit of -38.40 for a case of romaine from the 11/14 delivery. Subtotal 140.30, tax 0.00, total due $140.30.
The sample invoice from the demo repo. The credit sits below the other lines. Open the PDF

Get a key from the Claude Platform, then:

Terminal
export ANTHROPIC_API_KEY=your-key
uv run extract.py

After Pydantic AI's startup banner, you'll see:

Output
OK invoice-88412.pdf 140.30
Saved invoices-2026-12-03.csv

Each 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

  1. Run 20 of last month's invoices and compare them with what was typed by hand.
  2. Then point it at new ones.
  3. 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.

Common questions

Does Pydantic AI work with any model?
With most major providers, including OpenAI, Anthropic, Google and Amazon Bedrock. Change the model string and install that provider's extra, such as pydantic-ai-slim[openai]. Because LiteParse turns the PDF into text first, the model doesn't need to read PDFs itself.
What happens when an invoice's totals don't add up?
Pydantic AI sends the validator's error back and the model reads the invoice once more. If it still doesn't add up, the script prints CHECK BY HAND, skips that file and carries on with the rest. Sometimes the vendor made the mistake, and that's worth a phone call.
Why use Decimal instead of float for money?
Floats store most cents approximately, so 0.1 + 0.2 comes out as 0.30000000000000004. Decimal keeps cents exact, which matters when code compares a sum against a printed total.

Rather have it fixed
and running for you?

Start with a free 45-minute call. Bring the workflow, the part that breaks, and what it should do. If it's a fit, the first step is a fixed-price milestone, scoped in writing before any work starts, with the goal of something that runs, not a report.

Fixed price · scoped in writing first · in person in the Phoenix area

Read next

Automate Data Entry from PDFs and Email with AI

To automate data entry from PDFs and emails, let AI read orders, bills and forms into Excel or QuickBooks. Let formulas do the math, and send handwriting, totals that don't match and anything not on the page to a person.