AI Invoice Processing System
Document extraction with a confidence threshold and a human in the loop
By Renjith ·
Prerequisites
- Python and basic FastAPI
- A language model API with vision support
- Sample invoices (the repository includes synthetic ones)
The problem
Document extraction demos quote accuracy figures like 95% and treat that as success. In accounts payable it is not.
Five percent of a thousand invoices a month is fifty wrong payments. Some are wrong by a rounding error and some are wrong by a decimal place, and the system as usually built gives you no way to tell which fifty they are. The failure is not the error rate — it is that errors arrive indistinguishable from correct results.
What was built
An extraction pipeline where per-field confidence is a first-class output. Every extracted field carries a score, thresholds are set per field according to what an error costs, and anything below threshold goes to a review queue with the source document region highlighted.
Total amount and bank details have high thresholds because getting them wrong is expensive. Supplier address has a low one because getting it wrong is a nuisance. Treating every field with the same threshold is what makes review queues either useless or unbearable.
How it works
Arithmetic validation beats model confidence#
Self-reported confidence from a language model is weakly calibrated. Arithmetic is not.
validate.pypythondef validate(invoice: Invoice) -> list[FieldFlag]:
flags = []
line_total = sum(line.quantity * line.unit_price for line in invoice.lines)
if abs(line_total - invoice.subtotal) > Decimal("0.02"):
flags.append(FieldFlag("subtotal", "Line items do not sum to subtotal"))
expected_total = invoice.subtotal + invoice.tax
if abs(expected_total - invoice.total) > Decimal("0.02"):
flags.append(FieldFlag("total", "Subtotal plus tax does not equal total"))
if invoice.iban and not valid_iban_checksum(invoice.iban):
flags.append(FieldFlag("iban", "IBAN checksum failed"))
return flags
These three checks caught more real errors than the confidence scores did. An IBAN checksum failure is not a probability — it is a fact, and it is exactly the field where an undetected error is most expensive.
Why n8n is one component and not the architecture#
The orchestration between mailbox, extraction service, review queue and the finance system runs in n8n, because that glue is genuinely faster to build and change in a visual tool than in code.
The extraction service, validation rules and confidence logic are a Python service with tests. That split matters: the parts that encode business rules need version control, review and a test suite, and the parts that route messages between systems benefit from being visibly editable by someone who is not the author.
Tool choice is a component decision
The same system has been built with Power Automate for the orchestration layer with no change to the extraction service. The workflow tool is the most replaceable part of the architecture, which is precisely why the important logic should never live inside it.
The number that mattered#
Not extraction accuracy — review time per flagged invoice. Early on it was around 90 seconds, mostly spent hunting for the relevant part of the document. Highlighting the source region for the uncertain field brought it to roughly 20. That single change did more for the business case than any accuracy improvement.
Build steps
- 1
Define the target schema
Explicit fields with types and validation rules — a total that does not equal the sum of lines is a detectable error, not a judgement call.
- 2
Extract with structured output
Constrained JSON output against the schema, never free text parsed afterwards.
- 3
Add per-field confidence
Self-reported confidence, cross-checked against arithmetic validation and format rules. Self-reported alone is not trustworthy.
- 4
Set thresholds by cost of error
Bank details and totals high, cosmetic fields low. This is a finance decision, not a technical one — make it with the finance team.
- 5
Build the review queue
Side-by-side document and extracted values, with the uncertain field highlighted. Review speed is what determines whether the system saves time.
- 6
Feed corrections back
Every human correction is stored as a labelled example, which turns the review queue into an evaluation set that grows itself.
Lessons learned
Confidence per field, not per document. A document-level score cannot tell a reviewer where to look.
Validate with arithmetic wherever arithmetic exists. It is free, deterministic, and catches the expensive errors.
Set thresholds by cost of error, with the people who bear the cost.
Optimise review time, not just model accuracy. The system's value is bounded by how fast a person can resolve what it flags.
Limitations
Handwritten and poorly scanned invoices perform substantially worse and largely end up in the review queue.
Multi-page invoices with line items spanning pages need extra handling not covered here.
Currency and locale handling covers GBP, EUR and USD formats; other decimal conventions need additional parsing rules.
No fraud detection — this validates internal consistency, not whether the invoice is legitimate.
Future improvements
Supplier-specific templates learned from correction history, since most volume comes from a small set of recurring suppliers.
Duplicate invoice detection using fuzzy matching on supplier, amount and date.
Confidence calibration measured against the accumulated correction set, so thresholds are tuned by evidence rather than intuition.
Premium version
AI Invoice Processing System
The complete document processing system: per-field confidence, arithmetic validation, a human review queue, and correction feedback.
Related course
Business Automation Engineering
Process design, idempotency, error handling and observability — the engineering discipline that separates a workflow demo from a production system.
Related builds and resources
AI Invoice Processing System
The complete document processing system: per-field confidence, arithmetic validation, a human review queue, and correction feedback.
Business Automation Engineering
Process design, idempotency, error handling and observability — the engineering discipline that separates a workflow demo from a production system.
Automation ROI Calculator
Model time saved, error reduction, build cost and ongoing maintenance to get a payback period you can defend.
Automation That Survives Monday Morning
Most business automations break quietly within a month. Idempotency, error handling and observability are what separate a demo from a system.
Business Automation Audit
A structured review of your operational processes identifying what to automate, in what order, and what it is worth.