Building a Reliable AI Document Processing Pipeline
Supplier invoices and receipts arrived as Arabic and English PDFs, phone photos and office scans. I built an event-driven service that reads each one with an AI vision model, checks the numbers, and fills in a draft accounting record for a person to approve.
Client documents are confidential. The visuals on this page are illustrative and use fictional data.
- My role
- Sole engineer, design to deployment
- Project type
- AI document processing service
- Industry
- Material trading & manpower contracting, Saudi Arabia
- Timeline
- Oct 2026
- Core stack
- TypeScript, Supabase Edge Functions, DeepSeek
The starting point
Supplier bills and staff expense receipts were read by the accounting system's built-in digitization service, which runs on prepaid credits. When the credits ran out, documents stopped being read and staff went back to typing them in. Topping up was judged too expensive, and the paid service wasn't flawless either: it had once read an invoice number as the bill amount.
The documents themselves are hard. They come in Arabic, English or both, as clean digital PDFs, phone photos and heavily compressed office-scanner files. Amounts and VAT numbers are often printed in Arabic-Indic digits. And the hosted ERP couldn't run custom modules or make outbound calls from its own code, so any replacement had to live outside it and plug into the existing review and posting workflow.
My contribution
I owned the service end to end: the architecture, the serverless function, the AI provider integration, the normalisation and validation rules, vendor matching, the retry and safety mechanisms, and the benchmark used to choose a model. I also wrote the reversible setup script that adds the triggers, status fields and re-run button on the ERP side, and rolled the service out on a test company before switching it on for the main one.
Engineering approach
Five decisions shaped the build. The AI reads the document; everything around it decides whether to trust what it read.
Event-driven processing
Uploading a document creates a draft bill or expense as before. An automation rule then sends a webhook carrying only the record's model and ID. A Supabase Edge Function verifies a secret token, claims a processing slot in Postgres, and re-reads the record and its attachment through the ERP's API rather than trusting the payload. A unique index allows one run per document at a time, and a concurrency cap leaves overflow from upload bursts to the scheduled sweep.
Why: Staff keep their usual upload flow and nothing has to be started by hand. Reading everything fresh from the source means a forged or stale webhook can't put data into the books.
AI-powered structured extraction
Each document goes to a vision model with a fixed JSON schema: document kind, vendor name and VAT number, document number, dates, currency, line items, subtotal, VAT, total and a confidence level. Scanned PDFs are split into page images, digital PDFs also send their text layer, and compressed scanner PDFs are re-rendered into clean greyscale pages first. The model must answer with a single JSON object, which is type-checked and coerced before anything else sees it. The provider sits behind one interface: DeepSeek runs in production, and OpenRouter can be switched in through configuration.
Why: Free-form model output can't be posted to a ledger. A strict contract turns the model into one replaceable component instead of the centre of the system.
One schema for every document, in either language.Illustration · fictional data Data normalisation & validation
Arabic-Indic and Persian digits are converted to ASCII before any parsing, dates to ISO format and amounts to two decimals. Subtotal plus VAT must equal the total, and the written lines must add up to it, within 0.05 SAR. Vendors are matched by VAT number first, after checking the Saudi format and excluding the client's own VAT numbers, which often appear on the page as the buyer. Then by exact name, then by normalised name with Arabic and English legal words such as شركة, مؤسسة and LLC ignored. A similar-name match is never accepted silently.
Why: Models misread digits. Arithmetic and format checks catch the errors that matter most for the books, and they work the same however the document was written.
Normalise, check the arithmetic, then match the vendor.Illustration · fictional data Safe automation & reliability
The service only fills fields that are still empty, and only on drafts. Just before writing it re-reads the record and stops if staff have posted it, keeping any edits they made while the AI was reading. When staff-entered values disagree with the document, the confidence is low or key fields are missing, the record is marked Needs review with a note explaining why. Failed reads stay queued: a pg_cron job calls the function every five minutes, each document gets three attempts, and the last one leaves a note with the reason. A run log records cost, timing and outcome, but no document images or extracted data.
Why: An assistant that overwrites people's work loses their trust quickly. Leaving the final decision to a person makes the AI safe to switch on.
Existing values are never overwritten; doubts go to a person.Illustration · fictional data Evaluation & benchmarking
Before choosing a model, I built a read-only benchmark that takes bills and receipts staff had already posted, runs extraction only, and compares vendor, number, date, total, VAT and expense category with what was actually booked. It records the cost and duration of every run, so models and reasoning settings can be compared on the client's own documents. A companion script rescores vendor matching against the same set whenever the matching rules change.
Why: Posted documents are an answer key that already exists. Measuring against them replaced guesswork with evidence when choosing the provider and settings.
Each candidate model is measured against documents staff had already booked.Illustration · sample rows fictional, figures from the 7 Oct 2026 benchmark
Architecture & workflows
Two paths lead into the same function: a webhook when a document is uploaded, and a scheduled sweep that picks up anything still waiting. The diagram shows the main path. Each run ends in one of three states, Done, Needs review or Failed, and posts a note on the record explaining what happened.
Upload & event
- Draft bill or expense created
- Automation rule fires
- Webhook: record ID only
Edge Function
- Verify token, claim slot
- Re-read record and file
- PDF → page images + text
AI extraction
- Vision model
- JSON-only response
- Schema-checked output
Normalise & validate
- Arabic digits, dates, amounts
- Totals tie within 0.05
- Vendor: VAT → name
Accounting record
- Still a draft? Then write
- Empty fields only
- Done · Needs review · Failed
Retry sweep: pg_cron calls the function every five minutes for documents still waiting; each gets three attempts before it is marked failed with the reason.
Results
Cost and speed are preliminary: an early benchmark on 7 October 2026 using 39 previously posted bills and receipts, at the reasoning setting used in production. They are not production averages or guarantees.
- Cost per document
- ≈ $0.0004
- Preliminary benchmark, 7 Oct 2026
- Time per document
- ≈ 3–4 s
- Preliminary benchmark, 7 Oct 2026
- Automated tests
- 147
- Parsing, matching, write rules and retries
- Retry policy
- 3 attempts
- Swept every 5 minutes, then flagged
- Replaced the credit-based digitization service with a service the client controls.
- Uploaded invoices and receipts are read and filled in automatically, with no manual trigger.
- Arabic, English and mixed documents, including Arabic-Indic digits, go through the same pipeline.
- Values staff have already entered are never overwritten.
- Uncertain results are flagged for a person, with a note saying why.
- Failed reads retry on their own and end with a clear reason instead of disappearing.
Technology stack
- TypeScript
- Deno
- Supabase Edge Functions
- PostgreSQL
- pg_cron
- Webhooks
- DeepSeek
- OpenRouter
- pdf.js
- JSON-RPC