Sub topic 8
Sending Several Images and Placing the Prompt
This chapter assumes you can already send a single image in a request, as covered in "Sending your first image". You should know what a content block is and have a helper that returns a media type and base64 text for a local file. Here you extend that to several images and decide where the text instructions go.
What changes with more than one image
A user message holds a list of content blocks. Sending several images means adding several image blocks to that list. The model reads the blocks in order, so order and labeling now matter. With one image, "this image" is unambiguous. With four, it is not.
Typical uses:
- Comparing two versions of a design, a before and after photo, or two charts.
- Reading a multi-page document that you have rendered as page images.
- Giving a few example images with known answers, then a new image to classify.
- Processing a set of receipts or screenshots that belong to one task.
Build the content list
The helper below turns a list of file paths into content blocks. It adds a short text label before each image so the prompt can refer to each one by name. It reuses load_as_base64 from the earlier chapter.
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
def image_blocks(paths):
"""Build labeled image blocks in the Anthropic Messages format."""
blocks = []
for number, path in enumerate(paths, start=1):
media_type, data = load_as_base64(path)
blocks.append({"type": "text", "text": f"Image {number} ({path}):"})
blocks.append(
{
"type": "image",
"source": {
"type": "base64",
"media_type": media_type,
"data": data,
},
}
)
return blocksEach image gets a label such as Image 1 (before.png):. The model has no other way to know which file is which, because it never sees file names. The label gives your question something to point at.
Place the prompt
Where you put the question relative to the images changes results. Provider guidance generally recommends putting images first and the text question after them, especially when there are several images. Check your provider's current documentation, because advice can change between model versions.
A request with the question placed after the images:
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
content = image_blocks(["before.png", "after.png"])
content.append(
{
"type": "text",
"text": (
"Compare Image 1 and Image 2. "
"List every visible difference as a bullet list. "
"If you are unsure about a difference, say so."
),
}
)
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": content}],
)
print(message.content[0].text)The same layout works in other APIs with different block names. In the OpenAI Responses API, the blocks are input_text and input_image, and the image is a data URL. The principle is the same: label, image, label, image, question.
Why placement matters
Models process the message from start to finish. When the question comes first, the model reads the images without a clear goal. When the question comes last, it has already seen all the evidence and can answer with everything in view. This effect is usually modest for one image and more visible as the count grows. It is also stronger for long prompts, where instructions at the end are closer to the point where the model starts writing.
You do not have to put the question last every time. A useful pattern is to state the task briefly at the start, then repeat the exact question at the end. Test it on your own data instead of assuming.
Labeling styles
There are three common ways to tell the model which image is which.
| Style | Example | Best for |
|---|---|---|
| Numbered labels | `Image 1:`, `Image 2:` | Comparisons and short lists |
| Descriptive labels | `Before the repair:`, `After the repair:` | Tasks where the role of each image matters |
| XML-style tags | `<page number="3">` around the content | Long sets, where you want to refer to items precisely |
Descriptive labels often work better than numbers, because they carry meaning. Keep the same label in your question that you used above the image. If you write "Image 2" in the label, do not write "the second photo" in the question.
Few-shot examples with images
You can show the model solved examples before the real input. Each example is an image followed by its correct answer, then the final image has no answer.
examples = [
("ok_part.jpg", "PASS"),
("cracked_part.jpg", "FAIL: visible crack near the left edge"),
]
content = []
for path, answer in examples:
content.extend(image_blocks([path]))
content.append({"type": "text", "text": f"Result: {answer}"})
content.extend(image_blocks(["new_part.jpg"]))
content.append(
{
"type": "text",
"text": "Inspect the last image the same way. Reply with the result line only.",
}
)Make the examples cover the cases you care about, and keep the answer format identical across them. The model tends to copy the format it sees.
Limits to plan for
More images mean more of everything: tokens, latency, and request size.
- Image count. Providers cap the number of images per request. The cap differs by provider and model, and some set a lower cap for the whole conversation than for a single call. Look up the current number.
- Request size. Base64 text is about one third larger than the raw file. Many images can reach the maximum request size before they reach the image count cap.
- Token cost. Every image is billed. Ten images cost roughly ten times what one does, and the cost is paid again on every turn if you resend the history.
- Attention. Quality can drop as the number of images grows. Small details in the fifth image are more likely to be missed than in a single-image request.
Resize each image first, as covered in the preprocessing chapter, so you stay under the limits and keep costs down.
MAX_IMAGES = 20 # set this from your provider's documented limit
def check_batch(paths):
if len(paths) > MAX_IMAGES:
raise ValueError(
f"{len(paths)} images exceeds the limit of {MAX_IMAGES}. "
"Split the work into batches."
)Batching strategies
When you have more images than one request should carry, choose a strategy:
- Split and merge. Send fixed-size groups, such as five images each, and combine the answers in code. This works when each image can be analyzed alone.
- Per-image calls, then a summary call. Ask the same question of each image, collect short text answers, and send only the text to a final call. This is cheaper than resending all the images.
- Select first. Use a cheap filter, such as file metadata or a small classifier, to drop images that do not matter.
Pick split and merge only if images do not depend on each other. For comparisons, the images must appear in the same request.
Common mistakes
- Sending images with no labels, then asking about "the second one" and getting a guess.
- Mixing label styles so the question and the labels disagree.
- Putting a long question before many images and finding that details are ignored.
- Forgetting that each retry resends every image and pays for it again.
- Assuming the model knows file names. It does not unless you write them in text.
Summary of the working model
Each image is a block, the model reads blocks in order, and text is the only way to tell it what each image means. Label every image, keep the labels consistent with your question, and put the question after the images unless testing shows a better layout for your data. Watch the count, size, and cost, and batch when a single request is too large.
Exercise
You need a model to decide which of three product photos shows a damaged box. Describe the content block order you would use and why, and name one change that reduces cost without losing the comparison.
Show answer
Use this order: text label "Photo 1", image block, text label "Photo 2", image block, text label "Photo 3", image block, then a final text question such as "Which photo shows a damaged box? Answer with the photo number and a one-sentence reason." The labels give the question something to refer to, and placing the question last means the model has seen all three images first. To reduce cost, downscale each image to the provider's recommended maximum side length before encoding, since the token cost grows with image size and the comparison rarely needs full resolution.
Exercise
A request with 30 base64 images fails with a size error, although the provider's image count limit is 100. What is the likely cause, and what are two ways to fix it?
Show answer
The total request size, not the image count, is probably over the limit, because base64 adds about one third to the file size. Fixes: downscale and recompress the images before encoding, or split the images into smaller batches (or analyze each image separately and send a summary call with only the text results). Uploading the files through a file upload API, if the provider offers one, is another option because the request then carries a file reference instead of the data.