Sub topic 4
Choosing how to supply the data: base64, URL or file
This chapter covers the three ways to hand an image or document to a multimodal model, and how to pick one. It assumes you can read files as bytes in Python, have called a chat API through an SDK, and understand JSON request bodies and what a token is. The tutorial's other chapters cover the content-block structure and the per-format size limits, so this one stays on the delivery method.
The three source types
Most providers let a content block point to its data in one of three ways.
| Source | What you send | Who fetches the bytes | Typical use |
|---|---|---|---|
| Base64 | The file itself, encoded as text inside the JSON body | Nobody. The bytes travel with the request | Local files, private data, one-off calls |
| URL | A link to the file | The provider's servers, when they process the request | Public images already hosted somewhere |
| Uploaded file | A file ID returned by a separate upload call | Nobody at request time. The provider already holds the file | The same file used in many requests |
The field names differ between providers. The idea does not. Check your provider's documentation for which source types each content block supports, because support varies by block type and by model. A provider may accept URLs for images but only base64 or file IDs for PDFs.
Base64: the default for local data
Base64 is an encoding that turns arbitrary bytes into text made of 64 safe characters. JSON cannot hold raw binary, so the bytes must be encoded before they go into the request body.
The helper below reads a file, guesses its media type from the extension, and returns the encoded text.
import base64
import mimetypes
def load_as_base64(path):
"""Return (media_type, base64_text) for a local file."""
media_type, _ = mimetypes.guess_type(path)
if media_type is None:
raise ValueError(f"Cannot determine media type for {path}")
with open(path, "rb") as f:
data = base64.standard_b64encode(f.read()).decode("utf-8")
return media_type, data
media_type, data = load_as_base64("chart.png")
print(media_type, len(data))Three points matter in practice.
- Size grows by about one third. Base64 uses four characters for every three bytes. A 3 MB image becomes a payload of about 4 MB. Provider request-size limits apply to the encoded body, so a file that passes a "file size" limit can still fail as a request.
- The media type must match the content.
mimetypes.guess_typetrusts the file extension. A PNG renamed to.jpgproduces a mismatch, and many APIs reject it with a 400 error. If your files come from users, detect the type from the first bytes of the file instead of from its name. - Use standard base64, not URL-safe base64. Standard base64 uses
+and/. URL-safe base64 uses-and_. APIs expect the standard alphabet, and the wrong one yields a decoding error.
Base64 also does not change what the model sees. The provider decodes the bytes and processes the image exactly as if it had fetched it.
URL: the provider downloads it for you
With a URL source, your request stays small. You send a link, and the provider fetches the file during processing.
Anthropic's Messages API, for example, accepts an image block whose source has type url:
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
message = client.messages.create(
model="MODEL_NAME", # replace with a vision-capable model from the provider's docs
max_tokens=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "url",
"url": "https://example.com/chart.png",
},
},
{"type": "text", "text": "Describe the trend shown in this chart."},
],
}
],
)
print(message.content[0].text)The OpenAI Responses API takes the link directly in the image_url field of an input_image block. The same field also accepts a data URL (data:image/png;base64,...), which is how the base64 variant works there.
URLs have several failure modes that base64 does not.
- Reachability. The provider's servers must be able to open the link. Addresses behind a firewall, on
localhost, or on a corporate network will fail. A link that works in your browser may not work for the provider. - Authentication. A page that needs a login, a cookie or a custom header cannot be fetched. Signed URLs (for example, pre-signed cloud storage links) work if the signature is valid when the provider fetches the file. Set the expiry long enough to cover queueing and retries.
- Content that changes. The file is read at request time. If the object behind the URL is replaced, a retry may see different bytes than the first attempt. This makes results harder to reproduce.
- Hotlink and bot protection. Some hosts block automated clients or return an HTML page instead of an image. The request then fails or, worse, the model receives the wrong content.
- Redirects and content types. A URL that redirects, or that serves a type the provider does not accept, can produce an error even when the link looks fine.
A URL is a good fit when the files already live on public or signed storage and you do not want to download and re-encode them in your own service.
Uploaded files: send once, reference many times
A file upload API accepts the file in a separate request and returns an identifier. Later requests refer to that ID instead of carrying the data. This pays off when the same file appears in many requests, such as a long PDF you ask many questions about.
The details differ by provider: the upload endpoint, how long files are kept, whether they count against a storage quota, and which content blocks accept an ID. Some providers offer this feature in beta or only for certain file types. Read the current documentation before you build on it, and treat file IDs as provider-specific. An ID from one provider means nothing to another.
Keep these trade-offs in mind.
- Lifecycle. Uploaded files are stored on the provider's side. You are responsible for deleting them when you no longer need them, and they may expire on their own.
- Extra round trip. The first use costs two calls, an upload and a request. The saving appears only when the ID is reused.
- Tokens are still charged. An uploaded file avoids resending bytes. It does not make the model read the content for free. Each request that references the file still pays the input tokens for it, unless the provider offers a separate caching feature that you enable.
Comparing the options
| Concern | Base64 | URL | Uploaded file |
|---|---|---|---|
| Request body size | Largest, about 33% over file size | Smallest | Smallest |
| Works for local or private files | Yes | Only with signed or public links | Yes |
| Extra infrastructure | None | Hosted storage | Upload and cleanup logic |
| Reproducible on retry | Yes | Only if the object is immutable | Yes |
| Network dependency on your side | Upload bandwidth per request | None for the file | Upload bandwidth once |
| Data leaves your control | At request time | At fetch time, plus any hosting you set up | Stored at the provider until deleted |
The privacy row connects to a later chapter. A public URL exposes the file to anyone who has the link, not just the provider. Base64 limits exposure to the request itself.
A small helper that picks the source
If your pipeline accepts both local paths and web links, put the choice in one function. This one returns an Anthropic-style image source and uses only the standard library.
import base64
import mimetypes
def image_source(ref):
"""Build an image source dict from a local path or an https URL."""
if ref.startswith("https://"):
return {"type": "url", "url": ref}
media_type, _ = mimetypes.guess_type(ref)
if media_type is None or not media_type.startswith("image/"):
raise ValueError(f"Not a recognizable image: {ref}")
with open(ref, "rb") as f:
data = base64.standard_b64encode(f.read()).decode("utf-8")
return {"type": "base64", "media_type": media_type, "data": data}
print(image_source("https://example.com/chart.png"))The function rejects plain http:// links on purpose. Sending a link over an unencrypted connection leaks the address and, for signed URLs, the credential embedded in it.
Common mistakes
- Sending base64 text with a
data:image/png;base64,prefix to an API that expects the raw encoded string. Anthropic'sdatafield takes the raw string. OpenAI'simage_urlfield takes the full data URL. - Embedding a long-lived signed URL in logs. Anyone who reads the log can open the file.
- Re-encoding the same large image on every call. Cache the encoded string, or switch to an uploaded file.
- Assuming a URL source saves tokens. The model reads the same pixels, so the token count is identical across all three source types.
Exercise
Your service receives a 6 MB scanned form from a user and sends it to a model once. A teammate suggests uploading it to a public cloud bucket and passing the URL, to keep the request small. Which source would you use, and why?
Show answer
Use base64 (or an uploaded file if the provider supports it for this file type). The file is used once, so uploading to storage adds infrastructure and a second step without any reuse benefit. A public bucket also exposes a user's form to anyone with the link. Base64 keeps the data inside the request. Check that the encoded size, about 8 MB for a 6 MB file, stays below the provider's request-size limit.
Exercise
A request with a URL image source fails intermittently, and the same link opens fine in your browser. Name three possible causes.
Show answer
Any three of these: the provider's servers cannot reach the host (private network or firewall); the link needs a login, cookie or header; a signed URL expired before the provider fetched it; the host blocks automated clients or returns an HTML page; a redirect or unsupported content type; the object behind the URL changed between attempts.