◉GEMINI LABJP
●OMNI 1.2 — Gemini Omni 1.2 Flash is generally available (11/5) with up to 15-second video and conversational editing; 1.1 Flash is routed to 1.2 on 12/3●COMPUTER — Computer Use is now generally available in the Interactions and GenerateContent APIs (10/30)●LIVE — Live and TTS preview models shut down as early as 11/17 (7 days left). Move to gemini-3.8-live and the 3.8 TTS models●CLI — Gemini API CLI (gemini-api) is out in beta (10/27): a zero-dependency client for agents and CI●2.5 PRO — gemini-2.5-pro and 2.5-flash are routed automatically on 12/1 (21 days left), to 3.8 Flash and 3.5 Flash-Lite●NEW — Stop Re-Reading Every Crash Report: Gre…●OMNI 1.2 — Gemini Omni 1.2 Flash is generally available (11/5) with up to 15-second video and conversational editing; 1.1 Flash is routed to 1.2 on 12/3●COMPUTER — Computer Use is now generally available in the Interactions and GenerateContent APIs (10/30)●LIVE — Live and TTS preview models shut down as early as 11/17 (7 days left). Move to gemini-3.8-live and the 3.8 TTS models●CLI — Gemini API CLI (gemini-api) is out in beta (10/27): a zero-dependency client for agents and CI●2.5 PRO — gemini-2.5-pro and 2.5-flash are routed automatically on 12/1 (21 days left), to 3.8 Flash and 3.5 Flash-Lite●NEW — Stop Re-Reading Every Crash Report: Gre…
Articles/API / SDK
◈ API / SDK/2026-05-17Intermediate

Diagnosing INVALID_ARGUMENT Errors in Gemini API Batch Image Analysis

A batch of images to the Gemini API fails with INVALID_ARGUMENT (HTTP 400). This guide gives a triage table for MIME type, request size, contents structure and corrupt files, pre-flight checks rewritten for the google-genai SDK, and a rule for choosing inline data vs the File API (as of November 2026).

gemini-api291troubleshooting98image5python113invalid-argument

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.

SymptomLikely causeHow to confirmFix
One specific image always failsExtension and real format disagree (a .jpg that is really WebP)Read the first bytes and compare with the declared MIME typeDecide the MIME type from content, not extension
Fails with more images, passes with oneWhole-request size exceededSum the bytes, including base64 growthMove large images to the File API, or send fewer per request
Fails only when calling REST directlyWrong contents structure (parts nesting)Read the path in the message, such as contents[0].partsPut text and images in the same parts array
Small image still failsCorrupt or truncated file, unsupported formatOpen it with Pillow and call verify()Exclude the file and log it
Only File API references failFile still processing, or in a failed stateCheck stateWait 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}")
        raise

errors.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

MethodFitsWatch out for
Inline bytesA few small images, one-shot processingCounts toward whole-request size; base64 adds about 33%
File APILarge images, or the same image queried repeatedlyUpload takes time; files are kept for a limited period, so long-running reuse needs re-upload logic
Public URLAnalyzing images that are already publicCheck 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.

Share

Thank You for Reading

Gemini Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • ✦Copy-paste ready implementation code
  • ✦New advanced guides published daily
  • ✦$5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

◈ API / SDK2026-10-19
When 404 and 429 Show Up in the Same Gemini API Log, Check the Model Name Before the Quota
A triage order for Gemini API logs that mix 404 NOT_FOUND and 429 RESOURCE_EXHAUSTED, plus a small Python script that separates a bad model name from a real quota limit without generating anything.
◈ API / SDK2026-10-16
The Day /models Returns 200 but generateContent Returns 403 — Decide Your Triage Order Before It Happens
A triage order for the case where listing models succeeds with 200 but generation fails with 403 permission_denied. Includes a small diagnostic script that checks key, project, and billing in turn, why you should not retry a 403, and how to assemble what support needs.
◈ API / SDK2026-10-22
Before You Swap in gemini-4-argon, Search Your Own Code for What to Remove
Four habits can break or silently change when you move to gemini-4-argon: explicit caches, sampling parameters, small max_output_tokens and short timeouts. A stdlib-only script finds them in your repository, with what to check after the swap and when to stay on Flash.