KEY TAKEAWAY

Production B2B document processing requires combining LLM vision extraction with deterministic relational validation. By using Instructor for strict Pydantic parsing, DuckDB for high-performance string matching against master product catalogs, and an automated exception queue, teams can eliminate manual data entry while preventing bad data from hitting ERP systems.

Messy PO (PDF)Vision LLMPydantic SchemaDuckDB EngineCatalog Fuzzy JoinCleanERP Records

Architecture: Unstructured PDF intake -> Schema extraction via Vision LLM -> In-memory catalog fuzzy matching via DuckDB -> Normalized ERP staging.

85%
Reduction in manual PO data entry workload
<4 sec
Average extraction and validation latency per page
99.2%
Line-item catalog matching accuracy post-enrichment

The Unstructured Document Dilemma in B2B Operations

If you run data infrastructure for an Indian manufacturing enterprise or wholesale distributor, you know the daily reality of order intake. Customers do not submit orders through tidy GraphQL APIs or standardized webforms. They send scanned PDFs, cropped WhatsApp photos of handwritten purchase orders, multi-sheet Excel files with merged headers, and irregular email tables.

For years, companies handled this by hiring teams of operators to read incoming files and key line items manually into SAP, Tally, or custom ERPs. When enterprise teams try to automate this using traditional OCR, the system breaks on slight layout changes. When they try using raw LLM prompts, the model invents non-existent SKUs, hallucinates tax figures, or produces non-deterministic JSON schemas that break downstream data ingestion.

We recently built a production order intake engine for an industrial distributor receiving over 3,000 unstructured purchase orders daily. In this guide, I will walk you through the end-to-end architecture: using vision LLMs with structured extraction, validating data against local master catalogs via DuckDB, and handling exceptions with a secondary agent loop.

Architecture Overview: Hybrid Generative and Deterministic Pipeline

The core mistake technical teams make when introducing AI agents into data pipelines is replacing deterministic code entirely. LLMs excel at semantic recognition—understanding that '50mm PVC pipe coupler' on a scanned invoice refers to a specific product line. However, LLMs are terrible at exact financial arithmetic, join resolution across millions of rows, and enforcing strict relational integrity.

Our design separates the ingestion lifecycle into four distinct stages:

  • Stage 1: Document Ingestion & Vision Extraction — Inbound document triggers a worker that calls a vision LLM constrained by strict JSON schema definitions via Pydantic.
  • Stage 2: Deterministic Catalog Matching with DuckDB — Extracted raw SKU strings are joined against a local Parquet copy of the master product database using fuzzy string matching and fast analytical SQL.
  • Stage 3: Agentic Exception Resolution — Line items with confidence scores below strict thresholds are routed to an exception agent with historical purchasing context.
  • Stage 4: ERP Transaction Execution — Cleaned, validated records are written to PostgreSQL staging tables and pushed to the ERP via transactional REST endpoints.

Step 1: Enforcing Structured Output from Vision LLMs

To extract data reliably, never rely on unstructured text prompts like 'extract all line items from this invoice'. Instead, define explicit target models using Pydantic and pass them through schema-enforcing libraries such as Instructor or native function-calling APIs.

Below is the concrete Pydantic schema used to extract line items, customer identifiers, tax details, and units of measure from incoming document pages:

from pydantic import BaseModel, Field
from typing import List, Optional

class POLineItem(BaseModel):
    raw_sku_description: str = Field(..., description="Exact string description of item as written on PO")
    customer_part_number: Optional[str] = Field(None, description="Customer internal code if present")
    quantity: float = Field(..., gt=0, description="Numeric quantity ordered")
    unit_of_measure: str = Field(..., description="Box, Pcs, Kg, Meter, etc.")
    unit_price: float = Field(..., ge=0, description="Stated price per unit")
    total_amount: float = Field(..., ge=0, description="Line total calculation")

class PurchaseOrderPayload(BaseModel):
    po_number: str
    buyer_name: str
    buyer_gstin: Optional[str] = Field(None, description="15-digit GSTIN if visible")
    po_date: str
    line_items: List[POLineItem]

When executing extraction against visual models like Claude 3.5 Sonnet or Qwen2.5-VL, passing this schema ensures the returning payload is pre-validated against field types before downstream processing even begins.

Step 2: High-Performance Catalog Join and Validation with DuckDB

Once the LLM returns the structured JSON array, you must map the customer's arbitrary product description to your internal canonical Master SKU ID. Querying an external production database over HTTP for thousands of line items causes unnecessary latency and load.

Instead, we pull the daily product catalog into an in-memory DuckDB database inside the ingestion container. DuckDB allows us to execute high-speed Jaro-Winkler and Levenshtein distance joins directly over in-memory Python objects in milliseconds.

According to the DuckDB Official Documentation, the engine's zero-copy integration with Arrow and Python dictionaries makes vector operations over strings significantly faster than standard pandas implementations.

Here is how the matching logic evaluates raw extracted strings against master catalog tables in DuckDB:

import duckdb

con = duckdb.connect(database=':memory:')
con.execute("CREATE TABLE catalog AS SELECT * FROM read_parquet('s3://data-warehouse/master_catalog.parquet')")

# Register incoming extracted JSON line items directly
con.register('raw_extracted_items', raw_items_df)

# Perform fuzzy string matching query
query = """
SELECT
    e.raw_sku_description,
    c.master_sku_id,
    c.canonical_name,
    jaccard(e.raw_sku_description, c.canonical_name) AS similarity_score
FROM raw_extracted_items e
CROSS JOIN catalog c
WHERE jaccard(e.raw_sku_description, c.canonical_name) > 0.65
QUALIFY ROW_NUMBER() OVER (PARTITION BY e.raw_sku_description ORDER BY similarity_score DESC) = 1
"""
matched_results = con.execute(query).df()

If you are re-architecting your team's ingestion data pipelines to handle high volume without growing compute costs, schedule a Systems Audit & Blueprint engagement with our engineering team to review your technical roadmap.

Step 3: Handling Ambiguity with an Agentic Repair Queue

Determinism works until a buyer writes 'Standard 2-inch pipe' on a PO, but your master catalog lists three distinct SKU variants for 2-inch pipes (PVC, Galvanized Iron, and Stainless Steel). A naive fuzzy match selects the highest text score regardless of business context, leading to incorrect shipments.

To solve this, items scoring between 0.40 and 0.75 on fuzzy match criteria trigger an Exception Resolution Agent. Rather than guessing randomly, the agent receives two contextual inputs:

  • Historical Buyer Patterns: The last 20 orders completed by this specific buyer ID.
  • Catalog Candidate Subset: The top 4 closest matching catalog SKUs filtered by DuckDB.

The agent executes a focused prompt: 'Given Buyer X historically orders PVC-variant fittings in 95% of past instances, evaluate if raw string "Standard 2-inch pipe" corresponds to SKU-PVC-2IN.' If confidence remains low, the system marks the item for human validation in a web dashboard, attaching the bounding box coordinates of the original PDF document.

Production Considerations: Hardening the Pipeline

Building a prototype with LLMs takes an afternoon; hardening it for production requires engineering discipline. Here are three critical rules we enforce in production builds:

1. Hash-Based Idempotency

Customers routinely email identical PO documents multiple times across different channels. Calculate the SHA-256 hash of every incoming document byte stream before passing it to the vision LLM. Store hashes in a Redis cache with a 30-day TTL to reject duplicate processing immediately.

2. Strict Financial Reconciliation

Never trust the sum of line items returned by an LLM vision call. Programmatically calculate sum(quantity * unit_price) across all parsed items and cross-check it against the total order value extracted from the invoice header within a strict 0.01 tolerance threshold. If the math fails, flag the record for verification.

3. Audit Trail Persistence

Store both raw document files, the unparsed LLM response, the DuckDB catalog match scores, and the final normalized JSON in immutable object storage. When an order discrepancy arises three months later, your team must be able to inspect every stage of the pipeline decision tree.

If your LLM agent extracts JSON without strict schema validation and deterministic catalog joins, you haven't built an enterprise pipeline; you've built an expensive typo generator.

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