Sub topic 13
Extracting structured data from images and PDFs
This chapter assumes you can already send an image or PDF to a multimodal model with content blocks, as covered in earlier chapters. It also assumes basic Python, JSON, and familiarity with tokens. Here you will turn a document into validated data your program can use.
Why extraction needs more than a good prompt
Asking a model "what is on this invoice?" gives you prose. Code needs fields with known names and types: an invoice number, a date, a list of line items, a total. Extraction means asking the model for those fields in a fixed shape, then checking the result before you trust it.
Models read visual input well but not perfectly. They can misread a digit, skip a row in a long table, or invent a value for a field that is blank on the page. A reliable pipeline treats the model output as untrusted input, the same way you would treat a form submitted by a user.
Step 1: Define the schema first
Write the target shape as code before you write the prompt. A schema gives you one source of truth for the prompt, the parser, and the validator. This example uses pydantic v2 (pip install pydantic anthropic).
from pydantic import BaseModel
class LineItem(BaseModel):
description: str
quantity: float
unit_price: float
amount: float
class Invoice(BaseModel):
invoice_number: str | None
date: str | None # ISO 8601, for example 2026-03-14
currency: str | None
line_items: list[LineItem]
total: float | NoneTwo design choices matter here.
- Fields that may be missing from the page are typed as
str | Noneorfloat | None. If a field cannot be null, the model is pushed to guess when the page has no value. - Dates and currencies have a stated format. "03/04/2026" is ambiguous, so the prompt will ask for ISO 8601.
Step 2: Ask for the shape, and allow "not present"
The prompt should say what each field means, what format to use, and what to do when a value is missing or unreadable. Put the document first and the instructions after it, as in the earlier chapter on prompt placement.
import base64
import json
import mimetypes
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
INSTRUCTIONS = """Extract the invoice into JSON with exactly these keys:
invoice_number (string or null), date (YYYY-MM-DD or null),
currency (3-letter code or null), total (number or null),
line_items (list of objects with description, quantity, unit_price, amount).
Rules:
- Copy numbers exactly as printed. Do not calculate or correct them.
- Use null for any value that is missing or not legible. Never guess.
- Return only the JSON object, with no commentary."""
def load_as_base64(path):
media_type, _ = mimetypes.guess_type(path)
if media_type is None:
raise ValueError(f"Cannot determine media type for {path}")
with open(path, "rb") as f:
return media_type, base64.standard_b64encode(f.read()).decode("utf-8")
def document_block(path):
media_type, data = load_as_base64(path)
kind = "document" if media_type == "application/pdf" else "image"
return {"type": kind, "source": {"type": "base64", "media_type": media_type, "data": data}}
def ask_model(path, extra_messages=None):
messages = [
{
"role": "user",
"content": [document_block(path), {"type": "text", "text": INSTRUCTIONS}],
}
]
if extra_messages:
messages += extra_messages
reply = client.messages.create(
model="MODEL_NAME", # replace with a vision-capable model from the provider's docs
max_tokens=2048,
messages=messages,
)
return reply.content[0].textThe rule "Copy numbers exactly as printed. Do not calculate or correct them" is deliberate. If the model silently fixes a total so that it matches the line items, you lose the signal that the document or the reading was wrong. You want the discrepancy visible, so your own check can catch it.
Step 3: Parse, validate, and check business rules
Validation has three layers, and each catches different errors.
| Layer | Question | Example failure |
|---|---|---|
| Syntax | Is it valid JSON? | The model wraps the JSON in a Markdown fence or adds a sentence before it |
| Schema | Are keys and types right? | `quantity` returned as the string "two" |
| Business rules | Do the values make sense together? | Line items sum to 118.00 but the total says 181.00 |
Schema validation cannot detect a misread digit, because 181.00 is a valid number. Business rules can, because a document usually contains redundant information. Totals equal sums, dates fall in a plausible range, and quantity times unit price equals amount.
from pydantic import ValidationError
# Invoice and LineItem are defined in Step 1; ask_model in Step 2.
def parse_json(text):
text = text.strip()
if text.startswith("```"):
text = text.strip("`")
if text.startswith("json"):
text = text[4:]
return json.loads(text)
def check_rules(inv):
problems = []
for i, item in enumerate(inv.line_items):
if abs(item.quantity * item.unit_price - item.amount) > 0.01:
problems.append(f"line {i + 1}: quantity * unit_price does not equal amount")
if inv.total is not None and inv.line_items:
subtotal = sum(item.amount for item in inv.line_items)
# A total may include tax, so only flag totals below the subtotal.
if inv.total < subtotal - 0.01:
problems.append(f"total {inv.total} is less than line item sum {subtotal}")
return problems
def extract_invoice(path, max_retries=2):
extra = None
last_error = "unknown"
for _ in range(max_retries + 1):
raw = ask_model(path, extra)
try:
invoice = Invoice.model_validate(parse_json(raw))
except (json.JSONDecodeError, ValidationError) as exc:
last_error = f"Output was not valid: {exc}"
else:
problems = check_rules(invoice)
if not problems:
return invoice
last_error = "; ".join(problems)
extra = [
{"role": "assistant", "content": raw},
{
"role": "user",
"content": "That output failed validation: "
f"{last_error}. Re-read the document and return corrected JSON only.",
},
]
raise RuntimeError(f"Needs human review. Last problem: {last_error}")
invoice = extract_invoice("invoice.pdf")
print(invoice.invoice_number, invoice.total)The retry sends the previous answer back along with the specific failure. A targeted message such as "line 3: quantity * unit_price does not equal amount" gives the model something concrete to re-check. After a small, fixed number of attempts the record goes to a person. Unbounded retries cost money and often repeat the same mistake.
Getting stricter output from the API
Asking for JSON in the prompt works but is not guaranteed. Many providers offer stronger options, and you should check your provider's documentation for what the chosen model supports.
- Tool or function calling. You describe the schema as a tool, and the model returns arguments that follow it. This usually reduces syntax errors, though the values can still be wrong.
- JSON-schema response formats. Some APIs constrain decoding to a schema you supply.
- Prompt-only JSON. This is the most portable option. It needs the parsing and retry code above.
Whichever you pick, keep the schema validation and business rules. Constrained output guarantees shape, not correctness.
Choosing the input for extraction
The input form changes what extraction can get right.
- Text-heavy PDFs with a real text layer. Extracting the text yourself and sending it gives exact characters, with no misreading. Native PDF input or page images add layout awareness, such as which number sits under which column heading.
- Scans and photos. There is no text layer, so the model must read pixels. Use sufficient resolution and consider cropping to the relevant region.
- Long tables. Rows can be skipped or merged. Extract page by page, or table by table, and combine the results in code. Add a rule that compares your row count with a count printed on the document, when one exists.
- Mixed documents. Send text and page images together when layout and exact characters both matter. This raises token cost, so use it only for pages that need it.
Failure modes to design for
- Invented values. A blank field gets a plausible answer. Counter with explicit nullable fields and the "never guess" rule.
- Misread characters.
0versusO,1versusl, and5versusSfail often in small or low-contrast print. Counter with higher resolution, cropping, and checksums such as totals or ID check digits. - Skipped or duplicated rows in long tables. Counter with row-count checks and per-page extraction.
- Format drift. Dates and decimal separators vary by locale: "1.234,50" means 1234.50 in many countries. State the expected format and normalize in code.
- Instructions inside the document. A scanned page can contain text such as "ignore previous instructions". Treat extracted text as data. Never pass extracted values into a prompt that can trigger actions without a check.
Measure before you trust it
Keep a small set of documents with known correct values, called a gold set. Run your pipeline on it after every change to the prompt, schema, model, or image preprocessing. Compare field by field and report accuracy per field, not one overall score. A pipeline that gets invoice numbers right 99% of the time and totals right 90% of the time needs different fixes for each. Include hard cases in the gold set, such as skewed scans, small print, and missing fields.
Exercise
Your extraction returns valid JSON that matches the schema, but a total reads 1,810.00 when the page shows 181.00. Which validation layer would catch this, what check would you add, and why does the prompt say not to correct numbers?
Show answer
Syntax and schema validation both pass, because 1810.0 is a valid number. Only a business-rule check can catch it, for example comparing the total with the sum of the line item amounts (plus tax if the document has a tax field). The prompt says to copy numbers as printed so that a misread value stays visible and fails the rule check. If the model silently adjusted numbers to look consistent, errors would be hidden instead of flagged.
Exercise
A scanned multi-page table sometimes loses rows. Name two changes that reduce this and one check that detects it.
Show answer
Extract page by page (or table by table) instead of in one request, and crop or raise the resolution so each row is legible. To detect lost rows, compare the number of extracted rows with a row count or total printed on the document, or compare the sum of the extracted amounts with the stated total.