Sub topic 5
Sending your first image
This chapter builds a working image request, first with base64 data and then with a URL. It covers both the Anthropic Messages API and the OpenAI Responses API. It also covers the errors you are most likely to hit.
Prerequisites
This chapter assumes you can do the following:
- Write basic Python, including reading files as bytes.
- Call a chat LLM API through an SDK and read its response.
- Read a JSON request body.
- Explain what a token and a context window are.
It also builds on two earlier ideas. A message holds a list of typed content blocks. Image data reaches the API as base64 text, as a URL, or as an uploaded file.
What you are building
An image request is an ordinary chat request with one change. The content field of the user message is a list of blocks instead of a single string. One block carries the image and another carries your question. The model reads both in the same turn.
Step 1: Load the file as base64
Base64 turns binary bytes into plain text that fits inside a JSON string. The helper below also detects the media type from the file extension. APIs need the media type because they do not trust the extension to tell them how to decode the bytes.
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 details matter here:
- The file is opened in
"rb"mode. Text mode corrupts binary data. .decode("utf-8")converts the base64 bytes into astr, which JSON can carry.- The base64 string is about one third larger than the file. A 3 MB image becomes roughly 4 MB in the request body.
Step 2: Send it with the Anthropic Messages API
Put the image block and the text block in the same content list.
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
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=1024,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": media_type,
"data": data,
},
},
{"type": "text", "text": "Describe the trend shown in this chart."},
],
}
],
)
print(message.content[0].text)The data field holds only the base64 text. Do not prefix it with data:image/png;base64,. That prefix is a data URL, and this API expects the raw base64 string.
The response content is also a list of blocks. For a plain text answer, message.content[0].text works. In code that must be robust, loop over the blocks and keep those whose type is "text".
Step 3: The same request with the OpenAI Responses API
OpenAI uses different block names. The image is passed as a data URL, so here you do include the prefix.
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
media_type, data = load_as_base64("chart.png")
response = client.responses.create(
model="MODEL_NAME", # replace with a vision-capable model from the provider's docs
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": "Describe the trend shown in this chart."},
{
"type": "input_image",
"image_url": f"data:{media_type};base64,{data}",
},
],
}
],
)
print(response.output_text)The two APIs differ in a few ways:
| Aspect | Anthropic Messages | OpenAI Responses |
|---|---|---|
| Request field for messages | `messages` | `input` |
| Text block type | `text` | `input_text` |
| Image block type | `image` | `input_image` |
| Base64 form | Separate `media_type` and raw `data` | One data URL string |
| Reading the answer | `message.content[0].text` | `response.output_text` |
The ideas are the same in both. Only the field names change. If you support several providers, keep one internal representation of "text plus images" and write a small adapter for each API.
Step 4: Send an image by URL instead
If the image is already on a public web server, you can skip the encoding. The provider fetches the image itself, and your request body stays small.
On Anthropic, change the source:
image_block = {
"type": "image",
"source": {
"type": "url",
"url": "https://example.com/images/chart.png",
},
}On OpenAI, pass the URL directly:
image_block = {
"type": "input_image",
"image_url": "https://example.com/images/chart.png",
}URL input has trade-offs:
- The provider's servers must be able to reach the URL. Private networks, localhost, and links behind a login fail.
- The image can change or disappear between your request and the fetch. A request you retry later may behave differently.
- Short-lived signed URLs can expire before the provider fetches them.
- You send your data to a third-party host. Think about this before putting a sensitive image behind a public link.
For local files, tests that must be repeatable, and private data, base64 is usually the safer default.
Prompt wording and block order
Models read the blocks in order. A common and effective pattern is to put the image first and the question after it, as in the examples above. Be specific about what you want:
- Weak: "What is this?"
- Better: "List the three largest bars in this chart and their approximate values."
When you need a precise answer, say what format you want. For example, ask for one value per line, or ask the model to say "unreadable" when it cannot read a value. A model that is allowed to say it cannot read a value will usually guess less.
Common errors
Most first-image failures come from a small set of mistakes.
- Media type does not match the bytes. A PNG file renamed to
.jpggetsimage/jpegfrommimetypes, and the API may reject it with a 400 error about invalid image data. Check the real format with Pillow (Image.open(path).format) if your files come from users. - A data URL prefix inside Anthropic's
datafield. Send the raw base64 only. - Wrong
contentshape. Sending a list of blocks to a field that expects a string, or the reverse, raises a validation error. Check the field names for your provider. - Model without vision support. Some models accept the request shape but reject image blocks, or ignore them. Confirm in the provider's model list.
- Image too large. Providers cap file size, image dimensions, and total request size. A raw camera photo can exceed them. The next chapter shows how to resize before sending.
- Unsupported format. Stick to common formats such as PNG, JPEG, WebP, and GIF, and check your provider for the exact list. Formats such as HEIC or TIFF often need conversion first.
- URL not reachable. The error usually mentions that the image could not be fetched. Open the URL in a private browser window to test it.
A small reusable function
This function combines the pieces for Anthropic. It uses load_as_base64 from Step 1.
import anthropic
def ask_about_image(path, question, model="MODEL_NAME", max_tokens=1024):
client = anthropic.Anthropic()
media_type, data = load_as_base64(path)
message = client.messages.create(
model=model, # replace with a vision-capable model from the provider's docs
max_tokens=max_tokens,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": media_type,
"data": data,
},
},
{"type": "text", "text": question},
],
}
],
)
return "".join(b.text for b in message.content if b.type == "text")
print(ask_about_image("chart.png", "What is the highest value shown?"))Joining only the text blocks keeps the function correct if the response contains other block types.
Check your understanding
Exercise
Your Anthropic image request fails with a 400 error saying the image data is invalid. The file is a real PNG, and your code builds the data field as f"data:{media_type};base64,{encoded}". What is wrong, and how do you fix it?
Show answer
The Anthropic base64 source expects only the raw base64 text in the data field, with the media type given separately in mediatype. The data URL prefix makes the string invalid base64. Pass encoded alone. The prefix form belongs to OpenAI's imageurl field, which takes a data URL.
Exercise
You need to send a screenshot of a customer's private account page to the model, and your tests must give the same result every day. Do you choose base64 or a URL, and why?
Show answer
Base64. The bytes travel inside the request, so no public link is needed and the private page is not hosted anywhere. The input also cannot change or expire between runs, which keeps tests repeatable. A URL would require a publicly reachable host and could break when the link expires or the file changes.