I was building automatic category tagging for a wallpaper app when a batch of a few dozen images stopped halfway with INVALID_ARGUMENT. I suspected the API key, then the model name, then the prompt, and only at the end the images themselves. With one error code covering everything, I ended up doubting every part of the request.
I rewrote this article so you can skip that detour: what to check, in what order. It is aligned with the official docs as of November 2026, and the code that used the old google-generativeai package now uses google-genai.
The order that works
Narrow INVALID_ARGUMENT down in this order: read the error message, reproduce with a single image, then add a pre-flight check. Before suspecting the whole batch, send one image through the same code path. Whether that one passes is the fastest split you have.
The table below lists the causes I actually hit with image requests, with a way to recognize each.
| Symptom | Likely cause | How to confirm | Fix |
|---|---|---|---|
| One specific image always fails | Extension and real format disagree (a .jpg that is really WebP) | Read the first bytes and compare with the declared MIME type | Decide the MIME type from content, not extension |
| Fails with more images, passes with one | Whole-request size exceeded | Sum the bytes, including base64 growth | Move large images to the File API, or send fewer per request |
| Fails only when calling REST directly | Wrong contents structure (parts nesting) | Read the path in the message, such as contents[0].parts | Put text and images in the same parts array |
| Small image still fails | Corrupt or truncated file, unsupported format | Open it with Pillow and call verify() | Exclude the file and log it |
| Only File API references fail | File still processing, or in a failed state | Check state | Wait for ACTIVE before referencing it |
Error message wording changes across SDK versions and models. I avoid exact-match branching and look for fragments such as "size", "mime" or "parts" instead.
Why INVALID_ARGUMENT is vague
INVALID_ARGUMENT (HTTP 400) is Google's broad class for "the request content was not accepted." For images, the five rows above cover nearly everything. Several causes can also be mixed in one batch, so you fix one and still fail for another reason.
That is why a single pre-flight function pays off. The sections below give one check per cause.
Cause 1: decide the MIME type from content
This is the easiest one to miss. When images come from several sources, a .jpg that is really WebP is normal. Code that derives MIME from the extension declares image/jpeg and gets rejected.
My earlier version used the standard-library imghdr, but imghdr was removed from the standard library in Python 3.13. This version reads the first bytes directly, so there is no dependency.
from pathlib import Path
def sniff_mime(path: str) -> str:
"""Detect MIME from leading bytes, not the extension. Raise if unknown."""
head = Path(path).read_bytes()[:16]
if head.startswith(b"\xff\xd8\xff"):
return "image/jpeg"
if head.startswith(b"\x89PNG\r\n\x1a\n"):
return "image/png"
if head[:4] == b"RIFF" and head[8:12] == b"WEBP":
return "image/webp"
if head[:6] in (b"GIF87a", b"GIF89a"):
return "image/gif"
if head[4:8] == b"ftyp" and head[8:12] in (b"heic", b"heix", b"mif1"):
return "image/heic"
raise ValueError(f"Unsupported or possibly corrupt: {path}")Do not silently fall back to image/jpeg when detection fails. A fallback looks friendly, but it lets corrupt files seem fine and fail later. Raise, then skip and log the file in the caller.
Cause 2: measure the total, including base64 growth
Base64 makes inline data about 33% larger than the binary. The limit applies to the request as a whole, not per image, so ten images that are individually fine can add up to too much.
Check the current limit in the official docs before you pick a number. My earlier version said "inline is capped at 20 MB." Google has announced larger file limits for the Gemini API in an official blog post, and the figure may move again, so keep it in one setting rather than hard-coding it throughout.
import os
# Check the current limit on the official "File input methods" page and leave margin.
INLINE_BUDGET_BYTES = 15 * 1024 * 1024 # total inline bytes per request (conservative)
def b64_size(n_bytes: int) -> int:
return (n_bytes + 2) // 3 * 4
def plan_request(paths: list[str]) -> dict:
"""Split images into inline and File API groups."""
inline, upload, used = [], [], 0
for p in sorted(paths, key=os.path.getsize):
cost = b64_size(os.path.getsize(p))
if used + cost <= INLINE_BUDGET_BYTES:
inline.append(p); used += cost
else:
upload.append(p)
return {"inline": inline, "upload": upload, "inline_bytes": used}Small images fill the inline budget first and the overflow goes to the File API. Judging by the total works better in batches than a rule like "any single image over 15 MB uses the File API."
Cause 3: contents structure when calling REST
Through the Python SDK, the structure is built for you. With raw REST, text and images must live in the same parts array.
# Wrong: text and inline_data as separate elements
contents = [
{"text": "Classify the category of each image"},
{"inline_data": {"mime_type": "image/jpeg", "data": encoded_img}},
]
# Right: one content entry with a parts list
contents = [
{
"role": "user",
"parts": [
{"text": "Classify the category of each image"},
{"inline_data": {"mime_type": "image/jpeg", "data": encoded_img}},
],
}
]I hit this when I removed the SDK temporarily to time requests. The conversion the SDK had been doing for me was something I forgot to write myself.
Rewritten with the google-genai SDK
The old google-generativeai package has been replaced by google-genai. Migration pitfalls are covered in errors you hit when migrating to the google-genai SDK.
The code below combines the three checks. I could not run it against the live API in this environment. The call shapes follow the official migration guide, but please send a single image by hand before using it in a batch.
import time
from google import genai
from google.genai import types, errors
client = genai.Client() # reads the key from the environment; never hard-code it
MODEL = "gemini-2.5-flash" # replace with the model ID you use
def to_part(path: str) -> types.Part:
return types.Part.from_bytes(data=open(path, "rb").read(), mime_type=sniff_mime(path))
def upload_part(path: str) -> types.Part:
f = client.files.upload(file=path)
while f.state and f.state.name == "PROCESSING":
time.sleep(2)
f = client.files.get(name=f.name)
if f.state and f.state.name == "FAILED":
raise RuntimeError(f"Upload failed: {path}")
return types.Part.from_uri(file_uri=f.uri, mime_type=f.mime_type)
def classify(paths: list[str], prompt: str) -> str:
plan = plan_request(paths)
parts = [types.Part.from_text(text=prompt)]
parts += [to_part(p) for p in plan["inline"]]
parts += [upload_part(p) for p in plan["upload"]]
try:
res = client.models.generate_content(model=MODEL, contents=parts)
return res.text
except errors.ClientError as e:
# 400 is a request problem: do not retry. Keep the message for diagnosis.
print(f"HTTP {e.code} / {e.status}: {e.message}")
raiseerrors.ClientError covers the 4xx family, so treat only e.code == 400 as "retrying will not help" and 429 as retryable. How to tell the two kinds of 429 apart is in retryable 429 vs spend-cap exhaustion.
Inline, File API or URL
| Method | Fits | Watch out for |
|---|---|---|
| Inline bytes | A few small images, one-shot processing | Counts toward whole-request size; base64 adds about 33% |
| File API | Large images, or the same image queried repeatedly | Upload takes time; files are kept for a limited period, so long-running reuse needs re-upload logic |
| Public URL | Analyzing images that are already public | Check current support and limits in the docs; not usable for private images |
For a small image used once, I choose inline. For an image I will query many times, I choose the File API. Re-sending bytes on every call costs more than one upload as the number of references grows.
Common misunderstandings
"INVALID_ARGUMENT means the key is wrong" is off target. Key problems normally surface as 401 or 403; a 400 is about the request content. Authentication is covered separately in authentication error fixes.
"A matching extension means a matching MIME type" is wrong. With several image sources the extension cannot be trusted. Read the content.
"Bigger images give better results" is not guaranteed. Resizing before upload avoids size errors and shortens waits. The reasoning is in why to resize with Pillow before sending.
Operating notes for batches
Too many images per request can cause timeouts and slow responses. In the wallpaper app I started with a cap of five, and dropped to about three when large images were mixed in. The right number differs per environment, so start small and grow.
When a batch fails, do not throw the whole thing away. Re-send it one image at a time. Once you know which image fell over, you can inspect and exclude just that one. For unattended overnight runs, having this "narrow the failure to one image" step decides how much work is waiting the next morning.
Where you get stuck next
Once images pass, the next problems are usually rate limits (429) as volume grows, and images that are accepted but not recognized. For the latter see when an image is not recognized. For the overall map of errors, keep the Gemini API error troubleshooting guide nearby.
What I noticed in the end was that the failure was not in the code but in the missing check. Keep one function that inspects every image before it is sent. That is the line I hold whenever I write image handling. Start by running a single image from your own folder through sniff_mime.