KEY TAKEAWAY

Automating enterprise vendor invoice reconciliation requires decoupling unstructured parsing from deterministic mathematical matching. By utilizing structured LLM output schema to convert vendor PDFs into typed JSON records, and executing set-based 3-way matching in DuckDB, enterprise data teams can reduce invoice processing cycles from days to seconds while eliminating accounting errors.

Vendor PDFUnstructuredStructured ExtractionLLM + PydanticTyped JSON SchemaDuckDB Engine3-Way SQL MatchPO vs GRN vs Invoice

Architecture pipeline flow: Unstructured PDF invoices are parsed via Pydantic schema into structured JSON before undergoing deterministic 3-way SQL matching in DuckDB.

98.4%
First-pass extraction accuracy using strict JSON schema validation
< 3.8s
End-to-end pipeline execution time per 10-page vendor invoice PDF
85%
Reduction in manual accounts payable triage and exception handling

The Core Problem: Unstructured Invoices Meet Rigid ERP Schemas

Accounts Payable (AP) teams in mid-to-large enterprises process thousands of vendor invoices every month. In an ideal world, every supplier submits electronic invoices formatted perfectly according to your ERP schema. In reality, supplier PDFs arrive in hundreds of bespoke formats: inconsistent table layouts, custom tax itemizations, varied currency notation, missing metadata, and hand-written invoice numbers.

Traditional optical character recognition (OCR) systems relied on brittle coordinate templates. The moment a vendor updated their invoice design or added a marketing banner, the coordinate mapping failed, dropping the invoice into a manual review queue. Conversely, modern generative models can easily read messy document structures, but letting a probabilistic model directly perform monetary arithmetic or execute database updates is a recipe for accounting errors.

In this guide, I will walk you through the exact technical blueprint we use to solve this problem cleanly: a deterministic, 3-way invoice matching pipeline that pairs structured LLM extractions with DuckDB for local, high-speed relational reconciliation.

Pipeline Architecture Overview

The system breaks invoice processing into four distinct stages to guarantee both extraction flexibility and absolute mathematical precision:

  • Document Ingestion & Layout Parsing: Inbound PDF invoices from S3 or email attachments are converted into structured markdown or page image representations.
  • Structured LLM Extraction: An LLM extracts line items, PO references, vendor GSTIN, and tax subtotals into a validated, typed schema.
  • Deterministic 3-Way Matching Engine: DuckDB joins the extracted invoice JSON against active Purchase Orders (PO) and Goods Receipt Notes (GRN) from your operational PostgreSQL database.
  • Exception Routing Agent: Mismatches exceeding pre-defined financial thresholds are automatically flagged, summarized, and routed to AP teams with human-readable audit notes.

Step 1: Unstructured Extraction with Pydantic Schema Enforcement

The first rule of reliable document extraction is never accepting unconstrained text from an LLM. We force the model to conform strictly to a predefined schema using Pydantic structured outputs.

When an invoice arrives, our worker service passes the rendered page images or extracted layout text to an LLM endpoint, enforcing a strict target schema that includes the vendor name, invoice date, currency code, line items (description, quantity, unit price, total), and total tax amount. If the extracted JSON violates standard validation rules—such as a missing invoice number or negative quantities—the payload is immediately rejected before reaching downstream data layers.

Step 2: High-Performance 3-Way Matching with DuckDB

Once the invoice payload is validated into clean, typed JSON, we pass it into DuckDB alongside live tables mirrored from the core ERP database. Using DuckDB allows us to run relational joins between temporary JSON payloads and production database snapshots directly in memory, executing thousands of line-item comparisons in a few milliseconds without touching an expensive enterprise warehouse cluster.

The 3-Way Match Rules

A standard 3-way matching query evaluates three core financial conditions:

  • Line-Item Price Verification: Does the invoice line unit price match the unit price agreed upon in the approved Purchase Order?
  • Quantity Received Verification: Does the billed line item quantity match or stay below the physical quantity logged in the Goods Receipt Note (GRN)?
  • Tax Rate Compliance: Do the calculated tax percentages line up with expected local tax rules for that specific item category?

By executing these joins in DuckDB, we can isolate precise variance figures. For instance, if Vendor A bills for 100 units of an inventory item at ₹1,200 per unit, but the GRN confirms only 80 units arrived at the warehouse, DuckDB flags a immediate quantity discrepancy of 20 units and ₹24,000.

Step 3: AI Agent Exception Triage and Human-in-the-Loop Routing

Not all discrepancies require human intervention. Minor price variations caused by fractional penny rounding or minor freight surcharges can be auto-cleared if they fall within tolerance bands set by the finance team (for example, price variances under 0.5% or ₹100).

When a mismatch exceeds tolerance, the exception handler fires. Rather than dumping raw SQL join results on an AP clerk, an AI triage agent reads the DuckDB discrepancy log and generates a natural-language summary for the human reviewer. For example: "Invoice #INV-9022 from Apex Steel includes a 10% unit price increase on Item B over PO #88219 (₹1,500 vs ₹1,360). Warehouse logs show full delivery on GRN #4401."

The agent drafts a pre-filled clearance or rejection ticket directly inside the internal workflow tool, leaving the human clerk with a simple one-click decision: approve variance or issue debit note.

Step 4: Persistence and Production Metrics

Once cleared—either automatically by DuckDB or manually by the AP team—the structured invoice record writes back to the main database and downstream analytics stores. We record explicit metadata logs capturing raw OCR outputs, extraction confidence scores, match latency, and resolution types.

When we design these data workflows during our Systems Audit & Blueprint engagements, we emphasize building clear telemetry into every pipeline stage. Tracking first-pass match rates over time highlights which vendors regularly send inaccurate billing data or changing invoice formats.

Key Architectural Lessons from Production

Building this architecture in production across high-volume environments yielded several key technical takeaways:

  • Isolate Determinism from Inference: Let the LLM handle unstructured reading, but strictly isolate price calculation, tax computation, and variance checking inside standard SQL engines.
  • Validate Schemas Early: Catch structural parsing faults at the Pydantic boundary rather than allowing corrupt data into downstream accounting tables.
  • Preserve Lineage: Always persist the original raw PDF alongside the extracted JSON schema for audit compliance and historical model re-evaluations.

By treating document processing as a hybrid system—leveraging AI for text extraction and traditional relational engines for mathematical rules—you eliminate manual data entry backlogs while keeping full financial precision intact.

Never let an LLM execute financial arithmetic. Use the model solely to transform unstructured document layout into strictly typed JSON, then hand those records to an in-memory SQL engine for exact mathematical matching.

Want this level of rigor applied to your own analytics stack?

This comes from running BA/BI systems audits for real Indian enterprises — where the actual fix is decided by which stage of your analytics function is broken, not by which tool has the best demo. A Systems Audit tells you exactly where to start.

Book a Systems Audit