Multimodal: images, documents, PDFs
How a model reads a picture, what it reads well and badly, and how to get line items out of a scanned invoice without trusting a single number you have not checked
You photograph an A4 invoice at 4000x3000 pixels and send it to a model whose maximum long edge is 1,568 px. The invoice's footer has a VAT number in 7-point type. What is the most likely result?
The API chapter sent text. This chapter sends pictures and documents: photos, screenshots, scanned invoices, charts and PDFs. Models are now good enough at reading them that teams replace OCR pipelines wholesale, and bad enough at specific things that some of those replacements quietly corrupt data. You will learn how the input is represented and priced, what models do well and badly, the three ways to get a PDF into a model and when to use each, and the extraction patterns that make results checkable. The lab extracts line items from a scanned invoice with Tesseract and with Claude, scores both against ground truth, and then pulls the tables out of a published paper.
How a model sees an image
A vision-language model does not read pixels one by one. The image is cut into small square patches, each patch is turned into an embedding by a vision encoder, and those embeddings are placed in the model’s context next to the text tokens, where attention treats them like any other token. On Claude each patch is 28x28 pixels and counts as one visual token, so an image costs
ceil(width / 28) x ceil(height / 28) visual tokens
billed at the model’s normal input price. Each model also has a maximum native resolution. On Claude 4.7 and later models (the high-resolution tier) the long edge is capped at 2,576 px and the count at 4,784 visual tokens; on older models it is 1,568 px and 1,568 tokens. Anything larger is scaled down to fit, aspect ratio preserved, before the model sees it.
| Image | Standard tier | High-resolution tier |
|---|---|---|
| 1000x1000 px | 1,296 tokens | 1,296 tokens |
| 1920x1080 px | downsized to 1456x819, 1,560 tokens | not resized, 2,691 tokens |
| 3840x2160 px | downsized to 1456x819, 1,560 tokens | downsized to 2576x1449, 4,784 tokens |
Two consequences. First, the cost of an image is bounded: a 4K photo on claude-sonnet-5-5 ($2 per million input tokens) costs under a cent. Second, resolution you send above the cap is thrown away, and downscaling is exactly what destroys small text. If the detail matters, crop to it and send the crop; if it does not, downsample yourself and save tokens and upload time.
The practical limits from the vision docs: JPEG, PNG, GIF (first frame only) and WebP; up to 8000x8000 px and 10 MB base64-encoded per image on the Claude API; up to 600 images per request (100 on models with a 200k-token context), with a stricter per-image dimension limit once a request has more than 20 images, so resize to at most 3,000 px on each side if you send many. Images go in a user message as content blocks, by base64, by URL, or by a file_id from the Files API:
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": b64}}
{"type": "image", "source": {"type": "url", "url": "https://example.com/scan.png"}}
{"type": "image", "source": {"type": "file", "file_id": "file_011C..."}}
Put images before the question that refers to them. In a multi-turn conversation the model still sees images from earlier turns, and pays for them again on every request unless they sit inside a cached prefix.
What models are good at, and what they are bad at
Current models are strong at:
- Reading printed text in screenshots, photos of documents and slides, including mixed languages.
- Describing scenes, diagrams and UI states, and answering questions about them.
- Layout: which label goes with which value, which column a number is in, that a table continues on the next line. This is where they beat classic OCR most clearly.
- Charts, at the level of trends and approximate values.
- Turning what they read into structure: JSON fields, normalised dates, a currency inferred from context.
The vision docs list the limitations, and every one of them shows up in document extraction:
- Accuracy degrades on low-quality, rotated, or very small images (under about 200 pixels).
- Spatial reasoning is approximate. Coordinates and bounding boxes are estimates, to be verified.
- Counting many small objects is approximate.
- People identification is refused by policy.
Research backs this up. The 2024 paper Vision language models are blind showed leading models failing at tasks a child does, such as counting line intersections or saying whether two circles overlap, and found that the visual detail was present in the encoder but lost on the way to words. The lesson for engineering: a model’s fluency about an image says nothing about whether one specific digit is right. Small text and exact numbers are where errors concentrate, and the errors are plausible values, not obvious garbage.
PDFs: three ways in
A PDF is a container. A digital one (exported from a word processor) has a text layer with exact characters; a scanned one is pictures of pages with no text, or with a text layer from someone else’s OCR. There are three ways to give one to a model.
| Approach | What the model gets | Strong at | Weak at |
|---|---|---|---|
| Text extraction (pdfplumber, pypdf) then text prompt | Characters, no visuals | Cheap, exact characters, any model | Tables lose structure, charts vanish, scans give nothing |
| Rasterise pages (pdftoppm) then send images | Pictures only | You control resolution and which pages | No exact text; pay image tokens per page |
| Native PDF document block | Each page’s extracted text and a rendered image of the page | Tables, charts and text together, one call | Most expensive per page; limits on size and pages |
Native support on the Claude API is a document block:
{"type": "document", "source": {"type": "url", "url": "https://arxiv.org/pdf/1706.03762"}}
# or {"type": "base64", "media_type": "application/pdf", "data": b64}, or {"type": "file", "file_id": ...}
Behind the block, each page is converted to an image and its text is extracted and provided alongside. You pay for both: typically 1,500 to 3,000 text tokens per page depending on density, plus the image cost of each page. Limits: a 128 MB request on the first-party API, 600 pages per request (100 when the context window is under 1M tokens), and no password-protected or encrypted files. The docs’ best practices are short and worth following: put the PDF before the question, use upright pages, refer to pages by the number the PDF viewer shows, split very large documents, and cache the document block if you will ask several questions about it. Citations work on PDFs, returning page ranges for each claim.
Choose by what the document is. A 300-page digital contract you will search: text extraction and retrieval. A 12-page report whose meaning is in its tables and charts: native PDF. A scanned form: images (native PDF gives the same thing plus an empty text layer), or OCR first.
Tables from scanned documents
Tables are where the methods diverge most. Tesseract reads a scanned table row by row and gives you lines of words; reconstructing columns from that output is regex and guesswork, and it breaks on a wrapped description or a merged cell. A vision model sees the grid and assigns each value to its column, which is what you want, and occasionally misreads a digit inside a perfectly structured row, which is what you must catch.
What makes table extraction checkable is that tables carry redundancy. Invoice lines satisfy qty x unit_price = line_total; the line totals sum to the subtotal; subtotal plus tax equals the total. Financial statements foot and cross-foot. A schedule’s rows sum to the column total. Every one of these is a free check on the model’s reading. When a row fails, you have a precise question for a second pass (“re-read line 4 only”) or for a human.
Combining OCR with a model
OCR and a vision model fail differently, which makes them good partners.
- OCR as a hint. Send the image and the OCR text in the same message, labelled as noisy OCR. The model uses the image for layout and the OCR for exact characters, and you can ask it to flag disagreements.
- OCR for location, model for meaning. Tesseract’s TSV output gives each word’s bounding box and confidence. Use it to find the low-confidence regions, crop them, upscale, and send only those crops to the model.
- Model for structure, OCR for verification. The model returns line items; you check each extracted number appears in the OCR text. A number the model produced that OCR never saw is suspect.
- Text layer first. For digital PDFs, extracted text is exact; use the model to interpret it and the page image only where layout matters.
Classic OCR still wins when you need character-exact text with positions at high volume on clean print, at zero marginal cost and with deterministic output. OCR-free models trained end to end, such as Donut (2021), showed that document understanding without a separate OCR step is possible; general vision-language models made it a commodity. Neither made checks unnecessary.
Prompt patterns for extraction
The patterns that hold up in production:
- Schema, not prose. Ask for JSON that matches a schema, and enforce it with structured outputs (
client.messages.parsewith a Pydantic model), as in the structured-output chapter. Use strings for anything you must not reformat, such as invoice numbers with leading zeros. - Permission to say unknown. Make fields nullable and say so: “If a value is not legible, return null; never guess.” Without that, a model fills gaps with plausible values.
- Copy, then compute. Ask for values exactly as printed, then do arithmetic and normalisation in code. A model asked for the total will sometimes add the lines itself instead of reading the printed figure, which hides the very disagreement you want to catch.
- Locate each value. Ask for the page and row of every line. It makes errors easy to find and gives a human reviewer somewhere to look.
- Crop for detail. Small text gets its own image at full resolution. The high-resolution tier helps; cropping helps more.
- Validate, then route. Arithmetic and schema checks pass: post it. They fail: retry the failing rows with a targeted prompt, then send to a human. Track the failure rate as a metric; it is your accuracy estimate in production.
Volume work belongs in the Batch API at half price, and if you ask several questions about one document, put the document in a cached prefix.
Extraction from a degraded scan is a task where model quality decides the result, so the main comparison uses claude-sonnet-5-5: about 2,800 image tokens per invoice at $2 per million input tokens is under a cent of input per call, plus one to three cents of output and thinking at $10 per million, and the 15-page PDF in step 5 is the bulk of the cost at roughly $0.20. Tesseract is free. A local comparison with Ollama is optional in step 4. Work in labs/ai/vision/.
1. Generate an invoice with known contents.
mkdir -p labs/ai/vision && cd labs/ai/vision # from the root of your checkout
uv add anthropic playwright pillow pytesseract pdfplumber "psycopg[binary]"
uv run playwright install chromium # on Linux: uv run playwright install --with-deps chromiumpytesseract is only a wrapper: it calls the tesseract binary from the needs list, which must be on your PATH (tesseract --version prints 5.x).
Create make_invoice.py. It takes eight real products from the shop, writes the ground truth to truth.json, renders an HTML invoice to a PNG at roughly A4 and 150 dpi, then makes a degraded “scan” of it.
import json, os, random, psycopg
from PIL import Image, ImageFilter
from playwright.sync_api import sync_playwright
random.seed(7)
with psycopg.connect(os.environ.get("SHOP_DSN", "postgres://atlas:atlas@localhost:5432/shop")) as db:
prods = db.execute("select sku, name, price_cents from products order by random() limit 8").fetchall()
lines = [{"sku": s, "description": n, "qty": random.randint(1, 40), "unit_price": p / 100} for s, n, p in prods]
for l in lines:
l["line_total"] = round(l["qty"] * l["unit_price"], 2)
subtotal = round(sum(l["line_total"] for l in lines), 2)
tax = round(subtotal * 0.19, 2)
truth = {"invoice_number": "INV-004217", "lines": lines, "subtotal": subtotal, "tax": tax, "total": round(subtotal + tax, 2)}
json.dump(truth, open("truth.json", "w"), indent=2)
money = lambda v: f"{v:,.2f}"
rows = "".join(f"<tr><td>{l['sku']}</td><td>{l['description']}</td><td align=right>{l['qty']}</td>"
f"<td align=right>{money(l['unit_price'])}</td><td align=right>{money(l['line_total'])}</td></tr>" for l in lines)
html = f"""<html><body style="font-family:Georgia,serif;width:1180px;padding:30px">
<h1>INVOICE</h1><p>Atlas Supplies GmbH · Invoice no. {truth['invoice_number']} · 2026-10-28</p>
<table style="width:100%;border-collapse:collapse;font-size:20px" border=1 cellpadding=8>
<tr><th>SKU</th><th>Description</th><th>Qty</th><th>Unit price</th><th>Amount</th></tr>{rows}</table>
<p style="text-align:right;font-size:20px">Subtotal {money(subtotal)}<br>VAT 19% {money(tax)}<br><b>Total EUR {money(truth['total'])}</b></p>
<p style="font-size:9px">VAT ID DE298374615 · IBAN DE44 5001 0517 5407 3249 31 · payable within 14 days</p>
</body></html>"""
with sync_playwright() as p:
page = p.chromium.launch().new_page(viewport={"width": 1240, "height": 1754})
page.set_content(html); page.screenshot(path="invoice.png", full_page=True)
img = Image.open("invoice.png").convert("L").rotate(1.3, expand=True, fillcolor=255)
noise = Image.effect_noise(img.size, 40).convert("L")
img = Image.blend(img, noise, 0.12).filter(ImageFilter.GaussianBlur(0.9))
img.save("scan.jpg", quality=30)
print("total", truth["total"], "lines", len(lines), "scan size", img.size)uv run make_invoice.py && open scan.jpg 2>/dev/null || xdg-open scan.jpgtruth.json with eight lines and scan.jpg: a slightly rotated, grainy, blurred grey invoice, readable by you with some effort, with a footer in tiny type. Product names come from the shop loader, so they vary with your data; the seed keeps quantities stable between runs.2. Read it with Tesseract. Create ocr.py. It runs Tesseract, parses rows with a regex, and scores them against the truth. The scoring function is shared with the next step.
import json, re, sys, pytesseract
from PIL import Image
truth = json.load(open("truth.json"))
num = lambda s: float(s.replace(",", "")) if s else None
def score(lines):
"""A truth line counts as right if some extracted line has the same qty, unit price and amount."""
got = {(l.get("qty"), l.get("unit_price"), l.get("line_total")) for l in lines}
ok = sum((t["qty"], t["unit_price"], t["line_total"]) in got for t in truth["lines"])
return f"{ok}/{len(truth['lines'])} line items exactly right"
if __name__ == "__main__":
text = pytesseract.image_to_string(Image.open(sys.argv[1]), config="--psm 6")
pat = re.compile(r"(\d+)\s+([\d,]+\.\d{2})\s+([\d,]+\.\d{2})\s*$")
lines = [{"qty": int(m[1]), "unit_price": num(m[2]), "line_total": num(m[3])}
for row in text.splitlines() if (m := pat.search(row))]
print(text[:1200]); print("---\ntesseract:", score(lines))uv run ocr.py invoice.png
uv run ocr.py scan.jpginvoice.png Tesseract gets most or all lines right: printed text, straight, high contrast. On scan.jpg the score drops. Look at the raw text: dropped decimal points, 1 read as l or 7, the table borders turned into | characters that break the regex, a wrapped product name splitting a row. Each failure is a reason the pipeline around OCR is usually bigger than the OCR.3. Read it with Claude, with a schema and an arithmetic check. Create vision_extract.py:
import base64, json, sys, anthropic
from pydantic import BaseModel
from ocr import score, truth
class Line(BaseModel):
row: int
sku: str | None
description: str | None
qty: int | None
unit_price: float | None
line_total: float | None
class Invoice(BaseModel):
invoice_number: str | None
lines: list[Line]
subtotal: float | None
tax: float | None
total: float | None
vat_id: str | None
path = sys.argv[1]
media = "image/jpeg" if path.endswith(".jpg") else "image/png"
b64 = base64.standard_b64encode(open(path, "rb").read()).decode()
client = anthropic.Anthropic()
resp = client.beta.messages.parse(
model="claude-sonnet-5-5", max_tokens=16000,
betas=["server-side-fallback-2026-07-01"], fallbacks="default", # the API chapter's rule
messages=[{"role": "user", "content": [
{"type": "image", "source": {"type": "base64", "media_type": media, "data": b64}},
{"type": "text", "text": "Extract this invoice. Copy every number exactly as printed; do not compute "
"or correct anything. Number the table rows from 1. If a value is not legible, "
"use null rather than guessing."}]}],
output_format=Invoice,
)
if resp.stop_reason != "end_turn":
sys.exit(f"no invoice: stop_reason={resp.stop_reason}") # refusal or max_tokens: nothing to parse
inv = resp.parsed_output
print(json.dumps(inv.model_dump(), indent=1)[:1500])
print("claude:", score([l.model_dump() for l in inv.lines]))
for l in inv.lines: # the check that would have saved the Why's finance team
if None not in (l.qty, l.unit_price, l.line_total) and abs(l.qty * l.unit_price - l.line_total) > 0.005:
print(f"row {l.row}: {l.qty} x {l.unit_price} != {l.line_total} -> re-read or send to a human")
if inv.subtotal is not None and abs(sum(l.line_total or 0 for l in inv.lines) - inv.subtotal) > 0.005:
print("lines do not sum to subtotal")
print("vat id read as", inv.vat_id, "| truth DE298374615")
print(f"usage: {resp.usage.input_tokens} input, {resp.usage.output_tokens} output tokens")uv run vision_extract.py scan.jpg4. Optional: the same scan on a local vision model.
ollama pull llama3.2-vision
python3 - <<'PY'
import base64, json, urllib.request
img = base64.b64encode(open("scan.jpg", "rb").read()).decode()
body = {"model": "llama3.2-vision", "stream": False, "images": [img],
"prompt": "List every table row of this invoice as: SKU | description | qty | unit price | amount"}
r = json.load(urllib.request.urlopen(urllib.request.Request(
"http://localhost:11434/api/generate", json.dumps(body).encode(), {"Content-Type": "application/json"})))
print(r["response"])
PY5. Tables from a multi-page PDF. Create pdf_tables.py. It counts the tokens first, then asks for every table in Attention Is All You Need (15 pages), and compares with pdfplumber’s text-layer extraction of the same tables.
import io, urllib.request, anthropic, pdfplumber
URL = "https://arxiv.org/pdf/1706.03762"
client = anthropic.Anthropic()
doc = {"type": "document", "source": {"type": "url", "url": URL}}
ask = {"type": "text", "text": "List every table in this paper. For each: its number, caption, the page it is on, "
"and its contents as a Markdown table with the same rows and columns. "
"Copy values exactly; mark unreadable cells with ?."}
n = client.messages.count_tokens(model="claude-sonnet-5-5", messages=[{"role": "user", "content": [doc, ask]}])
print("input tokens:", n.input_tokens, f"(about ${n.input_tokens * 2 / 1e6:.2f} on claude-sonnet-5-5)")
with client.beta.messages.stream(model="claude-sonnet-5-5", max_tokens=16000,
betas=["server-side-fallback-2026-07-01"], fallbacks="default",
messages=[{"role": "user", "content": [doc, ask]}]) as s:
for t in s.text_stream:
print(t, end="", flush=True)
pdf = pdfplumber.open(io.BytesIO(urllib.request.urlopen(URL).read()))
print("\n\n--- pdfplumber, text layer only ---")
for i, page in enumerate(pdf.pages, 1):
for tbl in page.extract_tables():
print(f"page {i}: {len(tbl)} rows; first rows {tbl[:3]}")uv run pdf_tables.pyvision_extract.py, open the image with Pillow, img.thumbnail((700, 700)), save it as PNG, and send that instead. The usage drops to a few hundred image tokens and the bill with it. Now count how many lines are still exactly right and what the VAT id comes back as. The model still returns eight confident, schema-valid rows; some of the digits are now wrong, and only the arithmetic warnings tell you which. That is the Why’s incident in miniature: a cost optimisation that silently traded away the accuracy of the one thing that mattered.Template
# Document extraction: acceptance criteria and pilot results
Owner: <engineer or product owner>. Approver: <head of finance or operations>. Date: <date>.
Decision needed: <go, no-go or go with conditions, by when>. Scope: <document types>.
## 1. Fields and accuracy
| Field | Why it matters | Target | Pilot result | Sample |
## 2. Checks that run on every document
<arithmetic, schema and cross-checks, and what each one catches>
## 3. Failure cases
| Case | Example | Cause | Caught by | Residual risk |
## 4. Human-review threshold
Send a document to review when: <rule>. Expected share sent: <percent>. Cost per document: <dollars>.
## 5. How this could be wrong
<one way, and what would show it>
## 6. Go or no-go
<decision, conditions, rollback trigger>. Out of scope: <what this does not cover>. WORKED EXAMPLE
At a real company the engineer who built the pipeline writes this, and the head of accounts payable approves it. This is the shop’s supplier invoice, read with claude-sonnet-5-5, written on 20 November 2026 before the pilot, so the criteria cannot drift to fit the results. Lab figures: one scan, 8 lines, about 2,800 image tokens at $2 per million input tokens, under a cent of input per call plus one to three cents of output. Anything marked assumed is a choice to replace with your own data.
Fields. One target, assumed and open to the approver: invoice number, VAT ID and every money field exactly right on 99 documents in 100. Pilot: 100 real scans (assumed size). The Pilot result column stays empty until they are scored; the only measured evidence today is the lab scan, where the VAT ID in the 9-pixel footer (DE298374615) is the field to watch.
Checks. qty x unit price equals the line total; lines sum to the subtotal; subtotal plus 19% VAT equals the total; the VAT ID must also appear in the Tesseract text.
Failures. A 1 read as 7 passes the schema but not the arithmetic. A misread footer digit passes every arithmetic check, so only the OCR cross-check can catch it. Downscaled to 700 px, the model still returns eight confident rows.
Threshold. Review if any check fails, any money field is null, or the VAT ID is missing from the OCR text. Expected share sent: measured in the pilot. The plan holds if two clerks can clear it; assumed ceiling, 20 in 100.
Could be wrong. One lab scan and clean-ish pilot scans are not phone photos, and Tesseract may misread the footer too and flood the queue. A review share above 20% in week one would show it.
Go. Go for scans with review; no-go for auto-posting. Reverse if one wrong amount reaches the ledger. Out of scope: handwriting.
Now you
You are the engineer or product owner at Tallowmere, the 40-person online pharmacy in Ibadan, and the finance lead signs what you write. Supplier invoices arrive as PDFs and phone photos, and the finance lead wants extraction before the ledger is touched. Reuse your own lab runs: the score for scan.jpg from step 3, any arithmetic warnings, the VAT ID your run read, the usage line, and the result of the break experiment at 700 px. If you have not run the lab, use the lab figures in the worked example and say so. Choose which fields matter and set a target for each, labelled as an assumption. State your pilot size as an assumption too. Decide your review rule from the failures you saw. The finance lead reads this document to decide whether extraction goes live, and who clears the review queue.
Self-check
Accounts payable receives 20,000 supplier invoices a month: about half digital PDFs from large suppliers, half scans and phone photos from small ones. Every extracted amount is posted to the ledger. The team has a vision model, Tesseract, two clerks, and no labelled training data. How do you build the extraction pipeline?
- DOC Vision
Formats, size and count limits, the patch-based token formula and resolution tiers, and the limitations list. Read 'Image limits and costs' and 'Limitations'; skip the per-language examples beyond your own.
- DOC PDF support
How native PDF input works (page images plus extracted text), its limits, cost per page, and the best-practice list. Short; read it before choosing between native PDFs and your own text extraction.
- DOC Files API
Upload a document once and reference it by file_id across requests and batches. Read the workspace-scoping warning: file ids are visible to the whole workspace, so never accept one from a user.
- PAPER Vision language models are blind Rahmanzadehgervi, Bolton, Taesiri and Nguyen, 2024
Simple visual tasks (overlaps, intersections, counting) on which leading models fail, and evidence that the detail is lost between encoder and words. The best calibration for how much to trust a model reading an image. Read: the abstract, the task figures in section 2 and the probing results.
- PAPER OCR-free Document Understanding Transformer (Donut) Kim et al., 2021
An end-to-end model that reads documents into structured output without a separate OCR step, and why OCR pipelines accumulate errors. Read for the argument and the receipt-parsing results; skip the pre-training details. Read: sections 1 and 3, and the CORD results in section 4.
- DOC Tesseract command-line usage
Page segmentation modes (--psm), languages, and TSV output with word boxes and confidences, which is what you need to combine OCR with a model. Skim the training sections unless you have a custom font.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.