Sub topic 13
Measuring extraction accuracy
This chapter assumes you can call an LLM API, read and write JSON, and write basic Python. You should also have a working extraction function like the one built in the validation chapter: it takes document text and returns a validated Invoice object. Here you learn how to tell whether that function is any good, and how to tell whether a change made it better or worse.
Why you need a test set
An extraction pipeline that looks right on three documents can fail on the fourth. Prompts, models and document layouts all change over time. Without a fixed set of examples with known answers, you cannot compare two prompts, you cannot detect a regression after a model upgrade, and you cannot decide which fields need human review.
A test set is a collection of documents paired with gold labels. A gold label is the correct value for each field, written down by a person who read the document. The pipeline's output for each document is a prediction. Measuring accuracy means comparing predictions to gold labels.
Building a small labeled test set
Start with 30 to 50 documents. This is enough to catch large problems and cheap enough to label by hand. Choose documents that reflect what the pipeline will actually see, not only the clean ones.
- Include each document type you support: native-text PDFs, scans, and photos.
- Include each vendor or layout family, not several copies of the same one.
- Include hard cases: missing fields, multiple dates, foreign currencies, rotated pages, and tables that span pages.
- Keep a separate set of documents you never use while tuning the prompt. Check this held-out set only occasionally. If you tune against every document, the score stops predicting how the pipeline behaves on new ones.
Store labels in a JSON Lines file, one object per line, with a document identifier and the gold values. Use null where the document truly has no value, so the labels follow the same rules as the schema.
import json
gold_rows = [
{"doc_id": "inv-001", "vendor": "Acme GmbH", "invoice_number": "A-1042",
"invoice_date": "2026-03-14", "currency": "EUR", "total": 1190.0},
{"doc_id": "inv-002", "vendor": "Northwind Ltd", "invoice_number": "NW-77",
"invoice_date": None, "currency": "GBP", "total": 250.5},
]
with open("labels.jsonl", "w", encoding="utf-8") as f:
for row in gold_rows:
f.write(json.dumps(row) + "\n")
with open("labels.jsonl", encoding="utf-8") as f:
labels = [json.loads(line) for line in f]
print(len(labels), "labeled documents")Label carefully. Wrong labels make a correct prediction look like an error, and you will waste time debugging the model when the label was at fault. When the model and the label disagree, open the document and check who is right.
Field-level exact match
The simplest metric is exact match per field: the share of documents where the predicted value equals the gold value. This is the function from the topic's example code.
def field_accuracy(predictions, labels, fields):
correct = {f: 0 for f in fields}
for pred, gold in zip(predictions, labels):
for f in fields:
if pred.get(f) == gold.get(f):
correct[f] += 1
return {f: correct[f] / len(labels) for f in fields}Run it over the whole test set. The predictions list holds one dictionary per document, in the same order as labels.
fields = ["vendor", "invoice_number", "invoice_date", "currency", "total"]
predictions = []
for row in labels:
text = load_text(row["doc_id"]) # your own loader
invoice = extract_invoice(text, call_llm)
predictions.append(invoice.model_dump())
for name, score in field_accuracy(predictions, labels, fields).items():
print(f"{name:15s} {score:.0%}")A per-field report tells you where to work. If total is at 98% and vendor is at 70%, improving the vendor instructions is worth more than anything you do to the total.
The function assumes both lists have the same length and order. zip silently stops at the shorter list, so a missing prediction would shrink the comparison without any error. Check len(predictions) == len(labels) before scoring.
Normalize before you compare
Exact match is strict. A prediction of "Acme GmbH" against a label of "ACME GmbH" counts as wrong, and so does 1190 against 1190.0 in some serializations. Decide which differences matter and normalize both sides before comparing.
| Field type | Normalization | Why |
|---|---|---|
| Names | Collapse whitespace, lowercase | Case and spacing rarely change meaning |
| Identifiers | Strip spaces only | Case or punctuation may be significant |
| Dates | Parse to ISO 8601 | Formats vary, the date is the same |
| Amounts | Convert to a number, compare with a tolerance | Float rounding and thousand separators |
import math
def norm_text(value):
return None if value is None else " ".join(str(value).split()).lower()
def same_amount(a, b, tol=0.005):
if a is None or b is None:
return a is b
return math.isclose(float(a), float(b), abs_tol=tol)
def field_accuracy_normalized(predictions, labels, text_fields, amount_fields):
if len(predictions) != len(labels):
raise ValueError("predictions and labels differ in length")
scores = {}
for f in text_fields:
hits = sum(norm_text(p.get(f)) == norm_text(g.get(f))
for p, g in zip(predictions, labels))
scores[f] = hits / len(labels)
for f in amount_fields:
hits = sum(same_amount(p.get(f), g.get(f))
for p, g in zip(predictions, labels))
scores[f] = hits / len(labels)
return scoresNormalize in the evaluation code, not in the labels. Keep the labels as the true document values so that you can change the comparison rules later without relabeling.
Missing values need their own metric
In an extraction task, a null is an answer. Plain accuracy treats null matching null as a success, which can inflate scores for sparse fields. If 90% of documents have no invoice_date, a pipeline that always returns null scores 90% on that field.
Separate the cases by comparing gold and prediction:
- Both present and equal: correct value.
- Both present and different: wrong value.
- Gold present, prediction null: missed value.
- Gold null, prediction present: invented value. This is the hallucination case, and it is usually the most harmful.
from collections import Counter
def outcome_counts(predictions, labels, field):
counts = Counter()
for pred, gold in zip(predictions, labels):
p, g = pred.get(field), gold.get(field)
if g is None and p is None:
counts["both_null"] += 1
elif g is None:
counts["invented"] += 1
elif p is None:
counts["missed"] += 1
elif p == g:
counts["correct"] += 1
else:
counts["wrong_value"] += 1
return counts
print(outcome_counts(predictions, labels, "invoice_date"))From these counts you can compute precision and recall for a field. Precision is the share of returned values that are correct: correct / (correct + wrong_value + invented). Recall is the share of existing gold values that were found correctly: correct / (correct + wrong_value + missed). Low precision means the pipeline outputs bad values. Low recall means it gives up too often. The two call for different fixes, and which one matters more depends on the cost of each mistake in your application.
Document-level accuracy and failed runs
Field accuracy can hide how often a whole document is right. A document is fully correct only when every field matches. If each of five fields is 95% accurate and the errors are independent, only about 77% of documents are fully correct. Report both numbers: per-field scores to guide work, and the share of fully correct documents to describe what a user experiences.
Count failures too. If extract_invoice raises after three attempts, there is no prediction. Do not drop those documents from the test set. Score them as failures, with every field wrong, and report the failure rate separately. A pipeline that crashes on its hardest 10% of documents and scores perfectly on the rest has not earned a perfect score.
Reading the errors
A score tells you how much is wrong. The errors tell you why. After each run, print the mismatches and read them.
def show_errors(predictions, labels, field, limit=10):
shown = 0
for pred, gold in zip(predictions, labels):
if norm_text(pred.get(field)) != norm_text(gold.get(field)):
print(gold["doc_id"], "| predicted:", pred.get(field),
"| expected:", gold.get(field))
shown += 1
if shown == limit:
break
show_errors(predictions, labels, "vendor")Common patterns, and where to look first:
- Wrong vendor, with the customer's name returned instead: the prompt does not say which party to extract.
- Wrong total, with a subtotal returned: the schema description is ambiguous, or text extraction scrambled the table.
- Many invented values on one field: the prompt allows guessing, or the field description suggests a default.
- Errors concentrated on scans: the cause is OCR quality, not the model.
Combine this with grounding. The grounding check from the previous chapter flags values that do not appear in the source. Counting how many predicted values fail it gives you a cheap hallucination rate that needs no labels at all, so you can monitor it on production documents.
Comparing changes fairly
Treat each change to the prompt, model or text extraction step as an experiment.
- Run the current pipeline on the test set and save the predictions to a file with a version name.
- Change one thing.
- Run again on the same documents and compare per-field scores and the list of documents that changed from right to wrong.
Language model output can vary between runs, even at temperature 0, so a difference of one or two documents on a set of 40 is noise. Prefer changes that move a field by more than a few documents, and rerun borderline results. A small test set also gives wide uncertainty: 38 of 40 correct is 95%, but the true rate could plausibly be well above or below that. Grow the set when decisions depend on small differences.
Using the scores
Field scores feed the rest of the pipeline. Fields with high accuracy can flow straight through. Fields with low accuracy or high invention rates should go to human review. The score on the held-out set is also your honest estimate of how often an unreviewed result will be wrong, which is the number a stakeholder needs before deciding how much to automate.
Exercise
A test set has 100 invoices, and 90 of them have no purchase order number. Your pipeline returns null for the purchase order field on every document. Exact-match accuracy for that field is 90%. How would you measure this field more honestly, and what would the result show?
Show answer
Split the outcomes into correct, wrong value, missed, invented and both null. Here there are 90 both-null results and 10 missed values, with no correct values. Recall is 0 out of 10, which is 0%, so the pipeline never finds a purchase order number even though plain accuracy shows 90%. Precision is undefined because nothing was returned, which is itself a warning sign.
Exercise
Each of five fields is 96% accurate, and errors on different fields are independent. About what share of documents is fully correct, and why is this number worth reporting beside the per-field scores?
Show answer
About 0.96 to the fifth power, which is roughly 82%. Per-field scores guide where to improve, but a user who needs a whole record correct sees the lower document-level rate, so reporting both shows the real experience.