Skip to content

Lesson 33 of 40Building LLM systems

Multimodal Apps: Images, PDFs and Audio

Send images and PDFs to a model, estimate what they cost, extract structured data with review queues, and plan voice features and their privacy risks.

15 min read0/4 questions

An expenses app wants users to snap a receipt instead of typing it. An insurer wants claim PDFs turned into rows in a database. A support line wants a voice agent that answers the phone. All three are multimodal features: the input is not plain text. The API call is the easy part, a few extra lines. The work is everywhere else: how much each image costs, what the model reliably reads and what it quietly gets wrong, how to know an extraction is right before money moves, and what to do with the faces, ID cards and GPS coordinates hiding in user uploads. This lesson covers images, documents and audio the way you would ship them at work.

How an image reaches the model

An image is just another content block in a user message, next to the text. The block's source says where the bytes come from: base64 (embedded in the request), url (the provider fetches it), or file (an id from the Files API, uploaded once and reused).

receipt.py
import base64
import anthropic
 
client = anthropic.Anthropic()
 
with open("receipt.jpg", "rb") as f:
    data = base64.standard_b64encode(f.read()).decode("utf-8")
 
response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=16000,
    messages=[{
        "role": "user",
        "content": [
            {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": data}},
            {"type": "text", "text": "What is the total on this receipt?"},
        ],
    }],
)

Put images before the question, as you would a long document. When you send several, label them in text ("Image 1:", "Image 2:") so the prompt and later turns can refer to them by name.

Which source to use matters more in agents than in one-off calls. Every request resends the whole conversation, so a base64 image in turn 1 is uploaded again on turn 2, 3 and 30. Uploading once with the Files API and referencing {"type": "file", "file_id": ...} keeps every later request small. The Files API is not available on every cloud platform (on Amazon Bedrock and Google Cloud, images currently go in as base64), so check where you deploy.

At the time of writing, Claude accepts JPEG, PNG, GIF (first frame only) and WebP, up to 10 MB per image on the Claude API (less on some cloud platforms), up to 8000 pixels on a side, and up to 600 images per request on large-context models, with the whole request capped at 32 MB. Limits move, so read the current vision docs before you design an upload flow around them.

What an image costs

Images are billed as input tokens. Claude cuts an image into 28 by 28 pixel patches, and each patch is a visual token, so the cost is ceil(width / 28) × ceil(height / 28). Each model also has a maximum native size: an image over the long-edge or token limit is scaled down (keeping its aspect ratio) before processing. Claude 4.7 and later models use a high-resolution tier with a larger limit, so the same photo can cost roughly three times as many tokens as on an older model.

The block below implements that rule and reproduces the documented examples.

Python
import math PATCH = 28 # each visual token is a 28 x 28 pixel patchTIERS = { # (max long edge, max visual tokens): check the docs for your model "standard": (1568, 1568), "high-res": (2576, 4784),} def visual_tokens(w, h): return math.ceil(w / PATCH) * math.ceil(h / PATCH) def fit(w, h, tier): """Largest size with the same aspect ratio that fits both limits.""" max_edge, max_tokens = TIERS[tier] if max(w, h) <= max_edge and visual_tokens(w, h) <= max_tokens: return w, h best = (1, 1) for new_w in range(1, w + 1): new_h = int(new_w * h / w + 0.5) if max(new_w, new_h) <= max_edge and visual_tokens(new_w, new_h) <= max_tokens: best = (new_w, new_h) return best images = [("icon", 200, 200), ("scan", 1000, 1000), ("screenshot", 1920, 1080), ("phone photo", 4032, 3024), ("4K frame", 3840, 2160)] print(f"{'image':12} {'original':>10} | {'standard tier':>20} | {'high-res tier':>20}")for name, w, h in images: cells = [] for tier in TIERS: fw, fh = fit(w, h, tier) cells.append(f"{fw}x{fh} = {visual_tokens(fw, fh):>4}") print(f"{name:12} {f'{w}x{h}':>10} | {cells[0]:>20} | {cells[1]:>20}") # Resizing yourself: a phone photo of a receipt rarely needs full resolution.w, h = 4032, 3024small = (1200, 900)print(f"\nphone photo sent as-is on high-res tier: {visual_tokens(*fit(w, h, 'high-res'))} tokens")print(f"resized to {small[0]}x{small[1]} first: {visual_tokens(*small)} tokens")
Output
Press Run (⌘ Enter) to see what happens.

The lesson: the provider's downscaling caps your cost, but it does not choose the right size for your task. A receipt photo at 1200 by 900 is perfectly readable and costs about a third of the full-resolution version. Resize and crop before upload: it cuts tokens, upload time and latency. Do the opposite for dense screenshots and small print, where detail is the point. If you need coordinates back (bounding boxes, click positions), resize yourself so the model's pixel grid matches yours, as the vision coordinate docs explain.

Predict the outputPython

What does this print?

import math
w, h = 560, 300
print(math.ceil(w / 28) * math.ceil(h / 28))
Need a nudge? Hints walk you through it.

What vision is good and bad at

Vision models are strong at screenshots and UI, printed text in clear photos, charts with labelled axes, diagrams, forms, and describing scenes. They are weaker in ways that matter for production:

  • Small or degraded text. Blurry, rotated, low-contrast or tiny text (images under about 200 pixels) leads to confident misreads: a 6 read as an 8, a decimal point lost.
  • Counting and precise positions. Counts of many small objects are approximate, and coordinates are approximate. Never trust a count of 47 screws for inventory.
  • Spatial reasoning. "Which shelf is the red box on, from the left?" is less reliable than "what does the label say?".
  • Handwriting. Often good, sometimes badly wrong, and you cannot tell which from the output alone.
  • Things it will not or cannot do. Claude will not identify people by their faces, cannot tell whether an image is AI-generated, and is not a diagnostic tool for medical scans.

The practical rule: treat every extraction as a claim to verify, especially numbers. Cross-check what you can (totals add up, dates are plausible, ids pass checksums), and design the product so a human sees the uncertain ones.

Quick check
Which vision task needs the strongest verification before you rely on it?
Need a nudge? A hint rules out a wrong answer.

Documents: native PDF or your own pipeline

Claude can take a PDF directly as a document block. Underneath, each page is processed twice: the extracted text and an image of the page, so charts, stamps and layout are visible as well as the words. That convenience has a price: text tokens (typically 1,500 to 3,000 per page, by density) plus image tokens for every page. A 40-page contract is a large request, every time you send it.

contract.py
from pathlib import Path
 
uploaded = client.files.upload(file=Path("contract.pdf"))  # upload once, reuse the id
 
response = client.messages.create(
    model="claude-opus-5-5",
    max_tokens=16000,
    messages=[{
        "role": "user",
        "content": [
            {"type": "document", "source": {"type": "file", "file_id": uploaded.id},
             "citations": {"enabled": True}},
            {"type": "text", "text": "What is the notice period for termination?"},
        ],
    }],
)

With citations on, the answer comes back as text blocks carrying page_location citations (start and end page numbers) and the quoted text, so your UI can link "see page 14" to the source. That is the strongest grounding you can get for document Q&A. Two catches: citations cannot be combined with structured output formats in the same request, and encrypted or password-protected PDFs are not supported. Page and size limits apply too (check the PDF support docs).

The alternative is your own parsing pipeline: a document AI service (Amazon Textract, Google Document AI, Azure Document Intelligence) or open-source parsers (Docling, Unstructured) turn files into text, tables and layout, and you send only the parts you need. Choose by the job:

SituationBetter fit
Occasional questions over a few documentsNative PDF input, with citations
Charts, stamps, signatures and layout matterNative PDF input (it sees page images)
Millions of pages, mostly textOwn parse pipeline, then send relevant chunks
You need the same text for search indexing anywayOwn pipeline, shared with your RAG index
Scanned forms with fixed fieldsForm-extraction service, or model on page images with checks

Many teams do both: parse once for search and chunking, as in RAG and Embeddings, and send the original page images only for the pages a question is about.

Structured extraction, end to end

The most common multimodal feature at work is extraction: invoices, receipts, IDs, claim forms, into rows. Doing it once is easy. Doing it so finance trusts it takes five parts.

  1. A schema. Structured output with exact types: dates as ISO strings, money as strings or integers of minor units (never floats), enums for document type, nullable fields for "not present" so the model does not invent a value.
  2. Validation in code. Net plus tax equals total. Dates are not in the future. The vendor exists in your system. The IBAN passes its checksum. These checks catch a large share of misreads for free.
  3. A confidence signal. You can ask the model for a confidence per field, but self-reported confidence is poorly calibrated: wrong answers often come back at 0.95. Treat it as one weak signal next to the validation checks, and agreement between two extraction passes where it is worth paying for.
  4. A review queue. Anything that fails a check or falls below a threshold goes to a person, who sees the image next to the extracted fields. Their corrections are your best training and eval data.
  5. An eval set. A few hundred labelled documents, measured per field, and split by how the document arrived (scan, phone photo, native PDF). Report two numbers: overall accuracy, and accuracy on what was auto-approved, because the second is the error rate that reaches your ledger.
Python
from datetime import datefrom decimal import Decimal FIELDS = ["vendor", "date", "net", "vat", "total"]KNOWN_VENDORS = {"Acme Ltd", "Northwind", "Globex"} # Hand-labelled truth for six invoices (your eval set).GOLD = { "inv-1": ["Acme Ltd", "2026-03-04", "100.00", "20.00", "120.00"], "inv-2": ["Northwind", "2026-03-09", "250.00", "50.00", "300.00"], "inv-3": ["Globex", "2026-02-28", "80.00", "16.00", "96.00"], "inv-4": ["Acme Ltd", "2026-03-15", "40.00", "8.00", "48.00"], "inv-5": ["Northwind", "2026-01-30", "500.00", "100.00", "600.00"], "inv-6": ["Globex", "2026-03-01", "12.50", "2.50", "15.00"],} # What the model extracted, plus the confidence it reported.EXTRACTED = { "inv-1": (["Acme Ltd", "2026-03-04", "100.00", "20.00", "120.00"], 0.97), "inv-2": (["Northwind", "2026-09-03", "250.00", "50.00", "300.00"], 0.95), # day/month swapped "inv-3": (["Globex", "2026-02-28", "80.00", "16.00", "69.00"], 0.93), # misread digits "inv-4": (["Acme Ltd", "2026-03-15", "40.00", "8.00", "48.00"], 0.62), # blurry photo "inv-5": (["Northwind", "2026-01-03", "500.00", "100.00", "600.00"], 0.96), # wrong but plausible "inv-6": (["Globex Corp", "2026-03-01", "12.50", "2.50", "15.00"], 0.91), # name variant} TODAY = date(2026, 4, 1) def checks(fields, confidence): vendor, day, net, vat, total = fields problems = [] if confidence < 0.8: problems.append("low confidence") if Decimal(net) + Decimal(vat) != Decimal(total): problems.append("net + vat != total") if date.fromisoformat(day) > TODAY: problems.append("date in the future") if vendor not in KNOWN_VENDORS: problems.append("unknown vendor") return problems auto, review = [], []for doc, (fields, conf) in EXTRACTED.items(): problems = checks(fields, conf) (review if problems else auto).append(doc) print(f"{doc}: {'REVIEW ' + ', '.join(problems) if problems else 'auto-approved'}") def field_accuracy(docs): right = sum(EXTRACTED[d][0][i] == GOLD[d][i] for d in docs for i in range(len(FIELDS))) return right / (len(docs) * len(FIELDS)) print(f"\nfield accuracy, all documents: {field_accuracy(list(EXTRACTED)):.0%}")print(f"field accuracy, auto-approved: {field_accuracy(auto):.0%} ({len(auto)} docs)")print(f"sent to human review: {len(review)} of {len(EXTRACTED)}")for i, name in enumerate(FIELDS): wrong = [d for d in EXTRACTED if EXTRACTED[d][0][i] != GOLD[d][i]] print(f" {name:6} errors: {wrong}")
Output
Press Run (⌘ Enter) to see what happens.

Look at what the checks caught. The day and month swap on inv-2 was only caught because it landed in the future; in March it would have sailed through. The misread total on inv-3 broke the arithmetic. The name variant on inv-6 is not really an error to a human, but it would create a duplicate vendor, so it is right to send it for review. And inv-5 is the dangerous one: a wrong date, high confidence, every check passing. That is why the auto-approved accuracy is the number you watch, and why you sample auto-approved documents for human audit too.

Audio: speech in, speech out

Many models, including Claude through the Messages API, take text, images and documents rather than raw audio, so a voice feature is usually a pipeline. Check your provider's docs, because native audio input and speech-to-speech models are available from several vendors and change quickly.

Speech-to-text (STT). Whisper-class models and hosted transcription services turn audio into text. The features that matter at work: diarization (who spoke when, essential for meeting notes and call centres), word timestamps (so a summary can link to the moment in the recording), custom vocabulary for product names, and language detection. Measure word error rate on your own audio: accents, phone-line quality and background noise move it a lot.

Text-to-speech (TTS). Turns the reply back into a voice. Choose for latency to first audio, naturalness, and how it handles numbers, names and addresses.

Realtime voice agents are where latency rules everything. People expect a reply within about a second of finishing speaking. A cascaded pipeline spends that budget in stages:

Where a voice agent's second goes
  1. Turn detectionhas the caller finished?
  2. Speech-to-textfinal transcript of the turn
  3. LLM first tokenusually the biggest slice
  4. Text-to-speech first audiostart speaking early
  5. Network both waysphone or WebRTC

Turn detection decides when the user has stopped. Wait too long and it feels slow; too short and the agent interrupts. Voice activity detection plus a small model that judges if the sentence is complete is common.

1/5

Voice also changes the product: users interrupt ("barge-in"), so playback must stop instantly; answers must be short, because nobody listens to a bulleted list; and confirmations of actions must be read back ("refund 40 pounds to the card ending 4242, shall I go ahead?").

Match the pairs0/5 matched

Match each feature to the technique it needs most.

Choose an item, then its match on the other side.

Generating images, and labelling them

Claude understands images but does not generate them; image generation and editing come from separate models from other providers. At awareness level, know the uses (product mock-ups, marketing variants, editing backgrounds) and the obligations. Provenance standards such as C2PA attach signed metadata saying how an image was made and edited, and many generators add it or an invisible watermark. The EU AI Act includes transparency duties to mark AI-generated content in a machine-readable way and to disclose deepfakes; dates and guidance have been moving, so check the current position before launch. In product terms: label generated images, keep provenance metadata intact through your pipeline, and do not strip it when resizing.

Computer use and browser agents

Computer use flips the direction: screenshots go in, actions such as clicks and keystrokes come out, in a loop. Claude provides this through a computer use tool (the tool version depends on the model, so check the docs), and browser agents work the same way inside a browser. It is powerful for legacy apps with no API, and it is slow, token-heavy (every step is a screenshot) and risky. Every web page is untrusted input that can carry an injection, and the agent has your session. Run it in an isolated VM or container with no access to real credentials, allowlist the sites it may visit, and require confirmation for purchases, sends and deletes. All of AI Security applies, with a bigger attack surface.

Privacy: images carry more than you think

A photo of a receipt can contain the user's face in a reflection, a colleague in the background, a payment card, and EXIF metadata with the GPS coordinates of their home and the device serial. The model may ignore metadata, but your storage, logs and support tools keep it.

  • Strip metadata on upload (re-encode the image), before storage, not later.
  • Minimise. Crop to the document, blur faces and card numbers you do not need, and keep the smallest resolution that does the job.
  • Retention. Delete originals once extraction is approved, unless a regulation says otherwise, and remember the copies in the Files API, queues and review tools.
  • Special categories. IDs, medical documents and biometrics trigger stricter rules (GDPR special category data, sector rules). Get your privacy team involved before launch.
Put it in order5 steps

Order the steps of a careful receipt-upload pipeline.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
multimodal
A model or feature that works with more than text, such as images, documents or audio.
visual token
A 28 by 28 pixel patch of an image; image cost is the number of patches, after any downscaling.
Files API
An endpoint for uploading a file once and referencing it by id in later requests.
citations
References in a model's answer to the exact passage and page of a source document.
diarization
Labelling which speaker said each part of a transcript.
turn detection
Deciding when a speaker has finished, so a voice agent replies neither too early nor too late.
EXIF metadata
Data embedded in image files, such as camera model, time and GPS location.