Document Processing with OCR and LLMs: Invoices, Forms, Contracts

Document pipeline: ingest, classify, OCR, extract, validate, human review, export

An accounts-payable inbox may receive digital PDFs, scans, photographs, and email text. Staff then transfer fields such as supplier, invoice number, date, currency, tax, and total into an accounting system. OCR and language models can help extract those fields, but the value of a system depends on how it handles uncertain cases. A useful design keeps the original source, checks extracted values, and routes unresolved items for review. The goal is to decide which fields can be accepted automatically under defined controls and which need a person.

1. The problem as it appears in the inbox

Documents that arrive through one channel can still have different layouts, field names, image quality, and review needs. A supplier may label the amount due “Total,” “Balance,” or “Amount payable.” A scan may be skewed, a stamp may cover text, or a table may continue on another page. The same extraction error can also have different consequences: a missed field may stop processing, while a plausible but incorrect value may pass unnoticed unless the workflow checks it.

Three design questions help frame the work. First, which documents and fields are in scope? Invoices, credit notes, purchase orders, receipts, and contracts do not share one schema. Second, what evidence supports each extracted value? Keep a link to the source page or region where possible. Third, what happens when evidence is weak or checks disagree? A safe workflow has a review route rather than forcing every record through the same path.

Processing approaches have different trade-offs. Fixed templates can work for stable layouts but need maintenance when those layouts change. Direct image-to-JSON extraction can reduce pipeline steps, but it may be harder to trace a returned value to the source. A hybrid design can retain OCR text and coordinates, use a model to map fields, then apply deterministic checks. No approach is universally best; compare them on representative documents, review effort, and the cost of errors for your workflow.

2. How the pipeline works, stage by stage

A practical document workflow can be divided into stages. The boundaries make it easier to identify where a bad value entered and where it should be stopped. Each stage should preserve enough context for the next one to check the result.

  • 1. Intake and duplicate screening: Accept files from approved sources and preserve the original according to the organization’s retention policy. A cryptographic hash can identify byte-for-byte duplicate files; a separate comparison of supplier, invoice number, date, and amount can flag likely duplicates whose files differ. Treat a match as a review signal, since repeated documents can be legitimate.
  • 2. Classification: Identify the document type and page orientation. Digital PDFs may contain selectable text, while scans require OCR. Send uncertain classifications to a person instead of applying an unsuitable extraction schema.
  • 3. OCR and layout analysis: Extract text and, where supported, retain page and region coordinates. Coordinates help a reviewer compare an extracted value with the image. Check multi-page tables and reading order rather than assuming the text stream preserves the original layout.
  • 4. Field extraction: Ask the model to return a fixed schema, such as supplier, invoice number, date, currency, line items, tax, and total. Require a value to be marked missing when the source does not support it. A model’s confidence estimate can help route work, but it is not proof that a value is correct.
  • 5. Deterministic validation: Check data types, required fields, arithmetic relationships, date formats, currency, and supplier identifiers against the organization’s own records. These checks can catch inconsistencies, but they cannot establish that every extracted value reflects the source.
  • 6. Human review: Show the source beside the extracted fields and explain why the record was routed. Reviewers should be able to correct a value, record the reason, and send the document back for reprocessing when needed.
  • 7. Export: Send only records that pass the configured checks and approval steps to the accounting system. Record the source reference, validation outcome, and whether a person reviewed the record.
Seven-stage document processing pipeline architecture 1. Ingest Email / form SHA-256 Dup check 2. Classify Type Invoice Template 3. OCR Boxes Tables Coordinates 4. Extract JSON fields Confidence Source link 5. Validate Totals Vendor list Date format 6. Review Compare source Review queue Review 7. Export ERP Audit log Approved LLM is one stage in a seven-stage pipeline Checks support review before ledger entry
Figure 1. The complete 7-stage document processing architecture incorporates duplicate checks and post-extraction validation before ledger entry. These controls reduce risk but do not guarantee correct extraction.
# Illustrative validation and routing example. Replace sample values and thresholds.
from datetime import date
from decimal import Decimal, InvalidOperation

KNOWN_VENDORS = {"ACME SUPPLY LTD", "NORTHWIND FREIGHT"}
TOLERANCE = Decimal("0.02")
CRITICAL_FIELDS = ("vendor", "invoice_date", "total")

def validate(doc):
    problems = []
    required = ("vendor", "invoice_date", "lines", "tax", "total")
    if not isinstance(doc, dict) or any(key not in doc for key in required):
        return ["MISSING_FIELD"]
    if not isinstance(doc["lines"], list) or not doc["lines"]:
        problems.append("NO_LINE_ITEMS")
    else:
        try:
            amounts = [Decimal(line["amount"]) for line in doc["lines"]]
            tax, total = Decimal(doc["tax"]), Decimal(doc["total"])
            if any(not value.is_finite() for value in amounts + [tax, total]):
                raise InvalidOperation
            if abs(sum(amounts) + tax - total) > TOLERANCE:
                problems.append("TOTAL_MISMATCH")
        except (KeyError, TypeError, ValueError, InvalidOperation):
            problems.append("INVALID_AMOUNT")
    try:
        date.fromisoformat(doc["invoice_date"])
    except (TypeError, ValueError):
        problems.append("DATE_FORMAT_INVALID")
    if not isinstance(doc["vendor"], str) or doc["vendor"].upper() not in KNOWN_VENDORS:
        problems.append("VENDOR_UNKNOWN")
    return problems

def route(conf, problems, auto_at=0.95, review_at=0.70):
    if problems or not (0 <= review_at <= auto_at <= 1):
        return "exception_queue"
    try:
        values = [conf[field] for field in CRITICAL_FIELDS]
        if any(not isinstance(value, (int, float)) or not 0 <= value <= 1 for value in values):
            return "exception_queue"
    except (KeyError, TypeError):
        return "exception_queue"
    weakest = min(values)
    if weakest >= auto_at:
        return "auto_export"
    if weakest >= review_at:
        return "quick_review"
    return "exception_queue"

sample = {
    "vendor": "ACME SUPPLY LTD", "invoice_date": "2026-10-15",
    "lines": [{"amount": "40.00"}], "tax": "8.00", "total": "48.00"
}
confidence = {"vendor": 0.98, "invoice_date": 0.99, "total": 0.97}
issues = validate(sample)
print(issues, route(confidence, issues))  # [] auto_export

The model is one part of the workflow. Intake controls, source links, validation, and review determine how errors are handled. Calibrate routing thresholds on labeled examples from the organization’s own documents. Check performance by field and document type: a threshold that works for supplier names may not be appropriate for totals or payment details. Recheck the calibration when document sources, layouts, or extraction settings change.

3. A decision framework and an illustrative cost example

Straight-through processing (STP) is the share of documents that reach the configured export step without human intervention. Unit processing cost can include machine fees and review labor. Raising an automatic-acceptance threshold may send more records to people; lowering it may reduce review while increasing the chance that an error passes. Set the trade-off with the people accountable for the workflow and its financial controls.

The following calculation is hypothetical. It uses simple assumptions to show how STP changes modeled labor cost; it is not a benchmark or an expected result. Assume 10,000 documents per month, a machine cost of $0.04 per document, three minutes to review each routed document, and labor valued at $0.50 per minute. A fully manual baseline at four minutes per document is 10,000 × 4 × $0.50 = $20,000. Replace all inputs with measured local costs.

# Illustrative cost model; replace every input with measured local values.
docs, machine_cost, review_minutes, rate_per_minute = 10_000, 0.04, 3, 0.50
manual_minutes = 4
manual_total = docs * manual_minutes * rate_per_minute
print(f"Manual baseline: ${manual_total:,.0f} per month")
for stp in (0.60, 0.70, 0.80):
    reviewed = docs * (1 - stp)
    total = docs * machine_cost + reviewed * review_minutes * rate_per_minute
    print(f"STP {stp:.0%}: ${total:,.0f} per month, ${total / docs:.2f} per document")
# Manual baseline: $20,000 per month
# STP 60%: $6,400 per month, $0.64 per document
# STP 70%: $4,900 per month, $0.49 per document
# STP 80%: $3,400 per month, $0.34 per document

Under those assumptions, each 10 percentage-point increase in STP removes 1,000 reviews. At three minutes and $0.50 per minute, that reduces modeled review labor by $1,500 per month; machine cost remains in the model for every document. This is a sensitivity calculation, not a recommendation to lower a threshold. Compare the labor difference with the expected cost of errors and with the controls needed to prevent incorrect records from being exported.

Illustrative STP rate and monthly cost 20,000 Manual 4 min / doc 0% STP 2.00 / doc 6,400 40% Review 60% STP 0.64 / doc 4,900 30% Review 70% STP 0.49 / doc 3,400 20% Review 80% STP 0.34 / doc
Figure 2. Illustrative monthly costs for 10,000 invoices under the assumptions in the example; bar heights are proportional to the modeled totals.

Arithmetic checks are useful when the source provides values that should reconcile, such as line amounts, tax, and a stated total. They are not enough on their own. The same total can be wrong in both the extracted lines and the total field, and an arithmetic match cannot confirm the currency or the supplier. Use independent checks where available, and route unresolved discrepancies for review rather than widening a tolerance solely to increase STP.

ExceptionPossible signalReview action
TOTAL_MISMATCHLine items and tax do not reconcile to the stated total.Compare the source, discounts, tax lines, and arithmetic.
VENDOR_UNKNOWNSupplier does not match the approved reference list.Confirm identity and mapping before export.
DATE_OR_CURRENCY_UNCLEARFormat or currency cannot be resolved from the source.Check the source and applicable business records.
DUPLICATE_SUSPECTFile hash or key fields resemble an earlier record.Compare both records before suppressing either one.
PAYMENT_DETAILS_CHANGEDPayment details differ from the approved record.Pause export and follow the organization’s independent verification process.

4. Failure modes to plan for

Document pipelines can fail quietly as well as visibly. A useful incident review records the source, extracted value, check result, reviewer action, and downstream effect. That evidence helps distinguish an OCR problem from a schema, threshold, or interface problem.

  • Table fragmentation: A multi-page table may lose the relationship between a column heading and a row. Compare extracted row counts and totals with the source; route incomplete tables to review.
  • Field confusion: Invoice date and due date, billing address and remittance address, or subtotal and total can occupy similar-looking regions. Use labels and surrounding context as checks, then show the source region to the reviewer.
  • Duplicate handling: Identical files are easy to identify by hash, but a re-scanned or re-exported copy has a different hash. Combine file-level checks with key-field matching and let a person resolve ambiguous matches.
  • Review fatigue: A queue that shows only extracted values encourages shallow approval. Display source evidence, make the reason for review clear, and monitor corrections and missed errors. Set queue sizes and sampling practices using local workload and risk rather than a universal number.

Documents such as contracts contain clauses whose meaning depends on context, not just arithmetic. A model may help locate passages or prepare a structured summary, but a qualified reviewer should assess legal meaning before the organization relies on it. Define access, retention, and secondary use for source files and extracted data with the organization’s privacy and legal teams. Requirements vary by context; this article does not provide legal advice.

5. An illustrative first-month plan

The sequence below is a planning template. Adjust its pace and sample size to the document volume, available reviewers, and risk of the workflow. Keep the system in shadow mode until the organization has reviewed evidence and approved the controls.

  1. Days 1–5 — Define scope and reference data: Choose one document type and source. Define the fields, acceptable formats, missing-value behavior, and cases that must always be reviewed. Select a representative evaluation sample and have qualified staff agree on the reference values.
  2. Days 6–12 — Build the pipeline: Implement intake, classification, OCR, extraction, and validation. Preserve source references and record each stage’s output. Test malformed, incomplete, duplicate, and multi-page documents.
  3. Days 13–20 — Run in shadow mode: Process incoming documents without exporting model results. Compare output with the existing process, measure errors and review effort by field, and tune routing using labeled examples.
  4. Days 21–25 — Test the review experience: Ask reviewers to resolve representative exceptions. Check whether the interface shows enough source context and whether corrections are recorded consistently. Update routing when a review reason is unclear.
  5. Days 26–30 — Make a controlled decision: Review accuracy, exception volume, correction effort, and downstream issues with the process owner. Enable limited export only for fields and document types that meet locally agreed requirements, keep an audit sample, and define a pause condition.

Do not define success as an STP percentage alone. Include the cost of review and support, the quality of exported records, and the outcome of exceptions. If evidence is too limited, continue the shadow evaluation. If a control fails, pause the affected route and investigate before expanding it.

6. Addressing common objections and trade-offs

“Why not send every image directly to a vision model?” A direct vision path can be simpler for some documents. An OCR-plus-model path can retain text coordinates that help trace a field to its source and can make deterministic checks easier to apply. Compare both approaches on the organization’s documents, including processing cost, extraction quality, latency, and review effort. Do not assume one has lower cost or higher accuracy without measuring it.

“Will human review eliminate the savings?” Review has a cost, but it also handles cases that automated checks cannot resolve. The example above shows how to calculate labor under stated assumptions. A real decision also needs the cost of machine processing, corrections, failures, and controls. Measure the queue rather than assuming that every routed document takes the same time.

“Will structured e-invoicing make extraction unnecessary?” Structured exchange can reduce manual extraction for transactions that use it. An organization may still receive documents in other formats. Design the intake around actual sources and use structured data where available; route the remaining formats through a process that preserves source evidence and review.

Document automation works best when each extracted field has a source, a validation path, and an owner for exceptions. Track those controls alongside STP and unit cost. Expand only when the measured workflow meets the organization’s accuracy, review, and risk requirements.