Sub topic 7
What images and pages cost in tokens and time
This chapter assumes you can call an LLM chat API from Python, know what tokens and context windows are, and have read the earlier chapters on content blocks, base64 data and image preprocessing. It covers how visual inputs consume tokens, how that affects price and latency, and how to reduce both without losing the information you need.
Why visual inputs cost tokens
A language model only processes tokens. Before the model sees an image, the provider converts it into a sequence of visual tokens. Those tokens sit in the context window next to your text tokens. They count toward the context limit, and you pay for them as input tokens.
Providers use different conversion schemes, and they change over time. Three patterns are common:
- Pixel-based formulas. The token count grows with the image's width times its height. One widely documented formula divides the pixel area by a constant. Larger images cost more, up to a cap.
- Tile-based formulas. The image is scaled, split into fixed-size tiles, and each tile costs a set number of tokens. A base charge is often added on top.
- Detail settings. Some APIs let you choose a low or high detail level. Low detail uses a small, fixed budget. High detail uses the tile or pixel formula.
Because of this variety, the numbers in this chapter are illustrations. Check your provider's current documentation for the exact formula and limits.
Estimating cost before you send
A rough estimate helps you budget and decide whether to resize. The sketch below uses a pixel-area rule. The constant is an assumption for illustration.
import math
PIXELS_PER_TOKEN = 750 # illustrative constant; check your provider's docs
MAX_SIDE = 1568 # illustrative maximum side before the provider rescales
def estimate_image_tokens(width, height):
"""Rough token estimate for an image under a pixel-area rule."""
scale = min(1.0, MAX_SIDE / max(width, height))
w = int(width * scale)
h = int(height * scale)
return math.ceil((w * h) / PIXELS_PER_TOKEN)
for size in [(400, 300), (1568, 1568), (4000, 3000)]:
print(size, estimate_image_tokens(*size))Run it and you will see that the 4000 by 3000 image does not cost 10 times more than the 1568 by 1568 one. Most providers rescale oversized images down to a maximum size, so the extra pixels buy you nothing. Worse, the rescale happens on the provider side, and you still pay to upload the larger file.
The estimate is only a planning tool. After the real call, read the usage field of the response.
import anthropic
client = anthropic.Anthropic()
media_type, data = load_as_base64("chart.png")
message = client.messages.create(
model="MODEL_NAME", # replace with a vision-capable model from the provider's docs
max_tokens=256,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {"type": "base64", "media_type": media_type, "data": data},
},
{"type": "text", "text": "Describe this chart in one sentence."},
],
}
],
)
usage = message.usage
print("input tokens:", usage.input_tokens)
print("output tokens:", usage.output_tokens)To measure only the image, send the same request with just a short text prompt and subtract the input tokens. Some providers also offer a token-counting endpoint that accepts the same message structure without running the model. Use it when you want a count before spending money on generation.
The shape of the cost curve
The diagram shows the pattern most providers follow: cost rises with image size until a cap, then flattens.
Two consequences follow:
- Images below the cap are cheap in proportion to their size. A small icon costs only a few hundred tokens.
- Images above the cap cost the same as images at the cap, but they take longer to upload and may be slower to process.
What PDFs cost
A natively sent PDF usually costs more than the equivalent plain text. Providers typically extract the text of each page and also render each page as an image. You pay for both. So the cost of a PDF page is roughly the text tokens plus the image tokens for that page.
This has practical effects:
- A text-heavy page might cost about as many tokens as its words suggest, plus an image charge on top.
- A page that is mostly a chart or scan costs mainly image tokens, since little text can be extracted.
- A 100-page PDF can use a large share of the context window. Providers also set page limits and file-size limits, so check them.
The table compares common ways of sending a document. The costs are relative, not absolute.
| Method | Token cost | Keeps layout and charts | Typical use |
|---|---|---|---|
| Extract text only | Lowest | No | Text-heavy reports, contracts |
| Native PDF input | Highest per page (text plus image) | Yes | Mixed documents with figures and tables |
| Selected page images | Medium, you choose the pages | Yes | Only a few pages carry visual content |
You can often combine methods. Extract text for the whole document, then send only the pages with charts as images. A later chapter covers this decision in more detail.
Reducing cost
Apply these steps in order, because each one removes waste without hurting the result.
- Resize to the provider's cap. Sending more pixels than the provider uses wastes bandwidth. The
downscalefunction from the preprocessing chapter does this. - Crop to the region that matters. If the question is about one chart on a page, send the chart, not the page.
- Choose a lower detail level when the task is coarse. Telling a photo of a cat from a photo of a dog does not need high detail. Reading a receipt does.
- Drop pages you do not need. Send the relevant page range instead of the whole PDF.
- Use a smaller model for easy tasks. Per-token prices differ between models in the same family.
- Cache repeated inputs. If you ask many questions about the same document, prompt caching or file reuse can reduce the repeated input charge. Support and discount levels vary by provider.
Latency
Time to first response has several parts:
- Upload time. Base64 grows the data by about one third. A 5 MB photo becomes roughly 6.7 MB in the request body. On a slow connection this is measurable.
- Server-side preprocessing. The provider decodes the image, rescales it, and for PDFs extracts text and renders pages.
- Prefill. The model processes all input tokens before it writes the first output token. More visual tokens mean a longer wait.
- Generation. Output length controls this part. A short answer finishes quickly. A full transcription of a page does not.
You can measure these effects directly. This script times the same request at several widths.
import time
from PIL import Image
import anthropic
client = anthropic.Anthropic()
def resized_copy(src, dst, max_side):
with Image.open(src) as img:
img = img.convert("RGB")
img.thumbnail((max_side, max_side))
img.save(dst, format="JPEG", quality=90)
def timed_call(path):
media_type, data = load_as_base64(path)
start = time.perf_counter()
message = client.messages.create(
model="MODEL_NAME", # replace with a vision-capable model from the provider's docs
max_tokens=64,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {"type": "base64", "media_type": media_type, "data": data},
},
{"type": "text", "text": "What is the title of this chart?"},
],
}
],
)
elapsed = time.perf_counter() - start
return message.usage.input_tokens, elapsed
for side in (512, 1024, 1568):
out = f"chart_{side}.jpg"
resized_copy("chart.png", out, side)
tokens, seconds = timed_call(out)
print(f"{side}px: {tokens} input tokens, {seconds:.2f}s")The script reuses load_as_base64 from the earlier chapters. Run each size several times and compare medians, because network jitter can hide small differences. Limiting max_tokens keeps generation time from dominating the measurement.
Common mistakes
- Treating a token estimate as exact and not checking the usage field.
- Sending full-resolution phone photos, which are often 4000 pixels or more on the long side.
- Sending a whole PDF to answer a question about one page.
- Resending the same large document with every message in a chat, so that you pay for it again on each turn.
- Forgetting that images in earlier turns stay in the conversation history and count toward every later request.
The last point deserves care. In a multi-turn chat, each request carries the full history. A conversation with three images in the first turn pays for those three images on every following turn, unless caching applies or you remove them from the history.
Exercise
A user chat sends a 4000 by 3000 pixel photo in turn 1, and the app resends the whole history on every turn. The provider scales images down to a longest side of 1568 pixels. Name two changes that reduce cost, and say which one also helps latency on the first turn.
Show answer
First, resize the photo to at most 1568 pixels on its longest side before upload. Second, drop the image from the history after it is no longer needed, or use prompt caching or file reuse so later turns do not pay the full price again. Resizing also helps latency on the first turn, because it shrinks the upload body and the provider's preprocessing work. Removing the image from history helps only later turns.
Exercise
You send a 40-page PDF natively and the input token count is much higher than the word count suggests. Why, and what alternative would lower the cost if only 3 pages contain charts?
Show answer
Native PDF input typically charges for the extracted text and for an image of each page, so every page costs both. To lower the cost, extract the text for the whole document and send only the 3 chart pages as images, or send only those 3 pages as a shorter PDF.