Sub topic 3
Supported Formats and Size Limits
This chapter covers which image and document formats multimodal APIs accept, which limits you will hit, and how to check inputs before you send them. It assumes you can read files and bytes in Python, have called an LLM chat API before, and know what tokens and context windows are.
Why limits matter before you write any request
A vision request fails in one of two ways. The API rejects it with an error, or it accepts it and produces a worse answer than you expected. Format and size limits cause both. An unsupported format gives an error. An image that the provider silently shrinks can make small text unreadable.
Limits differ by provider and change between model versions. The numbers in this chapter are typical values, used to show the shape of the problem. Check your provider's documentation for the current ones, and keep them in one configuration place in your code so you can update them quickly.
Image formats
Most providers accept the same small set of raster formats. A raster image is a grid of colored pixels.
| Format | Media type | Notes |
|---|---|---|
| JPEG | `image/jpeg` | Lossy. Small files. Good for photos. |
| PNG | `image/png` | Lossless. Best for screenshots, charts and text. |
| WebP | `image/webp` | Lossy or lossless. Widely accepted. |
| GIF | `image/gif` | Usually accepted, but only one frame is typically used. |
Formats such as TIFF, BMP, HEIC, SVG and AVIF are often not accepted. If you have one of these, convert it first. SVG is a vector format (shapes described by text), so you must render it to pixels before sending.
Two details cause trouble in practice:
- The media type you declare must match the actual bytes. If you label a PNG as
image/jpeg, many APIs return a validation error. - A file extension is only a hint. A file named
photo.jpgcan contain PNG data. Check the real format from the file content.
Animated GIFs and animated WebP files are usually treated as a single still image, often the first frame. If the motion matters, extract several frames yourself and send them as separate images.
Size limits
Three kinds of limit apply to images. They are separate, and you can break any one of them.
- File size. The encoded image has a maximum number of bytes, commonly a few megabytes per image.
- Pixel dimensions. There is a maximum width and height. Larger images are either rejected or resized by the provider.
- Request size. The whole HTTP body, including every image, has a ceiling. Base64 encoding adds about 33% to the size, so a 6 MB image becomes roughly 8 MB in the request.
There is also usually a cap on the number of images per request. Some providers set a lower cap for bulk requests than for single ones.
The dimension limit has a hidden effect. When an image is larger than the provider's internal working size, it is scaled down before the model sees it. You pay the upload cost for the large file and get the quality of the small one. Resizing it yourself, as the next chapters show, gives you control over the result and a smaller request.
PDF limits
PDF input has its own limits, and they are usually stricter in ways that surprise people.
- File size. Often tens of megabytes at most for the whole file.
- Page count. Providers cap pages per request. A 400-page manual may not fit.
- Per-page cost. Each page is usually processed as both extracted text and a page image, so long PDFs use many tokens.
- Encrypted or password-protected files. These are normally rejected.
- Scanned PDFs. These contain page pictures with no text layer. They work with providers that look at the page visuals, but not with pipelines that depend only on extracted text.
The page limit and the context window both apply. A PDF can be under the page cap and still exceed the token budget once text and page images are counted. The token chapter returns to this.
Documents other than PDF
Native document input is mostly limited to PDF. Word files, spreadsheets and slide decks are normally not accepted as binary input. Convert them to PDF, or extract their text or tables with a library, and send the result. Plain text and Markdown can go in as ordinary text blocks.
Checking inputs in code
Rather than finding out about a limit from an error message, validate locally. The function below reads the real format from the file's first bytes, checks the file size, and reports the dimensions. It uses Pillow, which you can install with pip install pillow.
import os
from PIL import Image
ALLOWED_FORMATS = {"JPEG": "image/jpeg", "PNG": "image/png", "WEBP": "image/webp", "GIF": "image/gif"}
MAX_BYTES = 5 * 1024 * 1024 # example limit, check your provider
MAX_SIDE = 8000 # example limit, check your provider
def check_image(path):
"""Return (media_type, width, height). Raise ValueError if the image breaks a limit."""
size = os.path.getsize(path)
if size > MAX_BYTES:
raise ValueError(f"{path}: {size} bytes exceeds {MAX_BYTES}")
with Image.open(path) as img:
fmt = img.format
width, height = img.size
if fmt not in ALLOWED_FORMATS:
raise ValueError(f"{path}: format {fmt} is not supported")
if max(width, height) > MAX_SIDE:
raise ValueError(f"{path}: {width}x{height} exceeds {MAX_SIDE} pixels on a side")
return ALLOWED_FORMATS[fmt], width, height
print(check_image("chart.png"))Using img.format gives the media type from the content, not from the extension. That avoids the mislabeled-file error described above. This also means you do not need mimetypes.guess_type, which only looks at the file name, when the exact type matters.
For the request-size limit, estimate the encoded size before sending. Base64 turns every 3 bytes into 4 characters, so the encoded length is about 4 * ceil(n / 3).
import math
def base64_size(n_bytes):
"""Length in characters of the base64 text for n_bytes of data."""
return 4 * math.ceil(n_bytes / 3)
print(base64_size(6 * 1024 * 1024))Sum this value over all images and compare the total with the request ceiling.
Edge cases
- Very small images. Some providers reject images below a minimum size, such as a few pixels on a side. Even when accepted, tiny images carry little information.
- Transparency. PNG files with an alpha channel (a transparency layer) can appear on a black or white background depending on how the provider flattens them. Convert to RGB on a known background if the result matters.
- Color mode. CMYK and some 16-bit files can fail or look wrong. Converting to RGB avoids this.
- EXIF rotation. A phone photo may store pixels sideways and a rotation flag. If the flag is stripped, the model sees a rotated image. Apply the rotation, for example with
ImageOps.exif_transpose, before saving. - Corrupt files. A truncated download passes a file-name check. Opening it with Pillow catches many of these.
Summary of decisions
| Situation | Action |
|---|---|
| Format is TIFF, HEIC, BMP or SVG | Convert to PNG or JPEG |
| Screenshot or text-heavy image | Keep as PNG, downscale only if over a limit |
| Large photo | Downscale and save as JPEG |
| File over the byte limit | Lower quality or dimensions |
| Many images | Check the image count and total request size |
| Office document | Convert to PDF or extract text |
| Long PDF | Split into page ranges |
Exercise
A 7.5 MB PNG passes a 10 MB per-image limit, but the API returns a "request too large" error when you send it as base64 along with a 2 MB image. Why, and what are two ways to fix it?
Show answer
Base64 adds about 33% to the size. The 7.5 MB image becomes about 10 MB and the 2 MB image about 2.7 MB, so the request body is around 12.7 MB, which can exceed the request ceiling even though each file is under its own limit. Fixes: downscale or recompress the large image (for example to JPEG), or send the images in separate requests. Supplying the image by URL or an uploaded file also avoids putting the bytes in the request body.
Exercise
A user uploads a file named scan.jpg. Your code declares its media type as image/jpeg based on the extension, and the API rejects it. What is the likely cause, and how do you prevent it?
Show answer
The file probably contains PNG or another format, so the declared media type does not match the bytes. Open the file with an image library such as Pillow, read img.format, and map that to the media type instead of using the extension.