Case study · October 2026
LIVEInvoice Agent API
An LLM that reads an invoice, checks its own arithmetic against six rules, and files a receipt — on Cloudflare Python Workers, for zero dollars a month.
- Policy rules
- 6
- Pytest tests
- 11
- Endpoints
- 8
- Monthly cost
- $0
Role · Sole engineer — service, policy engine, data model, deploy
invoice-agent-api.ashrafulislamse.workers.devContext
Invoice extraction demos are easy and invoice extraction systems are not. A demo parses one clean PDF and prints JSON. A system has to survive a model that returns prose, a provider that is down, an invoice whose lines do not sum to its total, and the same invoice filed twice.
This service does the unglamorous half: extract, validate, decide, record. The model is one component inside a pipeline that assumes it will be wrong.
The problem
The model is not a validator
A language model will confidently return a total that does not equal the sum of its own lines. Trusting it means the ledger becomes a record of what a model believed.
Models deprecate under running services
A hard-coded model id is a scheduled outage. The failure is not gradual: one day the provider retires the model and every request fails at once.
Chat wrappers break naive parsing
A regex that grabs the first curly brace to the last one parses the wrapper around the answer, not the answer. It works on the happy path and corrupts everything else.
Constraints
- Zero operating budget — free tier or nothing
- No container, no server to patch
- Every extraction must be auditable after the fact
- Policy checks must be testable without a model or a database
- Nothing from the model reaches storage unvalidated
Decisions
The choices that carried most of the system. Each one lists the alternative that was on the table and the bill that came with the choice.
A six-rule policy engine of pure functions that runs after extraction and before storage.
- Not this
- Letting the model decide whether an invoice is acceptable, with a confidence score in the prompt.
- Why
- Arithmetic, date windows, currency allowlists and duplicate detection are deterministic. Pure functions can be tested in milliseconds, return a named reason, and cannot be talked out of a rejection.
- The cost
- The rules are rigid by design: a legitimate invoice outside the date window is refused, and every new business rule is code plus a test rather than a prompt edit.
A model fallback chain, with a second path for reasoning-mode responses.
- Not this
- One model id and a retry.
- Why
- Retrying the same retired model fails identically. A chain across two providers turns a deprecation into a latency event, and the reasoning-content path handles models that spend their budget thinking and return the answer in a different field.
- The cost
- Two prompt contracts and two response shapes to keep valid, and the fallback model is worse at extraction, so quality is not constant.
A brace-depth scanner that returns the first balanced JSON object carrying the expected key.
- Not this
- A greedy regular expression over the response body.
- Why
- The scanner is ten lines and fails correctly: it walks depth, ignores braces inside strings, and only accepts an object that has the key it came for. The regex fails by returning a plausible wrong object.
- The cost
- It is stricter than necessary on malformed output, so some recoverable responses become 502s instead of partial successes.
Cloudflare Python Workers with D1 and Workers AI, edge-deployed with no container.
- Not this
- FastAPI in a container on a VPS, which is what I would reach for by default.
- Why
- The service is a thin pipeline around two remote calls. A container adds a host, a TLS terminator, a deploy pipeline and a bill for a workload that is mostly idle.
- The cost
- Edge constraints are real: no long-running work, a Python runtime that is close to but not identical to CPython, and a database that is SQLite — fine for receipts, wrong the day this needs joins across tenants.
How it is put together
- Surface
- A single-page demo UI on the same worker: paste an invoice, get a receipt with the extraction, the rule results and the raw model output.
- API
- FastAPI running through an ASGI entrypoint on the Python Workers runtime — eight routes covering extract, verify, list, read, delete and stats.
- Inference
- Workers AI with a fallback chain, an OpenAI-compatible request shape and explicit handling for reasoning-mode responses.
- Validation
- Pydantic models first, then the six policy rules: line-sum math, positive totals, per-line sanity, date windows, currency allowlist, vendor identity.
- Storage
- D1 with an invoices table and an append-only audit log; a repeat invoice number is stamped as duplicate rather than filed twice.
What broke, and what it taught
A case study that only lists wins is a sales page. These are the defects the audit found in my own system, how each surfaced, and what fixing it takes.
Defect
The README advertises a workers.dev host that no longer answers.
Found by
Checking every live link on this site on 30 November 2026: the documented URL returned no response, the other deployment answered.
Fix
Point the README and the work index at the host that actually serves, and add a link check to CI so a dead URL fails the build rather than the reader.
Defect
Greedy JSON extraction returned the chat wrapper instead of the payload.
Found by
A multi-object response during manual testing — the regex matched from the first brace to the last.
Fix
The brace-depth scanner, with a test that feeds it a wrapper containing two JSON objects and asserts the right one comes back.
Defect
A model that spent its budget thinking returned an empty content field, and the request failed as if the model were down.
Found by
Provider responses during extraction testing on a long invoice.
Fix
Read the reasoning field when content is empty, and treat a genuinely empty answer as a provider failure with its own error path.
Defect
Eleven tests all mock the bindings, so the deployed path is only exercised by hand.
Found by
Reading the suite before trusting its green run.
Fix
A smoke test against the deployed worker on a fixed invoice, run after deploy, asserting the receipt id and the policy verdict. Small, but it tests the thing that actually ships.
Evidence
- Live service answering on the public workers.dev host, with a readable stats endpoint
- Eleven pytest tests covering the happy path, provider failure, JSON repair and policy rejection
- Six policy rules implemented as pure functions with no binding dependency
- Append-only audit log for every extraction and deletion
Checked 30 November 2026. Service live on workers.dev. Repository private; public counterpart at github.com/ashrafulislamse/invoice-sheriff.