Beyond the Prompt: Production LLM OCR for Tax Documents
APRIL ENGINEERING
11 MINUTES
Share

How the pipeline around a multimodal LLM took our field accuracy from ~80% to ~98% and cut latency from ~12 to ~5 seconds.
Overview
Every tax return starts with paperwork: W-2s, 1099s, mortgage statements, and last year’s return. For many Americans, the easiest way to share that paperwork is a photo of that document, taken from their phone, on the kitchen counter.
Turning those convenient photos into accurate, tax-ready data is one of the hardest problems we’ve faced when developing our tax technology. It’s also one of the most important things to get right. A single misread decimal, or a wage form counted twice, can change a refund, deliver an incorrect output, and ultimately shake a client’s trust.
If you work on document intelligence, you have seen the demo: hand a clean digital PDF of a standard form to a frontier multimodal LLM with a JSON schema, and every field comes back in seconds. It feels like the entire discipline of document-related ML just collapsed into a single API call.
Then you run that same prompt against real production traffic.
At april, our tax engine resolves roughly 3,000 data points per filer, and most of them live inside documents that users upload in every imaginable condition. Picture an angled iPhone photo of a crumpled wage form (Form W-2) with a shadow across the numbers, a 30-page brokerage packet (Consolidated 1099) with hundreds of stock trades, or a 150-page prior-year return (Form 1040 plus dozens of federal schedules and state forms). Every employer, bank, and broker prints the same form its own way: a W-2 alone can be a sheet with four tear-off copies, a two-column table, or a page repeating “Copy B”, “Copy C”, and “Copy 2” of the same numbers.
We test for exactly that. Our benchmark has thousands of pages that we labeled by hand, and one of them is a W-2 that was printed, crumpled, smoothed flat again, and photographed at an angle:

A crumpled W-2 from our benchmark, with three copies on one page. For this post, we replaced every value with a made-up one.
Our pipeline reads the original in 4.3 seconds, returns its three copies as one set of values, and gets all 41 fields right.
What Document Extraction Actually Looks Like in Production
For readers outside the tax domain, here is what our system receives and what it must return:
The Input: A noisy, skewed smartphone photo or multi-page PDF whose boxes carry domain-specific labels like “1 Wages, tips, other compensation”, “12a See instructions for box 12”, or “15 State / Employer’s state ID number”.
The Required Output: A zero-hallucination, strictly typed payload mapped to our internal tax-engine schema. For the W-2 above, here is part of it:
A checkbox mistaken for true or a number pulled from the wrong column corrupts a financial calculation.
Moving from classic OCR to multimodal LLMs in 2024 taught us the lesson behind this post: the LLM is powerful, but the pipeline makes it production-ready. Patch every edge case with another rule in one giant prompt and the rules start to conflict: fixing false negatives on one layout creates false positives on three others. Good prompts are needed, but they are only the starting point, so this post is not about writing prompts. It is about the system architecture around the LLM: the pre-processing, inference engineering (warm caches, hyperparameter tuning, failover), and deterministic post-processing. Together, they took field accuracy from ~80% on camera photos to ~98% and cut latency from ~12 seconds to ~5 seconds, across more than 80 distinct tax document types, all evaluated in our benchmark.
For tax year 2025, this pipeline extracted nearly 35 million field values from more than 1.5 million documents uploaded by ~1M filers, reaching ~50K documents a day.
The Technical Details
1. Pipeline Architecture: From 11 Classic OCR Stages to a Two-Pass LLM Pipeline
We started in 2021 with classic OCR: Tesseract, OpenCV image processing, and our own framework of hand-built coordinate templates for the many variations of each form. On clean PDFs that matched a known template, it reached ~99% field accuracy within ~12 seconds, working through 11 stages from ingestion to validation, and even that required multi-processing: on a single process, a form took ~25-35 seconds.
The problem started with camera photos. Every stage inherited the errors of the one before it, so a small error in straightening an angled phone photo grew into a failed extraction, and accuracy dropped to ~80%. Each new layout variation needed another template, so keeping up took constant manual maintenance.
Frontier multimodal models collapse most of that chain into a single inference call, handle far more variations, and need much less maintenance.

Eight of the 11 legacy stages collapse into one LLM call, surrounded by deterministic pre-processing, post-processing, and PII validation.
One call does not mean the model should do everything. An LLM is a probabilistic perception engine, not a deterministic state machine, and every non-semantic job you hand it (stripping formatting, splitting compound strings, enforcing schema completeness) adds variance. So we wrap it in pre-processing, post-processing, and validation steps.
Why build it in house? Before building our own pipeline, we tried several off-the-shelf document understanding platforms. They read common documents well, but taxes need more than reading: every value must land in the exact field our tax engine expects, across a long tail of federal and state forms, and for whatever users upload, from crumpled phone photos to 150-page returns. To close those gaps, we would still have had to build routing, mapping, and validation around a platform we could not fully control. Building the pipeline ourselves gave us control of every step and let us measure each change against our own benchmark. It also meant we could tune inference to tax documents and the relationships between them, so the model ingests the pre-processing output correctly and we control the data that goes into post-processing.
1.1 Declarative Pipeline Variants
Our document processor is built from pluggable steps wired together by config files. The step order is predefined, and each variant picks the steps it needs from the pipeline, so adjustments are just configuring steps, not adding new code.
1.2 Two-Pass Orchestration: Single Forms, Multidoc Bunches, and Full Returns
Pass 1 runs on every upload, and its single LLM call classifies, extracts, and splits:
Input: The upload as it arrives, in any of the three shapes below.
Output: The form type, tax year, and page range of every form in the upload, with identical copies (W-2 Copy B, C, and 2) collapsed into one form. For a single form, it also includes the extracted values.
Pass 2 uses those forms and page ranges to extract the other two shapes.
Uploads come in three shapes, and treating them the same way is a modeling mistake:
Single Form: One logical document (a PDF or a folder of phone photos), such as a W-2 or a multi-page partnership statement (Schedule K-1) with its footnote pages. Pass 1 handles it in a single call.
Multidoc Bunch: Unrelated forms scanned into one PDF, such as a W-2, a mortgage interest statement (Form 1098), and a tuition statement (Form 1098-T). They share no context, so a combined call gains nothing and risks cross-form key collisions. We split the PDF by Pass 1’s page ranges and send each piece to Pass 2 in parallel.
Full Return: A prior-year Form 1040 with its federal schedules and state returns, often 30 to 150+ pages. These forms are linked: names, taxpayer IDs, filing status, and subtotals flow from the schedules into the 1040, so we build a schema from the forms Pass 1 found, inject it into the Pass 2 prompt, and let the model read the whole return in one call with that shared context.

Every upload goes through Pass 1. Single forms finish there, multidoc bunches split into N parallel Pass 2 pipelines, and full returns go through one Pass 2 call.
2. Pre-Processing: Everything We Do Before the LLM Call
The highest-leverage fixes rarely live in the prompt: they happen in pre-processing, by shaping the input, routing it to the right strategy, and narrowing the label space before the model generates a single token.
2.1 Dropping Irrelevant Pages
Tax forms have a distinct statistical signature compared to instruction sheets, cover letters, and legal disclosures: high numeric token density. When filers upload several photos at once, the page filter computes each page’s ratio of numeric tokens to words. Pages with a low ratio are flagged as irrelevant and dropped before the LLM call, so pages of plain text never distract the model or waste input tokens.
2.2 Breaking the “One-Prompt-Fits-All” Trap with the Strategy Pattern
A single global prompt hits a precision-recall ceiling as soon as different groups of documents need contradictory instructions. Take two common layouts:
Multiple copies in one document: The same form printed several times in one file, like the three copies on the W-2 above. The model must deduplicate them, or the filer’s income is counted more than once.
Summary tables: A table that lists several forms and adds up numbers already shown in the document. The model must keep every row, totals included, so our parser can rebuild each form.
Put both instructions in one prompt and they conflict: telling the model to keep every row makes it keep the repeated copies too.
A heuristic router solves this with the Strategy design pattern. It reads soft signals in a PDF’s text before the LLM call and selects a specialized prompt strategy, which coordinates three things downstream:
Modular prompt composition: swaps in the instruction blocks for that strategy without polluting the baseline prompt.
Dedicated warm cache selection: routes the request to the pre-warmed cache for that model and strategy.
Strategy-aware post-processing: sends the raw output to the matching post-processor.

One prompt does not fit all: the router sends each request to its own prompt, warm cache, and post-processor.
2.3 Per-Request Priors, Constraints & Candidate Pruning
The last pre-processing step conditions the request on what we already know, without touching the system prompt:
Soft Bayesian Prior: A file uploaded from a specific interview screen (e.g., “Upload your W-2”) is very likely a W-2, though users sometimes upload the wrong document. Pre-processing adds the expected form type to the request as a hint, and the model treats it as a strong prior when the visual evidence is ambiguous, overriding it only when clear visual anchors (form title, OMB number, unique box labels) contradict it.
Hard Constraint: Once Pass 1 has classified and split a multi-document PDF, Pass 2 tells the model the form type Pass 1 found for each piece, locking it to that form’s schema.
Candidate Pruning on Full Returns: When running a full return against the entire catalog, form-type accuracy peaked at 82% because the number of candidates was too large. We narrowed down the candidates to the ones found in Pass 1, which got us to 100% form-type accuracy, as there were fewer irrelevant variables.
3. The LLM Inference Layer: Warm Caches, Hyperparameter Tuning & Resilience
The LLM call itself sits between pre-processing and post-processing. With the same prompt, the way you cache, configure and guard the LLM call directly affects the runtime and performance of the system - from increased runtime (~12 seconds instead of ~5) to crashing on traffic spikes.
3.1 Pre-Warmed Multimodal Context Caches
Why do naive multimodal LLM calls take ~12 seconds? Because re-tokenizing a long system instruction, dozens of form schemas, and high-resolution few-shot examples on every request dominates time-to-first-token (TTFT).
To make multimodal in-context learning nearly free at serving time, we pre-warm a context cache for every model and strategy. Each cache holds the compiled system instruction plus tokenized multimodal few-shot examples: real anonymized form images and PDFs paired with their exact ground-truth output. Because pre-processing puts all per-request state (hints, constraints, allowed candidates, and the document itself) in the uncached user message, 100% of requests hit the warm cache:

Everything that changes per request goes into the uncached user message, so the cached prefix stays identical and every request hits the warm cache.
3.2 Hyperparameter Tuning
In data science, you never trust default parameters. We ran a grid search over model tiers and reasoning budgets on our benchmark. We gained no value when using extra reasoning: it increased latency per document but provided no accuracy gain. Turning reasoning off gave us the best latency-accuracy trade-off.
3.3 Endpoint Failover & Blocking Truncated Output
In production, cloud LLM endpoints hit regional quota spikes (HTTP 429) and temporary 5xx errors, while dense multi-page documents can hit output token limits. Two mechanisms guard every call:
Multi-Endpoint Circuit Breaking: Each step has an ordered chain of fallback models. Failed calls are retried with exponential backoff, and when an endpoint keeps failing, a circuit breaker stops routing traffic to the failing endpoint for a while and moves requests to the next healthy model in the chain.
Blocking Truncated Output: On a dense document, such as a brokerage statement with dozens of trades, the response can hit the output token limit and come back as truncated output. A tolerant output parser will happily clean it up and return it as a valid output, while silently dropping half of the user document and returning an incomplete extraction. So we check why generation stopped, and if it hit the token limit, we raise a fatal error before the incomplete extraction can reach post-processing.
4. Post-Processing & Validation: Enforcing Determinism After the LLM Call
Once the LLM returns the raw output, deterministic post-processing and validation turn the probabilistic output into a schema-strict, PII-safe payload.
4.1 Guaranteed 100.00% Coverage and 0.00% Redundancy by Construction
Raw LLM output has two structural failure modes: it omits keys when a box looks empty (hurting coverage) and invents keys that are not in the schema (hallucinated redundancy). So our post-processor never trusts the model’s keys; it iterates over the schema whitelist for that form type:
0.00% Redundancy (zero hallucinated keys): Any key the LLM invented that is not in the schema is dropped and never reaches downstream services.
100.00% Coverage (and stricter accuracy scoring): Any schema key the LLM omitted is added. Downstream services always receive a complete schema, and our evaluation framework scores a missed non-empty field as a value error, which lowers field accuracy directly.
4.2 Field-Level Normalization & PII Validation
By inspecting the residual error distribution (the fields we still got wrong) in our evaluation reports, we found recurring formatting and domain patterns. We moved them out of the prompt and into deterministic rules. For example, when a form prints only a masked SSN or TIN (***-**-4829), the model returns it exactly as printed. Post-processing saves the last four digits (4829) so we can match the form to the right spouse on a joint return, and validation then deletes the masked value so asterisks never enter a tax filing.
5. Production Benchmark Results: Legacy OCR vs. april’s Multimodal LLM Pipeline
Every model change, heuristic, and post-processing rule is benchmarked against our hand-labeled golden dataset of thousands of real-world pages, spanning digital PDFs, single camera photos, and multi-image phone uploads:
Metric | Legacy Classic OCR (Tesseract + Templates) | april Multimodal LLM Pipeline |
|---|---|---|
General Quality | ~80% field accuracy on camera photos, with more missing fields and wrong extractions. Adding templates and variations raised it, but required constant maintenance | ~98% field accuracy |
Full-Return Detection | Not supported, due to the time and resources extraction would take | 100.00% of full returns recognized as full returns |
End-to-End Latency | ~12 seconds (single form), using multi-processing; ~25-35 seconds on a single process | ~5s median |
Three Takeaways from a Data Scientist’s Perspective
Prompt engineering is the bare minimum. The pipeline around the model is the differentiator:
Shape the input before the call. Drop irrelevant pages, route conflicting layouts to dedicated strategies, and pass what you already know (hints, constraints, allowed candidates) in the request instead of the system prompt.
Engineer the call itself. Keep instructions and few-shot examples in a warm cache, tune hyperparameters on your own benchmark, and block truncated outputs.
Make outputs deterministic and guaranteed after the call. Whitelist the schema for 100% coverage and 0% hallucinated keys, and move every recurring fix from the prompt into code.
What’s Next
~98% is not 100%, and the main problem that remains is very long documents. Full returns have our lowest field accuracy, and documents of 400+ pages can push a single extraction call to its output limit.
Every decision in this post, from hyperparameter tuning to strategy routing to candidate pruning, had to answer one question: did this change improve the system across every schema without introducing regressions? In Part 2, we open up the evaluation framework we use to answer it: a hand-labeled benchmark of thousands of real-world pages and 10 strict expected-vs-actual metrics that we chose over LLM-as-a-judge.

Orel Elimelech
Staff Data Scientist at april

