Loading…
Loading…
Build an AI document processing pipeline with OCR, classification, and data extraction. Automate invoice, receipt, and contract processing with LLMs and vision.
Tags
This is part of the AI Automation Engineer Roadmap series.
A production document processing pipeline turns messy PDFs, scans, invoices, forms, and contracts into structured data you can search, validate, and route into downstream systems. The practical architecture combines ingestion, OCR, classification, extraction, confidence scoring, and human review. The goal is not just to read documents, but to build a reliable workflow that survives low-quality scans, layout variation, and operational edge cases.
Most business processes still start with documents:
The problem is that these files are usually built for humans, not systems. A PDF may look clean on a screen and still be painful to parse programmatically. Tables break across pages, form fields shift position, and scanned pages introduce OCR noise.
That is why document automation is more than "run OCR and hope for the best." A useful system needs to answer three questions:
Once you treat those as explicit pipeline stages, the system becomes much easier to monitor and improve.
OCR is often the first step, but not the whole solution. It converts pixels into text, which is necessary for scanned files, but the output still needs structure.
A typical document processing pipeline includes:
If you stop after OCR, you only have text. If you finish the pipeline, you have usable business data.
Even when language models are involved, layout remains important. The same invoice total means something very different depending on whether it appears in:
That is why the best systems preserve bounding boxes, page numbers, table structure, and neighboring labels whenever possible. Those signals help both rules-based extractors and LLM-based extractors disambiguate the result.
Teams often treat confidence as an implementation detail. That is a mistake.
If the system extracts an invoice number with 99 percent confidence and a tax amount with 52 percent confidence, the product should behave differently for each case. Reliable automation comes from routing low-confidence cases into review instead of pretending every extraction is equally trustworthy.
A practical pipeline usually looks like this:
That separation matters because every stage can fail for different reasons. A blurry scan is not the same problem as a missing vendor name or a misclassified document.
Avoid processing large uploads directly inside the request cycle. Accept the file, store it, and enqueue a job.
type DocumentJob = {
id: string;
fileUrl: string;
status: "queued" | "processing" | "review" | "completed" | "failed";
documentType?: "invoice" | "contract" | "resume" | "form";
confidence?: number;
createdAt: string;
};
export async function createDocumentJob(fileUrl: string) {
return db.documentJob.create({
data: {
fileUrl,
status: "queued",
},
});
}This gives you retry support, observability, and a stable way to report progress in the UI.
Not every PDF requires OCR. Many contain selectable text already. If you OCR everything, you add cost, latency, and more opportunities for mistakes.
Use a lightweight detection step first:
async function determineExtractionMode(fileBuffer: Buffer) {
const hasEmbeddedText = await pdfHasSelectableText(fileBuffer);
return hasEmbeddedText ? "native-text" : "ocr";
}A hybrid system usually performs better:
Extraction logic should depend on document type. A purchase order and a resume may both contain names, dates, and totals, but the meaning is different.
You can start with a simple classifier using:
async function classifyDocument(textPreview: string) {
const result = await generateObject({
model: openai("gpt-4.1-mini"),
schema: z.object({
documentType: z.enum(["invoice", "receipt", "contract", "resume", "form", "other"]),
reasoning: z.string(),
}),
system: "Classify the document type from extracted text.",
prompt: textPreview,
});
return result.object;
}The important part is not model sophistication. It is making sure classification happens before downstream extraction.
Each document type needs a target shape. For invoices, that might be:
const invoiceSchema = z.object({
vendorName: z.string().optional(),
invoiceNumber: z.string().optional(),
invoiceDate: z.string().optional(),
dueDate: z.string().optional(),
currency: z.string().optional(),
totalAmount: z.number().optional(),
taxAmount: z.number().optional(),
lineItems: z.array(
z.object({
description: z.string(),
quantity: z.number().optional(),
unitPrice: z.number().optional(),
amount: z.number().optional(),
})
),
});Then run extraction with both text and layout-aware context when available. This is where many teams benefit from combining deterministic preprocessing with LLM extraction rather than relying on one or the other alone.
Raw extraction is not the final product. You still need to normalize values:
function validateInvoiceTotals(invoice: z.infer<typeof invoiceSchema>) {
const lineTotal = invoice.lineItems.reduce((sum, item) => sum + (item.amount ?? 0), 0);
const expectedTotal = lineTotal + (invoice.taxAmount ?? 0);
return {
isConsistent: invoice.totalAmount === expectedTotal,
expectedTotal,
};
}Validation is what turns extraction into something finance, operations, or compliance teams can actually use.
Do not force full automation too early. Human review is not failure. It is how you make the system safe while you collect better examples.
Common review triggers:
The review queue should show the original page, highlighted source spans when possible, extracted fields, and the reason the item was flagged.
Large document batches should run in queues, not synchronous API handlers. Each stage should be restartable, with idempotent job logic so a retry does not duplicate downstream writes.
If you improve prompts, change OCR vendors, or update field schemas, version the pipeline. Otherwise, you will struggle to explain why two invoices processed a week apart produced different outputs.
High-level job success metrics are not enough. Measure:
That tells you where to improve first. Usually the bottleneck is not "AI quality" in general. It is one or two specific fields with weak signals.
Document pipelines often process PII, financial data, or contracts. That means:
You should decide early which fields can leave your environment and which must stay inside your own infrastructure.
A lot of document intelligence problems are layout problems. Ignoring tables, regions, and labels usually degrades extraction quality fast.
One huge prompt that tries to classify, extract, validate, and summarize everything is hard to debug. Small composable stages are more reliable.
If reviewers cannot correct data efficiently, the system never improves. Build a feedback path from reviewed corrections back into prompts, rules, or training sets.
A notebook demo can extract a few PDFs. A production pipeline needs queueing, retries, observability, versioning, and security controls.
If you were shipping this for a real product, the safest rollout path would be:
That approach is slower than a flashy all-in-one demo, but it creates a system people can actually trust.
If you are building your first document automation system, optimize for reliability over sophistication:
The winning architecture is usually the one your operations team can debug on a bad day, not the one with the most impressive benchmark on a clean sample file.
Once the extraction pipeline is stable, the next layer is automation around it:
That is where document processing becomes a real business workflow instead of a standalone AI feature.
Collaboration
I help startups and established companies design, build, and scale world-class digital products. From deep technical architecture to pixel-perfect UI: let's bring your vision to life.
Learn how to evaluate AI workflows in production using task-based metrics, human review, regression checks, and business-aligned quality thresholds.
A practical guide to designing and shipping AI workflows inside a production SaaS app, with orchestration, fallback logic, evaluation, and user trust considerations.
A production guide to shipping AI features safely with guardrails, confidence thresholds, fallback paths, auditability, and human-in-the-loop review.