# 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.

AI and LLM interview question Q448, Multimodal and newer topics. Intermediate, occasional (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/extract-structured-data-from-documents-and-images

## Say it in 30 seconds

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.

## Say it in 2 minutes

Structured extraction means pulling named fields out of a messy document, like the invoice number, date, supplier and total from a scanned PDF, and writing them into a fixed shape that your systems can store. Most of the real work sits around the model call: getting the page read properly and checking the answer.

There are two main routes. A document service reads the text, tables and layout, and gives back each value with a confidence score and its place on the page. A vision model reads the page as a picture and fills in the fields itself. Both can return output that follows a schema, but a schema only settles the shape. A total can have the right shape and still be the wrong number.

So I check in code. Do the line items add up to the total? Is the date a real date? Does the tax ID match its format? Any failure, or a low score, goes to a person's review queue. Every value keeps its page reference, so a reviewer can check it in seconds. Then I measure accuracy on a labelled sample each month, because a route that works for one supplier can fail on another's layout.

In short, the best route depends on the documents. Clean, fixed forms suit a document service. Messy, mixed packets may suit a model better, but I test on real files before trusting either one.

## 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.

- **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.

*Diagram, Two routes into one checked record: 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.*
1. The scan goes to a document service that reads the text and tables.
2. The same scan can go to a vision model that reads the page as a picture.
3. The service's output is turned into one set of fields.
4. The model's answer is put into the same set of fields.
5. The fields go to your code, which runs the checks.
6. Every check passed, so the record is posted.
7. A failed check or low score sends it 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. **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. **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. **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. **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. **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:

```text
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. **Sort by route first:** Send clean PDFs from regular suppliers to the document service, where output is more predictable. Measure before you decide.
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. **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. **Keep the trail:** Store the page image, the extracted fields and each check result against the invoice number.
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." Better: The schema makes the shape correct. Code checks the values, and a person sees every failure.
- Trap: "A bigger model reads any scan." Better: A bigger model still misreads small or rotated scans. Test on your own documents first.
- Trap: "Just ask it for the total." Better: Ask 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?

A. Number INV-20431, date 2026-10-02, total 1,500.00, lines 1,000.00 and 500.00.
B. Number INV-20432, date 2026-10-03, total 640.25, lines 400.00 and 240.00.
C. Number INV-20433, date 2026-10-04, total 2,310.00, lines 2,310.00, purchase order number left empty.
D. Number INV-20434, date 2026-10-31, total 77.00, lines 60.00 and 17.00.

**Answer:** B. Its lines add to 640.00, but the total says 640.25, so a person checks it. The other three pass. The empty purchase order number is allowed, because a missing field should stay empty rather than be guessed.

**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?

A. Use a bigger model
B. Check the total against the line items in code, and send any mismatch to a person
C. Raise its temperature, which controls how random its word choices are
D. Remove the schema, since it adds limits

**Answer:** B. A 0.00 passes the shape check, so only a value check catches it. Adding up the line items and comparing them to the total catches it. A bigger model or a higher temperature does not close that gap.

## Can you answer these from memory?

**Flash cards**

- **What is structured extraction?** Pulling named fields out of a document into a fixed shape your systems can store.
- **What are the two routes?** A document service that reads text and tables, or a vision model that reads the page image.
- **Does a schema check the values?** No. It checks the shape. Code has to check the numbers, like totals and dates.
- **Why allow an empty field?** So the model can say not found, instead of being forced to guess.
- **What goes to a person?** Any failed check, and any low confidence score, goes to a review queue.
- **What does a page reference do?** It lets a reviewer see the exact spot a value came from, in seconds.

## Likely follow-up questions

- Q130 How do you handle tables, PDFs and images? https://designervenkat.online/interview/ai/how-do-you-handle-tables-pdfs-and-images
- Q085 How do you get reliable JSON output? https://designervenkat.online/interview/ai/how-to-get-reliable-json-from-an-llm
- Q086 JSON mode vs strict schema structured outputs? https://designervenkat.online/interview/ai/json-mode-vs-strict-schema-structured-outputs
- Q478 Parse and validate LLM JSON, retrying on failure. https://designervenkat.online/interview/ai/parse-and-validate-llm-json-retrying-on-failure
- Q452 Native multimodal vs pipeline approach? https://designervenkat.online/interview/ai/native-multimodal-vs-pipeline-approach
- Q455 How do you evaluate multimodal outputs? https://designervenkat.online/interview/ai/how-do-you-evaluate-multimodal-outputs

## Learn it in depth

- [Structured Output](https://designervenkat.online/learn/ai-engineering/structured-output)
