Sub topic 2
Mixing text and images in one message
This chapter assumes you can call an LLM chat API through an SDK or over HTTP, read and write JSON request bodies, and read files as bytes in Python. It also assumes you know what tokens and context windows are. You will learn how a single message carries text and images together, how block order affects results, and which mistakes cause errors.
From a string to a list of blocks
In a text-only chat, a message looks like this: a role and a string.
{"role": "user", "content": "What is the capital of France?"}A multimodal message changes one thing. The content field becomes a list of content blocks. A content block is a small JSON object with a type field that says what kind of data it holds. Common types are text, image and document.
{
"role": "user",
"content": [
{"type": "text", "text": "What is the capital of France?"}
],
}Most SDKs accept both forms. A plain string is shorthand for a list with one text block. Once you add an image, you must use the list form.
The model sees the blocks in the order you give them, as one sequence. Internally, the provider converts each image into a series of image tokens. These sit in the same context window as your text tokens. The model does not receive a separate "image channel". It reads one mixed sequence.
The shape of an image block
Providers use different field names, but each image block answers the same questions. What kind of data is it? How is it supplied? What is its media type?
Anthropic Messages API image block with base64 data:
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": "<base64 text>",
},
}OpenAI Responses API image block, which uses a data URL:
{
"type": "input_image",
"image_url": "data:image/png;base64,<base64 text>",
}Note the naming differences. Anthropic uses image, and OpenAI uses input_image. OpenAI also names the text block input_text in the Responses API, while Anthropic uses text. Copying a block from one provider's docs into another provider's request is a common source of validation errors. Always check the block names against the API you are calling.
The media type tells the provider how to decode the bytes. It must match the real file format. If you label a JPEG as image/png, many APIs reject the request or fail to decode the image.
A helper that builds blocks
Writing block dictionaries by hand gets repetitive. A small helper keeps your code consistent. This one uses the standard library only.
import base64
import mimetypes
def image_block(path):
"""Build an Anthropic-style image block from a local file."""
media_type, _ = mimetypes.guess_type(path)
if media_type is None or not media_type.startswith("image/"):
raise ValueError(f"{path} does not look like an image")
with open(path, "rb") as f:
data = base64.standard_b64encode(f.read()).decode("utf-8")
return {
"type": "image",
"source": {"type": "base64", "media_type": media_type, "data": data},
}
def text_block(text):
return {"type": "text", "text": text}
content = [
image_block("chart.png"),
text_block("Describe the trend shown in this chart."),
]
print([block["type"] for block in content])This script needs a file named chart.png in the working directory. The check on media_type catches a PDF or a typo before you spend an API call on it.
Block order and prompt placement
Order matters. Providers and model vendors commonly advise placing images before the question about them, especially when you send several. Your provider's documentation states its own guidance, so check it. A reasonable default is:
- Image blocks first.
- Text instructions after the images.
When the question comes last, it is the nearest text to the model's answer, and the model has already read the images by the time it sees what you want.
Order also lets you label things. With several images, interleave short text blocks so the model can tell them apart:
content = [
text_block("Image 1: the dashboard before the change."),
image_block("before.png"),
text_block("Image 2: the dashboard after the change."),
image_block("after.png"),
text_block("List every visible difference between Image 1 and Image 2."),
]Without labels, the model has to guess which image you mean by "the first one" or "the new one". Labels cost a few tokens and remove that ambiguity. Later chapters cover multiple images in more detail. For now, remember that blocks are your only way to mark structure, so use them.
Where blocks can go
Block placement is limited by role.
| Role | Can contain images? | Notes |
|---|---|---|
| user | Yes | The normal place for images and documents. |
| assistant | Usually no | The model returns text. You send prior assistant turns back as text. |
| system | Provider specific | Many APIs accept only text here. Put images in a user message instead. |
In a multi-turn conversation, an image sent in an earlier user message stays part of the history. If you resend the full history on each turn, you pay for the image tokens again on every call. This is the most common surprise in multimodal chat apps. Options include dropping old images once they are no longer needed, replacing them with a short text description, or using a provider feature that caches or references uploaded files. Later chapters cover the last option.
Common errors
These problems appear in almost every first multimodal integration.
- Wrong content shape. Sending
"content": "text"plus a separate"image"key at the message level. Images belong inside thecontentlist. - Mismatched media type. The declared type and the actual bytes disagree. Guess the type from the file, and prefer checking the file contents when the input comes from users.
- Data URL prefix in the wrong place. Anthropic's base64 source wants only the raw base64 text in
data. OpenAI'simage_urlwants the fulldata:<type>;base64,<text>string. Mixing these up produces decode errors. - Empty or whitespace-only text blocks. Some APIs reject a text block with an empty string. Skip the block rather than sending it.
- Model without vision. Sending an image to a text-only model returns an error or ignores the image. Confirm vision support in the provider's model list.
- Oversized request. Large images encoded as base64 grow by about one third. A request can exceed the maximum body size even if the file itself seems small. The next chapter covers limits.
Reading the response
The reply format does not change. The model returns text, so you read it as you would for a text-only request. With the Anthropic SDK, the reply is a list of output blocks, and the first is usually text:
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=512,
messages=[
{
"role": "user",
"content": [
image_block("chart.png"),
text_block("In one sentence, what does this chart show?"),
],
}
],
)
print(message.content[0].text)This reuses image_block and text_block from earlier. Replace MODEL_NAME with a real model name before running it.
Checking your understanding
Exercise
A teammate's request sends one user message with content set to a single string, and puts the base64 image in a separate key named "image" on the message object. The API returns a validation error. What is wrong, and how do you fix it?
Show answer
Images must be content blocks inside the message's content list. Change content to a list, add an image block (with its media type and base64 data) and a text block holding the question, and remove the separate "image" key.
Exercise
You send two screenshots and ask "What changed in the second one?" The answers are inconsistent. Name two changes to the content list that would make the request clearer.
Show answer
Put the image blocks before the question, and add a short text block before each image that labels it (for example "Image 1: before", "Image 2: after"). Then phrase the question using those labels.
Exercise
A chat app resends the full conversation on every turn, and the first message contained a large image. Why do costs keep rising, and what can you do?
Show answer
The image tokens are part of the history, so they are billed again on every call. You can drop the image once it is no longer needed, replace it with a short text description, or use a provider feature that lets you reference an uploaded file instead of resending the data.