You bolted invoice reading onto your app with an AI coding agent. Paste a PDF, get clean JSON back, ship it in an afternoon. Then a client's books stop reconciling and the cause turns out to be a total the model misread weeks ago. Here is a setup that catches those misreads the day they happen.
The fix is a pipeline where the model extracts and plain code verifies. The model reads the page and returns structured fields, each with the exact source text next to it. Your code checks the arithmetic, the formats and the history. Whatever fails a check lands on a short review list for a human, and only what passes goes anywhere near your records.
The failure you can't see
An LLM reading an invoice is convincing by default. The output comes back as tidy JSON with every field filled, which reads as "checked" when it really means "present". The typical errors are boring and expensive:
- a total off by one digit, because a 7 in the scan looked like a 1
- a decimal separator flipped on a European invoice, where 1.234,56 means 1,234.56
- a date parsed into the wrong format, so the third of November becomes the eleventh of March
- an invoice number misread, so you pay the same bill twice or miss the duplicate
None of these look wrong on screen. That's the trap: an extraction that fails loudly (a crash, a null, an empty list) is safer than one that fills gaps with plausible values. Design for the loud failure. Everything below is about forcing one.
Define the fields before you prompt
Write the schema first and hand it to the model as part of the prompt. The one instruction that changes everything: if a value is not printed on the page, return null. Not a guess, not a reconstruction from context. The model should be a copier, not a filler.
Here is a prompt you can paste straight into your extraction step:
You are an invoice data extractor. Read the invoice text below and
return JSON only.
Fields:
- vendor: the company that issued the invoice
- invoice_number: exactly as printed
- invoice_date: the issue date in YYYY-MM-DD
- currency: the 3-letter code printed on the invoice (for example USD, EUR)
- line_items: a list of {description, quantity, unit_price, amount}
- subtotal: the printed subtotal before tax
- tax: the printed tax or VAT total
- total: the printed grand total
Rules:
- Return amounts as plain numbers with a dot as the decimal separator
(1234.56), no currency symbols. Put the printed form in source_text.
- If a field does not appear on the page, return null. Never guess,
infer, or reconstruct.
- For every field, add "source_text": the exact words from the page
you read the value from. Same for each line item.
- Return JSON only. No commentary.
Invoice text:
<PASTE THE EXTRACTED TEXT HERE>
The ISO 8601 date format exists precisely so dates travel between systems without ambiguity (iso.org); asking for YYYY-MM-DD up front removes an entire class of parsing bugs.
Make it quote the page
The source_text field is your review speed multiplier. When every value carries the words it came from, a human can confirm or reject a whole invoice with the original PDF open next to the JSON: run a find-in-page on the quote and see if the number matches.
This also catches a subtle failure: the model returns a value that was never on the page, and the quote for it turns out to be paraphrased, from a different part of the document, or missing. A quote that doesn't exist is itself a failed check, because the model was asked to point at the page and couldn't.
Check in code, not with the model
The tempting shortcut is asking the model to double-check its own extraction. Don't rely on it. The second pass runs through the same reading habits as the first, so it inherits the same blind spots. Verification belongs in plain code, where the rules are exact and the failures are loud.
These checks catch the common misreads:
- line items sum to the subtotal
- subtotal plus tax equals the total
- the date parses as YYYY-MM-DD and is not in the future
- the currency is a valid code from the ISO 4217 list (iso.org)
- the invoice number has not been seen before
And the code, small enough to drop into any script. It is exactly the kind of small, testable job to hand a coding agent, along with five sample invoices that should fail; if you want a harness that runs the code and the tests for you, you can try the zcode agent harness free.
from datetime import date
# Extend this from the official ISO 4217 list you ship with your app
ISO_4217 = {"USD", "EUR", "GBP", "CHF", "GEL", "PLN", "UAH", "RSD", "ILS"}
def check_invoice(inv, seen_numbers):
# seen_numbers: a set of (vendor, invoice_number) pairs
"""Returns a list of problems. Empty list means the invoice passed."""
problems = []
items = inv.get("line_items") or []
item_sum = round(sum(li.get("amount") or 0 for li in items), 2)
subtotal = inv.get("subtotal")
if subtotal is not None and item_sum != round(subtotal, 2):
problems.append(
f"line items sum to {item_sum}, subtotal says {subtotal}")
tax, total = inv.get("tax"), inv.get("total")
if None not in (subtotal, tax, total):
if round(subtotal + tax, 2) != round(total, 2):
problems.append(
f"{subtotal} + {tax} = {round(subtotal + tax, 2)}, total says {total}")
raw_date = inv.get("invoice_date")
if raw_date is None:
problems.append("no invoice date printed on the page")
else:
try:
d = date.fromisoformat(raw_date) # https://docs.python.org/3/library/datetime.html
if d > date.today():
problems.append(f"date {d} is in the future")
except ValueError:
problems.append(f"date {raw_date!r} is not YYYY-MM-DD")
if inv.get("currency") not in ISO_4217:
problems.append(f"currency {inv.get('currency')!r} is not a valid ISO 4217 code")
key = (inv.get("vendor"), inv.get("invoice_number"))
if key in seen_numbers:
problems.append(f"invoice {key!r} already processed")
return problems
Two practical notes. Invoices with a discount or a shipping line need those in the sum, so extract them as fields too. And some invoices round per line item, so the sum can sit a cent or two away from the printed subtotal. If you see that pattern in your own documents, allow a tolerance of a cent or two instead of rejecting every such invoice; the point of the check is to catch misreads, not formatting quirks.
The seen-numbers set can be a plain file at first and a tiny table later. Key it by vendor and invoice number together, since two vendors can use the same number. What matters is that it exists before your second invoice arrives.
What fails goes to a human, never to the books
When check_invoice returns anything, the record stops. Build a short review list and append the failure there: the file name, the field, the extracted value, the quote, and which check it failed. Something like "March receipts/inv-2214.pdf: subtotal says 4,120.00 but line items sum to 4,210.00, source quote reads 4,120.00".
Keep the list short and boring, and it will actually get reviewed. A person with the original PDF open and the quote in front of them can clear each entry quickly. Once they fix or confirm a value, let the checks run again on the corrected record, and only then write it anywhere permanent.
The rule that matters: nothing enters your ledger, your invoicing app, or your client's books on the strength of the model's output alone, no matter how clean it looks. The check list is not overhead. It is the part of the pipeline that catches the invoice that reads wrong.
Keep the original file and the raw output
Store two things for every invoice: the original file, untouched, and the raw model output before your code touched it. Key both by the file's hash so they stay linked even if the file gets renamed or moved.
Six months from now, when a client asks why a payment is off, or a tax authority asks how a number was derived, you will have the page it came from, the words the model quoted, and the exact output your pipeline produced. That chain answers the question in minutes. Without it, you are arguing from memory with a model that no longer exists in the same configuration.
The checklist
- Schema written before the prompt, nulls instead of guesses
- Amounts as plain numbers, printed form kept in source_text
- Arithmetic, date, currency and duplicate checks in code
- Failures go to a review list, never to the books
- Original file and raw output stored, keyed by hash
The pipeline is four small pieces: a schema prompt that refuses to guess, quoted source text, code checks that fail loudly, and a review list for everything that fails. None of it is hard to build in an evening, and together they turn a convincing wrong number into a caught one.
If your agent is going to run and re-run this pipeline as you add invoice formats, there's 10% off GLM coding plans. For the JSON side of this in more depth, see Get JSON you can trust from an LLM, and there's more on our blog about building small AI features that hold up.
If this kept a wrong number out of someone's books, a small tip on the post keeps these guides coming.






Latest comments
0