03.6 Images, PDFs and Files

Understand LLMsLesson 6 of 1326,145 words9 parts
Module 03 · 0 of 13 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13

Every model in this module's default line-up can read images, and every provider accepts PDFs. Most real products need that: a support bot that reads screenshots, an expense tool that reads receipts, a contract assistant that reads 80-page PDFs. Sending a file looks easy (one more content part in the request), but the details decide whether it works in production. Each provider has its own part shapes, its own size and count limits, its own image-token formula and its own controls for detail and cost. On top of that come Files APIs with different retention rules, privacy duties (phone photos carry GPS coordinates), and failure modes that never show up with text. This lesson covers the engineering of sending media to OpenAI, Anthropic, Gemini and OpenRouter: the three ways to attach a file, every provider's image and document shapes and limits, what media costs and how to estimate it before you send, the Files APIs end to end, a preprocessing toolkit that shrinks, rotates and strips files before upload, how to order and label media in a prompt, an overview of audio and video input, and the errors you'll meet along with how to catch them early.

What you'll learn

  • The three ways to attach media (inline base64, URL, and file ID), what each costs in request size, latency and privacy, and which providers support which
  • Why base64 makes every file about 33% bigger, and how to see the exact bytes each SDK sends
  • Image input on every provider: OpenAI's input_image and detail levels, Anthropic's image blocks and the many-image rule, Gemini's Part.from_bytes, Part.from_uri, Interactions image blocks and media_resolution, and OpenRouter's image_url and input_image
  • Every documented image limit (formats, counts, pixel and byte sizes), what happens to an image that's too big (rejected on some providers, silently downscaled on others), and one table with every request-size limit per provider and route (inline, Batch, Files)
  • What an image costs on each provider, a local estimator that reproduces the providers' own worked examples, and how to check it against counting endpoints and usage
  • PDFs and other documents on every provider: OpenAI's input_file, Anthropic's document blocks (including plain-text and custom-content documents), Gemini PDFs and their per-page cost, and OpenRouter's file-parser plugin with its three engines
  • The API surface of document citations, and where grounding as a pattern is taught instead
  • The Files APIs of OpenAI, Anthropic, Gemini and OpenRouter: upload, use, list and delete, retention periods, limits, and the privacy duties that come with storing user files on someone else's servers
  • A preprocessing toolkit: EXIF orientation, metadata and GPS stripping, resizing to each provider's sweet spot, format choice (without losing palette colours or turning transparency black), HEIC, cropping, and PDF page counting, splitting and text extraction with pypdf, plus the checks that make it safe to run on untrusted uploads
  • Where to put media relative to the question, how to label several images, and why images in conversation history are re-sent and re-billed on every turn
  • Audio and video input, at overview level
  • The failure modes specific to media, how they surface as SDK exceptions, and a preflight check that catches most of them before you pay for a request

What you don't need

  • Any API key. Every part has something you can run for free: pure-Python tools (base64, token estimators, image and PDF preprocessing), wire captures that show the exact request each SDK builds, mocked servers that return the providers' documented errors, and real image calls to a small local vision model. Samples that need a hosted provider are labelled, and their output is marked illustrative.
  • Experience with image processing. Pillow (the standard Python imaging library) is introduced as we go, and every operation is explained.
  • Document parsing, OCR or chunking. This lesson sends files to models as they are. Turning documents into clean text for search and retrieval is Module 05's subject, and building vision applications is Module 09's.

Setup

The samples need Python 3.11+, the three official SDKs, and two libraries for media: Pillow for images and pypdf for PDFs (with its crypto extra, for the encrypted-PDF demo).

Lessons 03.1 to 03.9 share one project folder, llm-apis. If you haven't created it yet, run uv init llm-apis --bare --python 3.13 && cd llm-apis first (see lesson 03.1, Part 4 for the full setup, including the .env file), then add this lesson's packages:

bash
uv add openai anthropic google-genai python-dotenv httpx pillow "pypdf[crypto]"
# or: pip install openai anthropic google-genai python-dotenv httpx pillow "pypdf[crypto]"

The .env file holds the keys:

bash
# .env  (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=...
OPENROUTER_API_KEY=...

Part 6 uses one optional extra, only for iPhone HEIC photos (6.2): uv add pillow-heif.

The samples were written and checked against openai 3.42.1, anthropic 2.4.0 and google-genai 2.34.0, and against these media libraries, as of November 2026: Pillow 13.0.0 (16 October 2026), pypdf 6.21.4 (28 October 2026) and pillow-heif 1.8.1. The commands install the newest releases, so a newer major version may change names or defaults. pypdf 7.0.0 followed on 6 November 2026 (its changelog lists security hardening, dropped Python 3.9 support and tighter image-size limits), so an unversioned install gives you 7.x and the limits may differ from what the samples show; read that changelog if a PDF or image sample behaves differently. httpx is in the command above because google-genai 3.x no longer installs it with the SDK, and a sample below does import httpx (lesson 03.1, 4.5); you can build the Gemini mocks with httpx2 instead.

The free local option. The "Try it free" samples run against a small local vision model. Install Ollama as described in lesson 03.1, Part 12, then pull a 2-billion-parameter model that can read images (about 1.9 GB):

bash
ollama pull qwen3-vl:2b

Ollama serves it through the OpenAI- and Anthropic-shaped APIs on http://localhost:11434, so the openai and anthropic SDKs can send it real images. A model this small makes mistakes, but it reads short text and colours reliably, and it exercises the real SDKs and request shapes, which is what this lesson is about. Two limits of the stand-in matter here: Ollama accepts base64 images only (no URLs), and it has no PDF support and no Files API. A third limit: Gemini has no local stand-in, because Ollama doesn't speak Gemini's API (03.1, 12.4), so the google-genai samples in this lesson are hosted-only (they need GEMINI_API_KEY) and were not run.

Step 0: create the test files. Every sample from Part 1 onwards reads three test files from the current directory, so make them first. One script generates them, so every result in this lesson is reproducible: shapes.png (640×400: a red square, a blue circle and the text "INVOICE 42"), photo.jpg (a 9.2 MB, 4032×3024 "phone photo" with an EXIF rotation flag and a GPS location) and report.pdf (three pages of real text). It takes two small files, both in the box below: make_pdf.py, a PDF writer with no libraries (4.2 explains how it works), and make_assets.py, which imports it and draws the two images. Open the box, save both files in your project folder, and run the second one once:

bash
uv run python make_assets.py
Output1 line
wrote shapes.png, photo.jpg, report.pdf

The photo is synthetic (a gradient with noise, which compresses like a real photo), and its GPS coordinates are made up. After running the samples you can delete photo.jpg: it's 9 MB, and the script recreates it identically.

The two generator scripts, make_pdf.py and make_assets.py, and what make_pdf.py prints

First make_pdf.py:

python
"""make_pdf.py: write a small, valid, multi-page PDF with real (extractable) text.

No libraries needed: a PDF is a text-like file of numbered objects plus a table
of byte offsets (the "xref") that tells readers where each object starts.
"""


def write_pdf(path: str, pages: list[str]) -> int:
    """Write one line of Helvetica text per page. Returns the file size in bytes."""
    n = len(pages)
    page_ids = [4 + 2 * i for i in range(n)]               # objects 1-3: catalog, page tree, font
    objects: dict[int, bytes] = {
        1: b"<< /Type /Catalog /Pages 2 0 R >>",
        2: b"<< /Type /Pages /Kids [%s] /Count %d >>"
           % (b" ".join(b"%d 0 R" % p for p in page_ids), n),
        3: b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
    }
    for pid, text in zip(page_ids, pages):
        safe = text.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)").encode("latin-1")
        stream = b"BT /F1 14 Tf 72 720 Td (" + safe + b") Tj ET"   # draw the text near the top-left
        objects[pid] = (b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "   # US Letter, in points
                        b"/Resources << /Font << /F1 3 0 R >> >> /Contents %d 0 R >>" % (pid + 1))
        objects[pid + 1] = b"<< /Length %d >>\nstream\n%s\nendstream" % (len(stream), stream)

    out = bytearray(b"%PDF-1.7\n")
    offsets = {}
    for num in sorted(objects):
        offsets[num] = len(out)                            # the xref needs each object's byte offset
        out += b"%d 0 obj\n%s\nendobj\n" % (num, objects[num])
    xref = len(out)
    out += b"xref\n0 %d\n0000000000 65535 f \n" % (len(objects) + 1)
    out += b"".join(b"%010d 00000 n \n" % offsets[num] for num in sorted(objects))
    out += b"trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n" % (len(objects) + 1, xref)
    with open(path, "wb") as f:
        f.write(out)
    return len(out)


if __name__ == "__main__":
    size = write_pdf("report.pdf", [
        "Quarterly report. Page 1. Revenue grew 12 percent to 4.2 million euros.",
        "Page 2. The Lisbon office opened in March with 14 staff.",
        "Page 3. Risks: supplier delays and currency changes.",
    ])
    print(f"report.pdf: {size} bytes")

    from pypdf import PdfReader                            # check it with a real PDF parser
    reader = PdfReader("report.pdf")
    print("pages:", len(reader.pages))
    for i, page in enumerate(reader.pages, start=1):
        print(f"  page {i}: {page.extract_text()!r}")
Output5 lines
report.pdf: 1263 bytes
pages: 3
  page 1: 'Quarterly report. Page 1. Revenue grew 12 percent to 4.2 million euros.'
  page 2: 'Page 2. The Lisbon office opened in March with 14 staff.'
  page 3: 'Page 3. Risks: supplier delays and currency changes.'

Then make_assets.py, which imports write_pdf from it and draws the two images:

python
# make_assets.py
"""Generate the test media used by the lesson's samples (layer 1: no network).

Creates, in the current directory:
  shapes.png  - 640x400 PNG: a red square, a blue circle and the text "INVOICE 42"
  photo.jpg   - 4032x3024 JPEG that looks like a phone photo: noisy gradient,
                EXIF orientation = 6 (rotate 90 degrees) and a GPS location
  report.pdf  - a 3-page PDF with real text on each page (see make_pdf.py)
"""
from PIL import Image, ImageDraw, ImageFont
import random

from make_pdf import write_pdf


def make_shapes(path: str = "shapes.png") -> None:
    img = Image.new("RGB", (640, 400), "white")
    draw = ImageDraw.Draw(img)
    draw.rectangle((60, 120, 260, 320), fill=(220, 30, 30))          # red square
    draw.ellipse((380, 120, 580, 320), fill=(30, 60, 220))           # blue circle
    font = ImageFont.load_default(size=48)
    draw.text((170, 30), "INVOICE 42", fill="black", font=font)
    img.save(path)


def make_photo(path: str = "photo.jpg") -> None:
    random.seed(7)
    w, h = 4032, 3024                                                 # a 12-megapixel phone photo
    img = Image.linear_gradient("L").resize((w, h)).convert("RGB")
    noise = Image.effect_noise((w, h), 40).convert("RGB")             # noise makes JPEG realistically large
    img = Image.blend(img, noise, 0.5)
    ImageDraw.Draw(img).text((200, 200), "BIKE SHOP", fill="white",
                             font=ImageFont.load_default(size=300))
    exif = Image.Exif()
    exif[0x0112] = 6                                                  # Orientation: rotate 90 degrees CW to view
    exif[0x010F] = "ExamplePhone"                                     # Make
    gps = {1: "N", 2: (51.0, 30.0, 26.0), 3: "W", 4: (0.0, 7.0, 39.0)}  # a location near London
    exif[0x8825] = gps                                                # GPSInfo IFD
    img.save(path, quality=97, exif=exif)


if __name__ == "__main__":
    make_shapes()
    make_photo()
    write_pdf("report.pdf", [
        "Quarterly report. Page 1. Revenue grew 12 percent to 4.2 million euros.",
        "Page 2. The Lisbon office opened in March with 14 staff.",
        "Page 3. Risks: supplier delays and currency changes.",
    ])
    print("wrote shapes.png, photo.jpg, report.pdf")

Files you'll create. Every sample in this lesson starts with a comment (or a docstring) naming its file, so you can save each one under that name. The exercises refer to files by these names. Five helper modules are imported by later samples, so keep them all in the same folder:

File Made in Used by
make_pdf.py, make_assets.py Setup Run once. make_pdf.py is also imported by make_assets.py
s1_3_base64_size.py, s1_5_wire_capture.py 1.3, 1.5 Exercises 1 and 2
s2_1_local_vision.py 2.1 Exercise 3
s2_4_audio_tokens.py 2.4 Needs a Gemini key
s2_5_openrouter_modalities.py 2.5 Exercise 7
s2_6a_openai_images.py, s2_6b_anthropic_images.py, s2_6c_gemini_images.py, s2_6d_openrouter_images.py 2.6 One per provider; need keys
media_tokens.py (helper) 3.2 Imported by s3_2_estimator.py, s3_3_count_vs_estimate.py, s6_7_preprocess_demo.py, s7_3_history_images.py, media_preflight.py and s9_5_production_image_call.py; Exercises 4 and 9
s3_2_estimator.py, s3_3_count_vs_estimate.py 3.2, 3.3 Exercises 4 and 5 (s3_3_... needs keys)
s4_7a_openai_pdf.py, s4_7b_anthropic_pdf.py, s4_7c_gemini_pdf.py, s4_7d_openrouter_pdf.py 4.7 One per provider; need keys
s4_9_citations_mock.py 4.9 Exercise 6
s5_2_upload_wire.py 5.2 Keyless
s5_6_openrouter_files.py, s5_7a_openai_files.py, s5_7b_anthropic_files.py, s5_7c_gemini_files.py 5.6, 5.7 Need keys
file_registry.py (helper) 5.9 Imported by s5_9_registry_demo.py; Exercise 8
preprocess.py (helper) 6.7 Imported by s6_7_preprocess_demo.py, s6_7_encode_regression.py, s6_2_heic.py, s6_3_icc_srgb.py, s6_8_hostile_uploads.py, media_preflight.py and s9_5_production_image_call.py; Exercise 9. Save it before running the 6.2 and 6.3 samples, which use it
s6_2_heic.py, s6_3_icc_srgb.py 6.2, 6.3 Need pillow-heif (6.2)
s6_7_preprocess_demo.py, s6_7_encode_regression.py, s6_8_hostile_uploads.py 6.7, 6.8 Keyless
s7_3_history_images.py 7.3 Exercise 10
s8_gemini_audio_video.py Part 8 Needs a key and your own voice_note.mp3
s9_2_media_errors.py, s9_3_standin_errors.py 9.2, 9.3 Keyless (9.3 needs Ollama)
media_preflight.py (helper) 9.4 Imported by s9_4_preflight_demo.py, s6_2_heic.py and s9_5_production_image_call.py; Exercise 11
s9_4_preflight_demo.py, s9_5_production_image_call.py 9.4, 9.5 9.5 needs a key (or the local model)

What you must be able to do after this lesson#

  • Send an image to a model
  • Send a PDF to a model
  • Estimate the cost of an image
  • Preprocess media before sending
  • Order and label media in a request

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Just base64 the image and put it in the request." 1.3 Base64 from zero, and the 33% tax
"Should we send a URL, or upload it first?" 1.4 Choosing a route
"The request is 14 MB, but the photo was only 10." 1.5 Try it: see the wire
"It worked in testing but fails for iPhone uploads." 1.6 MIME types, 6.3 Orientation and metadata
"Set detail to low, it's cheaper." 2.2 OpenAI, 3.4 The cost levers
"Why does a 4K screenshot cost 1.8 times a 1080p one on Claude 5.x, but the same on older Claude models?" 3.1 Four different rules, 3.2
"How many tokens is this image?" 3.2 Try it: a media-token estimator
"Can the model read this 300-page PDF?" 4.1 How each provider reads a PDF, 6.5 PDFs: count, split, extract
"OpenRouter charged us for OCR even though we use our own key." 4.6 OpenRouter
"Can Claude tell us which page that answer came from?" 4.9 Citations on documents
"The file ID in our database stopped working." 5.5 Gemini, 5.9 Keeping track of file IDs
"A user asked us to delete everything they uploaded." 5.8 Retention, privacy and cleanup
"We leaked a customer's home address in a photo." 6.3 Orientation and metadata
"Put the image before the question." 7.1 Where to put the media
"Our chat with screenshots gets slower and pricier every turn." 7.3 Images in conversation history
"Can we send it a voice note? A video?" Part 8: Audio and video input
"How big can the request be?" 1.7 Request-size limits side by side
"We got a 413." Part 9: When media goes wrong, 1.7
"Is it safe to run Pillow on whatever users upload?" 6.8 Treat uploads as hostile

Part 1: How media travels in a request#

1.1 Media is just another content part#

Lesson 03.2 showed that a user turn's content can be a list of typed parts (OpenAI) or content blocks (Anthropic), or a list of parts (Gemini). An image or a PDF is one more entry in that list, with its own type:

Provider and API Image part Document part
OpenAI Responses {"type": "input_image", "image_url": ...} or "file_id" {"type": "input_file", "file_data" / "file_url" / "file_id": ...}
OpenAI Chat Completions {"type": "image_url", "image_url": {"url": ...}} {"type": "file", "file": {"file_data" / "file_id": ...}} (PDF only)
Anthropic Messages {"type": "image", "source": {...}} {"type": "document", "source": {...}}
Provider and API Image part Document part
Gemini generate_content a Part with inline_data or file_data (types.Part.from_bytes, types.Part.from_uri) the same Part, with mime_type="application/pdf"
Gemini Interactions {"type": "image", "data" / "uri": ..., "mime_type": ...} {"type": "document", ...}
OpenRouter Chat Completions {"type": "image_url", "image_url": {"url": ...}} {"type": "file", "file": {"filename", "file_data" / "file_id"}}
OpenRouter Responses {"type": "input_image", "image_url": ...} {"type": "input_file", "file_url" / "file_data": ...}

The model then turns the media into tokens that sit in the same context window as your text (lesson 02.2, Part 11 explains how, at concept level). Everything else in this lesson is about the details around that one idea: how the bytes get there, how big they may be, what they cost, and what goes wrong.

Media goes in user turns. Anthropic's current API version rejects a document block in an assistant message with a 400, and none of the providers expects files in system instructions (lesson 03.2, Part 4). Tool results are the one other place images appear: a tool can return a screenshot, which lesson 03.5 covers.

1.2 Three ways to attach a file#

However a provider names its parts, there are only three ways to get the bytes to the model:

flowchart LR
    subgraph app ["Your app"]
        F["photo.jpg<br/>9.2 MB"]
    end
    F -->|"1. inline: base64 inside the JSON<br/>(about 33% bigger, every request)"| API["Provider API"]
    F -->|"2. by URL: you send a link,<br/>the provider downloads it"| PUB[("Public or signed URL<br/>(S3, GCS, CDN)")]
    PUB -.->|"fetched at request time"| API
    F -->|"3a. upload once"| FILES[("Provider Files API")]
    FILES -->|"3b. returns a file ID"| app
    app -->|"3c. send only the ID<br/>(a few bytes, any number of times)"| API
    FILES -.->|"read by ID"| API
  1. Inline. You encode the file's bytes as base64 text and put them inside the JSON request body. It's the simplest route, works everywhere (including the local stand-in), and needs nothing but the file. The cost is size: the request carries the whole file, inflated by a third, every time you send it.
  2. By URL. You put a link in the request, and the provider's servers download the file while handling it. The request stays small, but the file must be reachable from the provider's network, and every request triggers a fresh download.
  3. By file ID. You upload the file once to the provider's Files API, get back an ID such as file-abc123, and put only that ID in requests. The file is stored on the provider's side, for as long as their retention rules (or your expiry setting) allow.

1.3 Base64 from zero, and the 33% tax#

JSON is text. It can't hold raw bytes such as the inside of a PNG, because many byte values aren't valid text characters. Base64 solves this by rewriting any bytes using only 64 safe characters (A–Z, a–z, 0–9, + and /, with = for padding). It takes 3 bytes (24 bits) at a time and writes them as 4 characters of 6 bits each. That's why it's always about 4/3 the size of the original: a 33% tax on every inline file.

python
# s1_3_base64_size.py
"""Base64 makes media about 33% bigger: measure it on real files."""
import base64
import json
from pathlib import Path

for name in ["shapes.png", "photo.jpg", "report.pdf"]:
    raw = Path(name).read_bytes()
    b64 = base64.b64encode(raw).decode("ascii")          # bytes -> text the JSON body can carry
    body = json.dumps({"data": b64})                     # base64 needs no escaping inside JSON
    print(f"{name:11} raw={len(raw):>10,} B  base64={len(b64):>10,} B  "
          f"ratio={len(b64) / len(raw):.3f}  in JSON={len(body):>10,} B")

print("\nFirst 60 characters of the PNG as base64:", base64.b64encode(Path("shapes.png").read_bytes()).decode()[:60])
print("Every 3 bytes become 4 characters, so the size is 4 * ceil(n / 3):",
      4 * -(-len(Path("photo.jpg").read_bytes()) // 3))
Output6 lines
shapes.png  raw=     7,356 B  base64=     9,808 B  ratio=1.333  in JSON=     9,820 B
photo.jpg   raw= 9,165,390 B  base64=12,220,520 B  ratio=1.333  in JSON=12,220,532 B
report.pdf  raw=     1,263 B  base64=     1,684 B  ratio=1.333  in JSON=     1,696 B

First 60 characters of the PNG as base64: iVBORw0KGgoAAAANSUhEUgAAAoAAAAGQCAIAAACxkUZyAAAcg0lEQVR4nO3d
Every 3 bytes become 4 characters, so the size is 4 * ceil(n / 3): 12220520

Look at the photo: 9.2 MB on disk, which sounds safely under a "10 MB per image" limit, becomes 12.2 MB once encoded. Anthropic's per-image limit is "10 MB (base64-encoded)" (as of November 2026), so this photo is rejected even though the file is smaller than 10 MB. Request-size limits are measured on what you send, and what you send is the encoded form.

There are two forms of base64 string you'll pass:

  • Bare base64, with the media type in a separate field: Anthropic's {"type": "base64", "media_type": "image/png", "data": "iVBOR..."}, and Gemini Interactions' {"data": "...", "mime_type": "image/png"}.
  • A data URL, which glues both into one string: data:image/png;base64,iVBOR.... OpenAI and OpenRouter use this form for image_url and file_data.

Mixing them up is a classic bug: a data URL in Anthropic's data field, or bare base64 in OpenAI's image_url, is a 400.

1.4 Choosing a route: the decision table#

As of November 2026:

Inline (base64) URL File ID
Request size Grows with the file, ×1.33. Counts against each provider's request limit (the numbers are in 1.7) Tiny Tiny
Re-use None: re-sent with every request, including every later turn of a conversation The provider downloads it again each time Upload once, reference many times; the natural fit for files you ask several questions about and for batch jobs, whose request files have their own size limits (lesson 03.9)
Latency Upload time on every request: noticeable for multi-MB files on mobile networks The provider's download adds time; a slow or distant origin adds more One upload up front; each request is fast. Gemini may need processing time before a file is usable (5.5)
Privacy Nothing stored on purpose beyond the provider's normal request retention (lesson 02.9, Part 9) The file must be reachable by the provider, so anyone with the link can usually read it too. Use short-lived signed URLs The provider stores the file until you delete it or it expires; Anthropic's Files API is not eligible for zero data retention (5.8)
Failure modes Too large; wrong MIME type; corrupt data Unreachable, behind a login, blocked, expired, too large for the fetcher Expired or deleted ID; ID from another workspace or project; file still processing
OpenAI ✅ images and files ✅ images (image_url) and files (file_url, Responses only) ✅ file_id for images and files
Anthropic ✅ ✅ url sources (not on Bedrock or Google-managed Google Cloud, which accept base64 only) ✅ file sources
Local stand-in ✅ images only ❌ ❌
Inline (base64) URL File ID
Gemini ✅ inline data ✅ public HTTPS or signed URLs, up to 15 MB per file (not on Gemini 2.0 models); YouTube links for video ✅ Files API (Gemini Developer API only), or registered Google Cloud Storage files
OpenRouter ✅ data URLs ✅ images and PDFs (not audio) ✅ new Files API, documented in the API reference (5.6)

Rules of thumb:

  • One-off, small file (a screenshot, a receipt photo after resizing): inline. It's simplest, and nothing is stored.
  • A file you'll ask about several times, a long PDF, or a conversation that keeps referring to it: file ID. It keeps every request small, and 7.3 shows how fast inline history grows.
  • Files already in your object storage: a short-lived signed URL (a link with a cryptographic signature and an expiry time, which S3, Google Cloud Storage and Azure can all generate) avoids downloading and re-uploading. Make it live long enough for the request (minutes, not seconds) and no longer.

1.5 Try it: see the wire#

Here is exactly what each SDK sends when you attach the 9.2 MB photo inline. A mock transport (a fake network layer, lesson 03.1, 1.3) records each request instead of sending it, and answers 400 so the SDK stops. Nothing leaves your machine, and the keys are obvious fakes.

python
# s1_5_wire_capture.py
"""Show the wire: what each SDK really sends when you attach an image inline.

Nothing leaves your machine: a mock transport records each request and answers 400,
so the SDK raises and we move on. The keys are obvious fakes.
"""
import base64
import json
import re
from pathlib import Path

import anthropic
import httpx      # google-genai 2.34.0's HTTP library (3.x: uv add httpx, or use httpx2)
import httpx2     # the openai and anthropic SDKs' HTTP library (lesson 03.1, 4.5)
import openai
from google import genai
from google.genai import errors, types

captured: list[tuple[str, str, bytes]] = []


def record(request) -> tuple[int, dict]:
    captured.append((request.method, str(request.url), request.read()))
    return 400, {"error": {"type": "invalid_request_error", "message": "captured, not sent"}}


def h2(request: httpx2.Request) -> httpx2.Response:
    status, body = record(request)
    return httpx2.Response(status, json=body)


def h1(request: httpx.Request) -> httpx.Response:
    status, _ = record(request)
    return httpx.Response(status, json={"error": {"code": 400, "message": "captured", "status": "INVALID_ARGUMENT"}})


image = Path("photo.jpg").read_bytes()                  # a 9.2 MB phone photo
b64 = base64.b64encode(image).decode("ascii")

oai = openai.OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(h2)))
try:
    oai.responses.create(model="gpt-6-luna", input=[{"role": "user", "content": [
        {"type": "input_image", "image_url": f"data:image/jpeg;base64,{b64}", "detail": "auto"},
        {"type": "input_text", "text": "What shop is this?"}]}])
except openai.BadRequestError:
    pass

claude = anthropic.Anthropic(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(h2)))
try:
    claude.messages.create(model="claude-haiku-5-5", max_tokens=200, messages=[{"role": "user", "content": [
        {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": b64}},
        {"type": "text", "text": "What shop is this?"}]}])
except anthropic.BadRequestError:
    pass

gem = genai.Client(api_key="test-key", http_options=types.HttpOptions(
    httpx_client=httpx.Client(transport=httpx.MockTransport(h1))))
try:
    gem.models.generate_content(model="gemini-3.8-flash", contents=[
        types.Part.from_bytes(data=image, mime_type="image/jpeg"), "What shop is this?"])
except errors.ClientError:
    pass

print(f"image on disk: {len(image):,} bytes")
head = base64.b64decode(b64[:400])
print("metadata travels too:", head[head.find(b"Exif"):][:4], head[head.find(b"Example"):][:12], "\n")
for method, url, body in captured:
    short = re.sub(r"([A-Za-z0-9+/=_-]{200,})",                     # shorten long base64 runs
                   lambda m: f"{m.group(1)[:24]}...<{len(m.group(1)):,} chars>", body.decode())
    print(f"{method} {url}\n  body: {len(body):,} bytes ({len(body) / len(image):.2f}x the file)")
    print("  " + json.dumps(json.loads(short)), "\n")
Output14 lines
image on disk: 9,165,390 bytes
metadata travels too: b'Exif' b'ExamplePhone' 

POST https://api.openai.com/v1/responses
  body: 12,220,707 bytes (1.33x the file)
  {"model": "gpt-6-luna", "input": [{"role": "user", "content": [{"type": "input_image", "image_url": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQAB...<12,220,520 chars>", "detail": "auto"}, {"type": "input_text", "text": "What shop is this?"}]}]} 

POST https://api.anthropic.com/v1/messages
  body: 12,220,730 bytes (1.33x the file)
  {"max_tokens": 200, "messages": [{"role": "user", "content": [{"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "/9j/4AAQSkZJRgABAQAAAQAB...<12,220,520 chars>"}}, {"type": "text", "text": "What shop is this?"}]}], "model": "claude-haiku-5-5"} 

POST https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent
  body: 12,220,652 bytes (1.33x the file)
  {"contents": [{"parts": [{"inlineData": {"data": "_9j_4AAQSkZJRgABAQAAAQAB...<12,220,520 chars>", "mime_type": "image/jpeg"}}, {"text": "What shop is this?"}], "role": "user"}]}

Three things to notice:

  • Every request is 12.2 MB for a one-line question. On a phone connection that's seconds of upload before the model even starts, and it's repeated for every turn that keeps the image in history.
  • The photo's metadata rides along. The decoded start of the payload contains the EXIF block, including the camera make, and further in, the GPS coordinates. Models generally don't use it (Anthropic's vision FAQ says "Claude does not parse or receive any metadata from images passed to it"), but it has still left your system and sits in the provider's logs for their retention period. 6.3 strips it.
  • The shapes differ, the bytes don't. OpenAI wants a data URL; Anthropic wants bare base64 plus a media_type; google-genai takes raw bytes and does the base64 itself (in the URL-safe alphabet).

1.6 MIME types: say what the bytes are#

Every inline part carries a media type, and it must match the bytes. Three things trip people up:

  1. File extensions lie. A file called receipt.jpg that's really a PNG (common after screenshots are renamed) gets a wrong media_type. Some providers tolerate it; others reject it or misread the image. Check the bytes themselves: every format starts with a fixed magic number (PNG starts \x89PNG, JPEG \xFF\xD8\xFF, PDF %PDF-). 9.4 does this.
  2. iPhones save photos as HEIC by default. Gemini accepts image/heic and image/heif; OpenAI and Anthropic don't (as of November 2026), so convert to JPEG first. Pillow can't open HEIC on its own: 6.2 shows the one extra package that can.
  3. A client's Content-Type header is a claim, not a fact. When users upload files to your app, re-derive the type from the bytes before you forward it.

1.7 Request-size limits side by side#

This is the one place in the module that states request-size limits in full: lesson 03.2 and lesson 03.8 link here for the numbers. Everything in the table was read from the official pages in the last column as of 2026-11-11. Limits move with every model generation, so check the page before you depend on a number, and treat a figure quoted elsewhere in this lesson as a pointer to this table.

Provider Route Limit Official source
OpenAI Inline request (Responses and Chat Completions) Images: "Up to 512 MB total payload per request", up to 1,500 images, 30,000 patches per image. input_file: "each file must be under 50 MB. The combined limit across all files in the request is 50 MB". Plan around the smaller one if a request mixes both Images and vision, File inputs
Token counting (responses.input_tokens.count) No limit documented Counting tokens
Batch Input .jsonl file up to 200 MB, and up to 50,000 requests per batch Batch guide, Files: create
Files and Uploads 512 MB per file and 2.5 TB per project on files.create. The Uploads API takes up to 8 GB in parts of at most 64 MB Files: create, Uploads: create
Anthropic Messages (first-party API) 128 MB. Also per image 10 MB base64-encoded (5 MB on Bedrock), at most 600 images or pages per request (100 on 200K-context models) Errors: request size limits, Vision, PDF support
Messages on partner platforms Amazon Bedrock 20 MB; Claude on Google Cloud (Google-managed) 30 MB; Claude Platform on AWS, Claude on Google Cloud (Anthropic-managed) and Microsoft Foundry 32 MB for Messages and Token Counting API overview: request size limits
Token Counting 128 MB Errors: request size limits
Message Batches 256 MB Errors: request size limits
Files API 500 MB per upload, 1 TB per organization Errors: request size limits, Files API
Provider Route Limit Official source
Gemini (Developer API) Inline data Google's pages disagree. The file-input-methods and Files pages say "100 MB per request or payload (50 MB for PDFs)". The image, audio and video pages say the total request is limited to 20 MB. Design for 20 MB File input methods, Image understanding, Audio
URL (file_data with an https URL) 15 MB per file File input methods
Documents 50 MB or 1,000 pages per PDF, inline or via the Files API Document understanding
Batch Inline requests: "total request size under 20MB". Input file: "The maximum allowed file size for an input file is 2GB" Batch API
Files API 2 GB per file, 20 GB per project, deleted after 48 hours. Registered Google Cloud Storage files: 2 GB per file, no overall limit Files API, File input methods
OpenRouter Inline request (Chat Completions, Responses, Messages) No limit is stated. The upstream provider's limits apply, and an oversized body is a 413 with error_type: payload_too_large ("The request body exceeds the maximum allowed size"), without a number. Images have typed errors (9.1) Errors
Batch 200 MB per batch (a 413 above it); the request-count limit "generally follow[s] the batch limits of the upstream providers". The batch quickstart adds per-provider limits on inline media in a batch: for example 20 MiB decoded per file and per request for PDFs, and 5 MiB per image on Anthropic Batch API, Batch quickstart
Files API 100 MB per file, stored under the workspace of the key Upload a file

Three rules for reading it:

  • The first limit you hit wins, and it is not always the byte limit. A PDF can hit a page limit first (600 pages on Claude, 1,000 on Gemini), an image can hit a pixel or patch limit (2.7), and an Anthropic request with more than 20 images switches to a stricter per-image dimension limit.
  • Inline media travels base64-encoded, so it counts at about 1.33 times its size against any limit measured on the request body (1.3): a 100 MB inline limit is about 75 MB of files, and Anthropic states its per-image 10 MB on the base64 string itself. Plan with the encoded size.
  • Every "MB" is the provider's own. None of these pages says whether MB means 10^6 or 2^20 bytes. 9.4 takes the smaller reading, as a safety margin. OpenRouter's batch page writes MiB (2^20) for decoded inline media.

What an oversized request looks like when it fails, per provider, is in 9.1.


Part 2: Images on every provider#

2.1 Try it free: one image through the OpenAI and Anthropic SDKs#

This sample sends shapes.png as base64 to the local qwen3-vl:2b model through the OpenAI Responses API, OpenAI Chat Completions and Anthropic Messages. (The Gemini form of the same call has no local stand-in, so it is not in this script: see 2.4 and 2.6.) It prints the input token count next to each answer, which turns out to be the most important column:

python
# s2_1_local_vision.py
"""Try it free: one image, sent as base64 through the OpenAI and Anthropic SDKs to a local vision model.

Needs Ollama with `ollama pull qwen3-vl:2b`.
"""
import base64
from pathlib import Path

import anthropic
from openai import OpenAI

QUESTION = "What text is written at the top of the image? Quote it exactly."
image_bytes = Path("shapes.png").read_bytes()
b64 = base64.b64encode(image_bytes).decode("ascii")       # text-safe form of the PNG's bytes

# 1. openai SDK, Responses API: an input_image part whose image_url is a data URL
oai = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
r = oai.responses.create(
    model="qwen3-vl:2b",
    input=[{"role": "user", "content": [
        {"type": "input_image", "image_url": f"data:image/png;base64,{b64}", "detail": "auto"},
        {"type": "input_text", "text": QUESTION},
    ]}],
    reasoning={"effort": "none"},          # this small model can think; skip it to save time
    max_output_tokens=200,
)
print(f"OpenAI Responses        | in={r.usage.input_tokens if r.usage else '?':>5} | {r.output_text.strip()}")

# 2. openai SDK, Chat Completions: an image_url part (also OpenRouter's main shape)
c = oai.chat.completions.create(
    model="qwen3-vl:2b",
    messages=[{"role": "user", "content": [
        {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}},
        {"type": "text", "text": QUESTION},
    ]}],
    reasoning_effort="none",
    max_tokens=200,                        # Ollama honours max_tokens, not max_completion_tokens
)
print(f"OpenAI Chat Completions | in={c.usage.prompt_tokens if c.usage else '?':>5} | "
      f"{(c.choices[0].message.content or '').strip()}")

# 3. anthropic SDK: an image block with a base64 source (note: no "data:" prefix here)
claude = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama")
m = claude.messages.create(
    model="qwen3-vl:2b",
    max_tokens=400,
    messages=[{"role": "user", "content": [
        {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": b64}},
        {"type": "text", "text": QUESTION},
    ]}],
)
text = "".join(b.text for b in m.content if b.type == "text").strip()
print(f"Anthropic Messages      | in={m.usage.input_tokens:>5} | {text}")
Output · local model qwen3-vl:2b via Ollama3 lines
OpenAI Responses        | in= 1091 | INVOICE 42
OpenAI Chat Completions | in= 1096 | INVOICE 42
Anthropic Messages      | in= 1093 | INVOICE 42

The three lines are a real 2B model reading the image through the real openai and anthropic SDKs: each request is a different shape, and each costs about 1,090 input tokens, of which only about 20 are the question. The rest is the image. A hosted model would give a similar answer in different words.

The input-token column is the lesson. Only about 20 of those tokens are the question, so a count near that size would mean the image never reached the model, even though the call succeeded with a normal finish reason and the model answered politely. Nothing raises an exception when that happens.

2.2 OpenAI: input_image and detail#

Shapes. On the Responses API an image is an input_image part with either image_url (an https:// URL or a data: URL) or file_id (from the Files API), plus an optional detail. On Chat Completions it's an image_url part whose URL is nested one level deeper: {"type": "image_url", "image_url": {"url": ..., "detail": ...}}. Chat Completions has no file_id for images.

detail controls how the image is resized before it's turned into tokens. The values are low, high, original and auto, and if you omit it, it defaults to auto on both APIs. One SDK quirk: in openai 3.42.1 the input_image type marks detail as required, so a type checker flags a part without it even though the API accepts one. Always pass it ("auto" if you don't care); the samples in this lesson do. OpenAI's guidance, as of November 2026:

detail Best for
low "Coarse image understanding." OpenAI warns that "low does not always use fewer tokens than high" on some models
high "Standard high-fidelity image understanding when precise original-image coordinates are not required"
original "Large, dense, spatially sensitive, or computer-use images, when supported by the model", for example OCR or small-object detection
auto The model's default sizing (which, on the newest models, is the same as original)

What each level does depends on the model. From OpenAI's sizing table (November 2026):

Model family low high original auto means
gpt-6-astra Fits in 512×512 px Up to 2,500 patches and a 65,535 px maximum dimension Keeps the image's size (scaled down only beyond 65,535 px a side) original
gpt-5.6-sol, -terra, -luna Fits in 512×512 Fits in 2048×2048 and 2,500 patches As above original
gpt-5.5 Fits in 512×512 Up to 2,500 patches, 2,048 px Up to 10,000 patches, 6,000 px original
gpt-5.4, -mini, -nano 2,048 px and a 6,144-patch budget (so it can cost more than high) Up to 2,500 patches, 2,048 px Up to 10,000 patches, 6,000 px high
gpt-5.2, gpt-4.1-mini All three use 2,048 px and 6,144 patches Not supported
gpt-5.1, gpt-4.1, gpt-4o, gpt-4o-mini A fixed token count Tile-based rules (3.1) Not supported high

Note what's missing: as of November 2026, the table doesn't list gpt-6-luna or the GPT-6.1 models (the module's defaults). The gpt-5.6-luna in the second row is a different model from the module's default gpt-6-luna, so don't read its numbers as gpt-6-luna's. Their model pages say they accept image input, but OpenAI hasn't published their sizing rules or token multipliers. For those models, measure: count tokens with the input-token counting endpoint (3.3) or read usage after a call.

Formats and limits (as of November 2026): PNG, JPEG, WEBP and non-animated GIF; up to 1,500 images per request; and "Up to 512 MB total payload per request", in the words of OpenAI's vision guide. That payload figure is much larger than the 50 MB limit for file inputs (4.3), so plan around the smaller one if a request mixes both (every request-size limit is in 1.7). On patch-based models an image may need at most 30,000 patches after the model's resizing rules have been applied, and OpenAI is explicit about what happens beyond that: "Images that exceed the 30,000-patch limit after processing are rejected, not automatically resized to meet it." With high, the resizing budget keeps you far below the limit. With original, a large image can cross it: OpenAI's own example is a 6000×6000 image on gpt-6-astra, which needs 35,344 patches with original (rejected) and fits after resizing with high.

OpenAI also lists limitations worth designing around: rotated or upside-down images, non-Latin text, panoramic and fisheye images, precise spatial reasoning and exact counting are weak spots; medical scans are out of scope; and CAPTCHAs are blocked.

2.3 Anthropic: image blocks#

Shapes. An image content block has a source of one of three types:

python
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "<base64>"}}
{"type": "image", "source": {"type": "url", "url": "https://example.com/photo.jpg"}}
{"type": "image", "source": {"type": "file", "file_id": "file_011C..."}}

The block can also carry cache_control (prompt caching, lesson 03.7) and transformations, described below.

Formats and limits, from Anthropic's vision guide (November 2026):

Limit Value
Formats JPEG, PNG, GIF and WebP (image/jpeg, image/png, image/gif, image/webp). "Animations are unsupported, and only the first frame is used"
Images per request 600; 100 on models with a 200K-token context window (all Claude 5.x models have 1M)
Dimensions 8000×8000 px maximum
Size per image 10 MB base64-encoded on the Claude API (5 MB on Amazon Bedrock)
Many-image rule Above 20 images in one request, a stricter per-image dimension limit applies to every image. Every image block counts, including images in earlier turns you re-send and screenshots inside tool_result blocks. To be safe, "resize each image so that neither dimension exceeds 3,000 px, or keep the request to 20 or fewer image and document blocks." On Amazon Bedrock and Claude on Google Cloud (Google-managed), document blocks such as PDFs also count towards the 20. Over-limit images fail with an invalid_request_error mentioning "many-image requests"
Whole request 128 MB on the first-party API; Bedrock, Google Cloud and the other partner platforms are lower. All of them, with the Batch and Files limits, are in 1.7

On Amazon Bedrock and Claude on Google Cloud (Google-managed), only base64 sources work: no url and no file sources (lesson 03.1, Part 11 covers those clients). Anthropic's own page disagrees with itself about the Google-managed per-image limit: its platform notes say 5 MB, its limits section says 10 MB. Use 5 MB there until the page is fixed.

Oversized images are downscaled, not rejected, by default. Each model has a maximum native resolution, as a long-edge limit and a visual-token limit:

Tier Models Max long edge Max visual tokens
High-resolution Claude 4.7 and later (all Claude 5.x) 2,576 px 4,784
Standard Earlier models 1,568 px 1,568

A bigger image is shrunk, keeping its aspect ratio, to the largest size that fits both limits. For most photos the token limit is the one that bites: a 1920×1080 screenshot on a standard-tier model becomes 1456×819, not 1568×882. Claude then pads the image with empty space up to the next multiple of 28 pixels on the bottom and right edges. All of this happens silently, which matters if you ask Claude for coordinates (they refer to the resized image, not yours), and it's why pre-resizing (Part 6) is the reliable approach. To predict the processed size (and so map Claude's coordinates back to your original pixels), 09.1, 3.5 implements the documented resize rule as claude_resized().

If you'd rather get an error than a silent resize, mark the block:

python
{"type": "image",
 "source": {"type": "base64", "media_type": "image/png", "data": "<base64>"},
 "transformations": {"oversized_image": "error"}}     # default is "downsize"

A marked image that would be resized fails with a 400 that tells you the largest size that fits, for example: "messages.0.content.0: image dimensions 1920x1080 exceed the maximum image size of a model named on this request and would be downsized to 1456x819; scale the image to at most 1456x819 or set the image's oversized_image setting to "downsize"". The 8,000 px hard limit and the many-image limit still apply separately. Images returned in a tool_result to the computer-use and browser-use tools are the exception: they're rejected instead of downscaled.

Anthropic's guidance on ordering: "Claude works best when images come before text", though other orders "still perform well". Its listed limitations: it won't identify people, it can hallucinate on low-quality, rotated or very small images (under 200 pixels), its coordinates and counts are approximate, and it can't tell whether an image is AI-generated.

2.6 The same image on hosted providers: base64, URL and file ID#

These samples send the test image to the real APIs in each of the three ways. They need keys, and they leave nothing behind: each uploaded file is deleted in a finally block. The public URL is a Wikimedia Commons photo of an ant (1800×1200 px). Public hosts can block provider fetchers (1.4), so for your own tests put an image in a bucket you control and use that link. First, OpenAI:

python
# s2_6a_openai_images.py
"""OpenAI: one image three ways (data URL, public URL, file ID) on Responses, plus Chat Completions."""
import base64
from pathlib import Path

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

IMAGE_URL = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
png = Path("shapes.png").read_bytes()
data_url = "data:image/png;base64," + base64.b64encode(png).decode("ascii")

# 1. Inline: a data URL. The image travels inside this request (and inside every later
#    request that re-sends this turn).
r1 = client.responses.create(
    model="gpt-6-luna",
    input=[{"role": "user", "content": [
        {"type": "input_image", "image_url": data_url, "detail": "low"},   # low: coarse, cheap
        {"type": "input_text", "text": "What text is at the top of this image?"},
    ]}],
    reasoning={"effort": "none"},
    max_output_tokens=200,
)
print("data URL :", r1.output_text, "| input tokens:", r1.usage.input_tokens if r1.usage else None)

# 2. By URL: OpenAI's servers download the image. It must be publicly reachable.
r2 = client.responses.create(
    model="gpt-6-luna",
    input=[{"role": "user", "content": [
        {"type": "input_image", "image_url": IMAGE_URL, "detail": "high"},
        {"type": "input_text", "text": "What insect is this? One sentence."},
    ]}],
    reasoning={"effort": "none"},
    max_output_tokens=200,
)
print("URL      :", r2.output_text, "| input tokens:", r2.usage.input_tokens if r2.usage else None)

# 3. By file ID: upload once, reference many times (Part 5 covers the Files API).
uploaded = client.files.create(file=("shapes.png", png, "image/png"), purpose="vision",
                               expires_after={"anchor": "created_at", "seconds": 3600})
try:
    r3 = client.responses.create(
        model="gpt-6-luna",
        input=[{"role": "user", "content": [
            {"type": "input_image", "file_id": uploaded.id, "detail": "auto"},
            {"type": "input_text", "text": "What colour is the circle?"},
        ]}],
        reasoning={"effort": "none"},
        max_output_tokens=200,
    )
    print("file ID  :", r3.output_text, "| input tokens:", r3.usage.input_tokens if r3.usage else None)
finally:
    client.files.delete(uploaded.id)            # don't leave user data lying around

# 4. Chat Completions: the part is called image_url, and the URL sits one level deeper.
completion = client.chat.completions.create(
    model="gpt-6-luna",
    messages=[{"role": "user", "content": [
        {"type": "image_url", "image_url": {"url": data_url, "detail": "low"}},
        {"type": "text", "text": "What colour is the square?"},
    ]}],
    reasoning_effort="none",
    max_completion_tokens=200,
)
print("chat     :", completion.choices[0].message.content,
      "| prompt tokens:", completion.usage.prompt_tokens if completion.usage else None)
Example output · illustrative4 lines
data URL : The text at the top of the image reads "INVOICE 42". | input tokens: 205
URL      : It's an ant, most likely a carpenter ant (genus Camponotus), shown in close-up. | input tokens: 2614
file ID  : The circle is blue. | input tokens: 330
chat     : The square is red. | prompt tokens: 207

OpenAI's vision examples upload images with purpose="vision"; its file-inputs guide recommends user_data "for files you plan to pass as model inputs". Both work for input_image. Anthropic:

python
# s2_6b_anthropic_images.py
"""Anthropic: one image three ways (base64, URL, file ID), with the image before the question."""
import base64
from pathlib import Path

import anthropic
from anthropic.types import ImageBlockParam
from dotenv import load_dotenv

load_dotenv()
client = anthropic.Anthropic()

IMAGE_URL = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
png = Path("shapes.png").read_bytes()


def ask(image_block: ImageBlockParam, question: str) -> None:      # typed, so pyright checks the keys
    message = client.messages.create(
        model="claude-haiku-5-5",
        max_tokens=300,
        messages=[{"role": "user", "content": [image_block, {"type": "text", "text": question}]}],
    )
    text = "".join(b.text for b in message.content if b.type == "text")
    print(f"{image_block['source']['type']:7}: {text} | input tokens: {message.usage.input_tokens}")


# 1. base64: the raw base64 string, with the media type as a separate field (no "data:" prefix)
ask({"type": "image", "source": {"type": "base64", "media_type": "image/png",
                                 "data": base64.b64encode(png).decode("ascii")}},
    "What text is at the top of this image?")

# 2. URL: Anthropic downloads it. Not available on Bedrock or Google-managed Google Cloud.
ask({"type": "image", "source": {"type": "url", "url": IMAGE_URL}}, "What insect is this? One sentence.")

# 3. file ID, with the oversized-image guard: fail instead of silently downscaling
uploaded = client.files.upload(file=("shapes.png", png, "image/png"), expires_in_seconds=3600)
try:
    ask({"type": "image", "source": {"type": "file", "file_id": uploaded.id},
         "transformations": {"oversized_image": "error"}}, "What colour is the circle?")
finally:
    client.files.delete(uploaded.id)
Example output · illustrative3 lines
base64 : The text at the top of the image reads "INVOICE 42". | input tokens: 360
url    : This is an ant, most likely a carpenter ant (genus Camponotus), photographed in close-up. | input tokens: 2810
file   : The circle is blue. | input tokens: 357

Typing the helper's parameter as ImageBlockParam (the SDK's TypedDict for an image block) lets a type checker catch a misspelt key such as "oversized_imag", which a plain dict would let through to a 400 at run time. Gemini, on generate_content and Interactions:

python
# s2_6c_gemini_images.py
"""Gemini: inline bytes, a public URL and media_resolution, on generate_content and Interactions."""
import base64
from pathlib import Path

from dotenv import load_dotenv
from google import genai
from google.genai import types

load_dotenv()
client = genai.Client()

IMAGE_URL = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
png = Path("shapes.png").read_bytes()

# 1. Inline bytes: the SDK base64-encodes them for you. media_resolution is set per part
#    (Gemini 3 and 4); LOW caps this image at about 280 tokens instead of the default 1,120.
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=[
        types.Part.from_bytes(data=png, mime_type="image/png",
                              media_resolution=types.PartMediaResolutionLevel.MEDIA_RESOLUTION_LOW),
        "What text is at the top of this image?",
    ],
    config=types.GenerateContentConfig(max_output_tokens=300),
)
print("inline :", response.text)
usage = response.usage_metadata
if usage:
    print("         prompt tokens:", usage.prompt_token_count,
          "by modality:", [(d.modality.name if d.modality else None, d.token_count)
                           for d in usage.prompt_tokens_details or []])

# 2. A public URL as a file_data part (Gemini fetches it, up to 15 MB; not on Gemini 2.0).
#    media_resolution in the config applies to every media part in the request.
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=[types.Part.from_uri(file_uri=IMAGE_URL, mime_type="image/jpeg"),
              "What insect is this? One sentence."],
    config=types.GenerateContentConfig(max_output_tokens=300,
                                       media_resolution=types.MediaResolution.MEDIA_RESOLUTION_HIGH),
)
print("URL    :", response.text)

# 3. Interactions API: typed content blocks; "resolution" is the per-block setting
interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {"type": "image", "data": base64.b64encode(png).decode("ascii"), "mime_type": "image/png",
         "resolution": "low"},
        {"type": "text", "text": "What colour is the circle?"},
    ],
    generation_config={"max_output_tokens": 300},
)
print("interactions:", interaction.output_text)
if interaction.usage:
    print("         input tokens:", interaction.usage.total_input_tokens,
          "by modality:", interaction.usage.input_tokens_by_modality)
Example output · illustrative5 lines
inline : The text at the top of the image is "INVOICE 42".
         prompt tokens: 290 by modality: [('TEXT', 10), ('IMAGE', 280)]
URL    : This is an ant, likely a carpenter ant (Camponotus), seen close up.
interactions: The circle is blue.
         input tokens: 287 by modality: [ModalityTokens(modality='text', tokens=7), ModalityTokens(modality='image', tokens=280)]

Gemini is the only provider whose usage splits input tokens by modality (prompt_tokens_details on generate_content, input_tokens_by_modality on Interactions), which makes it easy to see what an image really cost. Finally OpenRouter, sending one image as a data URL and one as a URL in the same Chat Completions request, and then the Responses-compatible shape:

python
# s2_6d_openrouter_images.py
"""OpenRouter: images on Chat Completions (primary) and on the Responses-compatible API."""
import base64
import os
from pathlib import Path

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"],
    default_headers={"HTTP-Referer": "https://example.com/my-app", "X-OpenRouter-Title": "My App"},
)

IMAGE_URL = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
data_url = "data:image/png;base64," + base64.b64encode(Path("shapes.png").read_bytes()).decode("ascii")

# Chat Completions: OpenRouter recommends the text first, then the images
completion = client.chat.completions.create(
    model="anthropic/claude-haiku-5.5",
    messages=[{"role": "user", "content": [
        {"type": "text", "text": "Image 1 is a diagram, image 2 a photo. Describe each in five words."},
        {"type": "image_url", "image_url": {"url": data_url}},     # base64 data URL
        {"type": "image_url", "image_url": {"url": IMAGE_URL}},    # public URL
    ]}],
    max_completion_tokens=300,
)
print("chat     :", completion.choices[0].message.content)
if completion.usage:
    print("           prompt tokens:", completion.usage.prompt_tokens,
          "cost:", (completion.usage.model_extra or {}).get("cost"))   # OpenRouter-only field

# Responses-compatible API: the same input_image part as OpenAI's (stateless only on OpenRouter)
response = client.responses.create(
    model="google/gemini-3.8-flash",
    input=[{"role": "user", "content": [
        {"type": "input_text", "text": "What text is at the top of this image?"},
        {"type": "input_image", "image_url": data_url, "detail": "auto"},
    ]}],
    max_output_tokens=300,
)
print("responses:", response.output_text)
Example output · illustrative3 lines
chat     : Image 1: red square, blue circle, label. Image 2: close-up of an ant.
           prompt tokens: 3178 cost: 0.0004076
responses: The text at the top of the image is "INVOICE 42".

2.7 The image limits side by side#

As of November 2026 (check the linked pages before relying on a number: limits change with model generations):

OpenAI Anthropic
Formats PNG, JPEG, WEBP, non-animated GIF JPEG, PNG, GIF (first frame only), WebP
Images per request 1,500 600 (100 on 200K-context models)
Pixel limits 30,000 patches after resizing, else rejected 8000×8000; stricter above 20 images (keep ≤ 3,000 px)
Size limits 512 MB payload per request (vision guide) 10 MB per image, base64-encoded; 128 MB per request
Too big? Resized per detail; rejected past 30,000 patches Downscaled silently, unless oversized_image: "error"
Detail control detail: low, high, original, auto None: resolution follows the model tier
Sources data URL, URL, file_id base64, URL, file
Gemini OpenRouter
Formats PNG, JPEG, WEBP, HEIC, HEIF PNG, JPEG, WEBP, GIF (then the upstream provider's rules)
Images per request 3,600 Varies by provider and model
Pixel limits No documented pixel limit Upstream provider's
Size limits Inline: 20 MB safe, 100 MB per one page; URL: 15 MB per file Upstream provider's
Too big? Fixed token budget per media_resolution Upstream provider's
Detail control media_resolution: low … ultra_high detail, including original
Sources inline bytes, URL, Files API, Cloud Storage data URL, URL, file ID (5.6)

2.4 Gemini: parts, Interactions blocks and media_resolution#

Shapes on generate_content. An image is a types.Part, built with one of two helpers (SDK 2.34.0 signatures):

python
types.Part.from_bytes(data=image_bytes, mime_type="image/png", media_resolution=None)   # inline_data
types.Part.from_uri(file_uri="https://...", mime_type="image/jpeg", media_resolution=None)  # file_data

from_bytes takes raw bytes (the SDK does the base64). from_uri takes a Files API URI (5.5), a Google Cloud Storage registration, or a public https:// URL. You can also put a types.File object from client.files.upload straight into contents. On Interactions, an image is a typed block: {"type": "image", "data": "<base64>", "mime_type": "image/png"} or {"type": "image", "uri": "...", "mime_type": "..."}, with an optional "resolution".

Formats (November 2026): Google's image guide lists PNG, JPEG, WEBP, HEIC and HEIF. The SDK's Interactions types also list image/gif, image/bmp and image/tiff, and the external-URL list mentions image/bmp. Stick to the five documented formats unless you've tested the others.

Limits. Up to 3,600 images per request. For URLs: "Each file can be up to 15 MB", publicly accessible (or pre-signed), and not on Gemini 2.0 models; URLs that fail Google's safety check come back with a url_retrieval_status of URL_RETRIEVAL_STATUS_UNSAFE. For inline data, Google's documentation contradicts itself, as of November 2026:

  • The file-input-methods and Files pages say inline data is limited to "100 MB per request or payload (50 MB for PDFs)", and "Always use the Files API when the total request size ... is larger than 100 MB".
  • The image, audio and video pages still say inline data "limits your total request size (text prompts, system instructions, and inline bytes) to 20MB".

The safe reading: keep inline requests under 20 MB, and use the Files API for anything larger. That works whichever page is current, and a 20 MB request is already a slow one.

media_resolution (Gemini 3 and 4) sets the maximum number of tokens an image, video frame or PDF page may use, regardless of its pixel size. You can set it per part, which the docs recommend, or for the whole request on generate_content:

python
# per part (generate_content): LOW, MEDIUM, HIGH, ULTRA_HIGH (ULTRA_HIGH only per part)
types.Part.from_bytes(data=png, mime_type="image/png",
                      media_resolution=types.PartMediaResolutionLevel.MEDIA_RESOLUTION_LOW)

# per request (generate_content): LOW, MEDIUM or HIGH for every media part
types.GenerateContentConfig(media_resolution=types.MediaResolution.MEDIA_RESOLUTION_HIGH)

# per block (Interactions): "low" | "medium" | "high" | "ultra_high"
{"type": "image", "data": b64, "mime_type": "image/png", "resolution": "low"}

Google's token table for Gemini 3 and 4 models (approximate, November 2026):

media_resolution Image Video frame Audio PDF page
unspecified (default) 1,120 70 25 per second 560
low 280 70 25 per second 280 + native text
medium 560 70 25 per second 560 + native text
high 1,120 280 25 per second 1,120 + native text
ultra_high (per part only) 2,240 — — —

Google recommends high for images ("optimal performance for most use cases"), medium for PDFs (quality "typically saturates at medium"), and low for most video. Earlier Gemini models used different rules (258 tokens per 768×768 tile), covered in 3.1.

The "+ native text" in the PDF column is in tension with Google's other page. The media-resolution table above is written as if a PDF page costs its image budget plus the tokens of its embedded text, while the document-processing page says "You are not charged for tokens originating from the extracted native text" (4.5). Both are Google's wording as of November 2026. Don't budget from either: count a real PDF with count_tokens and, after a real call, compare the TEXT and IMAGE rows of usage_metadata.prompt_tokens_details.

Audio is where Google's own pages disagree, and a key settles it. As of 2026-11-04:

  • 25 tokens per second: the media-resolution page, the only page whose token table is scoped to "Gemini 4 and Gemini 3 models" ("Audio is tokenized at a fixed rate of 25 tokens per second across all supported resolution settings"). Google's pricing footnotes for audio models say the same ("Audio tokens correspond to 25 tokens per second of audio"), and so does the Live API context-management guide ("approximately 25 tokens per sec of audio").
  • 32 tokens per second: the audio-understanding page ("32 tokens per second of audio (1 minute = 1,920 tokens)"), the video page, and the token-counting page, whose audio example uses gemini-3.8-flash and says "A 60-second audio clip is approximately 32 * 60 = 1,920 tokens".
  • Why the 32 pages may be stale: the same token-counting page still says an image costs 258 tokens per 768×768 tile and video 263 tokens per second, which the Gemini 3 pages above replace (1,120 per image, 70 per video frame).

The better-supported reading is about 25 per second for Gemini 3 and 4, and 32 as the older figure. It is a reading, not a fact: Google's own pages disagree, and nobody can settle it without a key. So treat audio budgets as "25 to 32 tokens per second" (90,000 to 115,000 tokens an hour, as Part 8 uses), and measure the model you use. count_tokens on a 60-second clip does it:

python
# s2_4_audio_tokens.py
"""Settle Gemini's audio token rate yourself: count a 60-second WAV with count_tokens (needs a key)."""
import io
import math
import struct
import wave
from datetime import date

from dotenv import load_dotenv
from google import genai
from google.genai import types

load_dotenv()
MODEL = "gemini-3.8-flash"
SECONDS, SAMPLE_RATE = 60, 16_000

# 60 seconds of a 440 Hz tone as a 16-bit mono WAV (about 1.9 MB). Token counts follow duration, not content.
samples = (int(8000 * math.sin(2 * math.pi * 440 * n / SAMPLE_RATE)) for n in range(SECONDS * SAMPLE_RATE))
buffer = io.BytesIO()
with wave.open(buffer, "wb") as wav:
    wav.setnchannels(1)
    wav.setsampwidth(2)
    wav.setframerate(SAMPLE_RATE)
    wav.writeframes(b"".join(struct.pack("<h", s) for s in samples))

client = genai.Client()
count = client.models.count_tokens(          # audio only, no text, so nothing else is in the total
    model=MODEL,
    contents=[types.Part.from_bytes(data=buffer.getvalue(), mime_type="audio/wav")],
)
total = count.total_tokens or 0
rate = total / SECONDS
if rate < 10:                                # a 60-second clip can't be 10 tokens a second: it never arrived
    reading = "far too low: the audio was probably dropped on the way (a proxy, or a stand-in?)"
elif rate < 28.5:
    reading = "about 25 per second (the Gemini 3 and 4 figure)"
else:
    reading = "about 32 per second (the older figure)"
print(f"{date.today()}  {MODEL}: {total:,} tokens for {SECONDS} s = {rate:.1f} per second, {reading}")

There is no output to show, because the output is the measurement. About 1,500 tokens for the 60 seconds means 25 per second, and about 1,920 means 32 per second. A few dozen tokens means the audio never arrived. Record the date with the result, because Google can change the rate between model generations. (This sample is hosted-only: Gemini has no local stand-in, so it was not run.)

Google's tips: rotate images correctly, avoid blurry ones, and, on ordering, three Google pages give three different answers, which 7.1 sorts out.

2.5 OpenRouter: image_url and input_image#

OpenRouter takes the OpenAI shapes: image_url parts on Chat Completions (its primary API) and input_image parts on its Responses-compatible API, each holding a public URL or a base64 data URL. Supported types are image/png, image/jpeg, image/webp and image/gif. The number of images per request "varies per provider and per model", because OpenRouter forwards your request to whichever upstream provider serves the model, and that provider's limits apply.

Three OpenRouter specifics, as of November 2026:

  • Ordering advice: "Due to how the content is parsed, we recommend sending the text prompt first, then the images. If the images must come first, put them before the text within the same user message; system messages should contain text only."
  • detail on image_url accepts auto, low, high, and original, which OpenRouter's API reference describes as "an OpenRouter extension (not in the OpenAI Chat Completions spec)", downgraded to high for providers without an original-resolution tier.
  • Which models take images is data, not guesswork. Every model in OpenRouter's catalogue lists its input modalities, and the public /api/v1/models endpoint (no key needed) filters by them:
python
# s2_5_openrouter_modalities.py
"""Which models accept images, files, audio or video? Ask OpenRouter's public catalogue (no key needed)."""
import httpx

resp = httpx.get("https://openrouter.ai/api/v1/models", params={"input_modalities": "image"}, timeout=30.0)
resp.raise_for_status()
models = {m["id"]: m for m in resp.json()["data"]}
print(f"{len(models)} models accept image input")

for model_id in ["openai/gpt-6-luna", "anthropic/claude-haiku-5.5", "google/gemini-3.8-flash"]:
    m = models[model_id]
    print(f"  {model_id:28} in={m['architecture']['input_modalities']}  "
          f"image price field={m['pricing'].get('image')!r}")

# A text-only model is simply absent from the image-filtered list
everything = {m["id"] for m in httpx.get("https://openrouter.ai/api/v1/models", timeout=30.0).json()["data"]}
text_only = "meta-llama/llama-3.3-70b-instruct"
print(f"  {text_only}: in catalogue={text_only in everything}, accepts images={text_only in models}")

Output (a live call to OpenRouter's public catalogue on 4 November 2026; the counts change daily):

text
310 models accept image input
  openai/gpt-6-luna            in=['file', 'image', 'text']  image price field=None
  anthropic/claude-haiku-5.5   in=['text', 'image', 'file']  image price field=None
  google/gemini-3.8-flash      in=['text', 'image', 'video', 'file', 'audio']  image price field='0.000000825'
  meta-llama/llama-3.3-70b-instruct: in catalogue=True, accepts images=False

architecture.input_modalities is the field to check before you route an image to a model (lesson 02.9, 4.10 shows the same check on every provider's Models API). The input_modalities filter is documented with text, image, audio and file. A live call with input_modalities=video also worked on 4 November 2026 (92 models), but that value isn't in the OpenAPI spec, so treat it as undocumented, and read architecture.input_modalities per model when it matters. Some models also carry a separate pricing.image field; where it's absent, images are billed as input tokens at the model's normal rate.


Part 3: What an image costs#

3.1 Four different rules#

Every provider turns an image into input tokens, billed at the model's normal input price (lesson 02.9, 6.10), but each counts them differently. The documented rules, as of November 2026:

OpenAI, patch-based models (gpt-6-astra, the GPT-5.x families): cover the image with 32×32-pixel patches after resizing it for the chosen detail level, then multiply by a per-model factor. Step by step, from OpenAI's guide:

  1. Fit the image inside the detail level's pixel limit, keeping its aspect ratio and never enlarging it.
  2. If the level has a patch budget (2,500 for high), shrink the image proportionally until its patch count fits the budget.
  3. Count the patches. More than 30,000 means rejection.
  4. Multiply by the model's multiplier and round up. The multiplier is 1.2 for gpt-6-astra and every GPT-5.6, 5.5, 5.4 and 5.2 model (1.62 for gpt-4.1-mini).

OpenAI's worked examples for gpt-6-astra with detail: "high": a 1024×1024 image is 32 × 32 = 1,024 patches, so ⌈1,024 × 1.2⌉ = 1,229 tokens; a 2048×2048 image is shrunk to 1600×1600 (2,500 patches) and costs 3,000 tokens; a 4096×512 banner keeps its size (2,048 patches) and costs 2,458.

OpenAI, older tile-based models (gpt-5.1, gpt-4.1, gpt-4o): with low, a fixed base cost (70 tokens for gpt-5.1, 85 for gpt-4.1 and gpt-4o). With high or auto: fit in 2048×2048, scale the shortest side down to 768 px, count 512-pixel tiles, and charge base + tiles × tile tokens (70 + 140 per tile on gpt-5.1, 85 + 170 on gpt-4.1).

Anthropic: cover the image with 28×28-pixel patches: tokens = ⌈width / 28⌉ × ⌈height / 28⌉, after downscaling to fit the model tier's long-edge and token caps (2.3). Because of the cap, cost stops growing past a certain size: a 3840×2160 (4K) screenshot costs 4,784 tokens on a high-resolution-tier model, the same as any image that hits the cap. Anthropic's example: a 1000×1000 image is 1,296 tokens on either tier.

Gemini 3 and 4: a fixed budget per media part, set by media_resolution (2.4): about 1,120 tokens per image by default, 280 at low. Pixel size doesn't matter, within the limits. Older Gemini models charged 258 tokens for an image with both sides at most 384 px, and otherwise 258 per tile, where a tile is about ⌊shortest side ÷ 1.5⌋ pixels square (Google's example: 960×540 is 3 × 2 = 6 tiles, 1,548 tokens).

OpenRouter: whatever the upstream model's rule is, at the price in the model's catalogue entry.

3.2 Try it: a media-token estimator#

This module turns those rules into functions you can call before every request. It's a file you can drop into a project; the limits live in data structures at the top, so a new model generation means editing numbers, not logic.

python
"""media_tokens.py: estimate what an image or PDF will cost in input tokens, before you send it.

Each function implements a provider's *documented* rule (as of November 2026):
  OpenAI     developers.openai.com/api/docs/guides/images-vision#calculating-costs
  Anthropic  platform.claude.com/docs/en/build-with-claude/vision#evaluate-image-size
             (resize rule: .../vision-coordinates#how-claude-resizes-and-pads-images)
  Gemini     aistudio.google.com/docs/media-resolution and /docs/image-understanding
These are estimates: the providers' counting endpoints and the `usage` of a real call
are the ground truth (lesson 03.7). Keep the numbers in configuration, not in code,
because each model generation changes them.
"""
import math
from dataclasses import dataclass


# ---------- OpenAI: 32 px patches, a resizing budget, then a per-model multiplier ----------

@dataclass(frozen=True)
class OpenAIPatchRule:
    max_dim: int            # pixel-dimension limit for this detail level
    patch_budget: int | None  # resizing patch budget (None = no budget for this level)
    multiplier: float       # model-specific factor applied to the patch count


# From the images-vision guide's sizing table and multiplier table (gpt-6-astra row).
# The guide doesn't list gpt-6-luna or the GPT-6.1 models (November 2026): measure those.
OPENAI_GPT_6_ASTRA = {
    "low": OpenAIPatchRule(max_dim=512, patch_budget=None, multiplier=1.2),
    "high": OpenAIPatchRule(max_dim=65_535, patch_budget=2_500, multiplier=1.2),
    "original": OpenAIPatchRule(max_dim=65_535, patch_budget=None, multiplier=1.2),
}
OPENAI_REJECT_ABOVE_PATCHES = 30_000   # checked before the multiplier; rejected, not resized


def _patches(w: int, h: int, size: int = 32) -> int:
    return math.ceil(w / size) * math.ceil(h / size)


def openai_image_tokens(w: int, h: int, rule: OpenAIPatchRule) -> int:
    """Billable image tokens on a patch-based OpenAI model. Raises if the API would reject it."""
    # A. fit inside the pixel-dimension limit (never enlarge)
    scale = min(1.0, rule.max_dim / max(w, h))
    w, h = max(1, int(w * scale)), max(1, int(h * scale))
    # B/C. shrink to the patch budget, if this level has one
    if rule.patch_budget and _patches(w, h) > rule.patch_budget:
        s = math.sqrt(rule.patch_budget * 32 * 32 / (w * h))
        while _patches(int(w * s), int(h * s)) > rule.patch_budget:
            s *= 0.999                                  # nudge down until integer sizes fit
        w, h = int(w * s), int(h * s)
    patches = _patches(w, h)
    if patches > OPENAI_REJECT_ABOVE_PATCHES:
        raise ValueError(f"{patches} patches > {OPENAI_REJECT_ABOVE_PATCHES}: the API rejects this image")
    # D. multiply and round up
    return math.ceil(patches * rule.multiplier)


def openai_tile_tokens(w: int, h: int, detail: str, base: int, tile: int) -> int:
    """Older tile-based models (gpt-5.1: base 70, tile 140; gpt-4.1: 85 / 170)."""
    if detail == "low":
        return base
    scale = min(1.0, 2048 / max(w, h))                  # fit in a 2048 x 2048 square
    fw, fh = w * scale, h * scale
    if min(fw, fh) > 768:                               # shortest side down to 768
        scale = 768 / min(fw, fh)
        fw, fh = fw * scale, fh * scale
    return base + tile * math.ceil(int(fw) / 512) * math.ceil(int(fh) / 512)


# ---------- Anthropic: 28 px patches, capped by a long edge and a token budget ----------

ANTHROPIC_STANDARD = (1568, 1568)     # (max long edge, max visual tokens): models before Claude 4.7
ANTHROPIC_HIGH_RES = (2576, 4784)     # Claude 4.7 and later, including all Claude 5.x models


def anthropic_image_tokens(w: int, h: int, tier: tuple[int, int] = ANTHROPIC_HIGH_RES) -> tuple[int, int, int]:
    """Returns (tokens, resized_w, resized_h), following Anthropic's reference implementation."""
    max_edge, max_tokens = tier

    def count(a: int, b: int) -> int:
        return math.ceil(a / 28) * math.ceil(b / 28)

    def fits(a: int, b: int) -> bool:
        return (math.ceil(a / 28) * 28 <= max_edge and math.ceil(b / 28) * 28 <= max_edge
                and count(a, b) <= max_tokens)

    def resized(a: int, b: int) -> tuple[int, int]:
        if fits(a, b):
            return a, b
        if b > a:
            rb, ra = resized(b, a)
            return ra, rb
        ratio, lo, hi = a / b, 1, a                      # binary search on the long edge
        while lo + 1 < hi:
            mid = (lo + hi) // 2
            if fits(mid, max(round(mid / ratio), 1)):
                lo = mid
            else:
                hi = mid
        return lo, max(round(lo / ratio), 1)

    rw, rh = resized(w, h)
    return count(rw, rh), rw, rh


# ---------- Gemini: a fixed budget per media_resolution level (Gemini 3 and 4) ----------

GEMINI_3_IMAGE = {"unspecified": 1120, "low": 280, "medium": 560, "high": 1120, "ultra_high": 2240}
GEMINI_3_PDF_PAGE = {"unspecified": 560, "low": 280, "medium": 560, "high": 1120}  # + native text, not billed


def gemini_image_tokens(level: str = "unspecified") -> int:
    return GEMINI_3_IMAGE[level]          # the size of the image doesn't change the budget


def gemini_legacy_image_tokens(w: int, h: int) -> int:
    """Gemini 2.x: 258 tokens if both sides <= 384 px, else 258 per tile (crop unit = min side / 1.5)."""
    if w <= 384 and h <= 384:
        return 258
    crop = math.floor(min(w, h) / 1.5)
    return 258 * math.ceil(w / crop) * math.ceil(h / crop)


# ---------- PDFs ----------

def pdf_tokens_estimate(pages: int) -> dict[str, str]:
    """Rough per-request ranges. Only Gemini documents a per-page number; the others vary with content."""
    return {
        "OpenAI": "extracted text + page images: no per-page rule published; count it (03.7)",
        "Anthropic": f"{pages * 1_500:,}-{pages * 3_000:,} text tokens, plus up to "
                     f"{pages * ANTHROPIC_HIGH_RES[1]:,} for the page images",
        "Gemini 3/4": f"{pages * GEMINI_3_PDF_PAGE['unspecified']:,} at the default "
                      f"({pages * GEMINI_3_PDF_PAGE['low']:,} at low); embedded text not billed",
        "OpenRouter": "depends on the engine: native = the model's own rule; cloudflare-ai/mistral-ocr = text tokens",
    }

An estimator is only useful if it's right, so the demo first checks it against every worked example in the providers' own documentation, then prices the same images on every provider:

python
# s3_2_estimator.py
"""Estimate image tokens on each provider, and check the estimator against the docs' own examples."""
from media_tokens import (ANTHROPIC_HIGH_RES, ANTHROPIC_STANDARD, OPENAI_GPT_6_ASTRA,
                          anthropic_image_tokens, gemini_image_tokens, gemini_legacy_image_tokens,
                          openai_image_tokens, openai_tile_tokens, pdf_tokens_estimate)

# 1. Cross-check against the worked examples printed in each provider's documentation
checks = [
    ("OpenAI gpt-6-astra high 1024x1024", openai_image_tokens(1024, 1024, OPENAI_GPT_6_ASTRA["high"]), 1229),
    ("OpenAI gpt-6-astra high 2048x2048", openai_image_tokens(2048, 2048, OPENAI_GPT_6_ASTRA["high"]), 3000),
    ("OpenAI gpt-6-astra high 4096x512", openai_image_tokens(4096, 512, OPENAI_GPT_6_ASTRA["high"]), 2458),
    ("Anthropic standard 1920x1080", anthropic_image_tokens(1920, 1080, ANTHROPIC_STANDARD)[0], 1560),
    ("Anthropic high-res 1920x1080", anthropic_image_tokens(1920, 1080, ANTHROPIC_HIGH_RES)[0], 2691),
    ("Anthropic high-res 3840x2160", anthropic_image_tokens(3840, 2160, ANTHROPIC_HIGH_RES)[0], 4784),
    ("Anthropic standard A4 scan 1075x1520 -> size", anthropic_image_tokens(1075, 1520, ANTHROPIC_STANDARD)[1:], (924, 1307)),
    ("Gemini legacy 960x540", gemini_legacy_image_tokens(960, 540), 6 * 258),
]
for label, got, docs in checks:
    print(f"{'OK ' if got == docs else 'BAD'} {label:46} estimator={got!s:12} docs={docs}")

# 2. The same images on every provider
print(f"\n{'image (w x h)':>14} | {'OpenAI astra':^25} | {'Anthropic':^20} | {'Gemini 3/4':^17}")
print(f"{'':>14} | {'low':>7} {'high':>7} {'original':>9} | {'standard':>9} {'high-res':>9} | {'low':>5} {'default':>8}")
for w, h in [(200, 200), (640, 400), (1024, 1024), (1920, 1080), (4032, 3024), (6000, 6000)]:
    try:
        orig = str(openai_image_tokens(w, h, OPENAI_GPT_6_ASTRA["original"]))
    except ValueError:
        orig = "rejected"
    print(f"{f'{w} x {h}':>14} | {openai_image_tokens(w, h, OPENAI_GPT_6_ASTRA['low']):>7} "
          f"{openai_image_tokens(w, h, OPENAI_GPT_6_ASTRA['high']):>7} {orig:>9} | "
          f"{anthropic_image_tokens(w, h, ANTHROPIC_STANDARD)[0]:>9} {anthropic_image_tokens(w, h)[0]:>9} | "
          f"{gemini_image_tokens('low'):>5} {gemini_image_tokens():>8}")

print("\nOlder tile-based OpenAI model (gpt-5.1, base 70 / tile 140), 1920x1080 high:",
      openai_tile_tokens(1920, 1080, "high", base=70, tile=140))

print("\nA 40-page PDF:")
for provider, estimate in pdf_tokens_estimate(40).items():
    print(f"  {provider:11} {estimate}")
Output25 lines
OK  OpenAI gpt-6-astra high 1024x1024              estimator=1229         docs=1229
OK  OpenAI gpt-6-astra high 2048x2048              estimator=3000         docs=3000
OK  OpenAI gpt-6-astra high 4096x512               estimator=2458         docs=2458
OK  Anthropic standard 1920x1080                   estimator=1560         docs=1560
OK  Anthropic high-res 1920x1080                   estimator=2691         docs=2691
OK  Anthropic high-res 3840x2160                   estimator=4784         docs=4784
OK  Anthropic standard A4 scan 1075x1520 -> size   estimator=(924, 1307)  docs=(924, 1307)
OK  Gemini legacy 960x540                          estimator=1548         docs=1548

 image (w x h) |       OpenAI astra        |      Anthropic       |    Gemini 3/4    
               |     low    high  original |  standard  high-res |   low  default
     200 x 200 |      59      59        59 |        64        64 |   280     1120
     640 x 400 |     192     312       312 |       345       345 |   280     1120
   1024 x 1024 |     308    1229      1229 |      1369      1369 |   280     1120
   1920 x 1080 |     173    2448      2448 |      1560      2691 |   280     1120
   4032 x 3024 |     231    2993     14364 |      1564      4740 |   280     1120
   6000 x 6000 |     308    3000  rejected |      1521      4761 |   280     1120

Older tile-based OpenAI model (gpt-5.1, base 70 / tile 140), 1920x1080 high: 910

A 40-page PDF:
  OpenAI      extracted text + page images: no per-page rule published; count it (03.7)
  Anthropic   60,000-120,000 text tokens, plus up to 191,360 for the page images
  Gemini 3/4  22,400 at the default (11,200 at low); embedded text not billed
  OpenRouter  depends on the engine: native = the model's own rule; cloudflare-ai/mistral-ocr = text tokens

All eight documented examples match. Reading the table:

  • Small images are cheap everywhere except at Gemini's default. A 200×200 thumbnail is about 60 tokens on OpenAI and Anthropic, but Gemini's media_resolution is a maximum per image, and Google's table lists the default as 1,120 without saying whether small images use less. Measure it (the next section shows how), and set low for thumbnails.
  • Caps flatten the cost of big images, but not to zero difference. A 12-megapixel phone photo (4032×3024) costs 2,993 tokens with OpenAI high and 4,740 on Claude's high-resolution tier, because both providers shrink it first. Next to a 2-megapixel 1080p screenshot (2,448 and 2,691) that is about 22% more on OpenAI high and about 1.8 times as much on Claude 5.x. On Claude's standard tier the two cost the same (1,564 and 1,560), because both hit that tier's cap. And a 4K screenshot (4,784 on Claude 5.x) already sits at the cap, so it costs about the same as the photo (4,740). Uploading the full 9 MB buys nothing but upload time.
  • original is where the cost goes. The same photo with OpenAI original costs 14,364 tokens, nearly five times high, and a 6000×6000 image is rejected outright.
  • Claude 5.x costs up to three times more per large image than older Claude models, because the high-resolution tier allows more tokens (4,740 vs 1,564 for the photo). Anthropic suggests downsampling when you don't need the extra fidelity.

3.3 Checking the estimate: counting endpoints and usage#

There are two ways to check an estimate against the provider's own numbers.

Before the call: counting endpoints. All three first-party providers can count the tokens of a request that includes media, without running the model. Lesson 03.7 covers them in depth (their own rate limits, caching the counts, and budgets); here's the shape with an image:

python
# s3_3_count_vs_estimate.py
"""Estimate vs counting endpoint for one image, on each provider (lesson 03.7 covers counting in depth)."""
import base64
from pathlib import Path

import anthropic
from dotenv import load_dotenv
from google import genai
from google.genai import types
from openai import OpenAI

from media_tokens import anthropic_image_tokens, gemini_image_tokens

load_dotenv()
png = Path("shapes.png").read_bytes()                # 640 x 400
b64 = base64.b64encode(png).decode("ascii")      # count with base64: Anthropic rejects url and file sources here
QUESTION = "What text is at the top?"

oai = OpenAI()
count = oai.responses.input_tokens.count(model="gpt-6-luna", input=[{"role": "user", "content": [
    {"type": "input_image", "image_url": f"data:image/png;base64,{b64}", "detail": "high"},
    {"type": "input_text", "text": QUESTION}]}])
print(f"OpenAI    count={count.input_tokens:>5}  (no published gpt-6-luna rule; gpt-6-astra's would say 312 + text)")

claude = anthropic.Anthropic()
count2 = claude.messages.count_tokens(model="claude-haiku-5-5", messages=[{"role": "user", "content": [
    {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": b64}},
    {"type": "text", "text": QUESTION}]}])
print(f"Anthropic count={count2.input_tokens:>5}  estimate={anthropic_image_tokens(640, 400)[0]} + text")

gem = genai.Client()
count3 = gem.models.count_tokens(model="gemini-3.8-flash", contents=[
    types.Part.from_bytes(data=png, mime_type="image/png"), QUESTION])
print(f"Gemini    count={count3.total_tokens!s:>5}  estimate=up to {gemini_image_tokens()} + text")
Example output · illustrative3 lines
OpenAI    count=  327  (no published gpt-6-luna rule; gpt-6-astra's would say 312 + text)
Anthropic count=  357  estimate=345 + text
Gemini    count= 1128  estimate=up to 1120 + text

Anthropic notes a subtlety: its counting endpoint "estimates an image's token cost from its dimensions without fully processing it, so a successful count doesn't mean the image is within the Messages API's request limits". A count can succeed for an image the real request then rejects.

After the call: usage. Every response reports input tokens (lesson 02.2, 6.6), and media are part of them:

Where the image tokens show up
OpenAI Inside usage.input_tokens (Responses) or usage.prompt_tokens (Chat Completions); no per-modality split for images
Anthropic Inside usage.input_tokens; no split
Where the image tokens show up
Gemini generate_content usage_metadata.prompt_token_count, split by modality in prompt_tokens_details (TEXT, IMAGE, AUDIO, VIDEO, DOCUMENT); PDF page images count as IMAGE on Gemini 3 and 4
Gemini Interactions usage.total_input_tokens, split in input_tokens_by_modality
OpenRouter usage.prompt_tokens as reported by the upstream provider, plus usage.cost in dollars (lesson 03.7)

A useful production check, which 9.5 builds in: log your estimate next to the real input_tokens. A large gap means a rule changed, a proxy dropped the image (2.1), or the image wasn't the size you thought.

3.4 The cost levers#

In rough order of impact:

  1. Don't send the image at all when text will do: a product name, a form's typed fields, an error message the user can paste.
  2. Crop to what matters (6.4). The model spends its token budget on the region you care about.
  3. Pick the lowest detail that works. OpenAI detail: "low" costs at most 308 tokens on gpt-6-astra (a 512×512 image is 256 patches × 1.2); Gemini media_resolution low is 280. Test on your own images: low can't read small print.
  4. Resize to just below the cap (6.1). Resizing to the cap only saves upload bytes; going below it saves tokens too.
  5. Drop images from history once they've been discussed (7.3).
  6. Cache large, repeated media (a manual you ask many questions about). Prompt caching works on images and documents on all three providers, and lesson 03.7 covers it.

Media also uses up your rate limits, not only your money: image and PDF tokens are input tokens, so they count towards the tokens-per-minute limits (lesson 02.7, 6.4), and a burst of image requests can hit a token limit long before it hits the request-count limit. Lesson 03.8, Part 9 shows how to read and respect them.


Part 4: PDFs and other documents#

This Part is about how a PDF or document travels in a request. Three later lessons own what you do with the content: you will meet classic PDF parsing in 05.2, OCR for scanned pages in 05.4, and extraction with vision models (choosing between native PDF input, page images and a parser, then schemas and validation) in 09.2.

4.1 How each provider reads a PDF#

A PDF can hold real text (characters you can select and copy), images, vector drawings, or all three. A scanned document is usually just a picture of each page, with no text at all. Providers handle this by giving the model both views of each page: the extracted text and an image of the page. That's why models can read charts and tables in PDFs, and also why PDFs cost more than you'd guess from their word count. As of November 2026:

OpenAI Anthropic
What the model sees On vision models, "the API extracts both text and page images and sends both to the model" Each page converted to an image, with "the text from each page ... extracted and provided alongside each page's image"
Cost Text + page-image tokens; detail controls the images "Each page typically uses 1,500–3,000 tokens" of text, plus the page image at image rates
Size limits Each file under 50 MB, and 50 MB for all files in one request 128 MB request, 600 pages (100 when the context window is under 1M tokens)
Encrypted PDFs Not documented; assume rejected Rejected: "Standard PDF (no passwords/encryption)"
Scanned PDFs Page images still work; no extractable text Page images work, but scans aren't citable (4.9)
Gemini OpenRouter
What the model sees "Native vision" over the pages; on Gemini 3 and 4, text embedded in the PDF is also "extracted and provided to the model" Depends on the engine: the model's own PDF support (native), or text extracted by OpenRouter (cloudflare-ai, mistral-ocr)
Cost A budget per page by media_resolution (default 560); "You are not charged for tokens originating from the extracted native text" Model tokens, plus $2 per 1,000 pages for mistral-ocr
Size limits 50 MB or 1,000 pages, inline or via the Files API Upstream provider's
Encrypted PDFs Not documented; assume rejected Not documented
Scanned PDFs Page images work mistral-ocr is the engine meant for scans

Two consequences for engineering:

  • Page count drives cost more than file size. A 2 MB, 300-page text PDF costs far more than a 20 MB, 3-page brochure full of photos. Count pages before you send (6.5).
  • Limits apply to the whole request, not per file. Anthropic says so explicitly: "Both limits are on the entire request payload, including any other content sent alongside PDFs." Two 400-page PDFs in one Claude request exceed the 600-page limit even though each is fine on its own.

4.2 Try it: make a test PDF with no libraries#

You need small, predictable PDFs for tests: real text, known page count, a few hundred bytes. You already saved one generator in Setup: make_pdf.py, and its output there shows pypdf, a real PDF parser, reading all three pages back. Writing one by hand is a good way to see that a PDF is just a file of numbered objects followed by a table of byte offsets. write_pdf() builds the file in the order a reader expects:

  1. A header, %PDF-1.7.
  2. Numbered objects: object 1 is the catalogue (the root), object 2 the page tree that lists every page, object 3 the font (Helvetica, one of the "standard 14" fonts that readers have built in). Each page then adds two objects: a page object (its size in points, [0 0 612 792] for US Letter, and which font it uses) and a content stream with the drawing commands (BT ... Tj ET draws one line of text near the top left).
  3. The xref table: the byte offset at which each object starts, which is why the code records len(out) just before it writes each one. A reader jumps straight to an object instead of scanning the file.
  4. A trailer that names the root object and says where the xref table starts (startxref).

Change a single byte of an object and the offsets after it are wrong, which is why hand-editing PDFs is fragile, and why anything beyond test fixtures should use a proper library. write_pdf() is why this lesson's PDF is only 1,263 bytes: one font, one line per page, no images.

A 1.2 KB file that a real PDF library reads correctly, with facts on known pages: ideal for checking that a model (and its citations) found the right page. For anything beyond test fixtures, generate PDFs with a proper library; producing them isn't this lesson's topic.

4.3 OpenAI: input_file#

Shapes. On the Responses API a document is an input_file part with one of three sources:

python
{"type": "input_file", "filename": "report.pdf", "file_data": "data:application/pdf;base64,<base64>"}
{"type": "input_file", "file_url": "https://example.com/report.pdf"}
{"type": "input_file", "file_id": "file-abc123"}

file_data needs a filename alongside it: OpenAI's examples always pass one, because the name's extension is how the API knows what kind of file the data is. An optional detail (auto, low or high; default auto) applies to PDF page images only: "For GPT-5.6 and later models, auto uses high; for earlier models, it uses low." Extracted text is included either way.

Chat Completions supports PDF only, as a file part with file_data or file_id, and no file_url or detail:

python
{"type": "file", "file": {"filename": "report.pdf", "file_data": "data:application/pdf;base64,<base64>"}}

Limits: "each file must be under 50 MB. The combined limit across all files in the request is 50 MB." PDF page images need a vision model ("gpt-4o and later models"), which includes every GPT-6 model. For retrieval over large or many files, OpenAI points you to its File Search tool instead of input_file (Module 07 covers retrieval).

OpenAI also accepts many non-PDF files on the Responses API, processed differently (4.8).

4.4 Anthropic: document blocks#

Shapes. A document block's source can be a PDF (base64, URL or file), plain text, or a list of your own content blocks:

python
{"type": "document", "source": {"type": "base64", "media_type": "application/pdf", "data": "<base64>"}}
{"type": "document", "source": {"type": "url", "url": "https://example.com/report.pdf"}}
{"type": "document", "source": {"type": "file", "file_id": "file_011C..."}}       # PDF or text/plain upload
{"type": "document", "source": {"type": "text", "media_type": "text/plain", "data": "Plain text..."}}
{"type": "document", "source": {"type": "content", "content": [{"type": "text", "text": "Chunk 1"},
                                                               {"type": "text", "text": "Chunk 2"}]}}

Every document block can also carry:

  • title: a short name for the document, passed to the model. It "is limited in length".
  • context: extra information about the document that the model can use but never cites, such as metadata as text or stringified JSON.
  • citations: {"enabled": true} to get answers linked to exact passages (4.9).
  • cache_control: prompt caching for documents you ask about repeatedly (lesson 03.7).

Limits (November 2026): 128 MB maximum request size on the first-party API, 600 pages per request (100 when the request's context window is under 1M tokens), and no passwords or encryption. Anthropic adds that "Dense PDFs ... can fill the context window before reaching the page limit", and that large requests can fail before the page limit "even when using the Files API". Its advice: split long documents, and downsample embedded images. On Bedrock and Google-managed Google Cloud only base64 sources work, and on Microsoft Foundry file_id sources need a deployment hosted by Anthropic. PDF support works on every active Claude model.

Cost: extracted text at "1,500–3,000 tokens depending on content density" per page, plus each page's image at the normal image rates, "with no additional PDF fees". Pages are rasterized "at dimensions you don't control", so the image part isn't predictable from the file; use the counting endpoint for real numbers.

Anthropic's best practices: "Place PDFs before text in your requests", use standard fonts, rotate pages upright, "Use logical page numbers (from PDF viewer) in prompts", split large PDFs, and cache documents you query repeatedly.

Other formats: binary files such as .docx and .xlsx "are not supported in document blocks, so convert them to text or PDF first". Plain-text files (.txt, .csv, .md) can go in as text, or be uploaded to the Files API with the MIME type text/plain (4.8).

4.7 PDF input on all four providers#

The same three-page report.pdf on each provider. OpenAI, inline and by URL on Responses, then on Chat Completions. What to look for in the output: the input-token counts, and that file_data needs a filename next to it:

python
# s4_7a_openai_pdf.py
"""OpenAI: a PDF as input_file (inline and by URL) on Responses, and as a file part on Chat Completions."""
import base64
from pathlib import Path

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

pdf = Path("report.pdf").read_bytes()
pdf_data_url = "data:application/pdf;base64," + base64.b64encode(pdf).decode("ascii")

# Responses, inline: file_data needs a filename too (it tells the API the file type)
r = client.responses.create(
    model="gpt-6-luna",
    input=[{"role": "user", "content": [
        {"type": "input_file", "filename": "report.pdf", "file_data": pdf_data_url, "detail": "low"},
        {"type": "input_text", "text": "How many staff does the Lisbon office have? Cite the page."},
    ]}],
    reasoning={"effort": "none"},
    max_output_tokens=300,
)
print("inline:", r.output_text, "| input tokens:", r.usage.input_tokens if r.usage else None)

# Responses, by URL: OpenAI downloads the file (Responses only; Chat Completions has no file_url)
r = client.responses.create(
    model="gpt-6-luna",
    input=[{"role": "user", "content": [
        {"type": "input_file", "file_url": "https://arxiv.org/pdf/1706.03762"},
        {"type": "input_text", "text": "What is this paper's title? Answer with the title only."},
    ]}],
    reasoning={"effort": "none"},
    max_output_tokens=300,
)
print("URL   :", r.output_text, "| input tokens:", r.usage.input_tokens if r.usage else None)

# Chat Completions: PDF only, as a "file" part (file_data or file_id; no URL, no detail)
c = client.chat.completions.create(
    model="gpt-6-luna",
    messages=[{"role": "user", "content": [
        {"type": "file", "file": {"filename": "report.pdf", "file_data": pdf_data_url}},
        {"type": "text", "text": "What are the two risks on page 3?"},
    ]}],
    reasoning_effort="none",
    max_completion_tokens=300,
)
print("chat  :", c.choices[0].message.content)
Example output · illustrative3 lines
inline: The Lisbon office has 14 staff (page 2). | input tokens: 1418
URL   : Attention Is All You Need | input tokens: 38950
chat  : The two risks on page 3 are supplier delays and currency changes.

The URL example shows how fast PDFs add up: a 15-page paper costs tens of thousands of input tokens on every call. Anthropic, with a PDF and a plain-text document, citations on both. What to look for: the answer arrives as several text blocks, and only some carry citations, a page_location for the PDF and a char_location for the text:

python
# s4_7b_anthropic_pdf.py
"""Anthropic: a PDF document block with citations, and a plain-text document with title and context."""
import base64
from pathlib import Path

import anthropic
from dotenv import load_dotenv

load_dotenv()
client = anthropic.Anthropic()

pdf_b64 = base64.b64encode(Path("report.pdf").read_bytes()).decode("ascii")

message = client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=500,
    messages=[{"role": "user", "content": [
        {   # the document goes first: Anthropic's guidance is "place PDFs before text"
            "type": "document",
            "source": {"type": "base64", "media_type": "application/pdf", "data": pdf_b64},
            "title": "Q3 report",                       # passed to the model, never cited
            "context": "Internal, unaudited figures.",  # likewise: metadata for the model
            "citations": {"enabled": True},             # all documents in a request, or none
        },
        {
            "type": "document",
            "source": {"type": "text", "media_type": "text/plain",
                       "data": "Lisbon office memo. Headcount will rise to 20 by June."},
            "title": "Lisbon memo",
            "citations": {"enabled": True},
        },
        {"type": "text", "text": "How many staff does Lisbon have now, and how many are planned?"},
    ]}],
)

# With citations on, the answer comes back as several text blocks, some carrying citations
for block in message.content:
    if block.type != "text":
        continue
    print(repr(block.text))
    for cite in block.citations or []:
        if cite.type == "page_location":
            print(f"    -> doc {cite.document_index} ({cite.document_title}) pages "
                  f"{cite.start_page_number}-{cite.end_page_number - 1}: {cite.cited_text!r}")
        elif cite.type == "char_location":
            print(f"    -> doc {cite.document_index} ({cite.document_title}) chars "
                  f"{cite.start_char_index}-{cite.end_char_index}: {cite.cited_text!r}")
print("stop_reason:", message.stop_reason, "| input tokens:", message.usage.input_tokens)
Example output · illustrative8 lines
'Lisbon has '
'14 staff'
    -> doc 0 (Q3 report) pages 2-2: 'Page 2. The Lisbon office opened in March with 14 staff.'
' now, and the memo says headcount will rise to '
'20 by June'
    -> doc 1 (Lisbon memo) chars 20-54: 'Headcount will rise to 20 by June.'
'.'
stop_reason: end_turn | input tokens: 2134

The input count is small because this test PDF has one short line per page. Each page's image is several hundred tokens and its text only about 15, so three pages plus a memo and a question land near 2,000. A dense three-page report would cost far more: Anthropic quotes 1,500 to 3,000 text tokens per dense page, on top of the page images (4.1). The number is modelled, not measured.

Gemini, inline on generate_content (with media_resolution) and on Interactions. What to look for: the IMAGE row in the token breakdown, which is where PDF pages are counted:

python
# s4_7c_gemini_pdf.py
"""Gemini: a PDF inline on generate_content (with media_resolution) and on Interactions."""
import base64
from pathlib import Path

from dotenv import load_dotenv
from google import genai
from google.genai import types

load_dotenv()
client = genai.Client()

pdf = Path("report.pdf").read_bytes()

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=[
        types.Part.from_bytes(data=pdf, mime_type="application/pdf",
                              media_resolution=types.PartMediaResolutionLevel.MEDIA_RESOLUTION_MEDIUM),
        "How many staff does the Lisbon office have? Say which page.",
    ],
    config=types.GenerateContentConfig(max_output_tokens=300),
)
print("generate_content:", response.text)
usage = response.usage_metadata
if usage:   # page images are reported under the IMAGE modality on Gemini 3 and 4
    print("  prompt tokens:", usage.prompt_token_count, [(d.modality.name if d.modality else None, d.token_count)
                                                         for d in usage.prompt_tokens_details or []])

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {"type": "document", "data": base64.b64encode(pdf).decode("ascii"), "mime_type": "application/pdf"},
        {"type": "text", "text": "List the risks on page 3."},
    ],
    generation_config={"max_output_tokens": 300},
)
print("interactions:", interaction.output_text)
Example output · illustrative3 lines
generate_content: The Lisbon office has 14 staff, according to page 2.
  prompt tokens: 1697 [('TEXT', 17), ('IMAGE', 1680)]
interactions: The risks on page 3 are supplier delays and currency changes.

Three pages at medium is 3 × 560 = 1,680 image tokens, exactly the per-page budget, and the output shows 17 text tokens with the PDF's own text not counted, which is the reading of Google's document-processing page ("not charged" for native text). Google's media-resolution table says "+ native text" instead (2.4), so this output is illustrative of one reading: check the TEXT and IMAGE rows of your own usage_metadata. OpenRouter, sending the PDF to a text-only model with the free engine, then reusing the parse. What to look for: the annotations on the first reply, which the second call sends back:

python
# s4_7d_openrouter_pdf.py
"""OpenRouter: a PDF on any model via the file-parser plugin, then reuse the parse to skip paying again."""
import base64
import os
from pathlib import Path

from dotenv import load_dotenv
from openai import OpenAI
from openai.types.chat import ChatCompletionUserMessageParam

load_dotenv()
client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"],
    default_headers={"HTTP-Referer": "https://example.com/my-app", "X-OpenRouter-Title": "My App"},
)

pdf_data_url = "data:application/pdf;base64," + base64.b64encode(Path("report.pdf").read_bytes()).decode("ascii")
PLUGINS = [{"id": "file-parser", "pdf": {"engine": "cloudflare-ai"}}]   # free engine; see the pricing note

first_question: ChatCompletionUserMessageParam = {"role": "user", "content": [
    {"type": "text", "text": "How many staff does the Lisbon office have?"},
    {"type": "file", "file": {"filename": "report.pdf", "file_data": pdf_data_url}},
]}
first = client.chat.completions.create(
    model="meta-llama/llama-3.3-70b-instruct",         # a text-only model: OpenRouter parses the PDF for it
    messages=[first_question],
    max_completion_tokens=200,
    extra_body={"plugins": PLUGINS},                    # OpenRouter-only field, so it goes in extra_body
)
reply = first.choices[0].message
annotations = (reply.model_extra or {}).get("annotations") or []   # OpenRouter's parsed-file annotations
print("answer 1:", reply.content)
print("annotations:", [(a.get("type"), a.get("file", {}).get("name")) for a in annotations])

# Follow-up: send the assistant message back WITH its annotations, so OpenRouter reuses
# the parsed text instead of parsing (and, with mistral-ocr, billing) the PDF again.
second = client.chat.completions.create(
    model="meta-llama/llama-3.3-70b-instruct",
    messages=[
        first_question,
        # "annotations" isn't in the openai SDK's types: it's an OpenRouter extension
        {"role": "assistant", "content": reply.content, "annotations": annotations},  # type: ignore[list-item]
        {"role": "user", "content": "And what are the risks on page 3?"},
    ],
    max_completion_tokens=200,
    extra_body={"plugins": PLUGINS},
)
print("answer 2:", second.choices[0].message.content)
Example output · illustrative3 lines
answer 1: The Lisbon office has 14 staff.
annotations: [('file', 'report.pdf')]
answer 2: Page 3 lists two risks: supplier delays and currency changes.

4.8 Word, Excel, CSV and text files#

As of November 2026:

File type OpenAI (Responses input_file) Anthropic
.txt, .md, code, .json, .html, .xml ✅ text extracted ("the API extracts text only") ✅ as a text document (inline text source, or Files API upload as text/plain), or simply as a text block
.csv, .tsv, .xlsx, .xls ✅ "spreadsheet augmentation": "parses up to the first 1,000 rows per sheet and adds model-generated summary and header metadata" ❌ in document blocks. CSV as text; spreadsheets via the code execution tool (container_upload)
.docx, .doc, .rtf, .odt ✅ text only; "the Responses API doesn't extract embedded images or charts" ❌ "convert them to text or PDF first" (to PDF if they contain images)
.pptx, .ppt ✅ text only ❌ convert to PDF
On Chat Completions ❌ "Chat Completions accepts only PDF files as file content parts" —
File type Gemini OpenRouter
.txt, .md, code, .json, .html, .xml ✅ as text: "Other types will be extracted as pure text" Upstream provider's; or send as text
.csv, .tsv, .xlsx, .xls CSV as text (text/csv) Upstream provider's
.docx, .doc, .rtf, .odt ❌ not documented; convert to PDF Upstream provider's
.pptx, .ppt ❌ not documented; convert to PDF Upstream provider's
On Chat Completions — PDF via file parts

Two rules cover most cases. First, if layout, charts or images matter, convert to PDF (LibreOffice can do it headlessly: soffice --headless --convert-to pdf file.docx), because PDFs are the only document type every provider reads visually. Second, if only the words matter, extract the text yourself and send it as text: it's cheaper, works everywhere, and you control what's included. Doing that well (tables, headers, scanned pages, OCR) is Module 05's subject. Spreadsheets with more than a few hundred rows usually belong in code (pandas, SQL or a code-execution tool), not in a prompt: OpenAI itself only reads the first 1,000 rows per sheet.

4.9 Citations on documents: the API surface#

Citations link each claim in an answer to the exact passage that supports it, so a user can check it. As API features, as of November 2026:

Document citations What you get
OpenAI ❌ not for input_file. Citations come with the File Search and web search tools, as annotations on output text —
Anthropic ✅ citations: {"enabled": true} on each document block (all documents in a request, or none) Text blocks with a citations list: page_location for PDFs, char_location for plain text, content_block_location for custom content
Document citations What you get
Gemini ❌ no citation feature for documents you send. grounding_metadata is for Google Search and URL grounding. The File Search tool (a retrieval tool over a store you build, Module 07) returns file_citation annotations, with a page_number for paged documents such as PDFs —
OpenRouter Partial: the Responses API "may include a file_citation annotation when the provider cites a parsed file"; "Parsing a file alone does not guarantee a citation" {"type": "file_citation", "file_id", "filename", "index"}

Anthropic's is the full feature. The details that matter in code:

  • Indices: document indices are 0-based across all document blocks in the request (in every message). Character ranges are 0-based with an exclusive end. Page numbers are 1-based with an exclusive end, so a citation of page 2 alone says start_page_number: 2, end_page_number: 3.
  • Granularity: PDFs and plain text are split into sentences, so a citation is one or more sentences. Custom-content documents are cited block by block, which gives you control: put each chunk of a transcript, or each bullet, in its own block.
  • cited_text is free: it "does not count toward output tokens", and when passed back in later turns it's "not counted toward input tokens" either. Enabling citations adds a few input tokens.
  • Not citable: title and context, images in PDFs, and scanned PDFs with no extractable text.
  • Incompatible with structured outputs: enabling citations and also sending output_config.format returns a 400 (lesson 03.4).
  • Streaming: citations arrive as citations_delta events (lesson 03.3, 6.4).

Here's the response shape, parsed by the real SDK from a mock server, turned into footnotes:

python
# s4_9_citations_mock.py
"""Parse Anthropic citations with the real SDK, from a mock server (layer 3).

The fixture is the response shape from Anthropic's citations guide: several text
blocks, some carrying a list of citations whose type depends on the document type.
"""
import httpx2
import anthropic

FIXTURE = {
    "id": "msg_test", "type": "message", "role": "assistant", "model": "claude-haiku-5-5",
    "stop_reason": "end_turn", "stop_sequence": None,
    "usage": {"input_tokens": 2104, "output_tokens": 61},
    "content": [
        {"type": "text", "text": "The Lisbon office has "},
        {"type": "text", "text": "14 staff", "citations": [{
            "type": "page_location", "cited_text": "Page 2. The Lisbon office opened in March with 14 staff.",
            "document_index": 0, "document_title": "Q3 report", "start_page_number": 2, "end_page_number": 3}]},
        {"type": "text", "text": ", and the plan is to reach "},
        {"type": "text", "text": "20 by June", "citations": [{
            "type": "char_location", "cited_text": "Headcount will rise to 20 by June.",
            "document_index": 1, "document_title": "Lisbon memo", "start_char_index": 20, "end_char_index": 54}]},
        {"type": "text", "text": "."},
    ],
}

client = anthropic.Anthropic(api_key="sk-test", http_client=httpx2.Client(
    transport=httpx2.MockTransport(lambda request: httpx2.Response(200, json=FIXTURE))))
message = client.messages.create(model="claude-haiku-5-5", max_tokens=300,
                                 messages=[{"role": "user", "content": "How many staff in Lisbon?"}])

answer, sources = "", []
for block in message.content:
    if block.type != "text":
        continue
    answer += block.text
    for c in block.citations or []:
        sources.append(c)
        answer += f"[{len(sources)}]"            # put a footnote marker after the cited span

print(answer)
for n, c in enumerate(sources, start=1):
    if c.type == "page_location":                # PDFs: 1-indexed pages, exclusive end
        where = f"page {c.start_page_number}" + (f"-{c.end_page_number - 1}" if c.end_page_number - 1 > c.start_page_number else "")
    elif c.type == "char_location":              # plain text: 0-indexed characters, exclusive end
        where = f"chars {c.start_char_index}-{c.end_char_index}"
    else:                                        # content_block_location and search-result types
        where = c.type
    print(f"[{n}] {c.document_title} ({where}): \"{c.cited_text}\"   <{type(c).__name__}>")
Output3 lines
The Lisbon office has 14 staff[1], and the plan is to reach 20 by June[2].
[1] Q3 report (page 2): "Page 2. The Lisbon office opened in March with 14 staff."   <CitationPageLocation>
[2] Lisbon memo (chars 20-54): "Headcount will rise to 20 by June."   <CitationCharLocation>

The server is a mock, but the parsing is the real anthropic SDK: block.citations holds typed objects (CitationPageLocation, CitationCharLocation), and the code picks fields by c.type. That's the API surface. Designing a system around citations (choosing what to retrieve, chunking for citability, showing sources in a UI, checking that answers really are supported) is grounding, and it belongs to Module 07.

4.5 Gemini: PDFs as parts#

A PDF is a Part like an image: types.Part.from_bytes(data=pdf_bytes, mime_type="application/pdf") inline, types.Part.from_uri(...) for a URL or an uploaded file, or {"type": "document", ...} on Interactions.

Limits: "Gemini supports PDF files up to 50MB or 1000 pages. This limit applies to both inline data and Files API uploads", and multiple PDFs fit in one request "as long as the combined size of the documents and the text prompt stays within the model's context window". Pages are scaled to between 768×768 and 3072×3072 pixels, keeping their aspect ratio.

Cost on Gemini 3 and 4: a budget per page by media_resolution: 280 at low, 560 at medium and by default, 1,120 at high (2.4). Google recommends medium: quality "typically saturates at medium. Increasing to high rarely improves OCR results for standard documents." The text embedded in the PDF is given to the model too, and "You are not charged for tokens originating from the extracted native text". In usage_metadata, page tokens appear under the IMAGE modality. Older models charged 258 tokens per page.

Other document types: "you can pass other MIME types for document understanding, like TXT, Markdown, HTML, XML, etc. However, document vision only meaningfully understands PDFs. Other types will be extracted as pure text". Charts, layout and formatting in those files are lost.

4.6 OpenRouter: any model, through the file-parser plugin#

OpenRouter's PDF support "works on any model", including text-only ones. When the model reads files natively, OpenRouter passes the PDF straight through. When it doesn't, OpenRouter parses the PDF itself and sends the result. The shapes:

python
# Chat Completions (primary): a "file" part; file_data is a URL or a base64 data URL
{"type": "file", "file": {"filename": "report.pdf", "file_data": "data:application/pdf;base64,<base64>"}}
# Responses-compatible API
{"type": "input_file", "file_url": "https://example.com/report.pdf"}   # or "file_data": "data:..."

You choose how PDFs are parsed with the file-parser plugin, an OpenRouter-only field that goes in extra_body when you use the openai SDK:

python
extra_body={"plugins": [{"id": "file-parser", "pdf": {"engine": "cloudflare-ai"}}]}
Engine What it does Price (November 2026)
native Sends the PDF to a model that supports files natively The model's input tokens
cloudflare-ai "Converts PDFs to markdown using Cloudflare Workers AI" Free
mistral-ocr OCR, "Best for scanned documents or PDFs with images"; at most 8 extracted images per PDF are forwarded $2 per 1,000 pages ($2.20 when pinned to the US data region)
pdf-text Deprecated; "automatically redirected to cloudflare-ai" —
flowchart TB
    R["Request with a file part"] --> Q{"plugins: file-parser<br/>engine set?"}
    Q -->|"native"| N["Model reads the PDF itself<br/>(billed as the model's input tokens)"]
    Q -->|"cloudflare-ai"| C["OpenRouter converts it to Markdown<br/>(free), sends text to the model"]
    Q -->|"mistral-ocr"| M["OCR, also for scans<br/>($2 per 1,000 pages, even on BYOK)"]
    Q -->|"not set"| D{"Does the model accept<br/>files natively?"}
    D -->|"yes"| N
    D -->|"no"| M
    C --> AN["Chat Completions reply carries<br/>file annotations: send them back<br/>to skip parsing next time"]
    M --> AN

Don't pay to parse twice. On Chat Completions, a parsed PDF comes back as file annotations on the assistant message: {"type": "file", "file": {"hash", "name", "content": [...]}}. Send that assistant message back with its annotations in the next turn, and OpenRouter "will use this pre-parsed information instead of re-parsing the PDF". If parsing succeeded but every model provider then failed, the error body still carries them in error.metadata.file_annotations, so a retry can reuse them; deduplicate by file.hash. The Responses API returns file_citation annotations instead, which can't be sent back to skip parsing. The native engine produces no annotations, because nothing is parsed.


Part 5: The Files APIs#

Deep-dive

5.1 Why upload once#

A Files API stores a file on the provider's side and gives you an ID to use in requests. It's worth the extra step when:

  • You'll use the file more than once: several questions about one contract, or the same reference image in many requests.
  • The file is large: a request with an ID is a few hundred bytes instead of tens of megabytes, which keeps you under request-size limits and makes each call faster.
  • It's in a conversation: a 3 MB screenshot inline in turn 1 is re-sent in turns 2, 3, 4... An ID costs the same few bytes every time (7.3).
  • Batch jobs reference many files: OpenAI's Batch API takes its whole input as an uploaded file (lesson 03.9).

What a file ID does not do is save tokens. The model reads the whole file each time it's referenced, and you pay input tokens for it every time (prompt caching is the tool for that, lesson 03.7). Anthropic says it plainly: "File content used in Messages requests is priced as input tokens."

sequenceDiagram
    participant App as Your app
    participant DB as Your database
    participant Files as Provider Files API
    participant Model as Model endpoint
    App->>Files: upload bytes (multipart or resumable)
    Files-->>App: file ID, expiry
    App->>DB: save provider, file ID, owner, expires_at
    loop each question about the document
        App->>Model: request with the file ID
        Model->>Files: read the file
        Model-->>App: answer and usage
    end
    App->>Files: delete when done (or let it expire)
    App->>DB: remove the record

5.2 What an upload looks like on the wire#

Uploads are not JSON. OpenAI and Anthropic use multipart form data (the same encoding a browser uses for an <input type="file"> form), and Gemini uses Google's two-step resumable upload protocol. A mock transport shows each SDK's requests:

python
# s5_2_upload_wire.py
"""Show the wire: what a Files API upload sends on each SDK (nothing leaves your machine)."""
import json
from pathlib import Path

import anthropic
import httpx
import httpx2
import openai
from google import genai
from google.genai import types

pdf = Path("report.pdf").read_bytes()
log: list[str] = []


def show(request) -> None:
    body = request.read()
    ctype = request.headers.get("content-type", "")
    log.append(f"{request.method} {request.url}\n  content-type: {ctype.split(';')[0]}"
               + "".join(f"\n  {k}: {v}" for k, v in request.headers.items() if k.startswith("x-goog-upload")))
    if b"Content-Disposition" in body:                               # multipart: list the form fields
        for part in body.split(b"Content-Disposition: form-data; ")[1:]:
            header, _, value = part.partition(b"\r\n\r\n")
            name = header.split(b"\r\n")[0].decode()
            value = value.split(b"\r\n--")[0]                        # drop the next boundary
            log.append(f"    form field {name}: {value[:24]!r}")
    elif body:
        log.append(f"    body: {body[:60]!r}")


def openai_handler(request: httpx2.Request) -> httpx2.Response:
    show(request)
    return httpx2.Response(200, json={"id": "file-test", "object": "file", "bytes": len(pdf), "created_at": 0,
                                      "filename": "report.pdf", "purpose": "user_data", "status": "processed",
                                      "expires_at": 86400})


def anthropic_handler(request: httpx2.Request) -> httpx2.Response:
    show(request)
    return httpx2.Response(200, json={"id": "file_test", "type": "file", "filename": "report.pdf",
                                      "mime_type": "application/pdf", "size_bytes": len(pdf),
                                      "created_at": "2026-11-04T09:00:00Z", "downloadable": False,
                                      "expires_at": "2026-11-05T09:00:00Z"})


def gemini_handler(request: httpx.Request) -> httpx.Response:
    show(request)
    if request.headers.get("x-goog-upload-command") == "start":     # step 1: ask for an upload URL
        return httpx.Response(200, headers={"x-goog-upload-url": "https://upload.example/session-1",
                                            "x-goog-upload-status": "active"})
    return httpx.Response(200, headers={"x-goog-upload-status": "final"},  # step 2: bytes, then finalize
                          json={"file": {"name": "files/abc123", "uri": "https://generativelanguage.googleapis.com/v1beta/files/abc123",
                                         "mimeType": "application/pdf", "state": "ACTIVE"}})


o = openai.OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(openai_handler)))
f1 = o.files.create(file=("report.pdf", pdf, "application/pdf"), purpose="user_data",
                    expires_after={"anchor": "created_at", "seconds": 86400})
log.append(f"  -> {f1.id}\n")

a = anthropic.Anthropic(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(anthropic_handler)))
f2 = a.files.upload(file=("report.pdf", pdf, "application/pdf"), expires_in_seconds=86400)
log.append(f"  -> {f2.id}, expires_at {f2.expires_at}\n")

g = genai.Client(api_key="test-key", http_options=types.HttpOptions(
    httpx_client=httpx.Client(transport=httpx.MockTransport(gemini_handler))))
f3 = g.files.upload(file="report.pdf", config=types.UploadFileConfig(mime_type="application/pdf"))
log.append(f"  -> {f3.name}, state {f3.state}")

print("\n".join(log))
Output32 lines
POST https://api.openai.com/v1/files
  content-type: multipart/form-data
    form field name="purpose": b'user_data'
    form field name="expires_after[anchor]": b'created_at'
    form field name="expires_after[seconds]": b'86400'
    form field name="file"; filename="report.pdf": b'%PDF-1.7\n1 0 obj\n<< /Typ'
  -> file-test

POST https://api.anthropic.com/v1/files
  content-type: multipart/form-data
    form field name="expires_in_seconds": b'86400'
    form field name="file"; filename="report.pdf": b'%PDF-1.7\n1 0 obj\n<< /Typ'
  -> file_test, expires_at 2026-11-05 09:00:00+00:00

POST https://generativelanguage.googleapis.com/upload/v1beta/files
  content-type: application/json
  x-goog-upload-protocol: resumable
  x-goog-upload-command: start
  x-goog-upload-header-content-length: 1263
  x-goog-upload-header-content-type: application/pdf
  x-goog-upload-file-name: report.pdf
    body: b'{"file": {"mime_type": "application/pdf", "size_bytes": 1263'
POST https://upload.example/session-1
  content-type: application/json
  x-goog-upload-protocol: resumable
  x-goog-upload-command: upload, finalize
  x-goog-upload-header-content-length: 1263
  x-goog-upload-header-content-type: application/pdf
  x-goog-upload-file-name: report.pdf
  x-goog-upload-offset: 0
    body: b'%PDF-1.7\n1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n2 '
  -> files/abc123, state FileState.ACTIVE

Note that the file's bytes travel raw in all three: no base64, so no 33% tax. Gemini first sends the file's metadata to get a one-off upload URL, then sends the bytes to that URL with the upload, finalize command; the "resumable" name comes from the protocol's ability to continue an interrupted upload from an offset.

5.3 OpenAI: Files and Uploads#

As of November 2026:

  • Upload: client.files.create(file=..., purpose=..., expires_after=...). file can be a path, an open binary file, bytes, or a (filename, bytes, mime_type) tuple. purpose is one of assistants, batch, fine-tune, vision, user_data or evals; for model inputs, OpenAI says to "use user_data for files you plan to pass as model inputs".
  • Expiry: expires_after={"anchor": "created_at", "seconds": N} with N from 3,600 (1 hour) to 2,592,000 (30 days). "By default, files with purpose=batch expire after 30 days and all other files are persisted until they are manually deleted." The returned FileObject has id, bytes, created_at, expires_at, filename, purpose and a deprecated status.
  • Limits: "Individual files can be up to 512 MB, and each project can store up to 2.5 TB of files in total. There is no organization-wide storage limit." Uploads are rate-limited to 1,000 requests per minute per authenticated user. Batch input files are limited to 200 MB.
  • Manage: client.files.list(purpose=..., limit=..., order=..., after=...) (auto-paginating), client.files.retrieve(file_id), client.files.content(file_id) for file contents (the reference says only "Returns a response containing the contents of the specified file", but see the download caveat in 5.8 before you plan to read an upload back), and client.files.delete(file_id).
  • Bigger files: the Uploads API. For files over 512 MB, create an Upload, add Parts of at most 64 MB each (in parallel if you like), then complete it with the ordered part IDs and an optional MD5 checksum. "An Upload can accept at most 8 GB in total and expires after an hour after you create it." The SDK wraps all of it: client.uploads.upload_file_chunked(file=path, mime_type=..., purpose=..., part_size=...). The Uploads endpoint lists only assistants, batch, fine-tune and vision as purposes, so it's mainly for batch and fine-tuning data, not model inputs.

5.4 Anthropic: the Files API#

As of November 2026 the Files API is generally available, with no beta header:

  • Upload: client.files.upload(file=(name, bytes_or_file, mime_type), expires_in_seconds=...) returns FileMetadata with id, filename, mime_type, size_bytes, created_at, downloadable and expires_at.
  • Expiry: expires_in_seconds from 3,600 (1 hour) to 7,776,000 (90 days), set once at upload. Without it, expires_at is null and the file stays until you delete it. After expiry, a Messages request referencing it "fails before inference", and its metadata stays visible for up to 30 days.
  • Manage: client.files.list(limit=..., page=...) (newest first, 20 per page by default, at most 1,000; pass up to 100 ids to check a known set), client.files.retrieve_metadata(file_id), client.files.delete(file_id). client.files.download(file_id) works only for files that skills or the code execution tool created: "Downloading a file you uploaded returns a 400 error."
  • Which blocks take a file_id: document (PDF and text/plain), image (JPEG, PNG, GIF, WebP), and container_upload (any file, for the code execution tool). Using an image file in a document block is a 400.
  • Limits: 500 MB per file, 1 TB per organization, file names of 1–255 characters without <, >, :, ", |, ?, *, \ or /, and about 500 file-API requests per minute. Files can't be modified or renamed: upload a new one and delete the old.
  • Price: uploading, listing, reading metadata, downloading and deleting are free. Using a file in a request is billed as input tokens.
  • Platforms: the Claude API, Claude Platform on AWS, Anthropic-managed Google Cloud, and Microsoft Foundry deployments hosted on Anthropic. Not Amazon Bedrock or Google-managed Google Cloud.

5.7 End to end on each provider#

The full lifecycle (upload, use twice, list, delete) on the three first-party APIs. Each deletes its file in finally, so a failed request doesn't leave user data behind. What to look for in each output: one short ID reused for both questions, then the delete at the end. OpenAI:

python
# s5_7a_openai_files.py
"""OpenAI Files API end to end: upload -> use -> list -> retrieve -> delete."""
from pathlib import Path

from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

# Upload. purpose="user_data" is OpenAI's advice for files you pass as model input.
# expires_after makes the file delete itself (1 hour to 30 days); without it, it stays forever.
uploaded = client.files.create(
    file=Path("report.pdf"),
    purpose="user_data",
    expires_after={"anchor": "created_at", "seconds": 24 * 3600},
)
print("uploaded:", uploaded.id, uploaded.filename, uploaded.bytes, "B, expires_at", uploaded.expires_at)

try:
    # Use it as often as you like: only the short ID travels in each request
    for question in ["What was revenue growth?", "Where did a new office open?"]:
        r = client.responses.create(
            model="gpt-6-luna",
            input=[{"role": "user", "content": [
                {"type": "input_file", "file_id": uploaded.id},
                {"type": "input_text", "text": question},
            ]}],
            reasoning={"effort": "none"},
            max_output_tokens=200,
        )
        print(f"  {question} -> {r.output_text}")

    # List (auto-paginating) and retrieve metadata
    mine = [f.id for f in client.files.list(purpose="user_data", limit=100)]
    print("listed:", uploaded.id in mine, "| retrieved:", client.files.retrieve(uploaded.id).filename)
finally:
    deleted = client.files.delete(uploaded.id)        # always clean up, even if a call failed
    print("deleted:", deleted.id, deleted.deleted)
Example output · illustrative5 lines
uploaded: file-7Rk2mQ9xVb4LtN1cZ8pW3e report.pdf 1263 B, expires_at 1793869200
  What was revenue growth? -> Revenue grew 12% to 4.2 million euros.
  Where did a new office open? -> A new office opened in Lisbon, in March.
listed: True | retrieved: report.pdf
deleted: file-7Rk2mQ9xVb4LtN1cZ8pW3e True

Anthropic (look for downloadable: False and the expiry time):

python
# s5_7b_anthropic_files.py
"""Anthropic Files API end to end: upload -> use -> list -> metadata -> delete."""
from pathlib import Path

import anthropic
from dotenv import load_dotenv

load_dotenv()
client = anthropic.Anthropic()

uploaded = client.files.upload(
    file=("report.pdf", Path("report.pdf").read_bytes(), "application/pdf"),
    expires_in_seconds=24 * 3600,           # 1 hour to 90 days; omit it and the file stays until deleted
)
print("uploaded:", uploaded.id, uploaded.mime_type, uploaded.size_bytes, "B",
      "| downloadable:", uploaded.downloadable, "| expires_at:", uploaded.expires_at)

try:
    for question in ["What was revenue growth?", "Where did a new office open?"]:
        message = client.messages.create(
            model="claude-haiku-5-5",
            max_tokens=200,
            messages=[{"role": "user", "content": [
                {"type": "document", "source": {"type": "file", "file_id": uploaded.id}},
                {"type": "text", "text": question},
            ]}],
        )
        print(f"  {question} -> {''.join(b.text for b in message.content if b.type == 'text')}")

    page = client.files.list(limit=20)                # newest first; iterate the page for auto-pagination
    print("listed:", any(f.id == uploaded.id for f in page),
          "| metadata:", client.files.retrieve_metadata(uploaded.id).filename)
finally:
    client.files.delete(uploaded.id)
    print("deleted:", uploaded.id)
Example output · illustrative5 lines
uploaded: file_011CPx8nY4cK2rT7vQ1mZ9wD application/pdf 1263 B | downloadable: False | expires_at: 2026-11-05 09:12:44+00:00
  What was revenue growth? -> Revenue grew 12 percent, to 4.2 million euros.
  Where did a new office open? -> In Lisbon. It opened in March with 14 staff.
listed: True | metadata: report.pdf
deleted: file_011CPx8nY4cK2rT7vQ1mZ9wD

Gemini, including the wait for ACTIVE (look for the file state and the 48-hour expiry):

python
# s5_7c_gemini_files.py
"""Gemini Files API end to end: upload -> wait until ACTIVE -> use -> list -> delete."""
import time

from dotenv import load_dotenv
from google import genai
from google.genai import types

load_dotenv()
client = genai.Client()

uploaded = client.files.upload(
    file="report.pdf",
    config=types.UploadFileConfig(display_name="Q3 report", mime_type="application/pdf"),
)
print("uploaded:", uploaded.name, uploaded.uri, uploaded.state, "| expires:", uploaded.expiration_time)

try:
    # Large files (especially video) are processed first: poll until ACTIVE, with a deadline
    deadline = time.monotonic() + 300
    while uploaded.state == types.FileState.PROCESSING:
        if time.monotonic() > deadline:
            raise TimeoutError(f"{uploaded.name} still processing after 5 minutes")
        time.sleep(5)
        uploaded = client.files.get(name=uploaded.name or "")
    if uploaded.state == types.FileState.FAILED:
        raise RuntimeError(f"processing failed: {uploaded.error}")

    for question in ["What was revenue growth?", "Where did a new office open?"]:
        response = client.models.generate_content(
            model="gemini-3.8-flash",
            contents=[uploaded, question],          # a File object becomes a file_data part
            config=types.GenerateContentConfig(max_output_tokens=200),
        )
        print(f"  {question} -> {response.text}")

    names = [f.name for f in client.files.list(config=types.ListFilesConfig(page_size=100))]
    print("listed:", uploaded.name in names)
finally:
    client.files.delete(name=uploaded.name or "")   # or let it auto-delete after 48 hours
    print("deleted:", uploaded.name)
Example output · illustrative5 lines
uploaded: files/8k2m4q7xz1vb https://generativelanguage.googleapis.com/v1beta/files/8k2m4q7xz1vb FileState.ACTIVE | expires: 2026-11-06 09:14:03.511208+00:00
  What was revenue growth? -> Revenue grew 12 percent to 4.2 million euros.
  Where did a new office open? -> A new office opened in Lisbon in March.
listed: True
deleted: files/8k2m4q7xz1vb

A small PDF is usually ACTIVE immediately; a long video can spend minutes in PROCESSING. The OpenAI and Anthropic samples fail on the local stand-in with a 404, because Ollama has no Files API (Gemini has no local stand-in at all); 5.2 is the keyless way to see what they send.

5.8 Retention, privacy and cleanup#

Uploading a user's file to a Files API means a third party now stores it, possibly for longer than your own policy allows. As of November 2026:

OpenAI Anthropic
Default retention Until you delete it (batch files: 30 days) Until you delete it
Expiry you can set 1 hour – 30 days (expires_after) 1 hour – 90 days (expires_in_seconds)
Max file / total 512 MB (8 GB via Uploads) / 2.5 TB per project 500 MB / 1 TB per organization
Scope Project Workspace
Download your upload? Unverified; don't plan on it. The reference has no purpose restriction, but developers report a 400, "Not allowed to download files of purpose: user_data" (forum thread; no OpenAI reply there), and the same for assistants. Batch and fine-tune outputs are what files.content is for No
Cost of storage No storage price listed for plain files (File Search vector storage is billed: 02.9, 6.10) Free
Zero data retention /v1/files is not ZDR-eligible: application state "Until deleted", abuse-monitoring logs 30 days Not eligible: "Files retained until explicitly deleted or they reach their configured expiration"
After delete Removed from the API "inaccessible through the API shortly after deletion", then deleted under Anthropic's retention policy
Gemini OpenRouter
Default retention 48 hours, automatic Not documented
Expiry you can set No (always 48 hours) Not documented
Max file / total 2 GB / 20 GB per project 100 MB / not documented
Scope Google Cloud project Workspace
Download your upload? No No
Cost of storage Free Not documented
Zero data retention Not on the Developer API: its terms apply (see the warning below), and Google Cloud's enterprise platform has its own controls (02.9, 9.2) Model routing can demand it (provider.zdr: true, below). The Files API's own retention isn't documented
After delete Removed "Deletion is irreversible"

On OpenRouter you can ask for zero-data-retention routing: set provider.zdr: true on a request, or enforce it for an account, key or guardrail (OpenRouter's ZDR guide). It limits which hosts serve your model call. It says nothing about how long OpenRouter's own Files API keeps an upload, which stays undocumented (5.6).

Also note that inline media isn't "nothing stored". It falls under each provider's normal retention for requests, which can include abuse-monitoring logs (lesson 02.9, Part 9). OpenAI adds a media-specific rule: "Image and file inputs are scanned for CSAM content upon submission", and flagged images are retained for review "even if Zero Data Retention ... is enabled".

What this means for you:

  • Deleting uploads is your job. Set the shortest expiry that fits the use case, delete files in a finally block when the task is done, and run a periodic sweep that lists your files and deletes anything your database doesn't know about.
  • Keep your own original. Provider storage is a cache, not an archive: Gemini deletes after 48 hours, Anthropic and Gemini won't give an upload back, and OpenAI's download of an upload is unverified. Store the original in your own storage, so a re-upload, a deletion request or an audit never depends on reading it back.
  • "Delete my data" must reach the provider. Lesson 03.2, 10.4 builds a function that deletes a conversation everywhere; uploaded files belong on its list, which is why the registry in the next section records the owner of every file ID.
  • Choose the route by sensitivity. For data that must not be stored by a third party, use inline media under a zero-data-retention agreement, not a Files API, and strip metadata before sending (6.3).

5.9 Keeping track of file IDs#

Three facts make file IDs awkward: they expire (Gemini after 48 hours, others when you say so), they're scoped to a workspace or project rather than to your user, and uploading the same file twice costs time and storage. A small registry in your own database handles all three. It reuses an unexpired ID for the same bytes and owner, re-uploads when an ID is near expiry, and can list everything to delete for one user:

python
"""file_registry.py: remember which provider file IDs you hold, for whom, and until when.

Provider file IDs expire (Gemini after 48 hours, others when you say so) and belong to a
workspace or project, not to your end user. Keep the mapping in your own database.
"""
import hashlib
import sqlite3
from collections.abc import Callable
from datetime import datetime, timedelta, timezone

SCHEMA = """
CREATE TABLE IF NOT EXISTS provider_files (
    provider    TEXT NOT NULL,          -- 'openai' | 'anthropic' | 'gemini' | 'openrouter'
    sha256      TEXT NOT NULL,          -- content hash: the same bytes are uploaded once
    owner_id    TEXT NOT NULL,          -- YOUR user or tenant; never trust a file ID from a client
    file_id     TEXT NOT NULL,          -- file-..., file_..., files/..., or_file_...
    expires_at  TEXT,                   -- ISO 8601 UTC; NULL = until deleted
    PRIMARY KEY (provider, sha256, owner_id)
)"""
SAFETY_MARGIN = timedelta(minutes=30)   # don't hand out an ID that may expire mid-request

Uploader = Callable[[bytes], tuple[str, datetime | None]]   # returns (file_id, expires_at)


class FileRegistry:
    def __init__(self, path: str = ":memory:", now: Callable[[], datetime] | None = None):
        self.db = sqlite3.connect(path)
        self.db.execute(SCHEMA)
        self.now = now or (lambda: datetime.now(timezone.utc))

    def get_or_upload(self, provider: str, owner_id: str, data: bytes, upload: Uploader) -> str:
        digest = hashlib.sha256(data).hexdigest()
        row = self.db.execute("SELECT file_id, expires_at FROM provider_files "
                              "WHERE provider=? AND sha256=? AND owner_id=?",
                              (provider, digest, owner_id)).fetchone()
        if row and (row[1] is None or datetime.fromisoformat(row[1]) - SAFETY_MARGIN > self.now()):
            return row[0]                                            # still valid: reuse it
        file_id, expires_at = upload(data)                           # missing or stale: upload again
        self.db.execute("INSERT OR REPLACE INTO provider_files VALUES (?, ?, ?, ?, ?)",
                        (provider, digest, owner_id, file_id, expires_at.isoformat() if expires_at else None))
        self.db.commit()
        return file_id

    def for_owner(self, owner_id: str) -> list[tuple[str, str]]:
        """Everything to delete when a user asks to be forgotten: (provider, file_id) pairs."""
        return self.db.execute("SELECT provider, file_id FROM provider_files WHERE owner_id=?",
                               (owner_id,)).fetchall()

    def forget(self, provider: str, file_id: str) -> None:
        self.db.execute("DELETE FROM provider_files WHERE provider=? AND file_id=?", (provider, file_id))
        self.db.commit()

Here it is with fake uploaders and a fake clock, so you can watch a Gemini ID expire without waiting two days:

python
# s5_9_registry_demo.py
"""The registry in action, with fake uploaders and a fake clock (layer 1: nothing is sent)."""
from datetime import datetime, timedelta, timezone
from itertools import count

from file_registry import FileRegistry

clock = [datetime(2026, 11, 4, 9, 0, tzinfo=timezone.utc)]
ids = count(1)


def gemini_upload(data: bytes):                      # Gemini Files: auto-deleted after 48 hours
    print("    (uploading to Gemini)")
    return f"files/doc{next(ids)}", clock[0] + timedelta(hours=48)


def anthropic_upload(data: bytes):                   # Anthropic: no expiry unless you set one
    print("    (uploading to Anthropic)")
    return f"file_01{next(ids)}", None


reg = FileRegistry(now=lambda: clock[0])
pdf = b"%PDF-1.7 ... the quarterly report ..."

print("Mon 09:00", reg.get_or_upload("gemini", "user-42", pdf, gemini_upload))
clock[0] += timedelta(hours=6)
print("Mon 15:00", reg.get_or_upload("gemini", "user-42", pdf, gemini_upload))  # reused, no upload
clock[0] += timedelta(hours=41, minutes=45)                                      # Wed 08:45
print("Wed 08:45", reg.get_or_upload("gemini", "user-42", pdf, gemini_upload))  # inside the margin: re-upload
print("other user", reg.get_or_upload("gemini", "user-7", pdf, gemini_upload))   # never share across owners
print("anthropic", reg.get_or_upload("anthropic", "user-42", pdf, anthropic_upload))

to_delete = reg.for_owner("user-42")
print("delete for user-42:", to_delete)
for provider, file_id in to_delete:
    # here you'd call the provider's delete endpoint, then:
    reg.forget(provider, file_id)
print("left for user-42:", reg.for_owner("user-42"))
Output11 lines
    (uploading to Gemini)
Mon 09:00 files/doc1
Mon 15:00 files/doc1
    (uploading to Gemini)
Wed 08:45 files/doc2
    (uploading to Gemini)
other user files/doc3
    (uploading to Anthropic)
anthropic file_014
delete for user-42: [('gemini', 'files/doc2'), ('anthropic', 'file_014')]
left for user-42: []

The same bytes uploaded for a second user get their own ID on purpose: if one user deletes their data, the other user's copy is unaffected, and nobody's ID is ever handed to another user. In production, add a nightly job that lists each provider's files and deletes any your table doesn't contain, so a crash between upload and insert can't leave orphans. The same job covers retries: an upload that times out may still have succeeded on the provider's side, and none of the Files APIs takes an idempotency key, so retrying creates a second file with a different ID (lesson 03.8, Part 11 on duplicate work). The registry only knows the upload you saw finish; the sweep finds the one you didn't.

5.5 Gemini: the Files API#

As of November 2026:

  • Upload: client.files.upload(file=path_or_binary_file, config=types.UploadFileConfig(display_name=..., mime_type=..., name=...)) returns a types.File with name (such as files/abc123), uri, mime_type, size_bytes, state, create_time, expiration_time, sha256_hash, source and error.
  • Use: pass the File object itself in contents, or types.Part.from_uri(file_uri=file.uri, mime_type=file.mime_type), or {"type": "...", "uri": file.uri, "mime_type": ...} on Interactions.
  • Manage: client.files.get(name=...), client.files.list(config=types.ListFilesConfig(page_size=...)), client.files.delete(name=...). client.files.download(file=...) is for model-generated files only: "you can't download user-uploaded files."
  • Limits and retention: "up to 20 GB of files per project, with a per-file maximum size of 2 GB. Files are stored for 48 hours." Uploading is "available at no cost in all regions where the Gemini API is available". Files are deleted automatically after 48 hours; you can't extend that. (Google's video page quotes different storage limits, "20GB (paid) / 2GB (free)"; the Files page is the one to trust.)
  • Processing state: a new file can be PROCESSING before it's usable, especially video. Its state moves to ACTIVE or FAILED, and a request using a file that isn't active yet fails. Poll files.get until it's ACTIVE, with a timeout:
stateDiagram-v2
    [*] --> PROCESSING: files.upload
    PROCESSING --> ACTIVE: ready for inference
    PROCESSING --> FAILED: processing error
    ACTIVE --> Deleted: files.delete
    ACTIVE --> Deleted: 48 hours after upload
    FAILED --> Deleted: files.delete
    Deleted --> [*]
  • Developer API only. In google-genai 2.34.0, files.upload on a Vertex AI client raises ValueError: This method is only supported in the Gemini Developer client. On Vertex AI (Google Cloud), reference files in Cloud Storage with gs:// URIs instead. The Developer API can also register existing Cloud Storage objects: client.files.register_files(uris=["gs://bucket/file.pdf"]), after granting the Gemini API's service agent read access to the bucket. Registered files have "no overall storage limits", aren't copied, and registration "can give access for up to 30 days".

5.6 OpenRouter: a Files API in the API reference#

As of November 2026 OpenRouter has a Files API, documented in its API reference and in its own SDKs, though not yet in its guides (older write-ups that say it has none are out of date):

  • POST /api/v1/files (multipart, one file field) uploads a file: "Maximum file size: 100 MB; empty files are rejected. The file type is determined from the file contents — not the filename or the declared content type — and must be a PDF, a PNG/JPEG/GIF/WebP image, a DOCX/XLSX/PPTX document, an MP3/WAV/FLAC/OGG audio file, or UTF-8 text."
  • Files are stored under the workspace of the API key. GET /api/v1/files lists them, GET /api/v1/files/{file_id} returns metadata (id such as or_file_..., filename, mime_type, size_bytes, created_at, downloadable), DELETE /api/v1/files/{file_id} deletes one ("Deletion is irreversible"), and GET .../content downloads only server-created files.
  • An optional provider parameter (openai or anthropic) stores the file on that provider with your own key for it, instead of in OpenRouter's storage.
  • Chat Completions file parts accept file_id ("File ID for previously uploaded files").
  • The reference doesn't state a retention period. Delete files yourself.

Because the openai SDK's client.files methods follow OpenAI's own shapes, this sample calls the REST endpoints directly with httpx:

python
# s5_6_openrouter_files.py
"""OpenRouter Files API (REST): upload -> use by file_id -> list -> delete.

The openai SDK has no OpenRouter-specific file methods, so this sample calls the
documented endpoints with httpx directly.
"""
import os
from pathlib import Path

import httpx
from dotenv import load_dotenv

load_dotenv()
api = httpx.Client(
    base_url="https://openrouter.ai/api/v1",
    headers={"Authorization": f"Bearer {os.environ['OPENROUTER_API_KEY']}",
             "HTTP-Referer": "https://example.com/my-app", "X-OpenRouter-Title": "My App"},
    timeout=httpx.Timeout(60.0, connect=10.0),
)

resp = api.post("/files", files={"file": ("report.pdf", Path("report.pdf").read_bytes(), "application/pdf")})
resp.raise_for_status()
meta = resp.json()
print("uploaded:", meta["id"], meta["mime_type"], meta["size_bytes"], "B")

try:
    chat = api.post("/chat/completions", json={
        "model": "anthropic/claude-haiku-5.5",
        "messages": [{"role": "user", "content": [
            {"type": "file", "file": {"file_id": meta["id"]}},
            {"type": "text", "text": "Where did a new office open?"},
        ]}],
        "max_tokens": 200,
    })
    chat.raise_for_status()
    print("  answer:", chat.json()["choices"][0]["message"]["content"])

    listed = api.get("/files", params={"limit": 100}).json()
    print("listed:", any(f["id"] == meta["id"] for f in listed.get("data", [])))
finally:
    print("deleted:", api.delete(f"/files/{meta['id']}").status_code)
Example output · illustrative4 lines
uploaded: or_file_011CPx7Qm2aTzK9wV4bH8nRe application/pdf 1263 B
  answer: A new office opened in Lisbon, in March.
listed: True
deleted: 200

Treat this as a young feature: the reference says response shapes are "negotiated per request" (OpenRouter, OpenAI or Anthropic style), and the guides don't document it yet. Check the API reference before you depend on it.


Part 6: Preprocessing before you send#

Deep-dive

Most media problems are cheaper to fix on your side than at the provider: a phone photo is usually too big, rotated by a metadata flag instead of in its pixels, and stamped with the location where it was taken. A few lines of Pillow fix all of that before the bytes leave your server.

flowchart LR
    A["Raw upload<br/>(any phone or scanner)"] --> B{"Sniff the bytes:<br/>real type?"}
    B -->|"unsupported"| X["Reject or convert<br/>(HEIC, SVG, TIFF...)"]
    B -->|"image"| C["Apply EXIF orientation"]
    C --> D["Crop to the region<br/>that matters"]
    D --> E["Shrink to the<br/>provider's sweet spot"]
    E --> G["Re-encode without metadata<br/>JPEG/WebP photos, PNG screenshots"]
    B -->|"PDF"| P{"Encrypted?<br/>Too many pages?"}
    P -->|"encrypted"| X
    P -->|"too long"| S["Split or extract<br/>the pages you need"]
    P -->|"fine"| SEND["Preflight limits,<br/>then send"]
    S --> SEND
    G --> SEND

6.1 Resize to the sweet spot#

Every provider shrinks large images itself (Part 2), so sending more pixels than the model will use costs upload time and, often, tokens, for nothing. The "sweet spot" is the largest size the model uses without downscaling, as of November 2026:

Provider and setting Largest size used as-is Notes
Anthropic, high-resolution tier (Claude 4.7+, all 5.x) Long edge ≤ 2,576 px and ⌈w/28⌉ × ⌈h/28⌉ ≤ 4,784 The token cap bites first for most photos: a 3:4 photo tops out at about 1659×2212
Anthropic, standard tier Long edge ≤ 1,568 px and ≤ 1,568 tokens About 1.15 megapixels
OpenAI high (gpt-6-astra) 2,500 patches of 32×32 px About 2.5 megapixels, for example 1600×1600
OpenAI high (GPT-5.6 family) 2048×2048 and 2,500 patches
OpenAI low 512×512 Anything larger is shrunk to fit
Provider and setting Largest size used as-is Notes
Gemini 3 and 4 No documented pixel cap The token budget is fixed by media_resolution, so size changes quality, not cost. PDF pages are scaled to at most 3072×3072

Two separate reasons to resize, which lead to two different targets:

  • To save bandwidth and latency without changing what the model sees: resize to the provider's sweet spot. The model receives the same pixels it would have produced itself, and coordinates it returns map directly onto your image (Anthropic: "the image you have is exactly the image Claude processes").
  • To save tokens: resize below the cap, to the smallest size that still shows the detail your task needs. Text needs pixels: test the size at which your documents' smallest text stays readable before you lock it in.

Use a high-quality resampling filter when shrinking (Image.Resampling.LANCZOS in Pillow), and never enlarge: upscaling adds tokens but no information.

6.2 Format and quality#

Content Best format Why
Photos JPEG (quality 80–90) or WebP Lossy compression suits natural images: a fraction of PNG's size with no visible loss
Screenshots, diagrams, charts, scanned text PNG (or lossless WebP) Large flat colours and sharp edges compress well losslessly; JPEG adds blur and "ringing" around text, and can even come out bigger
Animated GIF Extract key frames as separate PNG/JPEG images Anthropic and OpenAI read only one frame, or reject animation
HEIC/HEIF (iPhone photos) Convert to JPEG Only Gemini accepts it (1.6). Pillow needs one extra package to read it, shown below
Anything with transparency (a PNG screenshot with a see-through background) Keep PNG, or flatten onto white before JPEG JPEG has no alpha channel, and a naive conversion paints transparent pixels black (6.7)

Anthropic warns that heavy compression "can introduce artifacts that are detrimental to model performance, especially when multiple compression passes are applied. For example, heavy JPEG compression can make text difficult to read." Re-encode once, from the original, never from an already compressed copy.

HEIC. Pillow can't open HEIC or HEIF files by itself. Install the pillow-heif plugin (uv add pillow-heif), register it once at startup, and the rest of the pipeline works unchanged: prepare_image sees a HEIC upload as "not PNG" and writes JPEG, which every provider accepts. sniff() in 9.4 recognizes the HEIC family of brands (heic, heix, hevc, hevx, heim, heis, mif1, msf1), so you can route such uploads through the plugin deliberately:

python
# s6_2_heic.py
"""HEIC (iPhone) uploads: register pillow-heif once, then the normal pipeline converts them to JPEG (layer 1)."""
import io
from pathlib import Path

from PIL import Image
from pillow_heif import register_heif_opener     # uv add pillow-heif

from media_preflight import sniff
from preprocess import prepare_image

register_heif_opener()                            # once, at startup: Image.open() now reads HEIC and HEIF

# Make a HEIC file the way an iPhone would hand it over (here: from shapes.png)
buf = io.BytesIO()
Image.open("shapes.png").convert("RGB").save(buf, "HEIF", quality=80)
heic = buf.getvalue()
print(f"HEIC upload: {len(heic):,} bytes, sniffed as {sniff(heic)}, Pillow format {Image.open(io.BytesIO(heic)).format}")

jpeg, media_type = prepare_image(heic, 1568)      # HEIC is not PNG, so the pipeline writes JPEG
print(f"after prepare_image: {len(jpeg):,} bytes, {media_type}, sniffed as {sniff(jpeg)}")
Output2 lines
HEIC upload: 9,940 bytes, sniffed as image/heic, Pillow format HEIF
after prepare_image: 14,493 bytes, image/jpeg, sniffed as image/jpeg

The HEIC here is made from shapes.png with the same plugin, because the lesson can't ship an iPhone photo. (It uses preprocess.py from 6.7.)

6.3 Orientation and metadata#

Orientation. Phones don't rotate the pixels when you hold them sideways: they save the sensor's image as it was captured and add an EXIF flag (Orientation, tag 274) saying how to rotate it for display. Photo viewers obey the flag. Many image pipelines, and some vision models, don't, and OpenAI and Gemini both list rotated images as a cause of wrong answers. ImageOps.exif_transpose(img) applies the flag to the pixels, so the image is upright whatever reads it next. (Anthropic says its servers apply "orientation correction"; do it yourself anyway, so every provider gets the same pixels.)

Metadata. EXIF is a block of data inside JPEG (and other) files: camera make and model, lens, timestamps, editing software and, if location services were on, GPS coordinates precise enough to find someone's house. It travels inside the base64 payload (1.5), and inside any file you upload. The model doesn't need it, and your users didn't mean to send it.

python
# s6_3_icc_srgb.py
"""Convert a wide-gamut (Display P3) image to sRGB before the profile is dropped (layer 1)."""
import io
import os
from pathlib import Path

from PIL import Image

from preprocess import encode, to_srgb

# Any Display P3 .icc file works. This is where macOS keeps one; point P3_ICC at another file elsewhere.
P3 = Path(os.environ.get("P3_ICC", "/System/Library/ColorSync/Profiles/Display P3.icc"))

p3 = Image.new("RGB", (64, 64), (200, 100, 50))             # the numbers mean "this colour in Display P3"
p3.info["icc_profile"] = P3.read_bytes()
print("pixel as stored (P3 numbers):",  p3.getpixel((0, 0)))

naive, _ = encode(p3, "PNG")                                 # drops the profile: P3 numbers are now read as sRGB
print("profile dropped: same numbers, now read as sRGB (duller):", Image.open(io.BytesIO(naive)).getpixel((0, 0)))

right, _ = encode(to_srgb(p3), "PNG")                        # convert first, then drop the profile
print("converted to sRGB, then dropped:",  Image.open(io.BytesIO(right)).getpixel((0, 0)))

Output (using the Display P3 profile that macOS ships; any Display P3 .icc file works, via P3_ICC):

text
pixel as stored (P3 numbers): (200, 100, 50)
profile dropped: same numbers, now read as sRGB (duller): (200, 100, 50)
converted to sRGB, then dropped: (215, 93, 31)

The same stored numbers (200, 100, 50) are a different colour once the profile is applied: in sRGB it's (215, 93, 31). Skipping the conversion keeps the numbers and loses the meaning.

6.4 Cropping#

The most effective preprocessing step is often to send less of the image. If you know where the relevant part is (a form field, a receipt total, the error dialog in a screenshot, a product in a photo), crop to it before resizing. The model's fixed token budget then goes on the part that matters, so small text in that region becomes readable at the same cost. When you don't know the region, a cheap first call can find it (Gemini and Claude both return bounding boxes, Module 09), followed by a second call on the crop.

Anthropic adds one caution: "Avoid cropping out key visual context solely to enlarge the text." If the model needs to know the number is the total on an invoice, keep enough of the invoice to show that.

6.5 PDFs: count, split and extract#

Three PDF operations cover most needs, all with pypdf (a pure-Python PDF library):

  • Count pages before sending, to check page limits (600 on Claude, 1,000 on Gemini) and estimate cost (3.2).
  • Split or extract pages: send only the pages a question needs (a contract's signature page, a report's summary), or cut a long document into parts that fit the limits.
  • Extract embedded text, to check whether a PDF has real text at all: empty text on every page usually means a scan.

Also check reader.is_encrypted: a password-protected PDF fails at the provider.

6.6 Page images or extracted text?#

Sending a PDF lets the provider extract text and render page images, which is what you want for charts, tables, forms, handwriting and scans. But when a document is mostly plain prose, extracting the text yourself and sending it as text is cheaper (no page-image tokens), faster, works on every model and lets you clean it first. Rules of thumb:

Document Send
Layout, charts, tables, forms or scans matter The PDF (or page images)
Long prose (contracts, policies, articles) where only the words matter Extracted text
A large collection you'll search across Neither in full: retrieve the relevant parts first (Module 07)
Scanned pages with no text layer The PDF to a provider that renders pages, or OCR first (Module 05)

page.extract_text() is fine for a quick check, but extraction quality varies a lot with how a PDF was made (columns, tables, ligatures, headers and footers). Doing it well is Module 05's subject.

6.7 Try it: the preprocessing toolkit#

One module with everything above, plus to_srgb() (6.3) and the upload guards that 6.8 explains (open_image, read_capped, prepare_image_isolated and a page cap on pdf_text). It's layer 1: pure Python, no network.

python
"""preprocess.py: get images and PDFs into the right shape *before* you pay to send them."""
import io
import subprocess
import sys
import warnings
from pathlib import Path
from typing import BinaryIO

from PIL import Image, ImageCms, ImageOps
from pypdf import PdfReader, PdfWriter

# Long-edge targets: the largest size each provider uses without downscaling (November 2026).
# Anything bigger costs upload time and, on some models, tokens, for no extra detail.
TARGET_LONG_EDGE = {
    "anthropic-high-res": 2576,   # Claude 4.7+ (all Claude 5.x); the 4,784-token cap usually bites first
    "anthropic-standard": 1568,   # older Claude models
    "openai-high": 2048,          # gpt-5.6 family `high`; gpt-6-astra `high` is capped by 2,500 patches instead
    "gemini-3": 3072,             # no documented image cap (fixed token budget); PDF pages are scaled to <= 3072
}


MAX_PIXELS = 50_000_000   # your own cap. Pillow only *warns* above 89,478,485 pixels and raises above twice that


def open_image(data: bytes) -> Image.Image:
    """Open an upload lazily and refuse oversized images from the header alone, before decoding a pixel."""
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("error", Image.DecompressionBombWarning)   # Pillow's soft warning becomes a hard stop
            img = Image.open(io.BytesIO(data))    # reads the header only: the pixels are decoded later
    except (Image.DecompressionBombError, Image.DecompressionBombWarning) as e:
        raise ValueError(f"image rejected: {e}") from e
    if img.width * img.height > MAX_PIXELS:
        raise ValueError(f"image rejected: {img.width}x{img.height} = {img.width * img.height:,} pixels "
                         f"(cap {MAX_PIXELS:,})")
    return img


def read_capped(stream: BinaryIO, limit: int, chunk: int = 64 * 1024) -> bytes:
    """Read an upload, refusing as soon as it passes `limit` bytes instead of buffering all of it first."""
    buf = bytearray()
    while block := stream.read(chunk):
        buf += block
        if len(buf) > limit:
            raise ValueError(f"upload rejected: more than {limit:,} bytes")
    return bytes(buf)


def load_upright(data: bytes) -> Image.Image:
    """Decode an image and apply its EXIF orientation, so pixels are the right way up."""
    img = open_image(data)
    img = ImageOps.exif_transpose(img)            # phones store "rotate me" in EXIF instead of rotating pixels
    return img


def to_srgb(img: Image.Image) -> Image.Image:
    """Convert an image with an embedded ICC profile (for example Display P3) to sRGB pixels.

    Do this BEFORE encode(), which drops the profile. Images without a profile are assumed to be sRGB.
    """
    icc = img.info.get("icc_profile")
    if not icc:
        return img
    source = ImageCms.ImageCmsProfile(io.BytesIO(icc))
    srgb = ImageCms.createProfile("sRGB")
    converted = ImageCms.profileToProfile(img.convert("RGB"), source, srgb, outputMode="RGB")
    assert converted is not None                  # None only happens with inPlace=True
    if img.mode == "RGBA":                        # the colour channels were converted: carry the alpha across
        converted.putalpha(img.getchannel("A"))
    return converted


def resize_long_edge(img: Image.Image, long_edge: int) -> Image.Image:
    """Shrink (never enlarge) so the longer side is at most `long_edge` pixels."""
    if max(img.size) <= long_edge:
        return img
    scale = long_edge / max(img.size)
    new_size = (max(1, round(img.width * scale)), max(1, round(img.height * scale)))
    return img.resize(new_size, Image.Resampling.LANCZOS)   # LANCZOS keeps small text readable


def crop_box(img: Image.Image, left: float, top: float, right: float, bottom: float) -> Image.Image:
    """Crop to a region given as fractions of the width and height (0.0-1.0)."""
    w, h = img.size
    return img.crop((round(left * w), round(top * h), round(right * w), round(bottom * h)))


def encode(img: Image.Image, fmt: str = "JPEG", quality: int = 85) -> tuple[bytes, str]:
    """Re-encode WITHOUT metadata (EXIF, GPS, XMP, ICC profile, comments). Returns (bytes, media_type)."""
    if img.mode in ("I", "I;16", "I;16B", "I;16L"):  # 16/32-bit greyscale (scanners, medical): convert() would
        img = img.point(lambda v: v / 256).convert("L")  # clip everything above 255 to white, so scale to 8 bits
    has_alpha = img.mode in ("RGBA", "LA", "PA") or "transparency" in img.info
    if has_alpha and img.mode != "RGBA":
        img = img.convert("RGBA")                 # applies the palette (P) and keeps the transparency
    elif not has_alpha and img.mode not in ("RGB", "L"):
        img = img.convert("RGB")                  # applies the palette; also handles CMYK, 1-bit and so on
    if fmt == "JPEG" and img.mode == "RGBA":      # JPEG has no alpha channel
        flat = Image.new("RGB", img.size, "white")
        flat.paste(img, mask=img.getchannel("A")) # blend onto white, not black: black text must stay visible
        img = flat
    clean = Image.frombytes(img.mode, img.size, img.tobytes())   # pixels only: no metadata survives
    buf = io.BytesIO()
    if fmt == "PNG":
        clean.save(buf, "PNG", optimize=True)
    else:
        clean.save(buf, fmt, quality=quality)
    return buf.getvalue(), {"JPEG": "image/jpeg", "PNG": "image/png", "WEBP": "image/webp"}[fmt]


def prepare_image(data: bytes, long_edge: int, fmt: str | None = None, quality: int = 85) -> tuple[bytes, str]:
    """The usual pipeline: upright -> shrink -> re-encode without metadata.

    fmt=None keeps PNG sources as PNG (screenshots, diagrams) and turns everything else into JPEG.
    """
    source_format = open_image(data).format                      # read from the bytes, not the filename
    fmt = fmt or ("PNG" if source_format == "PNG" else "JPEG")
    return encode(resize_long_edge(load_upright(data), long_edge), fmt, quality)


def prepare_image_isolated(data: bytes, long_edge: int, timeout: float = 20.0) -> tuple[bytes, str]:
    """prepare_image() in a child process that is killed after `timeout` seconds.

    A hostile or just unlucky file can make decoding slow or memory-hungry. In a child process it can
    only hurt itself: add a memory limit (a container limit, or `ulimit -v` on Linux) for the rest.
    """
    code = ("import sys\nfrom preprocess import prepare_image\n"
            "out, media_type = prepare_image(sys.stdin.buffer.read(), int(sys.argv[1]))\n"
            "sys.stdout.buffer.write(media_type.encode() + b'\\n' + out)")
    done = subprocess.run([sys.executable, "-c", code, str(long_edge)], input=data, capture_output=True,
                          timeout=timeout, cwd=Path(__file__).parent)   # raises TimeoutExpired, and kills the child
    if done.returncode != 0:
        raise ValueError(done.stderr.decode(errors="replace").strip().splitlines()[-1])
    media_type, _, out = done.stdout.partition(b"\n")
    return out, media_type.decode()


# ---------- PDFs ----------

def pdf_page_count(data: bytes) -> int:
    reader = PdfReader(io.BytesIO(data))
    if reader.is_encrypted:
        raise ValueError("encrypted PDF: the model can't read it; ask for an unencrypted copy")
    return len(reader.pages)


def pdf_pages(data: bytes, first: int, last: int) -> bytes:
    """Return a new PDF holding pages first..last (1-based, inclusive)."""
    reader, writer = PdfReader(io.BytesIO(data)), PdfWriter()
    for page in reader.pages[first - 1:last]:
        writer.add_page(page)
    buf = io.BytesIO()
    writer.write(buf)
    return buf.getvalue()


def pdf_split(data: bytes, pages_per_part: int) -> list[bytes]:
    """Split a PDF into parts of at most `pages_per_part` pages (for page limits)."""
    total = pdf_page_count(data)
    return [pdf_pages(data, start, min(start + pages_per_part - 1, total))
            for start in range(1, total + 1, pages_per_part)]


def pdf_text(data: bytes, max_pages: int = 200) -> list[str]:
    """Embedded text, one string per page. Empty strings usually mean a scanned page.

    The page cap is checked before any text is extracted: extraction is the expensive part.
    """
    reader = PdfReader(io.BytesIO(data))
    if len(reader.pages) > max_pages:
        raise ValueError(f"PDF rejected: {len(reader.pages)} pages > {max_pages}")
    return [page.extract_text() or "" for page in reader.pages]

And a demo that runs each step on the test files and reports size, orientation, GPS and estimated tokens before and after:

python
# s6_7_preprocess_demo.py
"""Before and after: what preprocessing does to size, metadata and token cost."""
import io
from pathlib import Path

from PIL import Image
from pypdf import PdfWriter

from media_tokens import ANTHROPIC_HIGH_RES, OPENAI_GPT_6_ASTRA, anthropic_image_tokens, openai_image_tokens
from preprocess import (crop_box, encode, load_upright, pdf_page_count, pdf_pages,
                        pdf_split, pdf_text, prepare_image, resize_long_edge)


def describe(label: str, data: bytes) -> None:
    img = Image.open(io.BytesIO(data))
    exif = img.getexif()
    gps = "GPS present" if exif.get_ifd(0x8825) else "no GPS"
    print(f"{label:28} {len(data):>10,} B  {img.width}x{img.height}  {img.format:4}  "
          f"orientation={exif.get(0x0112, '-')}  {gps}  "
          f"openai-high={openai_image_tokens(img.width, img.height, OPENAI_GPT_6_ASTRA['high'])}  "
          f"claude={anthropic_image_tokens(img.width, img.height, ANTHROPIC_HIGH_RES)[0]}")


original = Path("photo.jpg").read_bytes()
describe("original phone photo", original)

# Shrinking to a provider's limit saves upload bytes; going *below* its token cap also saves tokens
claude_size = anthropic_image_tokens(3024, 4032, ANTHROPIC_HIGH_RES)[1:]     # what Claude would resize to
print("Claude high-res would resize the upright photo to", claude_size)
for label, long_edge in [("prepared at Claude's size", max(claude_size)),
                         ("prepared at 1568 px", 1568), ("prepared at 1024 px", 1024)]:
    small, media_type = prepare_image(original, long_edge, "JPEG", quality=85)
    describe(label, small)

upright = load_upright(original)
print(f"\nEXIF orientation applied: stored {Image.open(io.BytesIO(original)).size} -> upright {upright.size}")

# Format choice: photos compress well as JPEG/WebP; flat screenshots and diagrams as PNG
photo = resize_long_edge(upright, 1568)
shapes = Image.open("shapes.png")
for name, img in [("photo 1568px", photo), ("screenshot-like shapes.png", shapes)]:
    sizes = {fmt: len(encode(img, fmt)[0]) for fmt in ("PNG", "JPEG", "WEBP")}
    print(f"{name:28} " + "  ".join(f"{fmt}={size:>9,} B" for fmt, size in sizes.items()))

# Crop to the region of interest instead of sending the whole frame
top_left = crop_box(upright, 0.0, 0.0, 0.5, 0.5)
data, _ = encode(resize_long_edge(top_left, 1568))
describe("top-left quarter, cropped", data)

# PDFs: count, split, extract
pdf = Path("report.pdf").read_bytes()
print(f"\nreport.pdf: {pdf_page_count(pdf)} pages, {len(pdf):,} B")
parts = pdf_split(pdf, pages_per_part=2)
print("split into", [f"{pdf_page_count(p)} pages / {len(p):,} B" for p in parts])
print("page 2 only:", pdf_page_count(pdf_pages(pdf, 2, 2)), "page;", repr(pdf_text(pdf_pages(pdf, 2, 2))[0]))

# Anthropic documents that encrypted PDFs are rejected; catch them before sending
writer = PdfWriter(clone_from=io.BytesIO(pdf))
writer.encrypt(user_password="secret", algorithm="AES-256")
buf = io.BytesIO(); writer.write(buf)
try:
    pdf_page_count(buf.getvalue())
except ValueError as e:
    print("encrypted copy:", e)
Output15 lines
original phone photo          9,165,390 B  4032x3024  JPEG  orientation=6  GPS present  openai-high=2993  claude=4740
Claude high-res would resize the upright photo to (1659, 2212)
prepared at Claude's size     1,015,841 B  1659x2212  JPEG  orientation=-  no GPS  openai-high=2993  claude=4740
prepared at 1568 px             399,944 B  1176x1568  JPEG  orientation=-  no GPS  openai-high=2176  claude=2352
prepared at 1024 px             123,015 B  768x1024  JPEG  orientation=-  no GPS  openai-high=922  claude=1036

EXIF orientation applied: stored (4032, 3024) -> upright (3024, 4032)
photo 1568px                 PNG=1,637,072 B  JPEG=  399,944 B  WEBP=  386,438 B
screenshot-like shapes.png   PNG=    6,333 B  JPEG=   14,624 B  WEBP=    5,052 B
top-left quarter, cropped       630,687 B  1176x1568  JPEG  orientation=-  no GPS  openai-high=2176  claude=2352

report.pdf: 3 pages, 1,263 B
split into ['2 pages / 1,039 B', '1 pages / 708 B']
page 2 only: 1 page; 'Page 2. The Lisbon office opened in March with 14 staff.'
encrypted copy: encrypted PDF: the model can't read it; ask for an unencrypted copy

What the numbers show:

  • Upright, smaller, and no GPS. The original is stored sideways (4032×3024 with orientation 6) and carries GPS. Every prepared copy is upright (portrait), has no EXIF orientation flag left to misread, and has no GPS.
  • Resizing to the cap saves bytes, not tokens. At Claude's own resize size (1659×2212) the photo drops from 9.2 MB to 1.0 MB, a ninefold cut in upload, but it still costs about 4,740 tokens on Claude and 2,993 on OpenAI high: exactly what the providers would have charged after shrinking it themselves. Going below the cap is what cuts tokens: on Claude, 1568 px halves them (4,740 to 2,352) and 1024 px cuts them by about 78% (to 1,036); on OpenAI high the same two sizes cut 27% and 69%.
  • Pick the format by content. For the photo, JPEG and WebP are a quarter of PNG's size. For the flat, screenshot-like image, PNG and WebP win and JPEG is more than twice as big, as well as blurrier.
  • A crop costs the same tokens as the full frame at the same size, but every one of those tokens now covers a quarter of the scene, so details are four times sharper.
  • PDFs: splitting, extracting one page and detecting encryption all work locally before anything is sent.

Test the re-encoder on the awkward files, not only on photos. The demo above uses an RGB photo and an RGB screenshot, and a re-encoder that only ever sees those looks perfect. Real uploads include indexed PNGs (from pngquant and GIF conversions), screenshots with transparent backgrounds, and 16-bit greyscale scans. A first version of encode() copied the raw pixel bytes without normalizing the mode, which silently broke all three: a palette image lost its palette (every colour became a palette index), a transparent pixel became black in JPEG (so black text on a transparent background vanished), and a 16-bit grey value above 255 was clipped to white. This test keeps the old function so you can see the bugs next to the fixed result, and it fails loudly if they ever return:

python
# s6_7_encode_regression.py
"""Regression test for encode(): palette PNGs keep their colours, transparent pixels never turn black,
16-bit greyscale is not clipped to white (layer 1)."""
import io
from typing import cast

from PIL import Image, ImageDraw, ImageFont

from preprocess import encode, prepare_image


def old_encode(img: Image.Image, fmt: str = "JPEG", quality: int = 85) -> bytes:
    """The first version of encode(), kept ONLY to show the two bugs it had. Don't use it."""
    clean = Image.frombytes(img.mode, img.size, img.tobytes())    # copies palette INDICES, not the palette
    if fmt == "JPEG" and clean.mode not in ("RGB", "L"):
        clean = clean.convert("RGB")                              # drops alpha: transparent pixels become black
    buf = io.BytesIO()
    clean.save(buf, fmt, quality=quality) if fmt != "PNG" else clean.save(buf, "PNG")
    return buf.getvalue()


def pixel(data: bytes, xy: tuple[int, int]) -> tuple:
    img = Image.open(io.BytesIO(data))
    return img.mode, img.getpixel(xy)


def png_bytes(img: Image.Image) -> bytes:
    buf = io.BytesIO()
    img.save(buf, "PNG")
    return buf.getvalue()


# Case 1: an indexed (palette) PNG, as pngquant and GIF-to-PNG tools produce: 8 colours, one red and one blue box
flat = Image.new("RGB", (200, 100), "white")
draw = ImageDraw.Draw(flat)
draw.rectangle((10, 10, 90, 90), fill=(220, 30, 30))
draw.rectangle((110, 10, 190, 90), fill=(30, 60, 220))
indexed = png_bytes(flat.quantize(colors=8))
red_xy, blue_xy = (50, 50), (150, 50)

# Case 2: a screenshot with a transparent background and black text, saved as RGBA
shot = Image.new("RGBA", (200, 100), (0, 0, 0, 0))
ImageDraw.Draw(shot).text((20, 30), "HI", fill=(0, 0, 0, 255),
                          font=ImageFont.load_default(size=48))
rgba = png_bytes(shot)
bg_xy = (2, 2)

print(f"source 1: mode {Image.open(io.BytesIO(indexed)).mode}, red box pixel as an RGB viewer shows it:",
      Image.open(io.BytesIO(indexed)).convert("RGB").getpixel(red_xy))

old = Image.open(io.BytesIO(old_encode(Image.open(io.BytesIO(indexed)), "PNG")))
print("old encode, palette PNG   ->", old.mode, "red", old.getpixel(red_xy), "blue", old.getpixel(blue_xy),
      " (a palette index, and no palette to look it up in)")

new_png, _ = prepare_image(indexed, 1000)                        # PNG in, PNG out
print("new encode, palette PNG   ->", *pixel(new_png, red_xy), "blue", pixel(new_png, blue_xy)[1])

print()
print("source 2: transparent RGBA screenshot, background pixel:", Image.open(io.BytesIO(rgba)).getpixel(bg_xy))
print("old encode, RGBA to JPEG  ->", pixel(old_encode(Image.open(io.BytesIO(rgba)), "JPEG"), bg_xy),
      " (black: black text would vanish)")
jpeg, _ = prepare_image(rgba, 1000, "JPEG")
print("new encode, RGBA to JPEG  ->", *pixel(jpeg, bg_xy), " (flattened onto white)")
keep, _ = prepare_image(rgba, 1000)                              # PNG in, PNG out: alpha is kept
print("new encode, RGBA to PNG   ->", *pixel(keep, bg_xy), " (transparency kept)")


def extrema(data: bytes) -> tuple[int, int]:
    return cast(tuple[int, int], Image.open(io.BytesIO(data)).convert("L").getextrema())


def range_of(data: bytes) -> str:
    low, high = extrema(data)
    return f"darkest={low:>3} lightest={high:>3}"


print("text still readable? old JPEG:", range_of(old_encode(Image.open(io.BytesIO(rgba)), "JPEG")),
      "| new JPEG:", range_of(jpeg), "\n")

# Case 3: a palette image with a transparent index, like an animated-GIF frame
gif_like = Image.new("P", (50, 50), 0)
gif_like.putpalette([255, 255, 255, 200, 0, 0] + [0] * 250 * 3)      # 0 = white, 1 = red
gif_like.paste(1, (10, 10, 40, 40))
gif_like.info["transparency"] = 0                                    # index 0 is transparent
buf = io.BytesIO(); gif_like.save(buf, "PNG", transparency=0)
jpeg3, _ = prepare_image(buf.getvalue(), 1000, "JPEG")
print("new encode, P+transparency to JPEG ->", *pixel(jpeg3, (2, 2)), "background;", pixel(jpeg3, (25, 25))[1], "square")

# Case 4: a 16-bit greyscale scan, mid-grey (40,000 of 65,535)
grey16 = Image.new("I;16", (50, 50), 40000)
buf = io.BytesIO(); grey16.save(buf, "PNG")
old16 = pixel(old_encode(Image.open(io.BytesIO(buf.getvalue())), "JPEG"), (2, 2))
jpeg16, _ = prepare_image(buf.getvalue(), 1000, "JPEG")
print("old encode, 16-bit grey to JPEG ->", *old16, " (everything above 255 clipped to white)")
print("new encode, 16-bit grey to JPEG ->", *pixel(jpeg16, (2, 2)), " (scaled into 8 bits: 40000 / 256 = 156)")

# The test: fail loudly if either bug comes back
def near(a: tuple, b: tuple, tol: int = 6) -> bool:
    return all(abs(x - y) <= tol for x, y in zip(a, b))

assert near(pixel(new_png, red_xy)[1], (220, 30, 30)) and near(pixel(new_png, blue_xy)[1], (30, 60, 220))
assert near(pixel(jpeg, bg_xy)[1], (255, 255, 255))
assert pixel(keep, bg_xy)[1][3] == 0
assert extrema(jpeg)[0] < 40      # the black text survived
assert near(pixel(jpeg3, (2, 2))[1], (255, 255, 255)) and near(pixel(jpeg3, (25, 25))[1], (200, 0, 0), 12)
assert abs(pixel(jpeg16, (2, 2))[1] - 156) <= 3
print("\nall encode() regression checks passed")
Output15 lines
source 1: mode P, red box pixel as an RGB viewer shows it: (220, 30, 30)
old encode, palette PNG   -> P red 1 blue 1  (a palette index, and no palette to look it up in)
new encode, palette PNG   -> RGB (220, 30, 30) blue (30, 60, 220)

source 2: transparent RGBA screenshot, background pixel: (0, 0, 0, 0)
old encode, RGBA to JPEG  -> ('RGB', (0, 0, 0))  (black: black text would vanish)
new encode, RGBA to JPEG  -> RGB (255, 255, 255)  (flattened onto white)
new encode, RGBA to PNG   -> RGBA (0, 0, 0, 0)  (transparency kept)
text still readable? old JPEG: darkest=  0 lightest=  0 | new JPEG: darkest=  0 lightest=255 

new encode, P+transparency to JPEG -> RGB (255, 253, 255) background; (200, 0, 0) square
old encode, 16-bit grey to JPEG -> RGB (255, 255, 255)  (everything above 255 clipped to white)
new encode, 16-bit grey to JPEG -> L 156  (scaled into 8 bits: 40000 / 256 = 156)

all encode() regression checks passed

The fix is in the first lines of encode(): apply the palette by converting to RGB (or RGBA when there is transparency), scale 16-bit greys into 8 bits, and for JPEG alpha-blend onto white. For PNG and WebP the alpha channel is kept as it is. The (255, 253, 255) background in the last transparent case is JPEG's own rounding, within the test's tolerance.

6.8 Treat uploads as hostile#

Everything above assumes friendly files. An upload endpoint receives whatever anyone sends, and you are about to run image and PDF decoders on it, then forward it to a paid API. Five habits protect you:

  1. Cap the bytes at the edge, before reading the body into memory. A reverse proxy does it first (for example nginx's client_max_body_size), and your own code should read in chunks and stop at a limit, as read_capped() does. Check what your web framework does by default: many don't limit request bodies at all. A 413 from your server is yours to design, and a different thing from the provider's 413 (1.7).
  2. Check the pixel count from the header, before decoding. A decompression bomb is a small file that expands enormously. The PNG in the sample below is 194,504 bytes on disk and claims 40,000 × 40,000 pixels, which is 1.6 billion pixels: 200 MB as packed 1-bit data, and about 4.8 GB the moment you .convert("RGB"). Pillow has a guard: above Image.MAX_IMAGE_PIXELS (89,478,485 by default) it only warns, and above twice that (178,956,970) it raises DecompressionBombError. That leaves a wide gap, so set your own cap well below it (MAX_PIXELS in preprocess.py is 50 million) and compare img.width * img.height right after Image.open(), which reads only the header.
  3. Cap PDF pages before you extract anything. A PDF with thousands of pages, or deeply nested objects, makes extract_text() slow and memory-hungry. Count the pages first (6.5), and refuse above your limit.
  4. Decode in a worker with a deadline. Run the decoding in a child process that you can kill after a timeout, with a memory limit from your container or ulimit -v, so one bad file can't stall or crash the web server. prepare_image_isolated() does the first half with subprocess.run(..., timeout=...).
  5. Don't trust the type, the name or the size a client reports (1.6): sniff the bytes, and re-derive everything else.
python
# s6_8_hostile_uploads.py
"""Treat uploads as hostile: a decompression bomb, an oversized upload, a long PDF and a slow decoder (layer 1)."""
import io
import struct
import subprocess
import warnings
import zlib
from pathlib import Path

from PIL import Image
from pypdf import PdfWriter

from preprocess import open_image, pdf_text, prepare_image_isolated, read_capped


def png_of_zeros(width: int, height: int) -> bytes:
    """A valid 1-bit PNG whose pixels are all zero. Tiny on disk, enormous once decoded."""
    def chunk(kind: bytes, body: bytes) -> bytes:
        return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body))
    row = b"\x00" * (1 + -(-width // 8))                           # filter byte + packed 1-bit pixels
    packer = zlib.compressobj(9)
    parts = [packer.compress(row) for _ in range(height)] + [packer.flush()]
    return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 1, 0, 0, 0, 0))
            + chunk(b"IDAT", b"".join(parts)) + chunk(b"IEND", b""))


# 1. The bomb: 40,000 x 40,000 pixels, yet only about 200 KB on disk
bomb = png_of_zeros(40_000, 40_000)
print(f"bomb: {len(bomb):,} bytes on disk, claims {40_000 * 40_000:,} pixels")

try:
    Image.open(io.BytesIO(bomb))                                   # Pillow's own guard fires in open()
except Image.DecompressionBombError as e:
    print("Pillow alone      ->", type(e).__name__, "|", str(e)[:70])
try:
    open_image(bomb)
except ValueError as e:
    print("open_image()      ->", str(e)[:100])

# 2. The gap Pillow leaves: 64 million pixels pass silently, 144 million only warn, and both then decode
for side in (8_000, 12_000):
    sample = png_of_zeros(side, side)
    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter("always")
        Image.open(io.BytesIO(sample))
    print(f"Pillow alone, {side * side // 1_000_000} MP -> opened"
          + (f" with a {caught[0].category.__name__}" if caught else ", no warning at all"))
    try:
        open_image(sample)
    except ValueError as e:
        print(f"open_image(), {side * side // 1_000_000} MP -> {str(e)[:92]}")

# 3. Cap the upload while reading it, not after it is all in memory
try:
    read_capped(io.BytesIO(b"x" * 6_000_000), limit=5_000_000)
except ValueError as e:
    print("read_capped       ->", e)
print("read_capped, small ->", len(read_capped(io.BytesIO(b"x" * 1_000), limit=5_000_000)), "bytes read")

# 4. Cap PDF pages before extracting any text
writer = PdfWriter()
for _ in range(500):
    writer.add_blank_page(612, 792)
buf = io.BytesIO(); writer.write(buf)
try:
    pdf_text(buf.getvalue(), max_pages=200)
except ValueError as e:
    print("pdf_text          ->", e)

# 5. Decode in a child process with a deadline
jpeg, media_type = prepare_image_isolated(Path("shapes.png").read_bytes(), 1000, timeout=30.0)
print(f"isolated worker   -> {len(jpeg):,} bytes of {media_type}")
try:
    prepare_image_isolated(Path("shapes.png").read_bytes(), 1000, timeout=0.01)
except subprocess.TimeoutExpired:
    print("isolated worker   -> TimeoutExpired: the child was killed")
try:
    prepare_image_isolated(bomb, 1000)
except ValueError as e:
    print("isolated, bomb    ->", str(e)[:100])
Output13 lines
bomb: 194,504 bytes on disk, claims 1,600,000,000 pixels
Pillow alone      -> DecompressionBombError | Image size (1600000000 pixels) exceeds limit of 178956970 pixels, coul
open_image()      -> image rejected: Image size (1600000000 pixels) exceeds limit of 178956970 pixels, could be decompres
Pillow alone, 64 MP -> opened, no warning at all
open_image(), 64 MP -> image rejected: 8000x8000 = 64,000,000 pixels (cap 50,000,000)
Pillow alone, 144 MP -> opened with a DecompressionBombWarning
open_image(), 144 MP -> image rejected: Image size (144000000 pixels) exceeds limit of 89478485 pixels, could be dec
read_capped       -> upload rejected: more than 5,000,000 bytes
read_capped, small -> 1000 bytes read
pdf_text          -> PDF rejected: 500 pages > 200
isolated worker   -> 6,333 bytes of image/png
isolated worker   -> TimeoutExpired: the child was killed
isolated, bomb    -> ValueError: image rejected: Image size (1600000000 pixels) exceeds limit of 178956970 pixels, could 

Read the middle lines twice. A 64-megapixel image passes Pillow's own guard silently, and a 144-megapixel one only warns, so open_image() rejects both with the lower cap. The timeout line shows the child process being killed.


Part 7: Ordering, labelling and history#

Deep-dive

What to write in a prompt is Module 04's subject. This part covers the mechanics that are specific to media: where the files go in the content list, how to refer to several of them, and what happens to them in later turns.

7.1 Where to put the media#

The providers' own guidance, as of November 2026, doesn't agree:

Provider Guidance Source
OpenAI No ordering rule in the vision or file-inputs guides; their examples use both orders Images and vision, File inputs
Anthropic "Claude works best when images come before text" (same for long documents); "Place PDFs before text" Vision, PDF support
Provider Guidance Source
Gemini Three answers: the image guide says "place the text prompt before the image"; the Files prompting guide says "Put your image first for single-image prompts"; the document guide says "If using a single page, place the text prompt after the page" Image understanding, Files, Document understanding
OpenRouter "we recommend sending the text prompt first, then the images ... system messages should contain text only" (about how OpenRouter parses content) Image inputs

A practical default:

  • Claude: media first, then the question. Anthropic is consistent about it, and it matches its long-context advice.
  • Gemini: test both orders on your own data. Google's pages disagree, and the differences are likely small.
  • OpenRouter: put the text first in the message, as OpenRouter asks; the upstream model then gets content in the order OpenRouter expects.
  • OpenAI: either order works. Pick one and keep it consistent.
  • Everywhere: media goes in user turns, never in system instructions.

If you call several providers through one code path (lesson 03.11), make order a per-provider setting rather than hard-coding it: the defaults above differ (Claude: media first; OpenRouter: text first), so "media before the question" isn't a rule of this lesson, it's one provider's advice. Lesson 03.11 treats the order as a per-provider configuration value that the caller chooses, and this lesson uses the same words.

7.2 Several images: label them#

With more than one image, give each a short text label in the content list, so both you and the model can refer to them unambiguously. Anthropic recommends it explicitly ("introduce each one with a short text label (Image 1:, Image 2:, and so on) so you can refer to them by name in your prompt and in follow-up turns"), and it helps on every provider:

python
content = [
    {"type": "text", "text": "Image 1 (before repair):"},
    {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": before_b64}},
    {"type": "text", "text": "Image 2 (after repair):"},
    {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": after_b64}},
    {"type": "text", "text": "Is the crack visible in image 1 still present in image 2?"},
]

For comparisons, keep the images the same size and orientation (preprocess them the same way), name what each one is, and ask about specific differences rather than "what's different?". For a sequence (pages of a form, frames of a process), number them in order. Anthropic adds that Claude "has access to every image from earlier turns", so a follow-up such as "Are these similar to the first two?" works without re-attaching anything in the new turn; it does still re-send them, as the next section explains.

7.3 Images in conversation history#

The APIs are stateless (lesson 02.7, Part 3): every turn re-sends the whole history, and an image in turn 1 is re-sent, and re-billed, in turn 2, turn 3 and every turn after (lesson 02.7, 6.1). With a few screenshots per conversation, images quickly dominate both request size and cost. This sample measures a five-turn conversation where the user sends one 400 KB photo per turn, then prunes every image except the latest:

python
# s7_3_history_images.py
"""Images in history are re-sent, and re-billed, on every turn. Measure it, then prune (layer 1)."""
import base64
import copy
import json

from media_tokens import anthropic_image_tokens

PHOTO_B64 = base64.b64encode(b"\xff\xd8\xff" + b"x" * 400_000).decode()  # stands in for a 400 KB JPEG
PHOTO_TOKENS = anthropic_image_tokens(1176, 1568)[0]                       # what a 1176x1568 photo costs


def user_turn_with_photo(n: int) -> dict:
    return {"role": "user", "content": [
        {"type": "text", "text": f"Image {n}:"},
        {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": PHOTO_B64}},
        {"type": "text", "text": f"Is the bike in image {n} the same model as before?"}]}


def drop_old_images(messages: list[dict], keep_last: int = 1) -> list[dict]:
    """Replace image blocks with a short text note, except in the last `keep_last` user turns."""
    pruned = copy.deepcopy(messages)
    user_idx = [i for i, m in enumerate(pruned) if m["role"] == "user"]
    for i in user_idx[:-keep_last] if keep_last else user_idx:
        content = pruned[i]["content"]
        if isinstance(content, list):
            pruned[i]["content"] = [
                {"type": "text", "text": "[image removed after it was discussed; see the assistant's reply]"}
                if block.get("type") == "image" else block for block in content]
    return pruned


def stats(messages: list[dict]) -> tuple[int, int]:
    images = sum(1 for m in messages if isinstance(m["content"], list)
                 for b in m["content"] if b.get("type") == "image")
    return len(json.dumps(messages)), images * PHOTO_TOKENS


history: list[dict] = []
total_full = total_pruned = 0
print(f"{'turn':>4} | {'full history':>26} | {'pruned (keep last 1)':>26}")
for turn in range(1, 6):
    history.append(user_turn_with_photo(turn))
    full_bytes, full_tok = stats(history)
    pruned_bytes, pruned_tok = stats(drop_old_images(history, keep_last=1))
    total_full += full_tok
    total_pruned += pruned_tok
    print(f"{turn:>4} | {full_bytes:>11,} B {full_tok:>7,} img tok | {pruned_bytes:>11,} B {pruned_tok:>7,} img tok")
    history.append({"role": "assistant", "content": f"Image {turn} shows a red road bike, same model."})

print(f"image tokens billed over 5 turns: full={total_full:,}  pruned={total_pruned:,} "
      f"({100 * (1 - total_pruned / total_full):.0f}% fewer)")
Output7 lines
turn |               full history |       pruned (keep last 1)
   1 |     533,576 B   2,352 img tok |     533,576 B   2,352 img tok
   2 |   1,067,232 B   4,704 img tok |     533,898 B   2,352 img tok
   3 |   1,600,888 B   7,056 img tok |     534,220 B   2,352 img tok
   4 |   2,134,544 B   9,408 img tok |     534,542 B   2,352 img tok
   5 |   2,668,200 B  11,760 img tok |     534,864 B   2,352 img tok
image tokens billed over 5 turns: full=35,280  pruned=11,760 (67% fewer)

Unpruned, the fifth request carries five photos (2.7 MB) and about 11,800 image tokens. Pruned, every request carries one photo, and over five turns you pay for two-thirds fewer image tokens. The longer the conversation, the bigger the saving. The options, from cheapest to most faithful:

  1. Drop old images once the assistant has answered about them, leaving a text note (as above). The assistant's earlier answer, still in the history, carries what it saw.
  2. Replace an image with a description: ask the model once for a detailed description, then keep that text instead of the image.
  3. Reference images by file ID (Part 5): request size stays small, but you still pay input tokens for every image on every turn.
  4. Cache the prefix that contains the images (lesson 03.7): cached image tokens are billed at a fraction of the price, as long as the history before them doesn't change.

Server-side conversation state (OpenAI's previous_response_id, Gemini's previous_interaction_id, lesson 03.2, Part 7) saves you re-uploading the bytes, but the model still reads, and you still pay for, every earlier image as input on every turn.


Part 8: Audio and video input: an overview#

Deep-dive

Audio and video follow the same three routes as images (inline, URL, file), but the providers differ much more, and building speech and video applications is Module 09's subject. As of November 2026:

OpenAI Anthropic
Audio input Chat Completions only, with audio models such as gpt-audio-1.5: an input_audio part {"data": "<base64>", "format": "wav"} (the SDK types allow wav and mp3). "The Responses API docs currently describe text and image inputs with text outputs." The GPT-6 text models don't take audio. Speech-to-text and realtime voice have their own APIs ❌ No audio input in the Messages API: the content block types have no audio block
Video input ❌ Not on the GPT-6 models (their input modalities are text and image) ❌ None
Large files — —
Gemini OpenRouter
Audio input ✅ Inline, Files API or URL; WAV, MP3, AIFF, AAC, OGG, FLAC and more; up to 9.5 hours per prompt; 25 or 32 tokens per second: Google's pages disagree, so measure with count_tokens (2.4) ✅ input_audio, base64 only ("direct URLs are not supported for audio content"); Responses accepts wav and mp3, Chat Completions whatever the provider supports
Video input ✅ Files API (recommended), inline for short clips, Cloud Storage, or YouTube URLs (Preview: public videos only, up to 10 per request on Gemini 2.5+, 8 hours per day on the free tier). Sampled at 1 frame per second by default; about 100 tokens per second at low resolution, 300 at high; an "agentic" processing mode on recent models loads only what the question needs ✅ video_url (Chat Completions) or input_video (Responses) with a URL or base64 data URL, on video-capable models; for Gemini on AI Studio, only YouTube links
Large files Files API: upload, then poll until ACTIVE (5.5), because video processing takes time Base64 data URLs for local files

Here is what the Gemini column looks like in code: audio inline on generate_content, and a YouTube link on Interactions, where Google's current examples use typed audio and video blocks:

python
# s8_gemini_audio_video.py
"""Gemini audio and video input: inline audio on generate_content, a YouTube URL on Interactions."""
from pathlib import Path

from dotenv import load_dotenv
from google import genai
from google.genai import types

load_dotenv()
client = genai.Client()

# Audio: raw bytes inline (fine under 20 MB in total; use the Files API above that)
audio = Path("voice_note.mp3").read_bytes()                     # your own recording
response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=[types.Part.from_bytes(data=audio, mime_type="audio/mp3"),
              "Transcribe this voice note, then list any action items."],
    config=types.GenerateContentConfig(max_output_tokens=1000),
)
print("audio:", response.text)

# Video: a public YouTube URL as a typed block (a preview feature: public videos only)
interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {"type": "text", "text": "Please summarize the video in 3 sentences."},
        {"type": "video", "uri": "https://www.youtube.com/watch?v=9hE5-98ZeCg"},
    ],
)
print("video:", interaction.output_text)
Example output · illustrative2 lines
audio: Transcript: "Hi Priya, it's Sam. The quote is ready, I'll send it Thursday." Action items: send the quote on Thursday.
video: <a three-sentence summary of the video>

Two engineering notes. Audio and video are long in tokens: an hour of audio is about 90,000–115,000 tokens on Gemini (25 to 32 tokens per second, 2.4), and an hour of video about 360,000 at low resolution and over a million at high, so count before you send. And when you need a transcript rather than an answer, a dedicated speech-to-text API is usually cheaper and more accurate than a general chat model (Module 09).


Part 9: When media goes wrong#

Reference

9.1 The failure modes#

Media fails in ways text never does, and several of them don't raise an exception at all. Providers publish few of their media errors, so each cell in the table carries a label (as of 2026-11-04):

  • Plain text: documented on the provider's official pages.
  • Developer-reported: seen and posted by developers (a link is given), and not confirmed by the provider. They can change without notice.
  • Expected, undocumented: our inference. No official page names the error, so the cell gives the generic status the SDK raises (usually a 400, as BadRequestError or errors.ClientError). Don't match on its text.
Failure OpenAI Anthropic Prevent it by
Request too large Expected, undocumented: a 4xx. OpenAI's error page only says to "check the encoding, format, or size of your request data" 413 request_too_large (anthropic.RequestTooLargeError), returned by Cloudflare before the API Resizing; file IDs; preflight size check (1.7)
Image too large Over 30,000 patches: rejected (the error text isn't published, expected: 400) Over 8,000 px, or over the many-image limit: 400 invalid_request_error; otherwise silently downscaled Resizing to the sweet spot (6.1)
Image too small Not documented Not documented (Anthropic warns of poor results under 200 px) A minimum size in your own preflight
Too many images or pages Expected, undocumented: 400 (the limit is 1,500 images) The many-image rule: 400 invalid_request_error mentioning "many-image requests". Past 600 images or pages (100 below a 1M-token context) expected: 400 Counting first; splitting
Wrong or unsupported MIME type Developer-reported: 400 invalid_request_error, code: "invalid_image_format", "You uploaded an unsupported image. Please make sure your image has of one the following formats: ['png', 'jpeg', 'gif', 'webp']" (forum) 400; also "Invalid file type" when a file_id's type doesn't match the block Sniffing magic bytes (9.4); converting HEIC, SVG and TIFF
Corrupt bytes, or a data URL in the wrong field Expected, undocumented: 400 Expected, undocumented: 400 Decoding the image yourself before sending
Unreachable or blocked URL The whole request fails (expected: 400) The whole request fails (expected: 400) Short-lived signed URLs; never internal URLs; a URL you control for tests (1.4)
Encrypted PDF Not documented Documented as unsupported ("Standard PDF (no passwords/encryption)"); expected: 400 reader.is_encrypted (6.5)
Expired or deleted file ID Expected, undocumented: 404 404 not_found_error; an expired file "fails before inference" A registry with expiry times (5.9)
File still processing — — Polling with a deadline (5.7)
Model doesn't accept that modality Expected, undocumented: 400 — (every Claude model takes images and PDFs) Checking input_modalities (2.5)
Image blocked by a safety or moderation filter No exception: incomplete with reason content_filter (Responses), finish_reason: "content_filter" (Chat) No exception: stop_reason: "refusal" Don't retry unchanged. Mechanics and a check_response() helper: lesson 03.8, Part 10
Media silently dropped by a proxy, converter or stand-in No error: the model answers without it Comparing input tokens with the estimate (2.1)
Model misreads the media (rotated, blurry, tiny text) No error: a wrong answer Orientation, cropping, resolution; evaluation (Module 10A)
Failure Gemini OpenRouter
Request too large Developer-reported: 400 INVALID_ARGUMENT with "The request's total referenced files bytes are too large to be read" for oversized files (forum). Google's own pages name no size error 413, error_type: payload_too_large: "The request body exceeds the maximum allowed size" (no number given); batches over 200 MB also 413
Image too large Budget capped by media_resolution image_too_large (400): "An image exceeds the provider's maximum file size or pixel dimensions"
Image too small Not documented image_too_small (400): the image is below the provider's minimum dimensions
Too many images or pages Expected, undocumented: 400 Upstream provider's
Wrong or unsupported MIME type Expected, undocumented: 400 INVALID_ARGUMENT unsupported_image_format (400): the provider doesn't support the format
Corrupt bytes, or a data URL in the wrong field Expected, undocumented: 400 invalid_image (400): "An image in the request is corrupt or unreadable"
Unreachable or blocked URL The whole request fails; unsafe URLs give URL_RETRIEVAL_STATUS_UNSAFE image_download_failed (400): OpenRouter couldn't fetch the image from the URL
Encrypted PDF Not documented Not documented
Expired or deleted file ID Expected, undocumented: a 4xx after the 48 hours image_not_found (404): the referenced image URL or file ID can't be resolved
File still processing Request fails until state is ACTIVE —
Model doesn't accept that modality Expected, undocumented: 400 An error when no endpoint supports the input (OpenRouter "automatically filters available models based on your request content")
Image blocked by a safety or moderation filter No exception: prompt_feedback.block_reason such as IMAGE_SAFETY, PROHIBITED_CONTENT, and no candidates. On Interactions, error codes such as safety and prohibited_content A 403 moderation error with reasons, or content_policy_violation (403); or a content_filter finish
Media silently dropped by a proxy, converter or stand-in
Model misreads the media (rotated, blurry, tiny text)

OpenRouter's typed errors sit in error.metadata.error_type on Chat Completions (a top-level error_type on its Responses API): lesson 03.8, 3.5 lists them all with their HTTP statuses, and the image ones above are the media subset. Branch on error_type, not on message text.

None of the media errors above are worth retrying unchanged: a 400 or 413 is a property of the request, not a temporary problem. Fix the input, or fail with a clear message to the user. Which errors are retryable in general, and how the SDKs retry, is lesson 03.8's subject.

9.2 Try it: media errors as SDK exceptions#

A mock server returns each provider's documented error envelope, and the real SDKs turn them into their real exception classes. Nothing is sent. Anthropic publishes the exact text of its oversized-image and 413 errors, so those are quoted. OpenRouter documents the typed error_type values, so the OpenRouter fixture uses a real one (image_too_large). For the others, the envelope is the documented one and the message text is ours.

python
# s9_2_media_errors.py
"""Media errors as real SDK exceptions, from a mock server (layer 3: nothing is sent).

The envelopes and status codes follow each provider's documented error format; the
Anthropic oversized-image and 413 messages are quoted from Anthropic's docs, and the OpenRouter
`error_type` value is one of its documented typed errors. The other message texts are ours,
because the providers don't publish them.
"""
import httpx
import httpx2
import anthropic
import openai
from anthropic.types import MessageParam
from google import genai
from google.genai import errors, types

FIXTURES = {
    # Anthropic, vision-coordinates guide: an image marked "oversized_image": "error" that would be resized
    "anthropic-oversized": (400, {"type": "error", "error": {"type": "invalid_request_error", "message":
        "messages.0.content.0: image dimensions 1920x1080 exceed the maximum image size of a model named "
        "on this request and would be downsized to 1456x819; scale the image to at most 1456x819 or set "
        "the image's oversized_image setting to \"downsize\""}, "request_id": "req_test_1"}),
    # Anthropic, errors page: requests over 128 MB are refused by Cloudflare before the API sees them
    "anthropic-413": (413, {"type": "error", "error": {"type": "request_too_large",
        "message": "Request exceeds the maximum allowed number of bytes."}, "request_id": "req_test_2"}),
    # Anthropic, Files API guide lists 404 for a missing file_id (message text is ours)
    "anthropic-404": (404, {"type": "error", "error": {"type": "not_found_error",
        "message": "File not found: file_011CTEST"}, "request_id": "req_test_3"}),
    # OpenAI: the standard error envelope (message text is ours)
    "openai-400": (400, {"error": {"message": "Invalid image: the file is not a supported image format.",
        "type": "invalid_request_error", "param": "input[0].content[0].image_url", "code": None}}),
    # OpenRouter: Chat Completions errors carry a typed metadata.error_type (message text is ours)
    "openrouter-400": (400, {"error": {"code": 400, "message": "An image in the request is too large.",
        "metadata": {"error_type": "image_too_large"}}}),
    # Gemini generate_content: the Google API error envelope (message text is ours)
    "gemini-400": (400, {"error": {"code": 400, "status": "INVALID_ARGUMENT",
        "message": "Unsupported MIME type: image/svg+xml"}}),
}


def mock2(name: str) -> httpx2.Client:
    status, body = FIXTURES[name]
    headers = {"request-id": body.get("request_id", "")}          # Anthropic sends the ID as a header too
    return httpx2.Client(transport=httpx2.MockTransport(
        lambda req: httpx2.Response(status, json=body, headers=headers)))


def report(label: str, e: Exception, message: str) -> None:
    status = getattr(e, "status_code", None) or getattr(e, "code", None)
    print(f"{label:20} {type(e).__name__:21} {status}  {message[:88]}")


IMAGE: list[MessageParam] = [{"role": "user", "content": [
    {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "iVBORw0KGgo="}},
    {"type": "text", "text": "Describe this."}]}]

for name in ("anthropic-oversized", "anthropic-413", "anthropic-404"):
    claude = anthropic.Anthropic(api_key="sk-test", http_client=mock2(name), max_retries=0)
    try:
        claude.messages.create(model="claude-haiku-5-5", max_tokens=100, messages=IMAGE)
    except anthropic.APIStatusError as e:
        err = e.body["error"] if isinstance(e.body, dict) else {}     # the parsed JSON error body
        report(name, e, err.get("message", ""))
        print(f"{'':20} error.type={err.get('type')}  request_id={e.request_id}")

oai = openai.OpenAI(api_key="sk-test", http_client=mock2("openai-400"), max_retries=0)
try:
    oai.responses.create(model="gpt-6-luna", input=[{"role": "user", "content": [
        {"type": "input_image", "image_url": "data:image/png;base64,iVBORw0KGgo=", "detail": "auto"}]}])
except openai.BadRequestError as e:
    report("openai-400", e, e.message)
    print(f"{'':20} e.type={e.type!r}  e.param={e.param!r}  e.code={e.code!r}")

orc = openai.OpenAI(base_url="https://openrouter.ai/api/v1", api_key="sk-test", http_client=mock2("openrouter-400"),
                    max_retries=0)
try:
    orc.chat.completions.create(model="anthropic/claude-haiku-5.5", messages=[{"role": "user", "content": [
        {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgo="}},
        {"type": "text", "text": "Describe this."}]}])
except openai.BadRequestError as e:
    meta = e.body.get("metadata", {}) if isinstance(e.body, dict) else {}     # OpenRouter's extra detail
    report("openrouter-400", e, e.message)
    print(f"{'':20} metadata.error_type={meta.get('error_type')!r}")

status, body = FIXTURES["gemini-400"]
gem = genai.Client(api_key="test-key", http_options=types.HttpOptions(
    httpx_client=httpx.Client(transport=httpx.MockTransport(lambda req: httpx.Response(status, json=body)))))
try:
    gem.models.generate_content(model="gemini-3.8-flash", contents=[
        types.Part.from_bytes(data=b"<svg/>", mime_type="image/svg+xml"), "Describe this."])
except errors.ClientError as e:
    report("gemini-400", e, e.message or "")
    print(f"{'':20} e.code={e.code}  e.status={e.status!r}")
Output12 lines
anthropic-oversized  BadRequestError       400  messages.0.content.0: image dimensions 1920x1080 exceed the maximum image size of a mode
                     error.type=invalid_request_error  request_id=req_test_1
anthropic-413        RequestTooLargeError  413  Request exceeds the maximum allowed number of bytes.
                     error.type=request_too_large  request_id=req_test_2
anthropic-404        NotFoundError         404  File not found: file_011CTEST
                     error.type=not_found_error  request_id=req_test_3
openai-400           BadRequestError       400  Error code: 400 - Invalid image: the file is not a supported image format.
                     e.type='invalid_request_error'  e.param='input[0].content[0].image_url'  e.code=None
openrouter-400       BadRequestError       400  Error code: 400 - An image in the request is too large.
                     metadata.error_type='image_too_large'
gemini-400           ClientError           400  Unsupported MIME type: image/svg+xml
                     e.code=400  e.status='INVALID_ARGUMENT'

The useful parts of each exception: Anthropic's error.type (invalid_request_error, request_too_large, not_found_error) and request_id for support tickets (lesson 03.1, 8.6); OpenAI's param, which points at the offending part of the input; OpenRouter's metadata.error_type, which names the problem precisely (image_too_large here); and Gemini's code and status. A 413 gets its own class in the anthropic SDK, RequestTooLargeError, so you can catch size problems separately and respond by resizing or switching to a file ID.

9.3 Try it free: real errors from the stand-in#

The local stand-in produces real errors for several of these cases, through the real SDKs:

python
# s9_3_standin_errors.py
"""Try it free: real media errors from the local stand-in (Ollama), as real SDK exceptions."""
import base64
import json
from pathlib import Path

import anthropic
import openai

oai = openai.OpenAI(base_url="http://localhost:11434/v1", api_key="ollama", max_retries=0)
claude = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama", max_retries=0)
garbage = base64.b64encode(b"this is not a png").decode()
png = base64.b64encode(Path("shapes.png").read_bytes()).decode()
pdf = base64.b64encode(Path("report.pdf").read_bytes()).decode()


def ask_openai(image_url: str):
    return oai.responses.create(model="qwen3-vl:2b", max_output_tokens=20, reasoning={"effort": "none"},
                                input=[{"role": "user", "content": [
                                    {"type": "input_image", "image_url": image_url, "detail": "auto"},
                                    {"type": "input_text", "text": "Describe it."}]}])


def ask_claude(model: str, block: dict):
    return claude.messages.create(model=model, max_tokens=20, messages=[{"role": "user", "content": [
        block, {"type": "text", "text": "Describe it."}]}])  # type: ignore[list-item]


def message(body: object) -> str:
    """Dig the innermost error message out of a (possibly nested, possibly JSON-in-a-string) body."""
    while True:
        if isinstance(body, str):
            try:
                body = json.loads(body)
                continue
            except ValueError:
                return body
        if isinstance(body, dict):
            body = body.get("error", body) if "error" in body else body.get("message", str(body))
            continue
        return str(body)


cases = {
    "corrupt bytes": lambda: ask_openai(f"data:image/png;base64,{garbage}"),
    "a URL (Ollama won't fetch)": lambda: ask_openai("https://example.com/cat.png"),
    "a PDF sent as an image": lambda: ask_openai(f"data:application/pdf;base64,{pdf}"),
    "image to a text-only model": lambda: ask_claude("qwen2.5:0.5b", {"type": "image", "source": {
        "type": "base64", "media_type": "image/png", "data": png}}),
    "PDF document block": lambda: ask_claude("qwen3-vl:2b", {"type": "document", "source": {
        "type": "base64", "media_type": "application/pdf", "data": pdf}}),
}
for label, call in cases.items():
    try:
        result = call()
        print(f"{label:27} -> NO ERROR (input tokens: {result.usage.input_tokens if result.usage else '?'})")
    except openai.APIStatusError as e:
        print(f"{label:27} -> openai.{type(e).__name__} {e.status_code}: {message(e.body or e.message)}")
    except anthropic.APIStatusError as e:
        print(f"{label:27} -> anthropic.{type(e).__name__} {e.status_code}: {message(e.body)}")
Output · local models qwen3-vl:2b and qwen2.5:0.5b via Ollama5 lines
corrupt bytes               -> openai.BadRequestError 400: Failed to load image or audio file
a URL (Ollama won't fetch)  -> openai.BadRequestError 400: image URLs are not currently supported, please use base64 encoded data instead
a PDF sent as an image      -> openai.BadRequestError 400: invalid image input
image to a text-only model  -> anthropic.BadRequestError 400: Multimodal data provided, but model does not support multimodal requests.
PDF document block          -> NO ERROR (input tokens: 13)

The first four are genuine 400s, each a real BadRequestError. The messages are Ollama's, not OpenAI's or Anthropic's, but the shapes of the failures are the ones hosted providers produce too: undecodable bytes, a route the server doesn't support, the wrong kind of file in an image part, and a model that can't take images. The last line is the important one: a PDF in a document block produced no error, and 13 input tokens show the model never saw it.

9.4 Catch it before the provider does: a preflight check#

Most media errors can be detected locally in microseconds: sniff the real file type, compute the base64 size without encoding, read dimensions and page counts, spot encryption and animation, and compare all of it with each provider's limits. Rejecting bad input in your own code gives the user a clear message immediately, and saves the upload time (and sometimes the cost) of a request that was bound to fail. The module reuses two earlier ones: open_image() from preprocess.py (6.8), which reads dimensions from the header and refuses pixel bombs, and the estimators in media_tokens.py (3.2), which know OpenAI's patch limit and Claude's resize rule.

python
"""media_preflight.py: reject bad media in your own code, before a provider rejects (and bills) it.

The limits below are the documented first-party API values as of November 2026. Keep them
in configuration and re-check them when you change models: they move.
"""
import io
from dataclasses import dataclass, field

from pypdf import PdfReader

from media_tokens import OPENAI_GPT_6_ASTRA, anthropic_image_tokens, openai_image_tokens
from preprocess import open_image          # refuses oversized images from the header, before decoding

MB = 1_000_000   # providers write "MB" without saying 10**6 or 2**20: use the smaller one for a safety margin


@dataclass(frozen=True)
class Limits:
    image_types: frozenset[str]
    max_image_bytes_b64: int | None      # per image, measured after base64 encoding
    max_image_px: int | None             # longest side
    max_images: int
    max_request_bytes: int
    max_pdf_pages: int | None
    max_pdf_bytes: int | None
    max_url_file_bytes: int | None = None   # per file the provider fetches from a URL


LIMITS = {
    "openai": Limits(frozenset({"image/png", "image/jpeg", "image/webp", "image/gif"}),
                     None, None, 1_500, 512 * MB, None, 50 * MB),
    "anthropic": Limits(frozenset({"image/png", "image/jpeg", "image/webp", "image/gif"}),
                        10 * MB, 8_000, 600, 128 * MB, 600, None),
    "gemini": Limits(frozenset({"image/png", "image/jpeg", "image/webp", "image/heic", "image/heif"}),
                     None, None, 3_600, 20 * MB, 1_000, 50 * MB,   # 20 MB: the safe reading of the inline limit
                     max_url_file_bytes=15 * MB),
}


def sniff(data: bytes) -> str:
    """Identify a file by its first bytes ("magic numbers"), not by its name or a client's claim."""
    if data.startswith(b"\x89PNG\r\n\x1a\n"):
        return "image/png"
    if data.startswith(b"\xff\xd8\xff"):
        return "image/jpeg"
    if data[:6] in (b"GIF87a", b"GIF89a"):
        return "image/gif"
    if data[:4] == b"RIFF" and data[8:12] == b"WEBP":
        return "image/webp"
    if data[4:8] == b"ftyp":
        brand = data[8:12]
        if brand in (b"heic", b"heix", b"hevc", b"hevx", b"heim", b"heis", b"mif1", b"msf1"):
            return "image/heic"                  # iPhone photos: HEIC and the related HEIF brands
        if brand in (b"avif", b"avis"):
            return "image/avif"
    if data[:4] in (b"II*\x00", b"MM\x00*"):
        return "image/tiff"
    if data[:2] == b"BM":
        return "image/bmp"
    if data.startswith(b"%PDF-"):
        return "application/pdf"
    return "application/octet-stream"


def looks_like_svg(data: bytes) -> bool:
    head = data[:1024].lstrip().lower()
    return head.startswith(b"<svg") or (head.startswith(b"<?xml") and b"<svg" in head)


@dataclass
class Report:
    errors: list[str] = field(default_factory=list)
    warnings: list[str] = field(default_factory=list)
    request_bytes: int = 0


def check(provider: str, files: list[tuple[str, bytes]], extra_text_bytes: int = 0, *,
          context_window: int = 1_000_000, by_url: bool = False) -> Report:
    """Check a list of (declared_media_type, bytes) for one request to `provider`.

    by_url=True: the provider will fetch the files from URLs, so they don't count towards the request
    size, but the provider's per-file URL limit applies. On Claude, a context window below 1M tokens
    cuts the image and page limits from 600 to 100.
    """
    lim, rep = LIMITS[provider], Report()
    images = documents = 0
    max_images, max_pages = lim.max_images, lim.max_pdf_pages
    if provider == "anthropic" and context_window < 1_000_000:
        max_images = max_pages = 100                             # the limit on 200K-context models
    rep.request_bytes = extra_text_bytes
    for i, (declared, data) in enumerate(files):
        actual, b64_size = sniff(data), 4 * -(-len(data) // 3)    # base64 size, without encoding it
        if not by_url:
            rep.request_bytes += b64_size
        elif lim.max_url_file_bytes and len(data) > lim.max_url_file_bytes:
            rep.errors.append(f"file {i}: {len(data):,} B > {lim.max_url_file_bytes:,} B limit for files fetched by URL")
        where = f"file {i} ({actual})"
        if actual == "application/octet-stream" and looks_like_svg(data):
            rep.errors.append(f"file {i}: SVG is not a raster format; rasterize it first (for example with cairosvg)")
            continue
        if declared != actual:
            rep.errors.append(f"{where}: declared {declared} but the bytes are {actual}")
        if actual.startswith("image/"):
            images += 1
            if actual not in lim.image_types:
                rep.errors.append(f"{where}: {provider} doesn't accept {actual}; convert to PNG or JPEG")
                continue
            try:
                img = open_image(data)                            # header only; rejects pixel bombs
            except ValueError as e:
                rep.errors.append(f"{where}: {e}")
                continue
            except OSError as e:                                  # corrupt bytes, or HEIC without pillow-heif
                if actual == "image/heic":
                    rep.warnings.append(f"{where}: can't read HEIC dimensions without pillow-heif; size checks skipped")
                else:
                    rep.errors.append(f"{where}: Pillow can't decode it ({type(e).__name__}): corrupt file?")
                continue
            if not by_url and lim.max_image_bytes_b64 and b64_size > lim.max_image_bytes_b64:
                rep.errors.append(f"{where}: {b64_size:,} B as base64 > {lim.max_image_bytes_b64:,} B limit")
            if lim.max_image_px and max(img.size) > lim.max_image_px:
                rep.errors.append(f"{where}: {img.width}x{img.height} > {lim.max_image_px} px")
            if getattr(img, "is_animated", False):
                if provider == "openai":
                    rep.warnings.append(f"{where}: animated; OpenAI documents non-animated GIFs only, so it may reject this")
                else:
                    rep.warnings.append(f"{where}: animated; only one frame will be used (send key frames as images)")
            if provider == "openai":
                try:                                              # gpt-6-astra's rule, as a proxy (see 3.1)
                    openai_image_tokens(img.width, img.height, OPENAI_GPT_6_ASTRA["original"])
                except ValueError as e:
                    rep.warnings.append(f"{where}: {e} with detail=\"original\"; use \"high\" or shrink it first")
            if provider == "anthropic" and lim.max_image_px and max(img.size) <= lim.max_image_px:
                _, rw, rh = anthropic_image_tokens(img.width, img.height)
                if (rw, rh) != img.size:
                    rep.warnings.append(f"{where}: {img.width}x{img.height} will be silently downscaled to {rw}x{rh}; "
                                        f"resize it yourself, or set oversized_image to \"error\"")
        elif actual == "application/pdf":
            documents += 1
            reader = PdfReader(io.BytesIO(data))
            if reader.is_encrypted:
                rep.errors.append(f"{where}: encrypted PDFs are rejected")
                continue
            if max_pages and len(reader.pages) > max_pages:
                rep.errors.append(f"{where}: {len(reader.pages)} pages > {max_pages}; split it")
            if lim.max_pdf_bytes and len(data) > lim.max_pdf_bytes:
                rep.errors.append(f"{where}: {len(data):,} B > {lim.max_pdf_bytes:,} B; use the Files API or split")
        else:
            rep.errors.append(f"{where}: unrecognized file type")
    if images > max_images:
        rep.errors.append(f"{images} images > {max_images} per request")
    if provider == "anthropic" and images + documents > 20:
        rep.warnings.append("more than 20 image and document blocks: keep each image at or below 3,000 px (many-image limit)")
    if rep.request_bytes > lim.max_request_bytes:
        rep.errors.append(f"request ~{rep.request_bytes:,} B > {lim.max_request_bytes:,} B; use file IDs")
    return rep
python
# s9_4_preflight_demo.py
"""Run the preflight checks on good and bad inputs (layer 1: nothing is sent)."""
import io
from pathlib import Path

from PIL import Image
from pypdf import PdfWriter

from media_preflight import check
from preprocess import prepare_image

photo = Path("photo.jpg").read_bytes()
png = Path("shapes.png").read_bytes()
pdf = Path("report.pdf").read_bytes()

frames = [Image.new("RGB", (64, 64), c) for c in ("red", "blue")]          # a 2-frame animated GIF
buf = io.BytesIO(); frames[0].save(buf, "GIF", save_all=True, append_images=frames[1:]); gif = buf.getvalue()
w = PdfWriter(clone_from=io.BytesIO(pdf)); w.encrypt("secret", algorithm="AES-256")
buf = io.BytesIO(); w.write(buf); locked = buf.getvalue()
small, small_type = prepare_image(photo, 1568)


def png_of(img: Image.Image) -> bytes:
    buf = io.BytesIO(); img.save(buf, "PNG"); return buf.getvalue()


heic = b"\x00\x00\x00\x18ftypheic" + b"\x00" * 16                           # just the HEIC signature, for sniffing
blank = PdfWriter()
for _ in range(120):
    blank.add_blank_page(612, 792)
buf = io.BytesIO(); blank.write(buf); long_pdf = buf.getvalue()

cases = [
    ("anthropic", "raw 9.2 MB phone photo", [("image/jpeg", photo)], {}),
    ("anthropic", "same photo, prepared", [(small_type, small)], {}),
    ("openai", "PNG labelled as JPEG", [("image/jpeg", png)], {}),
    ("openai", "an SVG file", [("image/svg+xml", b"<svg xmlns='http://www.w3.org/2000/svg'/>")], {}),
    ("anthropic", "animated GIF", [("image/gif", gif)], {}),
    ("openai", "animated GIF", [("image/gif", gif)], {}),
    ("gemini", "encrypted PDF", [("application/pdf", locked)], {}),
    ("anthropic", "25 small images", [("image/png", png)] * 25, {}),
    ("gemini", "two raw photos inline", [("image/jpeg", photo)] * 2, {}),
    ("gemini", "same two photos, by URL", [("image/jpeg", photo)] * 2, {"by_url": True}),
    ("gemini", "photo padded to 16 MB, URL", [("image/jpeg", photo + b"\0" * 7_000_000)], {"by_url": True}),
    ("gemini", "iPhone HEIC", [("image/heic", heic)], {}),
    ("openai", "iPhone HEIC", [("image/heic", heic)], {}),
    ("anthropic", "5000x3000 screenshot", [("image/png", png_of(Image.new("RGB", (5000, 3000), "white")))], {}),
    ("openai", "6000x6000 image", [("image/png", png_of(Image.new("RGB", (6000, 6000), "white")))], {}),
    ("anthropic", "7000x8000 (56 MP) image", [("image/png", png_of(Image.new("L", (7000, 8000))))], {}),
    ("anthropic", "120-page PDF", [("application/pdf", long_pdf)], {}),
    ("anthropic", "120-page PDF, 200K window", [("application/pdf", long_pdf)], {"context_window": 200_000}),
]
for provider, label, files, options in cases:
    rep = check(provider, files, **options)
    verdict = "OK  " if not rep.errors else "FAIL"
    print(f"{verdict} {provider:9} {label:27} ~{rep.request_bytes:>11,} B")
    for msg in rep.errors:
        print(f"       error:   {msg}")
    for msg in rep.warnings:
        print(f"       warning: {msg}")
Output34 lines
FAIL anthropic raw 9.2 MB phone photo      ~ 12,220,520 B
       error:   file 0 (image/jpeg): 12,220,520 B as base64 > 10,000,000 B limit
       warning: file 0 (image/jpeg): 4032x3024 will be silently downscaled to 2212x1659; resize it yourself, or set oversized_image to "error"
OK   anthropic same photo, prepared        ~    533,260 B
FAIL openai    PNG labelled as JPEG        ~      9,808 B
       error:   file 0 (image/png): declared image/jpeg but the bytes are image/png
FAIL openai    an SVG file                 ~         56 B
       error:   file 0: SVG is not a raster format; rasterize it first (for example with cairosvg)
OK   anthropic animated GIF                ~        376 B
       warning: file 0 (image/gif): animated; only one frame will be used (send key frames as images)
OK   openai    animated GIF                ~        376 B
       warning: file 0 (image/gif): animated; OpenAI documents non-animated GIFs only, so it may reject this
FAIL gemini    encrypted PDF               ~      2,792 B
       error:   file 0 (application/pdf): encrypted PDFs are rejected
OK   anthropic 25 small images             ~    245,200 B
       warning: more than 20 image and document blocks: keep each image at or below 3,000 px (many-image limit)
FAIL gemini    two raw photos inline       ~ 24,441,040 B
       error:   request ~24,441,040 B > 20,000,000 B; use file IDs
OK   gemini    same two photos, by URL     ~          0 B
FAIL gemini    photo padded to 16 MB, URL  ~          0 B
       error:   file 0: 16,165,390 B > 15,000,000 B limit for files fetched by URL
OK   gemini    iPhone HEIC                 ~         40 B
       warning: file 0 (image/heic): can't read HEIC dimensions without pillow-heif; size checks skipped
FAIL openai    iPhone HEIC                 ~         40 B
       error:   file 0 (image/heic): openai doesn't accept image/heic; convert to PNG or JPEG
OK   anthropic 5000x3000 screenshot        ~     67,312 B
       warning: file 0 (image/png): 5000x3000 will be silently downscaled to 2474x1484; resize it yourself, or set oversized_image to "error"
OK   openai    6000x6000 image             ~    159,456 B
       warning: file 0 (image/png): 35344 patches > 30000: the API rejects this image with detail="original"; use "high" or shrink it first
FAIL anthropic 7000x8000 (56 MP) image     ~     72,572 B
       error:   file 0 (image/png): image rejected: 7000x8000 = 56,000,000 pixels (cap 50,000,000)
OK   anthropic 120-page PDF                ~     19,996 B
FAIL anthropic 120-page PDF, 200K window   ~     19,996 B
       error:   file 0 (application/pdf): 120 pages > 100; split it

Every failure here would otherwise have been a 400 or 413 after uploading the request, or, for an animated GIF, a silent loss of every frame but one. The second half of the cases goes beyond comparing sizes:

  • By URL, the request size doesn't count, but a per-file limit does. Gemini fetches URLs up to 15 MB per file, so two 9 MB photos pass by URL and fail inline (20 MB), and a 16 MB file fails by URL.
  • Warnings, not errors, where the provider doesn't refuse. A 5000×3000 screenshot is accepted by Claude, which silently downscales it to 2474×1484; the preflight says so, because Claude's coordinates then refer to the smaller image. A 6000×6000 image is fine on OpenAI at detail: "high" and rejected at "original" (35,344 patches against a limit of 30,000), so that is a warning about the setting. An animated GIF is "only the first frame" on Claude, and possibly rejected on OpenAI, whose guide documents non-animated GIFs only.
  • HEIC is recognized, not decoded. Gemini accepts it, so it passes with a warning that its dimensions can't be read without pillow-heif (6.2); OpenAI refuses it by name.
  • The pixel cap and the context window. The 56-megapixel image is rejected from its header alone (6.8), and a 120-page PDF fails on a 200K-context Claude model (100 pages) but passes at 1M.
  • One error per problem. An SVG gets a single message ("rasterize it first") instead of a type mismatch plus "unrecognized".

Two design choices are worth copying. The limits are data, dated, in one place, because they change. And MB is taken as 10^6 bytes: providers write "MB" without saying whether they mean 1,000,000 or 1,048,576 bytes, and the smaller reading gives you a safety margin.

9.5 Putting it together: a production-minded image call#

Everything from this lesson in one function: preprocessing (upright, resized, metadata stripped, format chosen by content), the preflight check, a token estimate, an explicit timeout, errors handled by type, a finish check, and a log line with sizes, the estimate, real usage and the request ID. It imports the three modules from this lesson (preprocess.py, media_preflight.py and media_tokens.py).

python
# s9_5_production_image_call.py
"""A production-minded image call: validate, shrink, strip metadata, send, check, log."""
import base64
import logging
from pathlib import Path

import openai
from dotenv import load_dotenv

from media_preflight import check
from media_tokens import OPENAI_GPT_6_ASTRA, openai_image_tokens
from preprocess import load_upright, prepare_image

logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
log = logging.getLogger("vision")
load_dotenv()

client = openai.OpenAI(timeout=60.0, max_retries=2)   # images make requests slower: be explicit


def ask_about_image(path: str, question: str, model: str = "gpt-6-luna") -> str:
    raw = Path(path).read_bytes()
    data, media_type = prepare_image(raw, long_edge=1568)        # upright, smaller, no EXIF/GPS
    report = check("openai", [(media_type, data)], extra_text_bytes=len(question))
    if report.errors:                                            # fail here, not at the provider
        raise ValueError("; ".join(report.errors))
    w, h = load_upright(data).size
    estimate = openai_image_tokens(w, h, OPENAI_GPT_6_ASTRA["high"])   # astra rule as a proxy (see 3.1)

    try:
        response = client.responses.create(
            model=model,
            input=[{"role": "user", "content": [
                {"type": "input_image", "detail": "high",
                 "image_url": f"data:{media_type};base64,{base64.b64encode(data).decode('ascii')}"},
                {"type": "input_text", "text": question},
            ]}],
            reasoning={"effort": "none"},
            max_output_tokens=500,
        )
    except openai.BadRequestError as e:                          # bad media: retrying won't help
        log.error("rejected image %s: %s (request %s)", path, e.message, e.request_id)
        raise
    except (openai.APIConnectionError, openai.APITimeoutError):  # already retried by the SDK
        log.error("network trouble sending %s (%d bytes)", path, len(data))
        raise

    if response.status != "completed":                           # e.g. incomplete: max_output_tokens
        raise RuntimeError(f"response {response.status}: {response.incomplete_details}")
    usage = response.usage
    log.info("model=%s request=%s bytes_sent=%d est_image_tokens=%d input_tokens=%s output_tokens=%s",
             response.model, response._request_id, len(data), estimate,
             usage.input_tokens if usage else None, usage.output_tokens if usage else None)
    return response.output_text


if __name__ == "__main__":
    print(ask_about_image("shapes.png", "What text is at the top of this image?"))
Example output · illustrative3 lines
INFO HTTP Request: POST https://api.openai.com/v1/responses "HTTP/1.1 200 OK"
INFO model=gpt-6-luna request=req_7c1e9f04b2a84d6e9a3f5b8c0d2e4f61 bytes_sent=6333 est_image_tokens=312 input_tokens=327 output_tokens=12
The text at the top of the image is "INVOICE 42".

With the model ID pointed at the local qwen3-vl:2b, the same function runs end to end for real and logs bytes_sent=6333 est_image_tokens=312 input_tokens=1086: the local model's image encoder counts tokens its own way, which is exactly the kind of gap the log line exists to show. Notice what the log doesn't contain: the image itself. Log sizes, types, hashes and IDs, never the payload (1.5).

The other samples in this lesson leave most of this out to stay readable: they use default timeouts, don't run the preflight check, don't check status or stop_reason, and print instead of logging. Real code should do all of it, and lesson 03.8 and lesson 03.10 add retries, request IDs and structured logging.


Common misconceptions#

Misconception Reality
"A 9 MB photo is under the 10 MB limit." Request and image limits are measured on what you send, and base64 makes it 12.2 MB. Anthropic's 10 MB limit is explicitly "base64-encoded" (1.3).
"Sending the full-resolution photo gives the model more detail." Every provider shrinks large images to a fixed budget first. Above the cap you pay upload time for pixels the model never sees (3.2, 6.1).
"Uploading a file with the Files API saves tokens." It saves request size and upload time. The model still reads the whole file on every request, and you pay for it as input every time (5.1).
"detail: low is always cheapest." Usually, but OpenAI warns it "does not always use fewer tokens than high" (on gpt-5.4 it allows 6,144 patches). And Gemini's media_resolution is a maximum per image, not a price per pixel (2.2).
"If an image is too big, the API returns an error." Anthropic silently downscales unless you set oversized_image: "error"; OpenAI resizes per detail and rejects only past 30,000 patches (2.3).
"The request succeeded, so the model saw the image." Proxies and stand-ins can drop media silently. Check input tokens against the estimate (2.1).
"The model reads EXIF, so the GPS data helps it." Anthropic says Claude "does not parse or receive any metadata", and OpenAI says the same of its models. The metadata still leaves your system: strip it (6.3).
"A PDF is billed by its file size." It's billed by pages (and text density): extracted text plus a page image per page (4.1).
"Every provider can cite pages of a PDF I send." Only Anthropic has document citations as an API feature for files you send. OpenAI and Gemini attach citations only through their retrieval tools (File Search), and OpenRouter may return file_citation annotations (4.9).
"Gemini file names are permanent IDs." Gemini deletes uploaded files after 48 hours, and you can't extend it (5.5).
"File IDs are private to the user who uploaded the file." They're scoped to a project or workspace: any key there can read them. Never accept file IDs from clients (5.4).
"OpenRouter's PDF parsing is free on BYOK." mistral-ocr is billed to your OpenRouter account even on BYOK, and it's the default fallback (4.6).
"Pillow's decompression-bomb protection covers my upload endpoint." By default it only warns above about 89 million pixels and raises above about 179 million, so a 64-megapixel bomb passes silently. Set your own, lower cap and check the size from the header (6.8).
"Re-encoding an image with Pillow is always safe." Copying pixels without normalizing the mode loses a palette image's colours and paints transparent pixels black in JPEG. Test the re-encoder on indexed, transparent and 16-bit files (6.7).
"An image in turn 1 is paid for once." It's re-sent and re-billed on every later turn unless you drop it or cache it (7.3).
"OpenRouter has no Files API." As of November 2026 it has one, documented in its API reference (5.6).

Key takeaways#

  • Media is one more content part, but every provider names and shapes it differently: input_image/input_file (OpenAI Responses), image_url/file (Chat Completions and OpenRouter), image/document blocks (Anthropic), Part.from_bytes/from_uri or typed blocks (Gemini).
  • There are three routes: inline base64 (simple, works everywhere, about 33% bigger and re-sent every time), URL (small requests, but the file must be reachable, and links leak), and file ID (upload once; the provider stores the file).
  • Limits are on the encoded request, and they differ per route (inline, Batch, Files). 1.7 has the one table, dated 2026-11-11: for example Anthropic 128 MB for Messages, 256 MB for Batch and 500 MB for Files, OpenAI 50 MB for input_file, and Gemini inline 20 MB to be safe. Image counts are 1,500 (OpenAI), 600 (Anthropic) and 3,600 (Gemini).
  • Oversized images are handled differently: OpenAI resizes per detail and rejects past 30,000 patches; Anthropic downscales silently unless you ask for an error; Gemini charges a fixed budget per media_resolution.
  • Image cost follows documented formulas: 32 px patches × a model multiplier (OpenAI), ⌈w/28⌉ × ⌈h/28⌉ with a cap (Anthropic), a fixed budget per image (Gemini). An estimator reproduces the providers' worked examples; check it against counting endpoints and usage.
  • PDFs are billed by pages: extracted text plus a page image per page. Gemini doesn't bill a PDF's native text; OpenRouter parses PDFs for any model, with an OCR engine that costs money even on BYOK unless you choose the free one.
  • Anthropic has document citations (page_location, char_location, content_block_location), with free cited_text; grounding as a pattern is Module 07's.
  • Files APIs differ in retention: OpenAI keeps files until deleted (or expires_after), Anthropic until deleted (or expires_in_seconds), Gemini deletes after 48 hours, and OpenRouter's new API doesn't say. File IDs are project- or workspace-scoped: keep the user-to-file mapping yourself, and delete what you no longer need.
  • Preprocess every upload: apply EXIF orientation, crop, resize to just below the provider's cap, choose JPEG/WebP for photos and PNG for screenshots (flatten transparency onto white, never black), and strip metadata, especially GPS.
  • Treat uploads as hostile: cap bytes at the edge, check pixel counts from the header before decoding, cap PDF pages, decode with a deadline, and remember that text inside an image is a prompt-injection channel.
  • Order and labels matter: media before the question on Claude, text first on OpenRouter, test both on Gemini, and label multiple images "Image 1:", "Image 2:".
  • Images in history are re-billed every turn. Drop or describe them after use, or cache them.
  • Audio input is Gemini, OpenRouter and OpenAI's audio models only; video input is Gemini and OpenRouter only. Module 09 builds on them.
  • Catch media errors locally with a preflight check, don't retry 400s and 413s unchanged, and compare input tokens with your estimate to catch media that was silently dropped.

Terms introduced in this lesson#

Term One-line definition
Base64 A way of writing any bytes as text using 64 safe characters; the result is about 4/3 the original size
Data URL A string that holds a file inline: data:<media type>;base64,<data>
MIME type / media type A type/subtype label for a kind of file, such as image/png or application/pdf
Magic number The fixed bytes at the start of a file that identify its real format
Inline media A file sent inside the request body, base64-encoded
File ID A provider's reference to a file uploaded to its Files API, used in place of the bytes
Files API A provider endpoint for uploading, listing, retrieving and deleting files used in requests
Signed URL A link to a private file that includes a cryptographic signature and an expiry time
Multipart form data The request encoding used to upload files: named fields, including files, separated by a boundary
Resumable upload Google's two-step upload protocol: request an upload URL, then send the bytes (and resume if interrupted)
Patch / visual token A small square of pixels (32×32 on OpenAI, 28×28 on Anthropic) that becomes one unit of image input
Image token multiplier OpenAI's per-model factor applied to an image's patch count to get billable tokens
Image detail level (detail) OpenAI's per-image setting (low, high, original, auto) that controls resizing and token cost
media_resolution Gemini's per-part or per-request setting for the maximum tokens per image, frame or PDF page
Resolution tier Anthropic's grouping of models by maximum image size: high-resolution (2,576 px, 4,784 tokens) and standard (1,568 px, 1,568 tokens)
Many-image rule Anthropic's stricter per-image dimension limit for requests with more than 20 images
Oversized-image setting (oversized_image) An Anthropic image-block setting that turns silent downscaling into a 400 error
Document block Anthropic's content block for PDFs, plain text and custom content
Custom content document An Anthropic document made of your own content blocks, cited block by block
Citations An API feature that links parts of an answer to exact passages in the documents provided
file-parser plugin OpenRouter's PDF processing option, with the native, cloudflare-ai and mistral-ocr engines
File annotations OpenRouter's parsed-PDF data on a Chat Completions reply, sent back to skip re-parsing
File state A Gemini file's processing status: PROCESSING, ACTIVE or FAILED
EXIF Metadata embedded in image files: camera, time, orientation and often GPS location
EXIF orientation An EXIF flag saying how to rotate an image for display, instead of rotating its pixels
ICC profile Embedded colour-space information in an image file
Preflight check Validating media against provider limits in your own code before sending
Decompression bomb A small file that expands to an enormous image (or archive) when decoded, used to exhaust memory
Spreadsheet augmentation OpenAI's processing of spreadsheet input_files: the first 1,000 rows per sheet plus a generated summary

All terms are also collected in the glossary.


Exercises#

  1. The base64 tax (1.3): run s1_3_base64_size.py on your own phone's photos. Which ones would fail Anthropic's 10 MB limit although they're under 10 MB on disk? What's the largest raw size that always fits?
  2. Wire capture (1.5): add an OpenAI Chat Completions call and an Anthropic url source to s1_5_wire_capture.py. How big is each request now? What would change if you used a file ID?
  3. The local model (2.1): with s2_1_local_vision.py, send the model photo.jpg without preprocessing and ask it to read the sign. Then rotate it with load_upright() from preprocess.py and try again. Does the 2B model notice the difference? Compare the input token counts.
  4. The estimator (3.2): in media_tokens.py and s3_2_estimator.py, add OpenAI's tile-based gpt-4.1 rule (base 85, tile 170) to the comparison table, and work out by hand why a 1920×1080 image is 6 tiles. Then write a function that, given a token budget per image, returns the largest size that fits on each provider.
  5. Counting vs estimate (3.3): if you have a key, run s3_3_count_vs_estimate.py with a few image sizes, and work out gpt-6-luna's multiplier from the results. Record the date: it may change.
  6. A PDF for citations (4.2, 4.9): extend write_pdf in make_pdf.py to put two sentences on each page, generate a five-page report with a different fact on each page, and extend s4_9_citations_mock.py so the answer cites pages 2 and 4. Print footnotes with page ranges.
  7. OpenRouter costs (4.6): adapt s2_5_openrouter_modalities.py to list models that accept file input natively. For a 300-page PDF sent to a text-only model with no engine set, what would OCR cost? With cloudflare-ai?
  8. The registry (5.9): add a sweep(list_provider_files) method to file_registry.py that deletes provider files your table doesn't know about and table rows whose files no longer exist. Test it with fake listings in s5_9_registry_demo.py.
  9. Preprocessing (6.7): pick a target of "at most 1,600 tokens on Claude's high-resolution tier" and write fit_token_budget(img, budget) in preprocess.py using anthropic_image_tokens from media_tokens.py. How large can a 4:3 photo be? A 9:16 phone screenshot?
  10. History pruning (7.3): change drop_old_images in s7_3_history_images.py to keep the last two images and replace older ones with a model-written description (a stub function is fine). Recompute the savings over 10 turns.
  11. Preflight (9.4): add OpenRouter to LIMITS in media_preflight.py using the facts in 2.5, 5.6 and 1.7, and add a check that warns when a request contains more than 8 images for a model whose provider you don't know.
  12. The re-encoder (6.7): add two more awkward inputs to s6_7_encode_regression.py: a CMYK JPEG and a greyscale PNG with a tRNS transparency chunk. Do both come out right? If one doesn't, fix encode() in preprocess.py and keep the test.
  13. Hostile uploads (6.8): use s6_8_hostile_uploads.py to build a 20,000 × 20,000 PNG. Does open_image() reject it? What does Pillow alone do, and at what pixel count would you set your own cap for an app that only accepts phone photos?
Hints for the exercises
  1. The limit is on the base64 string, so a raw file fits only if it is at most 10 MB × 3/4, which is 7.5 MB. Anything between 7.5 and 10 MB on disk fails.
  2. The Chat Completions call carries the same base64 body (about 12.2 MB for photo.jpg); an Anthropic url source and a file ID are a few hundred bytes, because only the link or ID travels. Print len(body) as the sample already does.
  3. Compare in= before and after: the token count follows the pixel size the server decodes, so an upright, smaller image should differ. Whether a 2B model reads the sign better is an observation to record, not a result to expect.
  4. For gpt-4.1 on 1920×1080: fit inside 2048×2048 (unchanged), scale the shortest side to 768 (about 1365×768), then ⌈1365/512⌉ × ⌈768/512⌉ = 3 × 2 = 6 tiles, so 85 + 6 × 170 = 1,105. For the budget function, search over the long edge (a binary search, as anthropic_image_tokens does) and keep the largest size whose estimate is within the budget.
  5. Count a text-only request too, subtract it, and divide the image part by the patch count (⌈640/32⌉ × ⌈400/32⌉ = 260 for shapes.png). Round, and remember a result near 1.2 only matches gpt-6-astra's published value, not a published gpt-6-luna rule.
  6. Give each page its own sentences in write_pdf, then in the fixture use start_page_number: 2, end_page_number: 3 for page 2 alone and 4, 5 for page 4. The footnote code already prints a range only when the end minus one exceeds the start.
  7. Filter the catalogue on 'file' in m['architecture']['input_modalities']. OCR cost is pages ÷ 1,000 × $2: 300 pages is $0.60 with mistral-ocr (the default fallback for a text-only model), and cloudflare-ai is free (4.6).
  8. List the provider's files, then delete those whose ID is not in the table and forget() the rows whose ID is not in the listing. Pass the listing and the delete call in as functions so the demo can use fakes, as get_or_upload does for uploads.
  9. Search for the largest size with ⌈w/28⌉ × ⌈h/28⌉ ≤ 1,600 at the photo's aspect ratio: roughly 1,270×952 for 4:3 and 835×1,484 for a 9:16 screenshot (about 1.25 megapixels either way).
  10. Keep the indices of the last two user turns, replace the older image blocks with the description text, and rerun the five-turn loop for ten turns; the steady state is two images per request instead of up to ten.
  11. Add a Limits entry from the facts in the three sections (no stated request limit, upstream provider's image rules), and make the unknown-provider check count image parts before calling check().
  12. Both inputs should already pass if encode() converts every mode it does not recognize to RGB and treats a tRNS chunk ("transparency" in img.info) as alpha. Verify with the pixel() helper against values you set yourself; if one fails, fix the mode handling at the top of encode() and keep the test.
  13. open_image() rejects it (400 million pixels is above both Pillow's limits and the 50-million cap), and Pillow alone raises DecompressionBombError above 178,956,970 pixels. For an app that accepts only phone photos, a cap just above the largest sensor you expect (for example 50 million pixels, as MAX_PIXELS is) is reasonable.

Check yourself#

  1. Why is a base64-encoded file about a third larger than the original?
  2. Name the three ways to attach media to a request, and one situation where each is the right choice.
  3. Your app sends a 9.5 MB JPEG to Claude inline and gets an error. Why, and what are two fixes?
  4. What does OpenAI do with an image that would need more than 30,000 patches? What does Anthropic do with an image larger than its resolution cap?
  5. How many tokens does a 1000×1000 image cost on Claude, and how do you work it out?
  6. Why does a 12-megapixel photo cost about the same as a 4K screenshot on Claude Sonnet 5.5, but about 1.8 times a 1080p screenshot?
  7. Google's documentation gives two different inline request limits. Which should you design for, and why?
  8. What does a PDF page cost on Gemini 3.8 Flash at the default media_resolution, and are you charged for its embedded text?
  9. You send a 400-page PDF to a text-only model through OpenRouter without setting plugins. What happens, and what does it cost?
  10. Which provider offers document citations as an API feature, and how is a citation of page 3 alone represented?
  11. A file name files/x7k2 stored in your database worked on Monday and fails on Thursday. Which provider, and why?
  12. Why must you never accept a file ID from your app's front end?
  13. List four things to do to a user's phone photo before sending it to a model, and one reason for each.
  14. A conversation includes a screenshot in every user turn and you never prune the history. What happens to cost, and to Claude's image limits, by turn 21?
  15. A local test of your PDF feature passes against Ollama, but the answers are generic. What's likely going on, and how would you detect it in code?

Further resources#


Appendix: the test file generator#

The generator now lives in Setup, Step 0, where you need it before Part 1: make_pdf.py (explained in 4.2) and make_assets.py, which creates shapes.png, photo.jpg and report.pdf. If you skipped Step 0, go back and run it first: every sample from 1.3 onwards reads those files from the current directory.


← 03.5 — Tool Calling: The API Mechanics | Module 03 overview | 03.7 — Token Counting, Cost Tracking and Prompt Caching →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close