esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
Let’s talk

I’ll build the agent for it.

How Do You Extract Structured Data From Documents and Images?

How to pull fields like totals and dates out of scanned invoices and photos, and how to check the result, for your AI interview.

In short

Read the page with a document service or a vision model, ask for the fields in one fixed shape, then check each value in code. The shape check does not catch a wrong number, so any failed check goes to a person.

12 min readIntermediateOccasional · estimateFacts checked 27 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

Structured extraction means pulling fields like the invoice number, date and total out of a scanned document into a fixed shape. I would read the page with a document service or a vision model, then check the result in code. A schema checks the shape, and the numbers still need checks of their own. So I check that the line items add up to the total and that the date is real. Anything that fails goes to a person, and every field keeps its page reference.

What is structured extraction, in plain words?

A supplier sends you a scanned invoice, a photo of a delivery note, or a PDF with a table in it. Structured extraction means reading that page and writing out a fixed set of fields: the invoice number, the date, the supplier, the currency and the total. Your accounts system can then store those fields, search them and add them up.

Think of an accounts clerk who copies totals from paper invoices into the ledger. The clerk reads the page, writes the same boxes every time, and flags anything that looks wrong. An AI system does that job at a far larger volume, so the checking step matters as much as the reading.

Anthropic's PDF guide lists converting document information into structured formats as a sample use. Amazon's Textract Insights lists turning invoices into structured records for downstream systems. Insights is currently available only in two US AWS regions.

Key words

OCR
Optical character recognition: reading the letters in a picture so a computer can use them as text.
Field
One named piece of data, like the total or the due date.
Schema
The fixed shape the output must follow: field names, types, and which fields are required.
JSON
A plain text format for structured data, written as named fields and values.
Confidence score
A number a reader gives for how sure it is about a value.

What are the two ways to read the page?

The first route is a document service: a product built to read scans with OCR. Amazon Textract is one example. Its core service detects printed text, handwriting, forms, tables and layout on scans. Microsoft's Azure Document Intelligence is the same kind of product.

  • “Azure Document Intelligence provides high-accuracy and reliable deterministic extraction from structured documents.”

    Microsoft Azure

  • “Content Understanding also offers LLM-powered analyzers for complex, unstructured, and multimodal content.”

    Microsoft Azure Content Understanding

Microsoft's wider Content Understanding service also offers LLM-powered analyzers for messier material.

The second route is a vision model: a language model that looks at the page image and writes the fields itself. It needs no separate reading step, so it can use the whole page at once. The cost is that it can make mistakes, and Anthropic's vision guide warns about low-quality, rotated or very small images (under 200 pixels). So the first route suits forms with a fixed layout, and the second suits messier mixed material.

For PDFs, OpenAI's guide says the API extracts both the text and the page images, and sends both to models that accept image inputs. Anthropic's PDF guide says each page is processed as an image.

Two routes into one checked record

Scanned invoice

a photo or PDF from a supplier

Route A: document service

Reads text and tables

gives a confidence score per field

Route B: vision model

Model reads the page

may misread small or rotated scans

Fields in a fixed shape

a field not found is left empty

Your code checks

Lines add to total

even a one-cent gap is caught

Date and ID are real

parses dates, checks formats

Posted

every check passed, page kept

A person checks

any failed check or low score

  1. 1The scan goes to a document service that reads the text and tables.
  2. 2The same scan can go to a vision model that reads the page as a picture.
  3. 3The service's output is turned into one set of fields.
  4. 4The model's answer is put into the same set of fields.
  5. 5The fields go to your code, which runs the checks.
  6. 6Every check passed, so the record is posted.
  7. 7A failed check or low score sends it to a person.
Two routes read the same scan, a document service or a vision model. Both end in one fixed set of fields. Code checks the numbers before anything is posted, and a failed check goes to a person.

Does a schema make the numbers right?

A schema tells the model the shape: which fields exist, what type each one is, and which ones are required. Structured outputs from Anthropic and OpenAI both keep the reply to a schema you supply. That cuts out broken JSON and missing fields. A refusal or a cut-off reply can still break that, so the code has to handle those cases too. It does not check the numbers. A model can still copy the wrong figure from the page into a perfectly shaped total.

  • “Structured Outputs constrains completed, non-refusal model output to your supplied JSON Schema.”

    OpenAI

  • “Your application still needs to handle refusals, incomplete responses, and API errors, and validate any business rules that the schema does not express.”

    OpenAI

Anthropic's structured outputs make the same promise about valid, schema-matching replies. Its SDK helpers, the code libraries your app uses to call the service, transform a schema that uses unsupported features before sending it. They move a limit such as a maximum into the field's description. The page says that a helper which validates responses still enforces every constraint in your code.

Tip

In an interview, say it plainly: the schema guards the shape, and your code guards the numbers.

How do you make the output reliable?

Five habits turn a plausible extraction into one you can trust, and a clever prompt is not among them.

  1. 1

    Let a field stay empty

    If the total is not on the page, the schema should allow an empty value, so the model is not forced to invent one.

  2. 2

    Keep a page reference

    Store the page and the spot each value came from. Textract Insights, for one, returns each field you define with a confidence score and its location on the page, so a reviewer can jump straight there.

  3. 3

    Check the numbers in code

    Line items must add up to the total, dates must read as real dates, and IDs must match their format. Code runs these checks on every record.

  4. 4

    Send failures to a person

    Any failed check, or a low confidence score, goes to a review queue. Keep the queue short enough that a person can really read it.

  5. 5

    Measure on real files

    Label a sample of documents by hand and score each field. Measure again when a supplier changes its layout, because a template change can break a route that worked last month.

Know the limits and say them out loud. Anthropic's PDF guide warns that dense pages, with small type, complex tables or heavy graphics, can fill the context window (the amount of text a model can read at once) before the page limit is reached. Each page also goes in as an image, so a blurry scan gives the model a blurry page.

What does a check in code look like?

Here is a small made-up check for two invoices that an AI extractor returned. The model is not called here. The code does the checking. It uses Decimal, a number type for exact amounts, so money adds up exactly. Ordinary floating-point numbers, the usual number type in most programs, can drift by a fraction of a cent.

Python
# A made-up check for two invoices an AI extractor returned. The model is not called here.
from datetime import date
from decimal import Decimal

def check_invoice(inv):
    problems = []
    lines_total = sum(Decimal(line["amount"]) for line in inv["lines"])
    if lines_total != Decimal(inv["total"]):
        problems.append(f"lines add to {lines_total}, total says {inv['total']}")
    try:
        date.fromisoformat(inv["date"])
    except ValueError:
        problems.append(f"date {inv['date']} is not a real date")
    if not problems:
        return "POST: " + inv["number"]
    return "REVIEW: " + inv["number"] + " (" + "; ".join(problems) + ")"

inv1 = {"number": "INV-20417", "date": "2026-10-14", "total": "4280.00",
        "lines": [{"amount": "3100.00"}, {"amount": "1180.00"}]}
inv2 = {"number": "INV-20418", "date": "2026-13-02", "total": "912.50",
        "lines": [{"amount": "812.50"}, {"amount": "90.00"}]}
print(check_invoice(inv1))
print(check_invoice(inv2))

Output

POST: INV-20417
REVIEW: INV-20418 (lines add to 902.50, total says 912.50; date 2026-13-02 is not a real date)

The first invoice posts. The second goes to a person: its lines add to 902.50 but the total says 912.50, and its month is 13. Neither check needs the model, so they are cheap to run on every record.

How would you run this for 40,000 invoices a month?

A mid-size distributor gets about 40,000 supplier invoices a month. Many arrive as phone photos from its branches. Finance wants them posted without retyping, and an auditor must be able to trace every number back to its page.

  1. 1

    Sort by route first

    Send clean PDFs from regular suppliers to the document service, where output is more predictable. Measure before you decide.

  2. 2

    Use a vision model for the rest

    Phone photos and odd layouts go to a vision model, behind the same schema and the same code checks.

  3. 3

    Post only what passes

    Records that pass every check are posted. The review queue is sized to what the finance team can read each day.

  4. 4

    Keep the trail

    Store the page image, the extracted fields and each check result against the invoice number.

  5. 5

    Re-measure each month

    Score a fresh labelled sample. A new supplier template can break a route that worked last month.

What does the interviewer want to hear?

A strong answer covers

  • Name the two routes: a document service, or a vision model.
  • Define the schema, and let a field stay empty when it is not found.
  • Say the schema checks the shape, and code checks the numbers.
  • Show the checks: totals, dates, IDs, and a page reference per field.
  • Send failures and low scores to a person.
  • Measure accuracy on a labelled sample, and again for each supplier.

Common traps

  • Trap"The schema makes the data correct."

    BetterThe schema makes the shape correct. Code checks the values, and a person sees every failure.

  • Trap"A bigger model reads any scan."

    BetterA bigger model still misreads small or rotated scans. Test on your own documents first.

  • Trap"Just ask it for the total."

    BetterAsk for the total in a schema that allows empty, then check it against the line items in code.

Can you spot the bad record?

Spot the bad record

Four invoices came back from the extractor. Which one should not be posted without a person?

Quick check

The extractor returns valid JSON, but the total is 0.00 on a document that clearly shows 1,284.00. What is the best first fix?

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q130How do you handle tables, PDFs and images?12 min
  2. Q085How do you get reliable JSON output?12 min
  3. Q086JSON mode vs strict schema structured outputs?10 min
  4. Q478Parse and validate LLM JSON, retrying on failure.11 min
  5. Q452Native multimodal vs pipeline approach?12 min
  6. Q455How do you evaluate multimodal outputs?14 min

Learn it in depth

Last updated on 27 November 2026

Building a document workflow that reads invoices or forms?

I design and build AI products and agents, including the screens and the system behind them. Book a short call and tell me which documents you need to read and where the data has to go.