How to Build an AI Invoice Processor with LLMs

An AI invoice processor automatically extracts structured data from invoice PDFs — vendor name, invoice number, date, line items, amounts, tax, and total — and pushes that data into your accounting system or spreadsheet. Manual invoice data entry is one of the most error-prone and time-consuming administrative tasks in small businesses. An LLM-based processor handles invoices from any supplier without templates, at a fraction of the cost of dedicated invoice processing SaaS, and runs locally if privacy is a concern.

Why Invoices Are Hard to Process Programmatically

Invoices are structurally inconsistent across suppliers. One calls the identifier “Invoice Number”, another uses “Reference” or “Bill Number”. Totals appear at the bottom of some invoices and in a header box on others. Line items may have 3 columns or 8. Dates use different formats — 01/11/2026, November 1 2026, 2026-11-01. Tax may be a single line or itemised by rate. Traditional template-based processors require a separate template per supplier format and break when a supplier redesigns their invoice. LLMs handle all this variation because they understand document content semantically rather than positionally.

The Extraction Prompt Schema

Define every field you need with its name, type, and description. For a standard invoice: invoice_number (string), invoice_date (ISO 8601 string), due_date (ISO 8601 string or null), vendor_name (string), vendor_address (string or null), currency (ISO 4217 code, default USD), subtotal (number), tax_amount (number or null), total_amount (number), line_items (array of objects with description, quantity, unit_price, and amount). End the prompt with “Return only the JSON object. If a field is not present, set its value to null. Do not invent or estimate values.” That last instruction is critical — without it, some models fill missing fields with plausible-sounding invented values.

Figure 1 — Invoice processor pipeline stages

PDF Input email/folder Extract Text pdfplumber/OCR LLM Extract JSON output Validate dupe check Output Sheets/Xero/QB

Validation: Never Skip This Step

Four checks catch the most common extraction errors. Math check: verify line item amounts sum to subtotal, and subtotal plus tax equals total — a mismatch flags an extraction error. Format check: dates parse as valid dates, amounts are positive numbers, invoice_number is non-empty. Duplicate check: query your invoice store for an existing record with the same vendor name and invoice number — if found, flag for review rather than creating a duplicate. Completeness check: verify invoice_number, invoice_date, vendor_name, and total_amount are all non-null. Any invoice failing these checks routes to a human review queue rather than the automated output step.

Line Item Extraction

Line items are the most variable part. Simple invoices have 3-5 clean items; complex ones have 50+ items across multiple pages with subtotals, discounts, and grouped categories. For complex invoices, use two passes: first extract header fields (number, dates, vendor, totals), then extract line items separately with a prompt focused only on the items table. Always validate that extracted line item amounts sum to the extracted subtotal — a mismatch flags a line item extraction error even when header fields are correct.

n8n Pipeline: Gmail to Google Sheets

A practical implementation in n8n: a Gmail trigger watches for emails with PDF attachments from known supplier email domains. A PDF Extract node converts the attachment to text. An Ollama LLM node runs the extraction prompt. A Code node validates the extracted JSON. A Switch node routes validated invoices to a Google Sheets append step and failed extractions to a Slack notification for human review. This handles the full accounts payable intake: invoices arrive by email, get processed automatically within a minute, and appear in the accounting spreadsheet with no manual data entry. Failed invoices notify the reviewer with the specific validation errors and the extracted data for quick correction.

Accounting System Integration

For Xero, the API accepts a JSON body with Contact (vendor), DateString, DueDateString, LineItems array, and CurrencyCode — mapping directly from extraction output. For QuickBooks Online, the Bill creation API has a similar structure. Create a vendor lookup step that maps extracted vendor names to your accounting system’s vendor IDs. Vendors not in the lookup table trigger a human review notification rather than creating an unmatched bill. For Google Sheets, n8n’s native Sheets node writes extracted fields directly to a predefined column structure with no additional configuration.

Performance at Scale

With Qwen2.5 7B running locally on Apple Silicon M4 Max, invoice extraction takes approximately 8-15 seconds per invoice including PDF text extraction. For a business processing 100 invoices per month, this amounts to under 30 minutes of total processing time across the month — down from hours of manual entry. For higher volumes (500+ invoices/month), batch the extraction jobs during off-hours and use OLLAMA_NUM_PARALLEL to process multiple invoices concurrently. Cloud LLMs (GPT-4o-mini) process faster (2-4 seconds per invoice) at approximately $0.002 per invoice at current pricing — negligible cost for the time saved.

Frequently Asked Questions

What accuracy should I expect?
For clearly printed PDFs from professional invoicing software, extraction accuracy exceeds 95% for header fields with a good prompt. Line items are typically 90-95% accurate. Always validate mathematically — a math check catches extraction errors that would be expensive to catch in the accounting system later.
Can I use local Ollama models?
Yes. Qwen2.5 7B handles simple to moderately complex invoices reliably. For complex multi-page invoices with many line items, Qwen2.5 14B produces better accuracy. Local inference keeps invoice content — which may include confidential commercial terms — entirely on your infrastructure.
How do I handle multi-page invoices?
Extract all pages to text first. If the full text fits in your model’s context window (most 7B+ models handle 32k+ tokens), pass it as a single extraction prompt. For very long invoices, use the two-pass approach: extract header fields from the first page, then extract line items from subsequent pages separately.

Last updated: October 2026

Approval Workflows for High-Value Invoices

For businesses where invoices above a certain amount require manager approval before payment, build an approval step into the pipeline. After successful validation, a conditional check compares total_amount against your approval threshold. Invoices below the threshold write directly to the accounting system. Invoices above it send a formatted Slack or email notification with the extracted invoice details and an approval link. The approval link triggers a webhook in n8n that marks the invoice as approved and completes the accounting system write. This pattern implements a full accounts payable workflow — intake, extraction, validation, approval routing, and system integration — entirely in n8n without any custom backend code. The same approval workflow works for new vendor invoices (any invoice from a vendor not already in the approved vendor list triggers approval regardless of amount), ensuring that new supplier relationships are reviewed before payments are made.

Error Recovery and Human Review Interface

Production invoice processing needs a reliable way to handle the 5-10% of invoices that fail automated processing — scanned documents with poor OCR quality, unusual formats, or missing required fields. Build a simple review interface: write failed invoices to a dedicated Google Sheet or Notion database with the extracted (partial) data, the failure reason, and a link to the original PDF. A reviewer opens the record, corrects any extraction errors in the sheet, and triggers a re-processing webhook that completes the accounting system write with the corrected data. This human-in-the-loop pattern keeps the automation running at high throughput on the majority of invoices while providing a clean handoff path for exceptions, rather than leaving failed invoices in a dead-letter queue that requires developers to intervene.

An AI invoice processor built with an LLM and n8n delivers meaningful value from day one and improves as you refine the extraction prompt and add validation rules for your specific supplier set. Start by processing a batch of 20-30 historical invoices, verify the extraction accuracy against the originals, adjust the prompt for any systematic errors, then activate the live pipeline. The first week typically reveals 2-3 supplier formats that need special handling — document these as prompt examples and re-test. After the initial tuning period, most small business invoice pipelines run reliably for months without adjustment as supplier formats remain stable.

Handling Poor-Quality and Foreign-Language Invoices

Real inboxes contain skewed phone photos, faded thermal receipts, and invoices in languages you do not read. For scanned documents, preprocessing makes a large difference before the text ever reaches the model: straighten skewed pages, increase contrast, remove noise, and render at a sensible resolution before running OCR. Keep the OCR confidence scores if your tool provides them, and treat low-confidence pages as candidates for human review rather than trusting the extraction.

Modern language models read many languages well, so you can often extract the same fields from a German or Japanese invoice using the same schema, but add a field for the detected language and the original currency so that your accounting step can handle conversion correctly. Dates are a common trap, because the same string can mean different days in different regions, so ask the model to output ISO format and validate that the result is a plausible date. Keep a small test set of awkward invoices from your actual suppliers and re-run it after every prompt change. The unusual documents are where errors concentrate, and a regression set of them is the best protection against fixing one case while breaking another.

Leave a Comment