Sub topic 12
Uploading files once and reusing them
This chapter assumes you can already send an image or PDF inline as base64 (covered in the earlier chapters on content blocks and sending your first image). It also assumes you know what a token is. Here you will upload a file once, get back an identifier, and refer to that identifier in later requests.
Why inline data gets wasteful
With base64, every request carries the whole file in its JSON body. Base64 text is about a third larger than the original bytes. If you ask ten questions about the same 8 MB PDF, you upload roughly 107 MB in total.
A file upload API changes the transfer pattern:
- You send the file once to a files endpoint.
- The provider stores it and returns a file ID, a short string such as
file_abc123. - Each later request contains the file ID instead of the bytes.
The upload happens once. The request bodies become small, and retries are cheap.
What a file ID does not give you
A file ID saves bandwidth. It does not remove the model's work.
- Token cost. The provider still converts the file into tokens on every request that references it. Ten questions about a 50-page PDF still cost ten times the input tokens for that PDF. Prompt caching, if your provider offers it, is a separate feature that reduces repeated input cost.
- Model limits. The file still has to fit in the context window together with your prompt. Page-count and size limits for PDFs and images still apply.
- Quality. A file you upload behaves like the same file sent inline. Small text is still misread at the same rate.
Differences between providers
File APIs differ in names, limits, and lifetime. The table shows the usual shape. Confirm every value against your provider's current documentation.
| Aspect | What to check |
|---|---|
| Upload endpoint | Whether it is stable or in beta. Some providers require a beta header or SDK namespace. |
| Allowed types | PDFs and images are common. Some endpoints accept only certain types for certain purposes. |
| Size limit | A per-file maximum, and sometimes a total storage quota. |
| Lifetime | Some files persist until you delete them. Others expire after a set time. |
| Scope | Files may be visible to the whole project, workspace, or organization, not only your script. |
| Download | Some providers let you download only files they generated, not ones you uploaded. |
| Billing | Storage may be free, limited, or charged. |
Uploading and referencing a file
Both examples use the same placeholder model names as earlier chapters. Replace them with a model that supports your input type.
Anthropic
At the time of writing, the Anthropic Files API is a beta feature. The SDK exposes it under client.beta, and requests that reference files must opt in with a beta flag.
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
BETA = ["files-api-2025-04-14"] # check the docs for the current flag name
with open("report.pdf", "rb") as f:
uploaded = client.beta.files.upload(
file=("report.pdf", f, "application/pdf")
)
print("file id:", uploaded.id)
message = client.beta.messages.create(
model="MODEL_NAME", # replace with a model that supports PDF input
max_tokens=1024,
betas=BETA,
messages=[
{
"role": "user",
"content": [
{
"type": "document",
"source": {"type": "file", "file_id": uploaded.id},
},
{"type": "text", "text": "Summarize the key findings in this report."},
],
}
],
)
print(message.content[0].text)The content block keeps its type (document here, image for pictures). Only the source changes, from {"type": "base64", ...} to {"type": "file", "file_id": ...}.
OpenAI
With the Responses API, you upload with a purpose and then use an input_file block for documents. For images, use an input_image block with a file_id field in place of image_url.
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
with open("report.pdf", "rb") as f:
uploaded = client.files.create(file=f, purpose="user_data")
print("file id:", uploaded.id)
response = client.responses.create(
model="MODEL_NAME", # replace with a model that supports file input
input=[
{
"role": "user",
"content": [
{"type": "input_file", "file_id": uploaded.id},
{"type": "input_text", "text": "Summarize the key findings in this report."},
],
}
],
)
print(response.output_text)Avoiding duplicate uploads
A file ID helps only if you keep it. A script that uploads on every run defeats the purpose, and it also fills your storage with copies. A common fix is to key a small cache on the content hash of the file, not its name. Two files with the same name but different contents then get different IDs.
import hashlib
import json
from pathlib import Path
CACHE_PATH = Path("file_ids.json")
def sha256_of(path):
"""Hash a file in chunks so large files do not fill memory."""
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def _load():
return json.loads(CACHE_PATH.read_text()) if CACHE_PATH.exists() else {}
def get_file_id(path, upload):
"""Return a cached file ID, or call upload(path) and cache its result.
`upload` is any function that takes a path and returns a file ID string.
"""
cache = _load()
key = sha256_of(path)
if key not in cache:
cache[key] = upload(path)
CACHE_PATH.write_text(json.dumps(cache))
return cache[key]
def forget(path):
"""Drop a cached ID, for example after the provider reports it missing."""
cache = _load()
cache.pop(sha256_of(path), None)
CACHE_PATH.write_text(json.dumps(cache))Pass the provider-specific upload as a function:
def upload_to_openai(path):
from openai import OpenAI
client = OpenAI()
with open(path, "rb") as f:
return client.files.create(file=f, purpose="user_data").id
file_id = get_file_id("report.pdf", upload_to_openai)A local JSON file is fine for a script. A shared service should keep the mapping in a database and include the provider, project, and API key owner in the key, because file IDs are not portable between them.
Handling stale IDs
A cached ID can become invalid. Common causes are:
- The file expired under the provider's retention rule.
- Someone deleted it, or you deleted it in an earlier cleanup.
- You are using a different project or API key than the one that uploaded it.
The usual symptom is a 404 (not found) or a 400-class error that names the file ID. Treat a cache entry as a hint, not a guarantee. Catch the error, drop the entry, upload again, and retry once:
import anthropic
def ask_about_pdf(client, path, question):
for attempt in range(2):
file_id = get_file_id(path, lambda p: upload_pdf_anthropic(client, p))
try:
msg = client.beta.messages.create(
model="MODEL_NAME",
max_tokens=1024,
betas=["files-api-2025-04-14"],
messages=[{
"role": "user",
"content": [
{"type": "document",
"source": {"type": "file", "file_id": file_id}},
{"type": "text", "text": question},
],
}],
)
return msg.content[0].text
except anthropic.NotFoundError:
forget(path) # stale ID: remove it and upload again
if attempt == 1:
raise
def upload_pdf_anthropic(client, path):
with open(path, "rb") as f:
return client.beta.files.upload(file=(Path(path).name, f, "application/pdf")).idRetry only once. If the second attempt also fails with 404, the cause is not a stale ID and repeating the call will not fix it.
When to use files and when to stay inline
Use uploaded files when:
- You ask several questions about the same file.
- The file is large and requests are retried often.
- Many services or workers need the same file, and you can share the ID safely.
Stay with inline base64 or a URL when:
- Each file is used once. The extra upload call and the cleanup add work without saving bytes.
- Your provider's file feature is in beta and you need stability.
- Policy requires that the provider keep no copy of the document beyond the request. Check the provider's retention terms first.
Cleaning up
Uploaded files are stored data, so they are your responsibility.
- Delete files when the job ends, using the provider's delete call (for example
client.beta.files.delete(file_id)orclient.files.delete(file_id)). - Remove the matching entry from your cache at the same time.
- Do not put sensitive documents in a project that many people can list. Anyone with access to the project may be able to reference the ID.
- Log file IDs if you need to, but never log the file contents.
Exercise
Exercise
You ask ten different questions about the same 40-page PDF. You upload it once and send the file ID with each question. Which two costs go down, and which cost stays about the same compared with sending base64 each time?
Show answer
Request body size and upload time go down, because the bytes are sent once instead of ten times. The input token cost for processing the document stays about the same, because the model still reads the file's content on every request that references it. Prompt caching, if available, is what reduces repeated token cost.
Exercise
Your script cached a file ID last week. Today the request fails with a 404 that names that ID. Describe what the code should do, and why it should limit the retries.
Show answer
Remove the cached entry for that file, upload the file again, store the new ID, and retry the request once. The retry should be limited because a second 404 suggests a different cause, such as the wrong project or API key, and repeating the same call will not fix that.