{"slug": "ai-data-extraction-three-approaches-compared-with-code", "title": "AI data extraction: Three approaches compared, with code", "summary": "Nutrient published a comparison of three approaches to AI data extraction from documents — templates and rules, trained machine learning models, and LLM schema extraction — with Python and Node.js walkthroughs of the schema-extraction method. The article states that templates require a separate setup per layout and fail silently when a sender changes its layout, trained ML models need hundreds of labeled documents per document type, and LLM schema extraction needs only a JSON Schema but risks returning made-up values for fields absent from the document. Nutrient's Data Extraction API is presented as returning structured output with per-field confidence scores and page locations for each extracted value.", "body_md": "# AI data extraction from documents: Templates, ML, and LLMs compared\n\n## Table of contents\n\nStructured output with per-field confidence scores through the Nutrient Data Extraction API.\n\nAI data extraction is the use of machine learning models to pull structured data — such as invoice numbers, dates, totals, and line items — out of unstructured documents like PDFs, scans, and photos. You get JSON or a database row back instead of a page of text, and an API like [Nutrient Data Extraction API](https://www.nutrient.io/api/data-extraction-api/) also tells you where on the page each value came from.\n\nThere are three common ways to extract data from documents: templates and rules, trained machine learning (ML) models, and schema extraction with large language models (LLMs). Only the last two use AI, but templates are the baseline they’re compared against. All three can read an invoice. They differ in setup time, cost per page, what breaks them, and what happens when they get a value wrong. Below, we compare the three and then walk through schema extraction in Python and Node.js.\n\n##      The three approaches at a glance \n\n| Approach | How it works | Setup per document type | What breaks it | How you find out it’s wrong | \n|---|---|---|---|---|\n| Templates and rules | Fixed page zones, keywords, and regular expressions on optical character recognition (OCR) text | A template per layout | A sender changes its layout | You don’t; a wrong zone still returns text | \n| Trained ML models | A model learns field locations from labeled examples | Hundreds of labeled documents | New document types, or documents that change over time | A model score, if it exposes one | \n| LLM schema extraction | A model maps the document to fields described in a JSON Schema | A schema, written in minutes | Fields that aren’t in the document, which can lead to made-up values | Citations and confidence per field, if the API returns them | \n\n##      Templates and rules \n\nTemplates are the oldest approach and still the most common. You draw boxes on a known layout and read whatever text lands inside them, or you search the OCR text with keywords and regular expressions. For example, find “Invoice no.” and take the next token.\n\nOn a document that never changes, this works well. It’s fast and cheap, and anyone can read the rules. The trouble starts when a supplier redesigns its invoice and the template doesn’t know anything changed. It reads whatever now sits in the old box, maybe the tax line, and passes it on as the total. Nobody notices until the numbers don’t reconcile. Multiply that by a few hundred suppliers, and keeping templates working becomes someone’s full-time job.\n\nIf most of your volume comes from a handful of layouts you control, like your own forms, templates are hard to beat.\n\n##      Trained machine learning models \n\nThe next step up is a model trained on labeled examples. Layout-aware models look at both the text and where it sits on the page, so they learn that the total is usually near the bottom right, under a column of amounts, even when it moves around from one supplier to the next.\n\nThe tradeoff is training data. Someone has to label hundreds of documents for each document type, and when a new type shows up or the existing ones slowly change, they label again and retrain. On the plus side, most of these models give you a score per field, so you have something to route on.\n\nIt’s a good fit if you already have labeled data for a few high-volume document types and someone on the team who can retrain the models.\n\n##      LLM schema extraction \n\nSchema extraction skips both the templates and the labeling. You describe the fields you want in a JSON Schema, and a model finds them on the page, wherever they are. A new field is one more line in the schema. A new document type is a new schema.\n\nThe risk is that a generative model returns an answer even when the document doesn’t contain one. Ask for a due date on an invoice that doesn’t have one, and you may get a believable date in valid JSON. Nothing in the output looks wrong. Our post on [catching hallucinated values in document extraction](https://www.nutrient.io/blog/extraction-hallucination-detection/) explains why this happens.\n\nWhen you evaluate an LLM extraction API, check what evidence comes back with each value: where on the page it was found, how closely it matched the source text, and how confident the model is. With that, your code can let clean values through and send doubtful ones to a person.\n\n##      Extract data with Nutrient Data Extraction API in Python and Node.js \n\nNutrient Data Extraction API has an [extract endpoint](https://www.nutrient.io/guides/dws-data-extraction/extract/) that takes a document and a JSON Schema and returns typed data. Both samples below set `includeCitations`, so each value comes with its page number, bounding box, and match label, and usually a confidence score as well. You’ll need an API key from the Nutrient dashboard, stored in the `NUTRIENT_API_KEY` environment variable.\n\nBoth samples send the same minimal invoice schema: an invoice number, an invoice date, and a total amount, with the number and the total required.\n\n###      Python \n\nThe Python version needs the `requests` package (`pip install requests`):\n\n###      Node.js \n\nThis version uses `fs.openAsBlob`, which needs Node.js 19.8 or later. It also uses top-level `await`, so save it as `extract.mjs`:\n\n###      Reading the result \n\nBoth scripts print one line per field: the field name, its value, the match label, the confidence, and the page number. For the second field below, that line is `total_amount 1547.5 fuzzy_match 0.76 1`.\n\nThe values are under `output.data`, and each one has a citation under `output.metadata`. Here’s a trimmed response for a sample invoice:\n\n`match` says how the value was tied to the page. The main labels are `id_match` (an exact match with the source text), `fuzzy_match` (close but not identical), and `not_found` (the API couldn’t find the value anywhere on the page). The guide also lists `id_match_multiblock`, for values assembled from several blocks, and `id_match_partial`, for values only partly matched. A sensible starting rule is to send every `fuzzy_match`, `id_match_partial`, and `not_found` to a person. In this response, `total_amount` is a `fuzzy_match` at 0.76, so that rule would send it to review.\n\n`confidence` is a score between 0 and 1. Higher means the value is more likely to be right, but it isn’t a guarantee. Read it alongside `match`, and test any threshold on a labeled sample of your own documents before you rely on it. A missing confidence value means no score was available, not that the score is low.\n\nThe [citations and confidence](https://www.nutrient.io/guides/dws-data-extraction/extract/citations-and-confidence/) guide lists every field and match label, and our post on [confidence scores](https://www.nutrient.io/blog/document-extraction-confidence-scores/) covers how to set thresholds. For a closer look at what a single extracted field should contain, see our post on [intelligent data extraction](https://www.nutrient.io/blog/intelligent-data-extraction/).\n\n##      Run the same extraction from Claude or Codex with Nutrient MCP \n\nIf you already work in Claude, Claude Code, or Codex, you don’t have to write the request yourself. [Nutrient MCP](https://www.nutrient.io/mcp/) is a hosted Model Context Protocol server that lets your assistant extract fields, parse documents to Markdown, and classify documents. There’s nothing to install and no API key to manage. You add the endpoint and sign in with your Nutrient account.\n\nIn Claude Code, run:\n\nThen type `/mcp`, choose **nutrient**, and select **Authenticate**. After that, you can ask in plain words, for example: “Extract the invoice number, date, and total from `invoice.pdf`, with citations.” Requests use your organization’s Nutrient access and plan. The [Nutrient MCP setup](https://www.nutrient.io/guides/dws-processor/getting-started/mcp-server/) guide covers Codex as well.\n\n##      How AI data extraction pricing works \n\nTemplates are nearly free to run. What they cost is the time to build them and keep them working. Training a model takes hours of labeling up front, and running and retraining it takes servers.\n\nAPIs charge per page. On Nutrient Data Extraction API, each page costs a parse charge that depends on the processing mode, plus a charge for the extraction itself:\n\n| Processing mode | Typical use | \n|---|---|\n| `text` | Born-digital PDFs with a clean text layer | \n| `structure` | OCR-backed structured extraction | \n| `understand` (default) | Tables, forms, and scans | \n| `agentic` | Difficult layouts that need a vision language model | \n\nThe modes are listed from cheapest to most expensive. For a PDF exported straight from accounting software, `text` mode is usually enough, but scans and documents with dense tables usually need `understand`. The free plan includes usage that refreshes every month, so you can try it on your own files before paying. Current rates are in the [pricing](https://www.nutrient.io/guides/dws-data-extraction/pricing/) guide.\n\nIf your documents can’t leave your own infrastructure, Nutrient’s [Data Extraction SDK](https://www.nutrient.io/sdk/ai-document-processing/) runs on your servers. It’s available today in the Nutrient Python SDK and Java SDK.\n\n##      Which approach should you use? \n\nMost teams use more than one. As a rough guide:\n\n- If a few fixed layouts make up most of your volume, templates are still the cheapest and most predictable choice.\n- If you have a few document types, labeled data for them, and an ML team to look after it, a trained model makes sense.\n- If documents come from many senders, layouts keep changing, or new document types arrive every quarter, schema extraction adapts without retraining, and per-field citations show you which values to check.\n\nA common setup is rules for the documents you control, schema extraction for everything else, and a review queue for anything with low confidence.\n\n##      FAQ \n\nAI data extraction uses machine learning models to pull structured data — such as names, dates, totals, and line items — out of unstructured documents like PDFs, scans, and photos. The result is JSON or a database row instead of a page of text. Nutrient Data Extraction API does this from a JSON Schema and returns a citation for every value.\n\nOCR turns an image of text into characters. AI data extraction works out which of those characters are the invoice number or the total, and it returns them as named, typed fields. For scanned documents, most extraction pipelines run OCR first.\n\nLLMs handle varied layouts well, but they can return a plausible value that isn’t in the document. Use an API that ties each value to the source — with a page location, a match label, and a confidence score — and send anything ungrounded or low-confidence to review.\n\nSchema extraction doesn’t need training data. You describe the fields in a JSON Schema, and the model finds them. Trained ML models do need labeled examples for every document type.\n\nYes. Claude and Codex can extract document data through an MCP server that connects them to an extraction API. Nutrient MCP adds extraction, parsing, and classification to Claude, Claude Code, and Codex, and it returns fields with citations and confidence from Nutrient Data Extraction API.", "url": "https://wpnews.pro/news/ai-data-extraction-three-approaches-compared-with-code", "canonical_source": "https://www.nutrient.io/blog/ai-data-extraction/", "published_at": "2026-12-03 09:00:00+00:00", "updated_at": "2026-12-03 15:16:08.408064+00:00", "lang": "en", "topics": ["artificial-intelligence", "machine-learning", "large-language-models", "ai-tools"], "entities": ["Nutrient", "Nutrient Data Extraction API", "Python", "Node.js"], "also_reported_by": [], "takeaway": "Describe extraction fields in a JSON Schema and have an LLM map the document to them instead of drawing per-layout templates or labeling hundreds of documents, but require per-field citations and confidence scores because a generative model will return a believable value for a field the document doe", "recommendation": {"advice": "Use LLM schema extraction for variable document layouts, but gate results on per-field citations and confidence scores so values invented for fields absent from the document are caught before they reach downstream systems.", "playbook": "output-verification", "playbook_url": "https://wpnews.pro/playbooks/output-verification"}, "alternates": {"html": "https://wpnews.pro/news/ai-data-extraction-three-approaches-compared-with-code", "markdown": "https://wpnews.pro/news/ai-data-extraction-three-approaches-compared-with-code.md", "text": "https://wpnews.pro/news/ai-data-extraction-three-approaches-compared-with-code.txt", "jsonld": "https://wpnews.pro/news/ai-data-extraction-three-approaches-compared-with-code.jsonld"}}