title: How to check numbers an LLM extracted from a PDF before you save them
description: An LLM reading a financial statement or invoice sometimes returns a number that is not on the page. Five checks that catch it before it reaches your database: the number is printed on the page, the arithmetic holds, two reads agree, the value has a source box, and low-confidence values go to a person. Working Python.
How to check numbers an LLM extracted from a PDF¶
Your model does not misread numbers. It fills gaps. When a table loses its structure on the way into the prompt, the model returns the number that would make sense there. It looks right, parses as a float, and is not in the document. On 10-Q filings we measured this directly: extracted values that disagreed with another value for the same thing were right only about 79% of the time, against 94% for the rest.
You cannot prompt this away. You can catch it. Five checks, cheapest first; the first two need no tool at all.
| Check | Catches | Cost |
|---|---|---|
| 1. The number is printed on the page | invented and transposed values | free, text-layer PDFs |
| 2. The arithmetic holds | a wrong line among right ones | free |
| 3. Two independent reads agree | unstable reads on scans and dense tables | one more model call |
| 4. The value has a source box | values with no evidence | needs an extractor with citations |
| 5. Low confidence goes to a person | everything the first four flag | a review queue |
1. Is the number printed on the page?¶
Normalise both sides, then look for the value in the page's own text. Works on born-digital PDFs; scans have no text layer (use check 4 there).
import re
import pymupdf # pip install pymupdf
def numbers_on_page(page):
"""Every number printed on the page, as floats: 1,575.00 / (1,575) / 1.575,00 -> 1575.0"""
found = set()
for tok in re.findall(r"\(?-?[\d][\d.,]*\d\)?|\d", page.get_text()):
neg = tok.startswith("(") or tok.startswith("-")
t = tok.strip("()-")
if re.search(r",\d{2}$", t): # 1.575,00 (decimal comma)
t = t.replace(".", "").replace(",", ".")
else:
t = t.replace(",", "")
try:
found.add(-float(t) if neg else float(t))
except ValueError:
pass
return found
def printed(pdf_path, value, tolerance=0.005):
"""Pages (from 1) where the value is printed."""
doc = pymupdf.open(pdf_path)
return [p.number + 1 for p in doc
if any(abs(abs(n) - abs(value)) <= tolerance for n in numbers_on_page(p))]
printed("statement.pdf", 162000.0) # [1] -> printed on page 1
printed("statement.pdf", 162500.0) # [] -> not in the document: do not save it
A value printed nowhere is either invented, computed by the model, or scaled ("in thousands"). All three deserve a flag. If you want computed values, ask for them in a separate field so you know which ones to expect here.
2. Does the arithmetic hold?¶
Documents carry their own checksums. Use them.
def check_invoice(inv, cents=0.01):
problems = []
lines = sum(l["amount"] for l in inv["line_items"])
if abs(lines - inv["subtotal"]) > cents:
problems.append(f"line items add to {lines:.2f}, subtotal says {inv['subtotal']:.2f}")
if abs(inv["subtotal"] + inv["tax"] - inv["total"]) > cents:
problems.append("subtotal + tax != total")
return problems
def check_statement(st, cents=0.01):
end = st["opening_balance"] + sum(t["amount"] for t in st["transactions"])
return [] if abs(end - st["closing_balance"]) <= cents else [
f"transactions give {end:.2f}, closing balance says {st['closing_balance']:.2f}"]
For financial statements: assets = liabilities + equity, segment rows add to the total, this year's opening figure equals last year's closing figure. When a check fails, the row count is the first thing to look at: a dropped row is more common than a wrong digit.
3. Do two independent reads agree?¶
Run the extraction twice (or with two models) and compare field by field. A value both reads agree on is rarely wrong; a disagreement tells you exactly which field to look at. This doubles the model cost, so use it on the fields that matter (totals, balances), not on every line.
4. Does the value have a source box?¶
The strongest evidence is a place on the page. An extractor that returns a citation with every value lets you reject values that have none. ReadAnyDoc (open source, Apache-2.0) does this for every field of your schema, on scans as well as digital PDFs:
import readanydoc
out = readanydoc.extract("statement.pdf", schema=Statement, array_extract=True)
for path, cites in out.citations.items():
if not cites:
print("no source found:", path) # never an invented position
elif any(c.confidence == "low" for c in cites):
print("check by hand:", path, [c.content for c in cites])
print(out.warnings) # required fields not found, printed values left out, short tables
It also does checks 1 to 3 for you where it can: values are matched against the PDF's own text, long lists are
compared with the parsed tables' row counts and a short part is extracted again, and a number that disagrees with
another value for the same metric and period is marked low. Reducto and LlamaExtract return citations too;
how they compare.
5. Send what is flagged to a person¶
Save automatically only when every check passes. Everything else goes to a review screen that shows the value next to its highlighted source: how to show where a value came from on the page. Track how often reviewers change a flagged value; that number tells you whether your thresholds are right.
Questions¶
Why does my LLM hallucinate numbers from financial statements? Mostly because the table reached it as a flattened run of text, so columns and rows no longer line up, and it completes the pattern. Sending the page as an image, or parsing tables into rows first, removes most of it; the checks above catch the rest.
Can I trust the confidence score an LLM gives? Not one it writes about itself. Use confidence that comes from evidence: the value was found in the text layer, two reads agreed, a total checked out.
How accurate is extraction after these checks?
On our tests, values ReadAnyDoc marked high on 10-Q filings were right 94% of the time and low ones 79%; on 20
invoices 99.8% of values were found. Measure it on your own documents the same way: a sample with known answers.