Drills D09

Document extraction at scale

We receive about 2 million PDFs a month (invoices, contracts and scanned forms) and need structured fields out of each one, accurately enough to post into our finance system. Design the extraction pipeline.

45 minutes · revise 13.02 · 13.05 · 13.07 · 13.10 · 14.02 · 19.09 · 31.07 · 32.06

Clarify and scope

Extraction is a batch data pipeline with an LLM in one stage. The hard parts are accuracy you can prove, and the human review queue. Ask:

Baseline architecture

 upload / email / SFTP
        |
 [ingest]   hash file -> skip duplicates -> object store -> queue (idempotent job key)
        |
 [triage per page]  text layer present?  scanned?  table-heavy?  corrupt or encrypted?
        |                |                  |               |
   text extraction   OCR / VLM OCR      table parser     quarantine
        \                |                  /
         +------ [classify doc type] ------+      small model or rules
                         |
         [extract]  LLM + JSON Schema for this doc type, per-field source quote
                         |
         [validate in code]  types, arithmetic, checksums, master-data lookup,
                         |   quote actually present in the page text
              pass       |        fail
               |         +--> one re-ask with the exact errors --> still failing
               v                                                      |
         [confidence from validators]                                 v
          high --> post downstream                       human review UI (pre-filled,
          low  ---------------------------------------->  page image beside each field)
                                                                      |
                           reviewer corrections --> gold set + few-shot bank

Cache every model output by (file hash, page, model id, prompt version). A re-run then costs nothing and gives identical text, and changing the model shows up in the data instead of silently mixing outputs.

Key choices and trade-offs

Triage per page, not per document. A contract can have 30 clean digital pages and one scanned signature page. For digital pages, read the text layer: it is exact and costs no OCR. Scanned pages go through OCR or a vision-language model. Pages that are mostly tables go to a table parser, or to a VLM with the page image. Classifying per page keeps the expensive path for the pages that need it.

Text-first or vision-first. A VLM can read the layout directly, which helps with tables and stamps. But image tokens per page depend on the provider and the resolution (check its formula), and a model can misread a digit while looking confident. Default to text where a text layer exists. Use vision for scans and layout-heavy pages, and validate the digits afterwards.

Schema design. One schema per document type:

Use schema-enforced output (constrained decoding) where the provider supports it. JSON mode only guarantees valid JSON, not your field names or types.

Validation is where the accuracy comes from. The model proposes and code checks:

These checks are cheap, deterministic and testable, and they turn “the model said so” into “the document says so”.

Confidence comes from evidence, not from the model’s own score. A model’s self-reported confidence is often poorly calibrated. Build confidence from things you can check: validators passed, quotes matched, the OCR quality score, and (for high-value fields only) agreement between two independent extractions. Then pick the auto-post threshold on a labelled sample (see Evals).

Model cascade. A small model or plain rules for classification. A mid-size model for extraction. Escalate to a larger model only when validation fails after the re-ask. Most documents never touch the expensive model.

Batch vs synchronous. The bulk lane uses the provider’s batch API: asynchronous, usually discounted (check current terms), and it fits a 4-hour SLA. The urgent lane calls the API synchronously and pays the normal price.

Long documents. Do not send a 60-page contract whole. First find the pages that hold the fields (a classifier or keywords: “Payment terms”, “Total”), then extract from those pages with their page numbers.

Evals

Guardrails and fallbacks

Observability and cost

Per document, log:

Dashboards show straight-through rate per type, cost per document, queue depth against the SLA, reviewer throughput, and the top failing fields. A spike in one field’s failures after a vendor changes its template is a typical incident.

The numbers

Volume. 2M documents × 4 pages = 8M pages a month. 8M / (30 × 86,400 s) ≈ 3.1 pages/s on average. Allow 5× for peaks (month end): about 15 pages/s.

Tokens for a digital document. Assume about 700 tokens of text per page and 1,500 tokens of instructions plus schema. Input = 1,500 + 4 × 700 = 4,300 tokens. Output is about 600 tokens of JSON. Per 1K digital documents: 4.3M input and 0.6M output tokens.

C_1K_digital = (4.3 x P_in + 0.6 x P_out) x d     dollars
   P in USD per million tokens, d = batch discount factor
   (check current prices and batch terms)

Scanned pages: replace 700 with T_img, the provider's image-token count
per page at your resolution (check its formula), plus the OCR cost if
you OCR first.

The instructions and schema (1,500 tokens) are the same for every document of a type. Put them first so the provider can serve them from its prompt cache.

Human review usually costs more than the tokens. Suppose 8% of documents go to review and a reviewer clears 60 pre-filled documents an hour. That is 2M × 0.08 = 160,000 documents, or 2,667 hours a month, roughly 17 full-time reviewers at 160 hours each. Cutting the review rate from 8% to 4% halves that. Better validators and better calibration usually save more money than a cheaper model.

Gold-set size. To estimate a field accuracy near 98% within ±1 point at 95% confidence: n = 1.96² × 0.98 × 0.02 / 0.01² = 3.8416 × 0.0196 / 0.0001 ≈ 753 labelled instances of that field.

Storage. At about 200 KB per page, 8M pages is about 1.6 TB a month of originals before compression. Retention policy sets the real bill.

Latency. On the bulk lane, queueing dominates. Triage takes a fraction of a second, an extraction call takes seconds, and validation takes milliseconds. The 4-hour SLA is a capacity question (workers, provider rate limits and batch turnaround), not a model-speed question.

Follow-ups they will ask

  1. A new document type arrives with no labels. What do you do? Ship it with a schema and send 100% of it to review for the first few hundred documents. Those reviews become the gold set, and you then set its auto-post threshold.
  2. How do you know your confidence is calibrated? On the random audit sample, plot the error rate per confidence bucket. Set the threshold where the measured error meets the target.
  3. A table spans two pages. How do you handle it? Parse the table on each page, then stitch the parts by matching the header row. Validate the row sum against the total, and send it to review if they disagree.
  4. You switch model providers. What breaks? Possibly every field. The cache key includes the model id, so re-run the gold set, compare paired, and migrate a document type all at once rather than mixing models within it.
  5. Why not fine-tune a model? Once you have thousands of reviewed labels and a stable schema, a small fine-tuned model may match a large prompted one at lower cost. Decide on the same gold set.

How to bring in your own work

You have built careful extraction from handwritten pages (Answer Grader) and the VLM OCR lane of a team’s ingest pipeline (Scheme Assistant). Neither ran at millions of documents.

esc

Narrow with repo:jm layer:eval q:naive mine · ↑↓ to move, enter to open