"Successfully extracted 10 invoices."


That was the agent's final message. The logs were clean. Ten JSON objects, every field filled in, every total a plausible number.

Then someone in finance opened the spreadsheet. Here’s what they found:


  • Invoice 3 was a scan. The model read an 8 as a 3 in the total. Plausible, confident, wrong.
  • Invoice 5 had a line-item table that ran across two pages. The rows on page two were dropped. The line items no longer added up to the subtotal, and nothing caught it.
  • Invoice 7 had no PO number. The schema marked po_number as required, so the model invented one. It looked exactly like a real PO number.
  • Invoice 9 was two invoices merged into one PDF. The agent returned one invoice.


This run is a composite, built from failure patterns teams describe when they move document agents from a demo folder to a real inbox. If you've built one of these, these returns are painfully familiar.

None of this raised an error. The agent didn't lie on purpose. It had no way to know it was wrong, and neither did we.

Why "extracted" doesn't mean "right"

Four things went wrong, and none of them is a prompt problem.

The model returned values, not evidence. A total with no link back to the page can only be checked one way: a person re-reads the whole invoice. At that point you've automated nothing.

Structure was lost before reasoning started. Raw PDF text flattens tables and scrambles reading order. A table that spans two pages becomes two unrelated blobs of numbers.

Required fields invited invention. Ask a model for a field the document doesn't have, and it will often give you one anyway.

"Success" meant "the call returned." Most agent loops treat a schema-valid response as a finished step. Valid JSON is not correct JSON.

Getting text out of a document is easy. Getting data you can act on is hard.

The fix: parse first, reason second

Split the job into steps that each do one thing well.

  1. Read the layout first. Use the text layer for born-digital PDFs, OCR for scans, and layout analysis for tables and reading order. Bring in a vision-language model only for the hardest pages. (On Nutrient's hosted API, auto mode picks structure, understand, or agentic for each page.)
  2. Extract against a schema. Define the fields you want as JSON Schema and get JSON back that matches it.
  3. Attach evidence to every value. Each value can come back with its page, its bounding box, a match label, and a confidence score.
  4. Route on the evidence. Clean values flow through. Doubtful ones go to a person, who checks them against the page.

The code

I'm using the Nutrient Data Extraction API here. The pattern works with any extractor that returns source locations and confidence.

Start with the schema. Notice what's not required. Save it as invoice_schema.json.


{   "type": "object",   "properties": {     "invoice_number": { "type": "string", "description": "Invoice identifier" },     "vendor_name": { "type": "string", "description": "Name of the company that issued the invoice" },     "issue_date": { "type": "string", "format": "date", "description": "Date the invoice was issued" },     "po_number": { "type": "string", "description": "Purchase order number, only if printed on the invoice" },     "subtotal": { "type": "number", "description": "Sum of the line items, before shipping and tax" },     "tax_amount": { "type": "number", "description": "Tax amount, only if printed" },     "shipping_amount": { "type": "number", "description": "Shipping or freight charge, only if printed" },     "total_amount": { "type": "number", "description": "Total including tax" },     "line_items": {       "type": "array",       "description": "One entry per row in the line-item table, across all pages",       "items": {         "type": "object",         "properties": {           "description": { "type": "string" },           "quantity": { "type": "number" },           "unit_price": { "type": "number" },           "amount": { "type": "number", "description": "Line total as printed" }         },         "required": ["description", "amount"]       }     }   },   "required": ["invoice_number", "total_amount"] } 


po_number is optional on purpose. The API can leave out fields that aren't required when the document doesn't contain them. That one change fixes invoice 7: an empty field instead of an invented one.

Now the call:


import json import os import requests API_KEY = os.environ["NUTRIENT_API_KEY"] with open("invoice_schema.json") as f:     schema = json.load(f) with open("invoice.pdf", "rb") as f:     resp = requests.post(         "https://api.nutrient.io/extraction/extract",         headers={"Authorization": f"Bearer {API_KEY}"},         files={"file": f},         data={"instructions": json.dumps({             "schema": schema,             "parseConfig": {"mode": "understand"},         })},         timeout=300,     ) resp.raise_for_status() output = resp.json()["output"] data, meta = output["data"], output["metadata"] 


Each entry carries the page number, a bounding box and a match label, plus a composite confidence score from 0 to 1 when the engine provides one. It's often omitted, so treat a missing score as "no score". Scanned pages also carry an OCR recognition score. Here's the evidence for total_amount from a live run (shortened):


"total_amount": {   "match": "id_match",   "pageNumber": 1,   "bbox": { "x": 874, "y": 1060.8, "width": 667, "height": 158.2 } } 


The match label tells you how the value was tied to the page. id_match means it matches a source block exactly. fuzzy_match means close but not identical. not_found means no source location was found at all. id_match_multiblock means the value spans several source blocks, and id_match_partial means only some of the cited blocks are resolved.

Route on evidence, not on "done"

Walk the data and the metadata together, and flag anything that looks doubtful:


REVIEW_MATCHES = {"fuzzy_match", "not_found"} CONFIDENCE_THRESHOLD = 0.7  # the docs' example value; tune it on labeled samples OCR_THRESHOLD = 0.7         # not from the docs; tune it separately def walk(value, evidence, path=""):     if isinstance(value, dict):         for key, child in value.items():             sub = evidence.get(key) if isinstance(evidence, dict) else None             yield from walk(child, sub, f"{path}.{key}" if path else key)     elif isinstance(value, list):         for i, child in enumerate(value):             sub = evidence[i] if isinstance(evidence, list) and i < len(evidence) else None             yield from walk(child, sub, f"{path}[{i}]")     else:         yield path, value, evidence or {} def needs_review(evidence):     if evidence.get("match") in REVIEW_MATCHES:         return True     confidence = evidence.get("confidence")     # A missing score means "no score", not "low score".     if confidence is not None and confidence < CONFIDENCE_THRESHOLD:         return True     # OCR recognition score, scanned pages only: a hint, not a confidence score     ocr = evidence.get("recognitionScore")     return ocr is not None and ocr < OCR_THRESHOLD flags = [     (path, f"{e.get('match')}, page {e.get('pageNumber')}")     for path, value, e in walk(data, meta)     if needs_review(e) ] 


Then add the checks a model can't talk its way around. Arithmetic is cheap. When every sum checks out, a fuzzy match on a number is formatting, not a misread, so it doesn't need a person.


def num(value):     return value if isinstance(value, (int, float)) else 0 fuzzy_numbers = {     path for path, value, e in walk(data, meta)     if e.get("match") == "fuzzy_match" and isinstance(value, (int, float)) } sum_errors = [] items = data.get("line_items", []) for i, item in enumerate(items):     q, p, a = item.get("quantity"), item.get("unit_price"), item.get("amount")     if all(isinstance(x, (int, float)) for x in (q, p, a)) and abs(q * p - a) > 0.01:         sum_errors.append((f"line_items[{i}]", f"{q} x {p} = {q * p:.2f}, amount says {a}")) lines_total = round(sum(num(i.get("amount")) for i in items), 2) checks_ran = "subtotal" in data and "total_amount" in data if checks_ran:     if abs(lines_total - num(data["subtotal"])) > 0.01:         sum_errors.append(("line_items", f"rows sum to {lines_total}, subtotal says {data['subtotal']}"))     expected = num(data["subtotal"]) + num(data.get("tax_amount")) + num(data.get("shipping_amount"))     if abs(expected - num(data["total_amount"])) > 0.01:         sum_errors.append(("total_amount", f"subtotal + tax + shipping = {expected:.2f}, total says {data['total_amount']}")) if checks_ran and not sum_errors:     # Every sum checks out, so fuzzy matches on numbers are formatting ("$1,014.00" vs 1014), not misreads     flags = [(path, reason) for path, reason in flags if path not in fuzzy_numbers] flags += sum_errors if flags:     send_to_review(data.get("invoice_number"), flags)  # your review queue else:     post_to_erp(data)                                   # your system of record 


Now the agent's report has to be specific. "Extracted 10 invoices" becomes a list: what was posted, what went to review, and for each review item the field, the page, and the reason.

How each failure gets caught

Invoice

What went wrong

What catches it now

3

Scan, 8 read as 3

A misread shows up as a fuzzy_match on total_amount, often with a low OCR recognition score, and the total no longer equals subtotal + tax + shipping.


5

Table split across pages

Parsing keeps tables and reading order instead of flattening them. If a row still goes missing, the subtotal check catches it.

7

Invented PO number

po_number isn't required, so it comes back missing instead of invented. If your ERP needs one, route the gap to review.

9

Two invoices in one PDF

Run Split before Extract, so each invoice is extracted on its own.

Invoice 5 is a common failure. On WholeDoc Bench, Nutrient's own whole-document benchmark (Season 1, November 2026), 15 of 19 parser settings returned a table that crosses a page break as one table in fewer than one case in five. Nutrient's Understand and Agentic modes were among the four settings that got it right almost every time.


Split and Classify run on the same API: Split finds where each document starts and ends in a merged PDF, and Classify labels each one before extraction.

What this doesn't fix

Some limits to know before you ship.


  • Confidence is a signal, not a guarantee. A model can misread a scan and still match it to the page. fuzzy_match also fires on correct numbers whose formatting changed: on our clean test invoice, ten correct numbers came back fuzzy. The sums cleared all ten. Text fields and numbers no sum covers still go to review.
  • Your threshold is yours. The docs use 0.7 as an example, not a rule. Validate it against a labeled sample of your own invoices before you automate anything.
  • Test on your documents, not the vendor's. Data Extraction Studio lets you build an evaluation set: your files plus the correct answers. Score each change against it before it ships. Availability depends on your account.
  • Pick the deployment that fits your data. Use the hosted API, run the SDK (Python, Java or .NET) on your own servers, or use Extract Studio, the desktop app for Apple silicon Macs, with your own AI model key or a local model. Does your agent call tools over MCP? Nutrient's hosted MCP server offers the same extraction as a tool.

Takeaways

  • An agent's "done" is a claim. Make it carry evidence.
  • Parse first, reason second. Don't hand a model flattened text and hope.
  • Only mark fields required if every document really has them.
  • Route on match labels and confidence, and back them with arithmetic you control.


Try it on your messiest invoice. The free plan includes $5 of usage a month, and the guides cover schemas, citations, and async runs.