Sub topic 16
Routing uncertain results to human review
This chapter assumes you have the pieces from earlier chapters. These are the Invoice Pydantic model, the extract_invoice retry loop, the is_grounded check, and field_accuracy on a labeled test set. You should also be comfortable with basic Python and JSON. Here you combine those signals into a decision. The decision is whether a result goes straight into your system or to a person first.
Why route at all
No extraction pipeline is perfect. Some documents are blurry, some are ambiguous, and some contain values the model misreads. If every result is reviewed by hand, the LLM saves you little. If none is reviewed, wrong values reach your database silently.
Routing sends the few risky results to a person and lets the rest through. The goal is to catch most errors while keeping the review queue small. You tune that balance with data, not by guessing.
Signals that a result is uncertain
You already produce several signals. Each one answers a different question.
| Signal | Source | What it tells you |
|---|---|---|
| Validation failed after all retries | `extract_invoice` raises | The output never matched the schema. |
| Needed a retry | Attempt count | The first answer was invalid, so the document may be unusual. |
| Required field is null | Parsed model | The value may be absent, or the model failed to find it. |
| Value not found in source | `is_grounded` | The value may be hallucinated or reformatted. |
| Source came from OCR | Ingestion step | Character errors are possible, such as `0` read as `O`. |
| Cross-field check fails | Your own rules | Values disagree with each other. |
| Low text yield | Text length per page | The extraction may have missed content. |
Hard signals mean the result is wrong or unusable. Soft signals only raise the odds of an error. Treat them differently: one hard signal sends the result to review, while soft signals need to add up.
Why not ask the model for a confidence score
It is tempting to add a confidence field to the schema. Models do produce numbers, but these numbers are weakly calibrated. A model can report 0.95 on a wrong value, and it often reports similar numbers for every field. Use a self-reported score as one weak soft signal at most. Signals you compute outside the model are more trustworthy, because the model cannot talk itself into them.
Some APIs expose token log probabilities. If yours does, the probability of the tokens in a field's value is a better signal than a stated number. It is still only a signal, so check it against labeled data before relying on it.
Cross-field checks
Cross-field rules catch errors that no single-field check can. For an invoice, you might check that the total is not negative, that the currency code is one you accept, and that the date is not in the future. If your schema includes line items, check that they sum to the total. A mismatch often means a misread digit or a missed row.
These rules are cheap, deterministic, and easy to explain to a reviewer.
A routing function
The function below collects reasons, then decides. It takes the grounding check as an argument so you can pass in the is_grounded function from the earlier chapter. The demo at the bottom uses a simple stand-in object so the code runs on its own.
from dataclasses import dataclass, field
from datetime import date
from types import SimpleNamespace
REQUIRED = ("vendor", "invoice_number", "total")
GROUNDED = ("vendor", "invoice_number")
ALLOWED_CURRENCIES = {"USD", "EUR", "GBP"}
SOFT_LIMIT = 2
@dataclass
class Decision:
route: str # "auto" or "review"
hard: list = field(default_factory=list)
soft: list = field(default_factory=list)
def is_grounded(value, source_text):
if value is None:
return True
normalized_source = " ".join(source_text.split()).lower()
normalized_value = " ".join(str(value).split()).lower()
return normalized_value in normalized_source
def route_result(invoice, source_text, attempts_used=1, ocr_used=False):
hard, soft = [], []
for name in REQUIRED:
if getattr(invoice, name) is None:
hard.append(f"missing:{name}")
for name in GROUNDED:
if not is_grounded(getattr(invoice, name), source_text):
hard.append(f"ungrounded:{name}")
if invoice.total is not None and invoice.total < 0:
hard.append("negative_total")
if invoice.currency is not None and invoice.currency not in ALLOWED_CURRENCIES:
hard.append("unknown_currency")
if invoice.invoice_date is not None:
try:
if date.fromisoformat(invoice.invoice_date) > date.today():
hard.append("future_date")
except ValueError:
hard.append("bad_date")
if attempts_used > 1:
soft.append("needed_retry")
if ocr_used:
soft.append("ocr_source")
if invoice.currency is None:
soft.append("no_currency")
needs_review = bool(hard) or len(soft) >= SOFT_LIMIT
return Decision("review" if needs_review else "auto", hard, soft)
text = "ACME Ltd Invoice INV-1042 Date 2026-03-01 Total 99.50 EUR"
good = SimpleNamespace(vendor="ACME Ltd", invoice_number="INV-1042",
invoice_date="2026-03-01", currency="EUR", total=99.5)
bad = SimpleNamespace(vendor="ACME Ltd", invoice_number="INV-1024",
invoice_date="2026-03-01", currency="EUR", total=99.5)
print(route_result(good, text))
print(route_result(bad, text))The second call routes to review. The invoice number INV-1024 does not appear in the source text, so the grounding check adds ungrounded:invoice_number as a hard reason.
Keep the reasons
Store the reasons with every routed result. A reviewer who sees "ungrounded:invoice_number" knows where to look first, and review goes faster. The reasons also show you which signals fire most often, which tells you where the pipeline needs work.
A review item should include the original file or page image, the extracted values, the reasons, and a place to record corrections. A JSON Lines file is enough to start:
import json
def enqueue_for_review(path, doc_id, extracted, decision):
item = {
"doc_id": doc_id,
"extracted": extracted,
"reasons": decision.hard + decision.soft,
"status": "pending",
}
with open(path, "a", encoding="utf-8") as f:
f.write(json.dumps(item) + "\n")In a real system this would be a database table or a ticket queue, but the fields are the same.
The routing flow
Auditing the automatic path
Routing rules only catch errors you thought of. Errors that pass every check will flow into your data unnoticed. To measure them, send a small random sample of auto-accepted results, such as 2 to 5 percent, to review anyway. Compare the reviewer's values with the pipeline's values.
This sample gives you an estimate of the error rate on the unreviewed path. If that rate rises, a new document layout or a model change has probably broken something your checks do not cover.
Tuning with your labeled set
Treat the routing rules as a classifier that predicts "this result has an error". Run them over your labeled test set from the evaluation chapter. For each document, a result is truly wrong if any field differs from the gold label. Then measure two things:
- Recall of errors: of the documents with at least one wrong field, what fraction did you route to review?
- Review rate: what fraction of all documents did you route?
Suppose 10 of 100 test documents have errors. Your rules route 20 documents, and 9 of those are the wrong ones. Error recall is 90 percent and the review rate is 20 percent. If you raise SOFT_LIMIT from 2 to 3, the review rate drops, but recall may drop too. Adjust the thresholds and watch both numbers move. Choose the point your cost of mistakes justifies.
Closing the loop
Reviewer corrections are the most valuable labels you will get, because they come from the documents that were hardest for the pipeline. Add them to your labeled test set. Also read them in batches. If reviewers keep fixing the same field, change the schema description, the prompt, or the ingestion step instead of paying for the same correction forever.
Common mistakes
- Reviewing everything flagged with no priority. Put documents with hard failures ahead of those with soft signals only.
- Letting reviewers see only the extracted values. Show the source page next to them, or review takes much longer and reviewers miss errors.
- Treating a null as safe. A null can be correct, but a required field that is null needs a person to confirm.
- Never changing thresholds after launch. Document mix changes over time, so re-measure.
- Sending sensitive documents to a review tool with weaker access controls than the pipeline itself. The privacy rules from the previous chapter apply to reviewers too.
Exercise
Your rules send 30 of 200 test documents to review. Of the 200, 16 have at least one wrong field, and 12 of those 16 are among the 30 routed. What are the error recall and the review rate? Name one change you could try to raise recall, and one cost of making it.
Show answer
Error recall is 12/16 = 75 percent. The review rate is 30/200 = 15 percent. To raise recall you could lower SOFT_LIMIT, or add a cross-field rule for the errors that were missed. The cost is a higher review rate, so more human work. Look at the 4 missed documents first to see which rule would have caught them.
Exercise
Why is a random audit sample of auto-accepted results still needed when you already have grounding and validation checks?
Show answer
Those checks only catch the failure types you designed them for. A wrong value that appears in the source text, such as a different number copied from another line, passes grounding. The sample measures the real error rate on the unreviewed path and reveals failures your rules do not cover.