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:
- Extract key fields (parties, amount, payment term, penalty clauses, invoice number, etc.)
- 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")
- Push structured results back to the customer's ERP (webhook / API)
- 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| Component | Choice | Why |
|---|---|---|
| Frontend | Next.js (App Router) + TypeScript + Tailwind + shadcn/ui + TanStack Query | A mainstream stack; shadcn makes it fast to build a professional admin UI without a designer |
| Backend API | FastAPI + Pydantic v2 + SQLAlchemy 2.0 (async) + Alembic | The mainstream choice for async Python backends; Pydantic validates both the API and LLM output |
| Orchestration | Option 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 |
| Database | PostgreSQL + pgvector | Business data and vectors in one database; simple to deploy, friendly to on-premises B2B delivery |
| Cache / queue | Redis | Rate limiting, idempotency keys, task queue (for the home-grown option) |
| File storage | MinIO (S3-compatible) | Usable in on-premises deployments |
| Document parsing | PyMuPDF / 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 |
| LLM | Primary: a strong model from one provider; backup: another provider; a small model for classification | Demonstrates "fallback" and cost tiering |
| Observability | Langfuse (self-hosted) + structured logging (structlog) + Sentry | Per-LLM-call traces and prompt version management |
| Deployment | Docker Compose (single-machine on-premises) + GitHub Actions | Close 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)
| Stage | Content | Output / acceptance criteria |
|---|---|---|
| W1 Skeleton | Monorepo (web/ + api/); FastAPI layering, auth, Alembic; Next.js admin shell; Docker Compose running PG/Redis/MinIO | Can upload files and see the task list |
| W1 Ingestion | Upload endpoint (chunking / size limits / type checks), webhook ingestion (signature verification), files into MinIO, create the task | All three entry points produce a unified Document |
| W2 LLM Gateway | Unified 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 MVP | Home-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 individually | Kill the worker midway; after restart it continues from the checkpoint |
| W3 Extraction & validation | Extraction 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 takeover | Triggers: 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 stored | Demo the full "AI extracts wrongly → human corrects → result pushed to ERP" flow |
| W4 RAG rule library | Customer 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 output | Risk judgments come with "based on rule X" |
| W4 Traceability & dashboard | Step 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 task | Explain how any result was produced within 1 minute |
| W5 Advanced | Migrate 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 recording | Online demo + README architecture diagram + evaluation report |
4. Hard problems and highlights
| Hard problem | Solution | How to talk about it in interviews |
|---|---|---|
| Unstable LLM output | Schema-constrained output + Pydantic validation + retry with errors fed back + secondary rule checks | Explain the "three lines of defence" and what share each one catches |
| Failures midway through a long pipeline | Step-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 unavailable | Classified retries + exponential backoff + jitter + circuit breaker + primary/backup switching + finally human takeover | Draw the fallback ladder and give the trigger threshold for each level |
| Resuming after human takeover | State machine suspend / Temporal Signal; human edits saved as a new version of the result, keeping the original AI result | Human edits flow back into the eval set, closing the loop |
| Traceability | End-to-end trace_id; versioned prompt templates; input snapshots | Live-demo replaying a failure case and pinpointing the exact prompt |
| Cost | Small model for classification + large model for extraction; prompt caching; text PDFs skip the multimodal path | Give 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.
6. Related knowledge base pages
- 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
