doc-extract-pipeline — Self-Checking Invoice Extraction

Featured Project
An invoice extraction service that checks its own work. It reads a PDF or scan, extracts the fields with an AI model, then verifies the answer before handing it over: totals, line items, tax and currency are checked by fixed rules, and every value must be found on the page it came from. Failed checks go back to the model for a limited retry. Uploads survive server restarts and queue outages, results arrive by API or signed webhook, and the public demo is protected by per-visitor limits.
2 weeks
Launched: 2026-09
0.0%
Field accuracy
109/110 fields on a golden set
0
Validation rules
Arithmetic, tax, currency, dates and source grounding
0
API endpoints
Upload, status, result, health and demo webhook
0
Automated tests
78 against a real MongoDB
Live Preview

Tech Stack Versions

Precise technology versions used in this project

Python3.13
FastAPI0.141
Celery5.6
LangGraph1.2
Pydantic2.13
PyMongo4.18

Screenshots

Main feature screens of the project

Extraction result — every value highlighted where it was found on the OCR text

A full run — one check failed, the model retried with that feedback, then a signed webhook was delivered

Capabilities Demonstrated

Technical and business capabilities demonstrated through this project

  • Extracts invoice data and verifies it before anyone relies on it
  • Reads both digital PDFs and scanned images
  • Keeps working through server restarts without losing documents
  • Delivers results to your systems by signed webhook
  • Safe to expose publicly, with abuse and cost limits built in

Challenges Faced

Main technical challenges encountered during development

  • LLM output is sometimes confidently wrong, and a model-based checker would exceed the 8K tokens-per-minute free limit.
  • Deploys SIGTERM the process group, killing OCR mid-page and marking documents as failed.
  • The free broker has no persistence, and a silent broker hung uploads for 30–90 seconds.
  • A public demo accepts attacker input: forged client IPs, webhook URLs aimed at the private network, and pixel-bomb images.
  • Render's free plan has no worker service and no memory metrics.

Solutions

Technical solutions and implementation strategies adopted

  • Eight plain-Python rules plus grounding, with failed rules fed back through a bounded LangGraph cycle.
  • Interrupted runs hand the document back to the queue under the same attempt ceiling as an expired lease.
  • MongoDB as the source of truth with a lease and sweeper; broker publish capped at 2 seconds.
  • Trust only Cloudflare-owned IP headers, pin webhook connections to the validated IP, and check limits from headers before spending quota.
  • One container under honcho with a Celery solo pool and lazy imports; memory measured locally from cgroup memory.peak.

Code Snippets

Key implementation code from the project

def build_graph(pipeline: Pipeline) -> Any:
    builder = StateGraph(GraphState)

    builder.add_node("ingest", pipeline.ingest)
    builder.add_node("classify", pipeline.classify)
    builder.add_node("extract", pipeline.extract)
    builder.add_node("validate", pipeline.validate)

    builder.add_edge(START, "ingest")
    builder.add_edge("ingest", "classify")
    builder.add_edge("classify", "extract")
    builder.add_edge("extract", "validate")
    builder.add_conditional_edges(
        "validate",
        route_after_validate,
        {"retry": "extract", "done": END},
    )

    return builder.compile()

Architecture Decisions

Key architectural and technical decisions made during development

Context

Extraction needs checking on a free tier of 8,000 tokens per minute.

Options Compared
LLM-as-judge (second model call)
Pros
  • Can catch semantic mistakes without writing a rule for each
Cons
  • Worst path ~9,900 tokens — over Groq's 8,000 tokens-per-minute free limit
  • A model checking its own arithmetic is still unreliable
Deterministic Python rules + grounding
Pros
  • sum(lines) + tax == total is decidable — zero tokens, milliseconds
  • Each failed rule becomes specific feedback for the retry
Cons
  • Grounding proves a value was copied, not that it went into the right field
Decision

Deterministic rules, with failures fed back for a bounded retry.

Outcome

11/11 golden invoices pass validation; 109/110 fields correct.

Technical Highlights

In-depth technical implementation details and architecture design

Deterministic validation with source grounding

AI
  • Eight plain-Python rules check LLM output, including grounding every value in the source text; failures feed back through a bounded LangGraph retry cycle instead of a second model call.

Broker-independent recovery

Backend
  • MongoDB is the source of truth; an atomic lease and a sweeper recover lost messages, duplicate deliveries and interrupted runs, verified on the live host.

Hardened public LLM demo

Security
  • Webhook SSRF guard pinned to the validated IP, quotas keyed on Cloudflare-owned client-IP headers, and page/pixel caps checked before any quota is spent.

Engineered to measured free-tier limits

DevOps
  • API and Celery worker share one 512 MB container under honcho; peak memory 339 MB, median 1,838 tokens per invoice, ~20 s per scanned page.

Key Takeaways

Important lessons and reflections from this project

Technical

Grounding proves a value was copied, not that it went to the right field.

Real Impact: The one golden-set miss was a mislabelled total; rule checks need a field-position cue for that case.

Architecture

Put state where it survives and send only ids through the queue.

Real Impact: Lost messages, duplicates and restarts became one event: an expired or refused lease.

Process

Only running on the real host finds the silent failures.

Real Impact: Three of four reliability scenarios found bugs no unit test had.

Interested in this project?

Feel free to reach out to discuss similar technical solutions or how I can help with your project.

Contact Me
Contact Me
doc-extract-pipeline — Self-Checking Invoice Extraction | Chih-Cheng Tien - Full Stack Developer