Skip to content
My role

To be added

—Results
—Results
—Results
Screenshot 1
Screenshot 2
Screenshot 3

AI Document Review Pipeline (DocFlow) ​

Covers: ingestion / orchestration / output / traceability, a Next.js review console, FastAPI, LLM APIs, retries, fallbacks and human takeover, RAG, workflows Status: not started | Priority P0


1. Business scenario ​

A B2B scenario: a supply-chain / finance outsourcing company receives large volumes of contracts, invoices and customs declarations every day (PDFs, scans, Excel files, email attachments) and needs to:

  1. Extract key fields (parties, amount, payment term, penalty clauses, invoice number, etc.)
  2. Check for risks against the customer's review rules (e.g. "payment term > 90 days", "abnormal penalty rate", "invoice title doesn't match the contracting party")
  3. Push structured results back to the customer's ERP (webhook / API)
  4. Hand low-confidence or high-risk items to a human reviewer for confirmation

This scenario is very common in B2B AI delivery, and it makes it easy to explain the "customer requirement → technical solution" translation in an interview.


2. Architecture and technology choices ​

[Ingestion]  upload page / mailbox polling / webhook / API
     │  everything becomes a Document (original file in object storage + metadata in the database)
     ▼
[Orchestration]  Workflow: parse → classify → extract → validate → risk_check → (human_review?) → deliver
     │  each step = a retryable, idempotent Activity / Step
     ▼
[Model layer]  LLM Gateway: multi-provider adapters, timeouts, retries, fallback, cost logging, structured output
     │  RAG: retrieve the customer's review rule library / past rulings as context for risk_check
     ▼
[Output]  result JSON (validated by Pydantic schema) → push to ERP webhook (signed, with retries) → Excel export
     ▼
[Traceability]  task / task_step / llm_call tables + Langfuse (or OTel) traces, replayable step by step in the frontend
[Frontend]  Next.js: task list, task details (step timeline + highlighted source), human review console, rule configuration, metrics dashboard
ComponentChoiceWhy
FrontendNext.js (App Router) + TypeScript + Tailwind + shadcn/ui + TanStack QueryA mainstream stack; shadcn makes it fast to build a professional admin UI without a designer
Backend APIFastAPI + Pydantic v2 + SQLAlchemy 2.0 (async) + AlembicThe mainstream choice for async Python backends; Pydantic validates both the API and LLM output
OrchestrationOption A: Temporal (Python SDK); Option B: home-grown "DB state machine + arq/Celery"Temporal natively provides retries, timeouts, resume from checkpoint and Signals (to resume after human takeover), showing hands-on workflow engine experience; the home-grown option better shows understanding of the principles. Build a home-grown MVP first, then migrate to Temporal, so both can be discussed in interviews
DatabasePostgreSQL + pgvectorBusiness data and vectors in one database; simple to deploy, friendly to on-premises B2B delivery
Cache / queueRedisRate limiting, idempotency keys, task queue (for the home-grown option)
File storageMinIO (S3-compatible)Usable in on-premises deployments
Document parsingPyMuPDF / pdfplumber + OCR (PaddleOCR, or a multimodal model reading the images directly)Scans go through OCR or a multimodal model; text PDFs are parsed directly to save cost
LLMPrimary: a strong model from one provider; backup: another provider; a small model for classificationDemonstrates "fallback" and cost tiering
ObservabilityLangfuse (self-hosted) + structured logging (structlog) + SentryPer-LLM-call traces and prompt version management
DeploymentDocker Compose (single-machine on-premises) + GitHub ActionsClose to the reality of B2B delivery

⚠️ For framework versions and the Temporal Python SDK and Langfuse APIs, follow the latest official docs (to be verified as of 2026-11).


3. Implementation plan (about 4–5 weeks, each stage demoable on its own) ​

StageContentOutput / acceptance criteria
W1 SkeletonMonorepo (web/ + api/); FastAPI layering, auth, Alembic; Next.js admin shell; Docker Compose running PG/Redis/MinIOCan upload files and see the task list
W1 IngestionUpload endpoint (chunking / size limits / type checks), webhook ingestion (signature verification), files into MinIO, create the taskAll three entry points produce a unified Document
W2 LLM GatewayUnified complete() / stream() / extract(schema); timeouts; classified retries (retry 429/5xx/timeouts, not 400); primary/backup fallback; every call written to the llm_call table (model, prompt version, tokens, duration, cost, error)With the primary model's key removed by hand, tasks still complete on the backup model and the reason for switching is recorded
W2 Orchestration MVPHome-grown state machine: task.status + task_step; every step idempotent (results cached by task_id+step_name+input_hash); workers take tasks from the queue; failed steps can be re-run individuallyKill the worker midway; after restart it continues from the checkpoint
W3 Extraction & validationExtraction with Pydantic schema + structured output; on validation failure, send the error back to the model and retry (at most N times); per-field confidence (model self-assessment + rule checks + whether the field can be located in the source)A field accuracy report on 30 samples
W3 Human takeoverTriggers: low confidence / validation retries exhausted / high-risk rule hit; the task enters waiting_review; review console: source on the left (with the field's origin highlighted), form on the right; submit edits → flow continues → edit history storedDemo the full "AI extracts wrongly → human corrects → result pushed to ERP" flow
W4 RAG rule libraryCustomer review rules and past rulings indexed (chunk + embedding + pgvector); risk_check uses hybrid search + rerank to take the Top-K as context, with citations in the outputRisk judgments come with "based on rule X"
W4 Traceability & dashboardStep timeline on the task details page (each step's input/output/duration/model/retry count), one-click replay; dashboard: success rate, human intervention rate, average duration, cost per taskExplain how any result was produced within 1 minute
W5 AdvancedMigrate orchestration to Temporal (human review resumes via Signal); eval set + prompt version A/B; rate limiting and circuit breaking; deploy to a cloud server + screen recordingOnline demo + README architecture diagram + evaluation report

4. Hard problems and highlights ​

Hard problemSolutionHow to talk about it in interviews
Unstable LLM outputSchema-constrained output + Pydantic validation + retry with errors fed back + secondary rule checksExplain the "three lines of defence" and what share each one catches
Failures midway through a long pipelineStep-level state + idempotency keys + resume from checkpoint; external pushes carry an idempotency ID"Why you can't simply re-run the whole task": cost and side effects (duplicate pushes to the ERP)
Model service unavailableClassified retries + exponential backoff + jitter + circuit breaker + primary/backup switching + finally human takeoverDraw the fallback ladder and give the trigger threshold for each level
Resuming after human takeoverState machine suspend / Temporal Signal; human edits saved as a new version of the result, keeping the original AI resultHuman edits flow back into the eval set, closing the loop
TraceabilityEnd-to-end trace_id; versioned prompt templates; input snapshotsLive-demo replaying a failure case and pinpointing the exact prompt
CostSmall model for classification + large model for extraction; prompt caching; text PDFs skip the multimodal pathGive before/after numbers for cost per document

5. Résumé description (STAR) ​

When writing this up as a real project, replace the numbers with your actual measured results; never invent data you didn't achieve.

AI Document Review Pipeline | Full-stack, sole owner

  • S: A B2B customer had to manually review hundreds of contracts and invoices a day, extracting key fields and checking risk clauses; manual review was slow and inconsistent.
  • T: Independently design and deliver a complete AI pipeline from document ingestion to pushing results into the ERP, with traceable results and automatic fallback or human takeover on production failures.
  • A:
    • Built a step-based "ingest → parse → extract → validate → risk check → output" workflow on FastAPI + PostgreSQL with step-level idempotency and resume from checkpoint, later migrated to Temporal;
    • Wrapped a multi-provider LLM Gateway with classified retries, circuit breaking and automatic primary/backup model switching; structured output that fails Pydantic validation is automatically retried with the errors;
    • Low-confidence / high-risk results go to a human review queue, with a Next.js review console showing the highlighted source side by side; the flow resumes automatically after human correction, and corrections flow back into the eval set;
    • Hybrid search over the customer's review rule library with pgvector (RAG), with risk conclusions citing rules; end-to-end traces and prompt version management make any result replayable.
  • R: Field extraction accuracy X% (eval set of N documents), human intervention rate down from X% to X%, processing time per document down from X minutes to X seconds, task success rate held at X% during model outages.

  • LLM Engineering: LLM Gateway, structured output, evaluation
  • Orchestration: state machines, idempotency, Temporal
  • Reliability: retries, fallbacks, circuit breaking, human takeover
  • RAG: rule library retrieval
  • Frontend: review console, streaming UI
  • Backend: FastAPI layering, async

Vin Amory · AI development × content creation · Technical notes cite official docs in each page’s sources section