Design: document extraction pipeline
The PDF text layer or OCR feeds an LLM that fills a strict per-type schema; deterministic rules and calibrated per-field confidence decide what auto-posts and what a reviewer sees, and every correction feeds back.
Analogy: An experienced accounts-payable clerk who types what they read, checks that the totals add up, and only walks over to their manager with the two lines they are unsure about.
Fundamentals you'll use
How it works
- ~1M documents/month at ~0.4/s is a cost problem, and human review is ~90% of the bill.
- Validate with deterministic rules: line items sum to subtotal, IBAN checksums pass, every value appears in the source.
- Start with an LLM over OCR text, a vision LLM as fallback; distill once ~10k documents are labeled.
- The worst failure is a wrong amount or bank account paid silently, so thresholds follow error cost: IBAN at 99.9%.
- Score per field, not per document, and audit 1–2% of unreviewed documents for the escape rate.
Check yourself
Answer to mark it learned; your answers aren't scored.
An invoice's IBAN passes the checksum, maps to an OCR span and clears its 99.9% calibrated threshold, but it differs from the vendor master record. Every other field passes. What should the pipeline do?
Go deeper
Full explanation
Requirements
Functional: turn ~1M invoices and contracts a month (born-digital PDFs, scans, email attachments) into typed records: vendor, dates, totals, tax, line items, bank details; for contracts, parties, term, renewal and liability cap. Every value carries the page location it came from.
Non-functional: ≥ 99% precision on money fields that skip review, a full audit trail, PII kept in-region (PII & data privacy), and cost per document tracked as a product metric.
What I'd ask first:
- What is the mix: how many vendors and languages, and what share are scans, born-digital PDFs or structured e-invoices?
- Which fields move money or create legal obligations, and what does one wrong value cost?
- Is overnight fine, or do some documents need an answer in seconds?
- Does anything auto-post to payment, or does a human approve downstream anyway?
- May documents go to a third-party model API?
Highest-cost failure: a confidently wrong amount or bank account posted straight to payment. It is silent and it moves money.
High-level design
One idempotent job per document, driven by a queue (Queues vs streams (Kafka)):
- Ingest: store the original, dedupe by content hash, classify the type and split multi-document PDFs.
- Read: use the PDF text layer when it exists; otherwise OCR/layout, keeping word boxes (Document ingestion & parsing).
- Extract: an LLM fills a per-type JSON schema with Structured outputs & JSON mode; instructions and schema are a cached prefix (Prompt caching).
- Validate: deterministic rules (line items sum to subtotal, subtotal + tax = total, valid dates, IBAN checksum, vendor in master data) plus a grounding check: each value must appear in the source text.
- Score and route: a calibrated confidence per field; fields under their threshold go to a Human-in-the-loop & approvals queue that shows only those fields, highlighted on the page.
- Export: write to the ERP keyed by vendor + invoice number, so retries never double-post (Idempotency).
Offline vs online: bulk work runs through provider Batch inference at ~50% off with results within 24 h; urgent uploads take the same pipeline on the synchronous API in ~10–20 s. Reviewer corrections flow back into the golden set, per-vendor few-shot examples and the confidence calibrator. That loop is what drives the review rate, and therefore the cost, down.
Code Deterministic checks decide which fields a human sees
from decimal import Decimal
from pydantic import BaseModel
class Line(BaseModel):
description: str
amount: Decimal
class Invoice(BaseModel): # schema for the LLM's structured output
vendor_name: str
invoice_number: str
invoice_date: str # normalized to ISO 8601 after extraction
currency: str # ISO 4217
subtotal: Decimal
tax: Decimal
total: Decimal
iban: str | None
lines: list[Line]
CENT = Decimal("0.01")
THRESHOLD = {"iban": 0.999, "total": 0.995, "invoice_number": 0.98} # from error cost
def failed_rules(inv: Invoice, vendor: dict) -> set[str]:
bad = set()
if abs(sum(ln.amount for ln in inv.lines) - inv.subtotal) > CENT:
bad |= {"lines", "subtotal"}
if abs(inv.subtotal + inv.tax - inv.total) > CENT:
bad |= {"tax", "total"}
if inv.iban and (not iban_mod97_ok(inv.iban) or inv.iban != vendor["iban"]):
bad.add("iban") # changed bank details = classic invoice fraud
return bad
def fields_to_review(inv, conf: dict, span: dict, vendor: dict) -> list[str]:
bad = failed_rules(inv, vendor)
return [f for f, c in conf.items()
if f in bad
or span.get(f) is None # value not found in the page text
or c < THRESHOLD.get(f, 0.95)] # calibrated confidence, per fieldReal example
A 2-page scanned invoice from a logistics vendor arrives by email. It has no text layer, so OCR runs (~2–4 s, ~$0.003 at $1.50 per 1,000 pages). The LLM reads ~1.5k cached tokens of schema and instructions plus ~1.4k tokens of page text and returns 28 fields in ~350 output tokens (under $0.002 at mini-model prices). Rules pass: lines sum to 4,180.00, 19% tax is 794.20, total 4,974.20, and every value maps to an OCR span. But the IBAN, although its checksum is valid, differs from the vendor master record, so that single field goes to review. The reviewer sees it highlighted, confirms by calling the vendor's number on file, and approves in ~40 s. The ERP posts once, keyed by vendor + invoice number.
Trade-offs +4 · −4
+ You gain
- The LLM handles the long tail of vendor layouts from day one, with no per-template rules.
- Deterministic rules plus the grounding check catch most silent model errors for almost nothing.
- Per-field routing: reviewers touch two flagged fields, not the whole document.
- The batch path halves model spend, and corrections compound into eval and training data.
− You pay
- Thresholds mean nothing until a labeled calibration set exists; month one runs at a high review rate.
- Two reading stacks (OCR and a vision fallback) to operate, version and evaluate.
- Batch APIs can take up to 24 h, so urgent documents need a separate, pricier lane.
- Human review still dominates cost; the savings depend on calibration quality.
Use it when
High-volume documents with many layouts feeding a system of record, where a wrong field has a real cost and people currently key the data by hand.
Avoid it when
A handful of fixed templates (zonal OCR or a fine-tuned layout model is cheaper), or e-invoices that already arrive as structured XML: parse them, don't read them.
Numbers to know 5
- Volume: 1M docs/month ≈ 33k/day ≈ 0.4/s; assume ~5× month-end peaks (~2/s) and 3 pages/doc → 3M pages/month.
- Tokens: assume ~1k tokens/page + 1.5k cached prompt ≈ 4.5k in and ~0.4k out per doc → 4.5B input + 0.4B output tokens/month.
- LLM: at an assumed $0.40/M input and $1.60/M output ≈ $1.8k + $0.6k = $2.4k/month list, ~$1.2k through a 50%-off batch API.
- OCR: at ~$1.50 per 1,000 pages, 3M pages ≈ $4.5k/month; if 60% are born-digital and skip OCR, ≈ $1.8k.
- Review: assume 8% of docs flagged × ~60 s ≈ 1,330 h/month ≈ 8 FTE ≈ $33k at $25/h, ~90% of a total ≈ $0.04/doc.
Common pitfalls 4
- Treating schema-valid JSON as correct: structured outputs will happily return a hallucinated invoice number. Require every value to map to a span in the source text, or send it to review.
- Measuring only what was flagged: errors in auto-accepted documents are invisible. Audit a random 1–2% of straight-through documents to measure the escape rate.
- Comparing raw strings: 03/04/2025 is April 3 or March 4 depending on the vendor's country. Normalize with the vendor's locale before validating and scoring.
- Auto-accepting a valid-checksum IBAN that differs from the vendor master: that is the classic business email compromise attack. Route every bank-detail change to review with out-of-band verification.
Interview questions 3
Answer out loud first, then reveal.
How do you get a per-field confidence from an LLM that you can actually trust?Show answer
I don't use the model's self-reported confidence; it's poorly calibrated. I combine signals per field: log-probabilities of the value tokens, agreement between two independent extractions, OCR word confidence, rule results, and whether the value appears verbatim on the page. A calibrator trained on reviewer outcomes turns that into a probability, so 0.99 really means one error in a hundred. Then I set thresholds per field from error cost: bank details at 99.9%, a PO number much lower. The catch is that calibration needs labeled outcomes and breaks on every model change, so recalibration is part of each rollout.
Straight-through processing is at 70% and finance wants 90%. What do you do?Show answer
First Error analysis: look at your data on the flagged fields: which field, which vendor, which reason (rule failure, low confidence, value not found). It's usually Pareto: a few vendors and two or three fields drive most reviews. Then fixes in cost order: vendor-specific few-shot from past corrections, better reading for bad scans, master-data lookups such as matching the PO and goods receipt, and finally fine-tuning for the top vendors. What I won't do is lower thresholds blindly. I check the escape rate on the random audit sample first, because each STP point saves ~$4k a month and one wrong payment can cost more than that.
Vision LLM end to end, or OCR then an LLM?Show answer
OCR then LLM by default. OCR gives word boxes, so every value can be grounded and highlighted for a reviewer, and text tokens are cheaper and more reproducible than image tokens. Vision models win on handwriting, stamps, checkboxes and tables that OCR mangles, so I route pages with low OCR confidence to a vision LLM and treat disagreement between the two paths as a review signal. I keep both behind one extraction interface, because the balance shifts with every model release. It's a two-way door, and the golden set tells me when to walk through it.
Deep dive 5
Data & ingestion
Dedupe twice: by file hash (the same PDF emailed twice) and by business key (vendor + invoice number + amount, the same invoice rescanned). Classify and split before extracting, because one PDF often bundles an invoice, a delivery note and terms and conditions. Check the text layer first: on a born-digital PDF, OCR only adds cost and errors. Structured e-invoices (UBL, Peppol, Factur-X with embedded XML) skip the LLM entirely; parse them. Keep the original, the OCR output with word boxes and the extraction as versioned artifacts, so any value traces back to pixels and any run can be replayed with a new model. Encrypt at rest, restrict who can see bank details, and set retention to the legal minimum.
Model choice
Three options. Template rules over zonal OCR break with every new vendor layout. A fine-tuned layout model (LayoutLMv3, Donut) is cheap per page and strong on stable fields, but needs thousands of labeled documents per type. An LLM over OCR text with a strict schema handles the long tail from day one. I start there, with a vision LLM fallback for pages where OCR confidence is low (handwriting, stamps, skewed tables), and I use disagreement between the two paths as a confidence signal (Multimodal models). OCR text keeps word boxes for provenance and costs less per page than image tokens. Once corrections reach ~10k labeled documents, I fine-tune or distill a smaller model for the top vendors (Knowledge distillation) and keep the LLM for the tail. Structured outputs guarantee shape, not truth.
Confidence & the review loop
Don't trust a model's self-reported confidence. Combine signals per field: log-probabilities of the value tokens, agreement between two extractions, OCR word confidence, rule results, and whether the value appears verbatim on the page. A small calibrator (logistic or isotonic regression) trained on reviewer outcomes turns them into a probability that means what it says. Set each threshold from the field's error cost: IBAN at 99.9%, total at 99.5%, a PO reference lower. The review UI shows only flagged fields, with the source box highlighted, and is keyboard-first. Store every correction with who made it: it becomes golden-set data, per-vendor few-shot examples and calibration data. Recalibrate after every model or prompt change, because calibration does not transfer.
Evaluation
Score per field, never per document: a 30-field invoice with one wrong total is a failure that a document-level average hides. Normalize before comparing (dates to ISO, amounts to decimals, IBAN without spaces), then use exact match for keys and amounts and token F1 for free text such as line descriptions (Code-based graders & assertions). Track four numbers: accuracy of auto-accepted fields, straight-through rate, review rate per field, and the escape rate, measured by auditing a random 1–2% of documents that skipped review. A golden set of ~1–2k documents stratified by vendor, language and scan quality runs in CI on every prompt, model or OCR change (Evals in CI/CD & release gates). Report slices: a regression on one large vendor can hide in the average.
Scale, latency & cost
Average load is ~0.4 documents per second, so this is a throughput and cost problem, not a latency one. A queue feeds idempotent per-document jobs with retries, backoff (Retries, backoff & circuit breakers) and a dead-letter queue for documents that fail three times. Bulk work goes to batch APIs (submit in chunks, poll, reconcile by custom id); a priority lane uses the synchronous API at ~20 s p95. Model spend is small and human review is ~90% of the cost, so each point of review rate is worth ~$4k a month and calibration is the main cost lever. Contracts differ: 20–60 pages, clause-level fields with citations, long context or section retrieval, and a higher review rate by design.