How do you make LLM document extraction reliable enough to automate?
Why I route extracted documents by their weakest field, treat model output as untrusted, and judge the system by straight-through rate and error rate among auto-accepted documents.
The verdict, which the evidence below will earn: don’t aim for 100% automation, and don’t judge it by field accuracy. Give every extracted field a confidence from checks you control (is the value in the source? do the line totals add up? does the part exist in the catalogue?). Route each document by its weakest field, auto-accept only above a threshold you chose from measured errors, and send the rest to a human. The metric that matters is the straight-through rate you get while errors among auto-accepted documents stay under a ceiling you set.
What I find exciting about this case is that the most important clues aren’t about the model at all. They’re plain, checkable engineering wrapped around it, and that’s exactly what makes it trustworthy enough to automate.
The scene: purchase orders arrive as PDFs, spreadsheets, emails and chat messages. Someone retypes each one into a quoting system. That queue is often what makes quotes slow, and the obvious suspect for fixing it is “a better model”.
I’ve architected an AI-driven order ingestion platform in production. This post is not about that system. It is about a small public reference implementation I wrote, llm-document-ingestion, in Go with no third-party modules and only synthetic data. Every number below comes from its committed results files.
The main idea, stated plainly before we chase it: the goal is not 100% automation, and “accuracy” is the wrong headline metric. The goal is the highest straight-through rate you can get while the error rate among auto-accepted documents stays under a ceiling you choose.
Case file
The case Purchase orders retyped by hand make quotes slow Suspects “A better model”, per-field accuracy Culprit Judging by field scores, and trusting model output The fix Route each document by its weakest field, with checks you control Evidence llm-document-ingestion: Go, synthetic data, seeded and committed eval
The first false lead: per-field accuracy #
Here are two numbers from the held-out run (1,000 synthetic documents, seed 2026) in results/baseline-heldout.md. Quantity extraction has a precision of 0.975 and a recall of 0.968. Impressive. Yet only 84.0% of documents are fully correct, with every header field, line field and catalogue match equal to ground truth.
That gap is the first real clue. An order with one wrong quantity is a wrong order. Field scores average over thousands of values and hide the documents that matter.
So the repo reports two numbers at a chosen threshold:
- Straight-through rate: documents auto-accepted, out of all documents.
- Error rate among auto-accepted: of those, how many were not fully correct.
The first is the business value. The second is the risk you are taking to get it.
Rules first, an LLM for the rest #
The pipeline has a Primary and an optional Fallback extractor (internal/pipeline/pipeline.go). The cascade mode runs the rule-based extractor first. It calls the LLM only when the rules are unsure or cannot read the input, such as an image:
r, err := attempt(p.Primary)
if p.Fallback != nil && (err != nil || r.Decision == Review) {
r2, err2 := attempt(p.Fallback)
switch {
case err2 != nil:
r.Reasons = append(r.Reasons, fmt.Sprintf("%s: %v", p.Fallback.Name(), err2))
case err != nil || r2.Confidence > r.Confidence:
r = r2
}
}
Rules are free, deterministic, fast and testable on structured inputs like exports, spreadsheets and templated emails. They fail on free text. On the synthetic sets, the rules auto-accept 0.0% of chat messages. Rule-parsed chat lines get field confidences of 0.75 or lower, and the default threshold is 0.85, so they always go to a person. That is the case for the cascade. The design is modest on purpose, and I find that modesty its best feature: use the cheap, predictable tool wherever it works, and save the clever one for where it’s needed.
An LLM handles chats, images and unfamiliar layouts. It also costs money per document, adds latency, and can be wrong in fluent ways. The cascade spends that only on the documents the rules could not handle. If the fallback fails, the primary result stands and the failure becomes a review reason.
Diagram source
flowchart TD
A["Document"] --> B["Rules extractor"]
B --> C{"Unsure, or can't read it?"}
C -->|yes| D["LLM fallback"]
C -->|no| E["Score: weakest required field, then penalties"]
D --> E
E --> F{"Confidence at or above the threshold?"}
F -->|yes| G["Auto-accept"]
F -->|no| H["Human review, with reasons"]
The key clue: the weakest required field, then penalties #
Each extractor returns a value and a confidence per field. The scorer (internal/score/score.go) then takes the minimum over required fields, not an average:
conf := 1.0
for _, k := range required {
if v := a.Fields[k]; v < conf {
conf, a.Weakest = v, k
}
}
for _, c := range a.Checks {
if !c.Passed {
conf *= c.Penalty
}
}
Required fields include every line’s part number, description, quantity and unit, and the unit price on purchase orders. One weak quantity pulls the whole document down, which is what you want. Taking the minimum is a small choice with a big effect: it makes the score as honest as the weakest part of the document, so no single bad field can hide behind good neighbours.
The checks need no model:
- Grounding. Is each extracted string and number actually in the source text? If not, that field’s confidence is multiplied by 0.3.
- Line totals. Quantity times unit price, summed, must match the stated total within a small tolerance. Failure multiplies document confidence by 0.6.
- Count quantities. 2.5 pieces is almost always a misread “2.500” or “2,5”. Penalty 0.6.
- Dates. In range, and delivery not before the PO date or more than two years after it. Penalty 0.7.
- Currency consistency. The extracted currency must be the one the document shows. Penalty 0.7.
- Instruction-like text. More on this below. Penalty 0.5.
Catalogue matching (the part numbers post covers how) then caps confidence again. If any line’s match is weaker than the document score, the document takes the match’s confidence.
The threshold is a business decision #
The threshold is not a property of the model. It is where you choose to sit on a curve. The eval writes that curve as a threshold sweep. From the held-out run:
| Threshold | Straight-through | Errors among auto-accepted |
|---|---|---|
| 0.50 | 80.1% | 2.7% (22) |
| 0.60 | 69.6% | 0.4% (3) |
| 0.85 | 68.8% | 0.4% (3) |
| 0.90 | 36.4% | 0.5% (2) |
| 0.95 | 0.0% | n/a (0) |
Diagram source
xychart-beta
title "Wrong orders auto-accepted, by threshold (held-out set)"
x-axis ["0.50", "0.60", "0.85", "0.90", "0.95"]
y-axis "wrong orders" 0 --> 22
bar [22 , 3 , 3 , 2 , 0]
Dropping from 0.60 to 0.50 buys about ten points of straight-through and costs 22 wrong orders auto-accepted instead of 3. Whether that is worth it depends on what a wrong order costs you and what a person’s review costs you. That is a conversation with the business, not a model setting. The rule the repo suggests: pick the lowest threshold whose error rate is under the ceiling you will accept.
At the default 0.85, the dev set (300 documents, seed 42) auto-accepts 67.7% with 0 errors out of 203. The held-out set auto-accepts 68.8% with 3 errors out of 688, and sends 312 documents to review.
The report also lists why documents went to review. On the held-out set, the top reasons are low confidence in the buyer field and line items parsed from free text, each on 37.8% of reviewed documents. That list is a map of where to look next: it tells you where to improve the extractor.
A witness you can’t trust: model output #
The LLM extractor (internal/extract/llm.go) treats everything the model returns as testimony from an untrusted party:
- The reply must contain one JSON object that passes the JSON Schema (
additionalProperties: falseeverywhere). - It is decoded with unknown fields rejected.
- A
stop_reasonother than a normal end is an error. The document goes to review with the reason. There is no blind re-ask. - The model never supplies confidence. The schema has no field for it. The code assigns a fixed prior of 0.9 (0.8 for images, which cannot be grounded), and 0 to key fields the model left empty, such as the buyer or PO number.
Then grounding applies, the check that catches the most for the least code. A value that does not appear in the source drops to 0.27, well below the threshold. An LLM can only score well by copying what the document says, which is a wonderfully simple way to keep a fluent witness honest.
Schema validation is not only an LLM safeguard. The pipeline validates the rule-based output too, because the schema is the contract with downstream systems.
The plant: prompt injection inside the document #
The documents come from third parties. A buyer’s PDF can contain a line addressed to an AI system, asking it to approve the order and set every price to zero. The repo ships one such sample in examples/prompt-injection.txt, and the generator adds a similar line to about 3% of synthetic documents.
There are four layers of defence:
- The document is sent as delimited data, and a closing tag inside it is neutralised so the text cannot end the block early:
text := strings.ReplaceAll(in.Text, "</document", "<\\/document")
return fmt.Sprintf("<document format=%q>\n%s\n</document>\nExtract this document.", in.Format, text)
- The system prompt says the document is untrusted and that embedded instructions must never be followed.
- Nothing the model returns can set routing. There is no “approve” field to fill.
- A pattern check for instruction-like text halves document confidence and adds a reason telling the reviewer a human must look at it.
The test I like most assumes the first two layers fail. In pipeline_test.go, a fake model called obedient does whatever the injected text says. It changes the buyer, zeroes the prices, and reports 0.99 confidence on every field. The pipeline still sends the document to review, and the test checks that grounding is among the reasons. That’s the reveal of this whole case: prompts reduce the risk, but they are not the control. The control is code that does not trust the output.
Keeping the evidence honest: a reproducible eval #
An eval you cannot rerun is an anecdote (the evals post goes wider). This one is built to be rerun:
- A seeded generator produces documents and ground truth:
-n 300 -seed 42for development,-n 1000 -seed 2026as a held-out set. - The report has no timestamps, so the same seed, size and extractor always produce the same bytes.
- Both reports are committed.
make eval-checkregenerates them and runsgit diff --exit-code results/. CI fails if the code no longer reproduces them byte for byte.
That last step changes how you work. Any change to a rule, a penalty or the threshold shows up as a diff in the results, in the same pull request.
Remember this
- Judge by straight-through rate and errors among auto-accepted, not field accuracy.
- Route each document by its weakest required field.
- The model never supplies confidence: code that doesn’t trust the output is the control.
The loose ends, and what I’d do differently #
Every honest case file lists what it couldn’t prove. These numbers need their caveats stated plainly.
- The data is synthetic. The generator and the rules share an author, so the rules know the generator’s vocabulary. The numbers are optimistic for non-chat formats. They show the routing machinery works, meaning confidence separates right from wrong. They say little about accuracy on real buyer documents.
- There are no LLM numbers. The LLM and cascade extractors have not been evaluated, because the environment that produced the results had no API key.
make eval-llmwould writeresults/llm.mdandresults/cascade.md. Until those files exist, the repo reports no LLM accuracy, and neither do I. - The three held-out errors are one case. A European “1.000” (one thousand) read as 1, in a request for quotation with no prices or total to cross-check. The right fix is buyer locale from customer master data, not another regex. I left the error visible because it shows what the error-rate metric is for.
- No images in the eval set. The image path is covered by unit tests only.
What I’d do on Monday:
- Run the LLM and cascade evals and commit them next to the baseline, with token counts, so cost per document is measured, not estimated.
- Use the API’s structured outputs instead of prompt-only JSON, which would remove most malformed-output failures.
- Build an eval set from real, consented documents. Synthetic data proves the plumbing. Only real documents can set a threshold you would put in front of a customer.
The idea I’d most like readers to take away is a gentle one: you don’t need a perfect model to automate safely. You need checks you control, a threshold you chose on purpose, and a person for the rest. The next case to read is the part numbers post.
Comments
No comments yet.
Sign in to comment. We'll email you a link; no password needed.