Sub topic 5
Sending your first image
This chapter builds a working image request. It assumes you can write basic Python, have called an LLM chat API through an SDK, read JSON request bodies, and know what tokens are. It covers the Anthropic Messages API and the OpenAI Responses API.
The working model
A multimodal request is a normal chat message whose content is a list of typed blocks instead of one string. One block carries the image. Another carries your question. The provider decodes the image, converts it to tokens, and the model reads those tokens next to your text.
Your code has three jobs:
- Read the file and detect its media type.
- Encode the bytes as base64 text.
- Wrap the result in the block shape your provider expects.
Step 1: load and encode the file
The helper below guesses the media type from the file extension. It raises an error if it can't tell, because the API needs the correct type.
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))The .decode("utf-8") call matters. Base64 encoding returns bytes, and JSON needs a string.
Step 2: send it with the Anthropic Messages API
The image block and the text block sit 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)This snippet reuses load_as_base64 from step 1, so keep both in one file or import the helper.
The same request with OpenAI
The OpenAI Responses API uses different names. Text is input_text. The image is input_image, and it takes a data URL, which is the media type and base64 text joined into one string.
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)| Item | Anthropic Messages | OpenAI Responses |
|---|---|---|
| Image block type | `image` | `input_image` |
| Text block type | `text` | `input_text` |
| Base64 shape | `source` object with `media_type` and `data` | Data URL string in `image_url` |
| Reply text | `message.content[0].text` | `response.output_text` |
Common errors
- Wrong media type. A file named
.pngthat is really a JPEG, or a type the model doesn't support, usually produces a 400 error. Check the supported formats for your provider. - Missing prefix. With OpenAI, sending raw base64 without
data:...;base64,in front fails. - Request too large. Base64 grows the file by about a third. A large photo can exceed the request size limit.
- Placeholder model.
MODEL_NAMEmust be replaced with a model that accepts images.
Exercise
Your OpenAI request fails with a 400 error. You passed "image_url": data where data is the plain base64 string. What is wrong, and how do you fix it?
Show answer
The image_url field expects a URL or a data URL, not raw base64. Build it as f"data:{media_type};base64,{data}".