KEY TAKEAWAY

Manual freight reconciliation causes 3% to 7% budget leakage in logistics-heavy enterprises due to hidden line-item charges and illegible paper documents. By pairing vision LLMs for extraction with Polars for vectorized line-item matching and Temporal for orchestrating async retries, engineering teams can achieve a 92% touchless approval rate with total audit compliance.

Dirty DocumentScanned LR PDFUnstructuredVision LLMExtraction AgentPolars EnginePO Line MatchTariff MathTolerance RulesAuto-PayException

Architecture flow showing probabilistic vision LLM parsing passing typed JSON payloads into a high-speed, deterministic Polars matching engine.

92%
Touchless auto-reconciliation rate
14x
Faster processing speed vs manual audit
4.2%
Average freight spend recovered from billing errors

The Freight Reconciliation Nightmare in Enterprise Supply Chains

If you have ever audited supply chain operations for a mid-market manufacturing enterprise in India, you know the freight payment pipeline is where accounting accuracy goes to die. Freight billing involves a chaotic mix of vendor invoices, physical Lorry Receipts (LRs), e-Way Bills, and agreed-upon contract rate sheets. Logistics providers bill for base freight, detention charges, toll fees, loading/unloading levies, and fuel surcharges. Half of these arrive as stamped, hand-annotated paper PDFs.

Most enterprise finance teams handle this by assigning junior accountants to manually cross-reference scanned LRs against purchase orders and SAP or Tally entries. The result? Processing costs hover between ₹120 and ₹250 per invoice, approval cycles take three weeks, and overpayment leakages swallow 3% to 7% of total logistics spend. Overcharges hidden inside complex tier-rates or incorrect axle-weight calculations slip past tired human eyes.

Building a fully automated freight reconciliation engine requires solving two distinct engineering problems: unstructured document ingestion and high-throughput, deterministic line-item matching. In this guide, I will walk you through the end-to-end architecture of a production-grade system we built using Python, Polars, and a vision-LLM extraction microservice.

Pipeline Architecture Overview

The core mistake I see engineering teams make when tackling document-heavy workflows is mixing non-deterministic AI decisions directly into the financial ledger math. If your pipeline relies on a large language model to decide whether a bill is approved or rejected, your auditor will reject the system on day one. You must enforce a strict separation of concerns.

Our production pipeline divides the work into three isolated components:

  • Stage 1: Document Parsing & Schema Normalization. Scanned LRs, e-Way Bills, and carrier PDFs are processed through a vision-LLM microservice that extracts raw text and emits structured JSON matching a strict Pydantic model.
  • Stage 2: Deterministic Reconciliation Engine. High-performance columnar joining written in Python using Polars High-Performance DataFrames to execute line-item matching, tolerance checks, and tariff calculation rules across millions of records in milliseconds.
  • Stage 3: Exception Routing & Human-in-the-Loop Workflow. An event-driven state engine that auto-approves 100% matched items and queues discrepancies with exact variance flags for human review.

Step 1: Building the Vision Extraction Agent

Lorry receipts in Indian logistics are notoriously dirty documents. They feature illegible carbon prints, rubber stamps overlaying key numbers, and handwritten weight entries. Traditional OCR solutions like basic Tesseract fail dramatically here because they lack spatial context.

We use a multimodal vision pipeline (specifically Claude 3.5 Sonnet or GPT-4o-mini depending on cost SLAs) instructed to output strict JSON. Rather than asking the model to perform logic, we only ask it to transcribe values into typed schema fields.

Defining the Extraction Schema

We enforce schema compliance by passing JSON Schema definitions during model invocation. Key extracted fields include:

  • Consignment Details: LR Number, LR Date, Origin Pin Code, Destination Pin Code.
  • Vehicle Metadata: Vehicle Number, Truck Type (e.g., 32ft Multi-Axle, 14ft Open), Billed Weight, Actual Weight.
  • Itemized Financials: Freight Charge, Fuel Surcharge, Labor/Hamali Charge, Detention Days, Total Taxable Value.

When an incoming document arrives via S3 or email webhook, an asynchronous queue triggers the extraction worker. If the model returns a confidence score below 0.85 on critical numeric fields like total bill amount or vehicle registration, the payload is immediately flagged as a unreadable document rather than passing garbage data downstream.

Step 2: Vectorized Line-Item Matching with Polars

Once the document data is normalized into structured JSON, it lands in our staging storage. The matching engine compares the extracted billing items against two internal sources of truth: Purchase Orders in the ERP and actual vehicle movement records from the National e-Way Bill portal.

Why use Polars instead of Pandas or heavy Spark clusters? Freight matching requires continuous multi-key joins (matching invoice lines to PO lines based on contract ID, date ranges, weight buckets, and route origin-destination pairs). Polars executes these joins in Rust with multi-threaded vectorization, executing 100,000 document comparisons in under two seconds on standard cloud compute instance types.

The Multi-Stage Matching Logic

We execute the matching process using a tiered evaluation strategy:

  1. Exact Entity Binding: Match the invoice LR Number and PO Number directly against ERP Purchase Order line items.
  2. Route & Tariff Calculation: Calculate expected freight costs dynamically: Expected Cost = Base Contract Rate + (Distance in km × Fuel Surcharge Multiplier) + Allowed Detention Rate.
  3. Tolerance Evaluation: Evaluate variance against enterprise tolerance rules. For instance, weight variances within ±1.5% due to weighbridge calibration differences are automatically accepted. Price variances over ₹0 are rejected.

If you are re-architecting legacy data stacks or migrating manual accounting workflows to event-driven processing engines, booking a Systems Audit & Blueprint with our team maps out your ideal architecture and data flow in two weeks.

Step 3: Handling Discrepancies and Exception Queues

In real-world logistics, zero human involvement is a myth. Around 8% of invoices will contain legitimate discrepancies: unannounced detention hours due to warehouse delays, driver toll expense claims without receipts, or mismatched vehicle classifications. The goal of automation is not to eliminate human oversight, but to ensure accountants only review genuine exceptions.

Our system handles exceptions through a state machine orchestrated with Temporal workflows. When Polars identifies a failure, it attaches an array of granular error codes to the record:

  • ERR_TARIFF_OVERCHARGE: Billed rate per ton exceeds active contract terms.
  • ERR_UNAUTHORIZED_DETENTION: Detention charges claimed without gate-register timestamp verification.
  • ERR_EWAY_WEIGHT_MISMATCH: Billed weight exceeds the registered e-Way Bill limit by more than 5%.

The Temporal workflow assigns the exception payload to the relevant procurement manager's queue. The frontend presents a side-by-side split screen: the original scanned document image on the left with glowing bounding-box highlights around the contested line item, and the deterministic rule calculation breakdown on the right. With one click, the manager can approve the variance, adjust the payout, or trigger an automated vendor dispute email.

Production Performance and Real-World Impact

When deployed across an enterprise fleet handling 45,000 monthly shipments, this architecture fundamentally alters supply chain operations. In our benchmark evaluations across production deployments:

  • Touchless Processing Rate: 92% of all incoming freight invoices passed from email ingestion to ERP payment batch entry without human touch.
  • Processing Speed: Average time-to-approve dropped from 18 days to 4 minutes.
  • Financial Recovery: The system automatically identified and blocked overcharges amounting to 4.2% of overall annual freight expenditure within the first quarter of deployment.

By keeping your AI model tightly focused on perception tasks and offloading all financial calculations to high-performance, deterministic engines like Polars, you build a system that is blazing fast, cost-effective, and fully accountable to financial auditors.

If your reconciliation pipeline relies on an LLM to decide whether a price is correct, you are burning money; let the LLM extract raw structure, and let deterministic code do the math.

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