Sub topic 13
Extracting structured data from images and PDFs
This chapter assumes you can already send an image or PDF as a content block and read the text reply. Here the goal is different. You want a JSON object that your code can trust, not a paragraph of prose.
The pattern
A model reads the visual input and writes text. To get structured data, you tell it the exact shape you want and then check what comes back. The model is not a parser. It can drop a field, invent a value, or wrap the JSON in extra words, so your code must verify the output.
Write a schema into the prompt
Describe each field, its type, and what to do when a value is missing. Telling the model to use null for unreadable values is important. Without it, the model tends to guess.
A worked example: invoice extraction
This script sends an invoice image and asks for fixed fields. It then checks that the line items add up to the total.
import base64
import json
import mimetypes
import anthropic
PROMPT = """Extract data from this invoice. Reply with JSON only, no other text.
Schema:
{"vendor": string, "invoice_date": "YYYY-MM-DD",
"line_items": [{"description": string, "amount": number}],
"total": number}
Use null for any value you cannot read clearly. Do not guess."""
def extract_invoice(path):
media_type, _ = mimetypes.guess_type(path)
with open(path, "rb") as f:
data = base64.standard_b64encode(f.read()).decode("utf-8")
client = anthropic.Anthropic()
message = client.messages.create(
model="MODEL_NAME", # replace with a vision-capable model
max_tokens=1024,
messages=[{
"role": "user",
"content": [
{"type": "image",
"source": {"type": "base64", "media_type": media_type, "data": data}},
{"type": "text", "text": PROMPT},
],
}],
)
text = message.content[0].text.strip()
if text.startswith("```"): # strip a markdown fence if the model adds one
text = text.strip("`").removeprefix("json").strip()
return json.loads(text)
def check(invoice):
problems = []
items = invoice.get("line_items") or []
amounts = [i["amount"] for i in items if i.get("amount") is not None]
if invoice.get("total") is None:
problems.append("total is missing")
elif amounts and abs(sum(amounts) - invoice["total"]) > 0.01:
problems.append(f"items sum to {sum(amounts)}, total says {invoice['total']}")
return problems
invoice = extract_invoice("invoice.png")
print(invoice)
print(check(invoice) or "checks passed")For a PDF, swap the image block for a document block with application/pdf, as shown in the native PDF chapter. The prompt and the checks stay the same.
Validate more than the syntax
json.loads only proves the text is valid JSON. It says nothing about whether the values are right. Add checks that match your data:
- Required fields are present.
- Dates parse and fall in a plausible range.
- Line items sum to the total, as in the example.
- Currency codes or categories belong to a known list.
A failed check does not tell you which field is wrong. Route those documents to a retry or to a person.
Common errors
- Prose around the JSON. Ask for "JSON only" and strip fences before parsing. If your provider offers structured output or tool-call schemas, use them. They constrain the format far better than a prompt does.
- Invented values. Models fill blanks with plausible text. Allow
nulland test for it. - Misread small text. Digits such as 3 and 8 are easy to confuse in low-resolution scans. Render at a higher DPI or crop the region.
- Wrong table rows. In long tables, rows can merge or repeat. The sum check catches many of these.
Exercise
An extraction returns valid JSON, but the line items sum to 410.00 and the total field says 401.00. What is the likely cause, and what should your code do?
Show answer
The model probably misread a digit, since 410 and 401 are transposed digits. The JSON is syntactically valid, so only a content check like the sum comparison catches it. The code should flag the document, then retry with a higher-resolution image or send it to human review. It should not save the values.