Sub topic 14
Common Failure Modes and API Errors
This chapter assumes you can already send an image or PDF to a multimodal API, as shown in earlier chapters. It covers what goes wrong, how to tell request errors from model errors, and how to handle each.
Two kinds of failure
Visual pipelines fail in two different ways:
- Request errors. The API rejects the call and returns an HTTP error. These are deterministic and easy to detect.
- Quality errors. The API returns HTTP 200 and fluent text that is wrong. Nothing in the response signals the problem.
Quality errors are the more dangerous kind, because your code will treat them as success.
Request errors
Most rejected requests fall into a few groups. Exact messages and limits vary by provider, so confirm them in your provider's documentation.
| Symptom | Likely cause | Fix |
|---|---|---|
| 400, invalid media type | Wrong or missing `media_type`, or the bytes do not match it | Detect the type from the file, and check the format is supported |
| 400, invalid base64 | Newlines, a `data:` prefix inside the data field, or truncated data | Use `base64.standard_b64encode` and send only the encoded text |
| 400 or 413, payload too large | Image, PDF, or whole request exceeds a size limit | Downscale images, or split the PDF into parts |
| 400, too many images or pages | Per-request count limit exceeded | Batch the request into several calls |
| 400, model does not support input | The model has no vision or PDF support | Pick a capable model |
| 400, URL could not be fetched | URL is private, expired, or blocked | Fall back to base64 |
| 429 | Rate limit, often hit faster because images use many tokens | Retry with backoff |
| 5xx or timeout | Provider-side problem, or a slow large request | Retry, and shrink the input |
Only retry errors that can succeed on a second try. A 400 will fail the same way every time.
import random
import time
import anthropic
client = anthropic.Anthropic()
def send_with_retry(**kwargs):
"""Retry transient errors only. Let 4xx request errors surface."""
for attempt in range(4):
try:
return client.messages.create(**kwargs)
except (anthropic.RateLimitError, anthropic.APIConnectionError):
pass
except anthropic.APIStatusError as e:
if e.status_code < 500:
raise # a bad request will not improve on retry
time.sleep(2**attempt + random.random())
raise RuntimeError("Request failed after retries")Quality failures
These produce valid responses that are wrong.
- Misread small text. The model downsamples large images internally, so fine print, dense tables, and small axis labels can be misread. Crop to the region of interest, or render at a higher resolution.
- Confident guessing. The model may fill in a value it cannot read instead of saying so. Digits such as 3, 5, 8 and 0 are common victims.
- Counting and spatial errors. Counting objects or judging exact positions is unreliable.
- Rotated or low-contrast input. Sideways scans and faint photocopies lower accuracy. Correct orientation and contrast before sending.
- Lost context in long documents. Details from the middle of a many-page PDF may be missed. Ask about specific pages, or process the pages in chunks.
- Prompt injection. Text inside an image or PDF can contain instructions. Treat it as data, and do not let it trigger actions.
Reducing quality errors
- Ask the model to answer "unreadable" instead of guessing.
- Request structured output and validate it, for example by checking that line items sum to the stated total.
- Look at what you actually sent. Open the preprocessed image and confirm it is legible to you.
- Keep the image and the response together in your logs, so you can reproduce a failure.
Exercise
Your pipeline gets a 400 error on a 40 MB scanned image, and later gets a 200 response that reports an invoice total of 1,386 when the page shows 1,886. Which of these should be retried, and what should you change for each?
Show answer
Neither should be retried unchanged. The 400 is a deterministic request error, so retrying fails the same way. Downscale or recompress the image below the size limit. The 200 response is a quality error that no status code flags. Crop or render the totals region at higher resolution, ask for a structured result with an "unreadable" option, and validate the total against the line items.