Sub topic 14
Common failure modes and API errors
This chapter assumes you can already send an image or PDF to a chat API, as in the earlier chapters. It also assumes you know what an HTTP status code is and how to catch exceptions in Python. It covers two kinds of failure. The first is requests the API rejects, which you see as errors. The second is requests the API accepts and answers wrongly, which you see only if you check.
Two families of failure
Visual inputs fail in two ways, and they need different handling.
- Loud failures return an HTTP error. The request was malformed, too large, rate limited, or the server had a problem. Your code sees an exception.
- Silent failures return a normal response with wrong content. The model misreads a digit, skips a page, or invents a value. Nothing in the response tells you this happened.
Loud failures are easier to deal with. Silent failures cost more, because wrong data can reach a database or a customer before anyone notices.
Loud failures: request errors
Exact status codes and messages differ by provider, so check your provider's error reference. The patterns below are common.
| Symptom | Likely cause | Fix |
|---|---|---|
| 400 with a message about media type or image data | Wrong `media_type`, corrupted base64, or an unsupported format | Detect the type from the file bytes and re-encode to PNG or JPEG |
| 400 or 413 about size | Image, PDF, or whole request body exceeds a limit | Downscale, compress, split the PDF, or upload the file instead of inlining it |
| 400 about too many images or pages | Count limit per request exceeded | Batch into several requests |
| 400 saying a URL could not be fetched | URL is private, expired, behind a login, or blocks the provider's fetcher | Send base64 instead, or use a public or signed URL with a long enough expiry |
| 400 about a PDF | Password protected, corrupted, or over the page limit | Decrypt it, repair it, or split it |
| 401 or 403 | Bad API key, or the key lacks access to the model or feature | Check the key and the account's model access |
| 429 | Rate limit, which often counts tokens as well as requests | Back off and retry, and reduce image tokens |
| 500, 502, 503, 529 | Provider-side problem or overload | Retry with backoff |
A frequent cause of a 400 error is a mismatch between the declared type and the real bytes. A file named scan.png that is actually a JPEG, or a .heic photo from a phone, can pass your extension check and fail at the API. Checking the first bytes of the file catches this.
Validate before you send
A cheap pre-flight check turns a slow network failure into an immediate local one. The limits below are placeholders. Replace them with the numbers in your provider's documentation.
import os
MAX_IMAGE_BYTES = 5 * 1024 * 1024 # placeholder: check your provider
MAX_PDF_BYTES = 30 * 1024 * 1024 # placeholder: check your provider
SIGNATURES = {
"image/png": lambda h: h.startswith(b"\x89PNG\r\n\x1a\n"),
"image/jpeg": lambda h: h.startswith(b"\xff\xd8\xff"),
"image/gif": lambda h: h.startswith(b"GIF8"),
"image/webp": lambda h: h[:4] == b"RIFF" and h[8:12] == b"WEBP",
"application/pdf": lambda h: h.startswith(b"%PDF-"),
}
def sniff_media_type(path):
"""Return the media type implied by the file's first bytes."""
with open(path, "rb") as f:
head = f.read(16)
for media_type, matches in SIGNATURES.items():
if matches(head):
return media_type
raise ValueError(f"{path}: unrecognized or unsupported file format")
def preflight(path):
"""Raise ValueError if the file would likely be rejected."""
media_type = sniff_media_type(path)
size = os.path.getsize(path)
limit = MAX_PDF_BYTES if media_type == "application/pdf" else MAX_IMAGE_BYTES
if size > limit:
raise ValueError(f"{path}: {size} bytes exceeds the {limit} byte limit")
return media_typeBase64 encoding makes data about one third larger. A file under the limit on disk can still push the request body over a total-request limit, so leave headroom.
Retry only what can succeed
Retrying a 400 error wastes time, because the same request will fail the same way. Retry rate limits, server errors, and network failures, and use exponential backoff with random jitter so many clients do not retry in lockstep.
import random
import time
import anthropic
def call_with_retry(make_request, max_attempts=4):
"""Run make_request(), retrying transient errors with backoff."""
for attempt in range(max_attempts):
try:
return make_request()
except (
anthropic.RateLimitError,
anthropic.InternalServerError,
anthropic.APIConnectionError, # includes timeouts
):
if attempt == max_attempts - 1:
raise
time.sleep(min(30, 2 ** attempt) + random.random())
# BadRequestError and other 4xx errors are not caught here.
# They propagate immediately because retrying cannot fix them.Use it by wrapping the call in a function, for example call_with_retry(lambda: client.messages.create(...)). The SDKs also have built-in retry settings. If you use those, do not stack a second retry loop on top without thinking about the multiplied wait time.
On a 429, retrying is only half the answer. If images drive your token usage, a retry loop just waits for the same limit. Downscaling images, as covered in the preprocessing chapter, lowers the load.
Silent failures: wrong answers
A model reads an image by encoding it into tokens that represent patches of the picture. That process loses detail, and the model then produces text that is plausible given what it saw. This leads to the following failure modes.
- Misread small text. Footnotes, dense tables, and fine print in a downscaled image may be unreadable. The model may guess instead of saying so.
- Digit and character confusion.
0andO,1andl,5andS, and similar pairs get swapped, especially in handwriting or low-quality scans. - Table structure errors. Merged cells, rotated headers, and tables that span pages are read with values shifted into the wrong column or row.
- Spatial mistakes. Counting objects, judging exact positions, and reading charts to a precise value are weak areas. A model can describe a chart's trend well and still misreport a specific bar.
- Skipped or merged content. With many pages or images in one request, the model may drop some or blend them. Refer to images by label in your prompt to reduce this.
- Rotated or low-contrast input. Sideways scans, shadows from phone photos, and faint text all reduce accuracy.
- Scanned PDFs treated as text PDFs. A PDF made of page photographs has no text layer. If your pipeline relies on text extraction, it returns an empty string, and the model then works from nothing.
- Hallucinated fields. Asked for an invoice number on a page that has none, a model may produce a realistic-looking one. An extraction prompt that demands every field encourages this.
- Prompt injection through the image. Text inside an image or PDF can contain instructions such as "ignore previous instructions". Treat text read from documents as data, not as commands.
Defences that work
- Raise the effective resolution of the area that matters. Crop to the region of interest, or render a PDF page at a higher DPI, instead of sending a whole page at a low size.
- Allow an explicit "unreadable" answer. Tell the model to return
nullfor any value it cannot read clearly, and never to guess. - Ask for evidence. Request the exact quoted text or page number that supports each value. Values with no quote are suspect.
- Cross-check with a second source. If a PDF has a text layer, compare the vision answer against extracted text for key numbers. A disagreement flags a record for review.
- Validate with ordinary code. Check that line items sum to the total, dates parse, and IDs match their expected pattern. Cheap deterministic checks catch many errors.
- Route low-confidence items to a person. Anything that fails a check goes to a review queue instead of the database.
Here is a small validator for an extracted invoice, showing the kind of check that catches silent errors:
from datetime import date
def check_invoice(record):
"""Return a list of problems found in an extracted invoice dict."""
problems = []
items = record.get("line_items") or []
total = record.get("total")
if total is None:
problems.append("total is missing or unreadable")
elif items:
computed = round(sum(i["quantity"] * i["unit_price"] for i in items), 2)
if abs(computed - total) > 0.01:
problems.append(f"line items sum to {computed}, but total is {total}")
try:
date.fromisoformat(record.get("invoice_date") or "")
except ValueError:
problems.append("invoice_date is missing or not a valid ISO date")
return problems
print(check_invoice({
"invoice_date": "2026-03-14",
"line_items": [{"quantity": 2, "unit_price": 9.5}],
"total": 19.0,
}))This prints an empty list. Change total to 91.0 and it reports the mismatch, which is the typical result of a misread digit.
Diagnosing a bad result
When output is wrong, change one thing at a time.
- Send the same file through a different path, such as page images instead of native PDF, and compare.
- Look at what you actually sent. Save the downscaled image to disk and open it. If you cannot read the text, the model probably could not either.
- Shorten the task. Ask for one field instead of twenty.
- Log request IDs, file names, and the preprocessing settings used. Without them, a bad extraction cannot be reproduced.
Exercise
Your pipeline gets a 400 error saying the image data is invalid, for a file named receipt.png that opens fine in an image viewer. Give two likely causes and one retry policy decision.
Show answer
Likely causes: the file is really a different format (for example a JPEG or HEIC renamed to .png), so the declared media type does not match the bytes, or the base64 was corrupted, for example by decoding to a string wrongly or adding line breaks or a data-URL prefix where raw base64 is expected. Detect the real type from the file's first bytes and re-encode to PNG or JPEG. Do not retry, because a 400 error is a client error and the same request will fail again. Retry only 429, 5xx, and network failures.
Exercise
A model returns an invoice total of 1,280.00, but the line items add up to 1,230.00. Name two possible explanations and the next step for each.
Show answer
The total may have been misread, for example 1,230 read as 1,280, so re-send a higher-resolution crop of the total and compare. Alternatively a line item may have been misread or skipped, so check each line's quote and page evidence against the source. In both cases, flag the record for human review instead of storing it, because the deterministic sum check has shown the data is inconsistent.