Repository navigation
fix(gemini): return n images for image generations and edits when n > 1 - #52103
kerry-berri merged 6 commits into
Conversation
Gemini image models reject a candidate count above one on the images routes, so n > 1 failed with a provider 400 on AI Studio and Vertex AI. The image generation and edit handlers now ask the provider config how many identical requests to send, and merge the returned images and token usage into one response. Vertex AI Gemini image edits also accept n now. Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
…ini-image-n-fan-out Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> # Conflicts: # litellm/llms/gemini/image_edit/transformation.py
[Medium impact] The PR appears safe to merge with no outstanding findings. SummaryGemini image generations and edits now send one upstream request per requested image, then merge the images and usage.
The previous concerns are addressed by the current code and supplied live proof. No new actionable issues were found. Reviews (5) · Last reviewed commit: "Expect the shared logging object in the ..." · Reviewed by Greptile |
…t fails Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
…ive the merged response its own hidden params Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
…fails Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
Merging this PR will not alter performance1 warning
Comparing |
…test Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
|
bugbot run |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 90425e8. Configure here.
…ges (#53940) Brings nine tests in line with behavior that intentionally changed: - SSO client removal: /sso/key/generate without SSO now redirects to /ui/login (#53205) - budget partial update: /budget/info returns the app relation keys (#52477, #52787, #53232) - performance alerts opt-out: /alerts/monitoring returns thresholds (#52139) - cost margin rejection: the error names 'customer' as a valid key (#52406) - regional two-image generation: Gemini gets n single-image requests (#52103) - customer app budget key rotation: the rotated key's cleanup tolerates /key/regenerate - DeepSeek 401: the upstream error type is relayed (#53217) - vLLM rejected predicate: the plain upstream message is relayed (#53217). The case still fails on the non-OpenAI error type that #51809 fixes - /callbacks/list e2e: the Rust spend logger is listed as spend_log (#52182)
… spend row Copies the generations route hunk of BerriAI#52103 (113766d) from main. The route now puts its logging object on the request, so the failure hook reads the usage the Gemini transformation billed instead of logging the failure at $0. The setup kwargs are discarded rather than rebound onto the request, which keeps the same request dict that the failure hook reads.
Handwritten 1-3 sentence description
Asking Gemini for more than one image used to fail with an error from Google. Now you get the number of images you asked for.
Details
Link to Devin session: https://app.devin.ai/sessions/5b81b3515c894260be307f18c9b21e02
Open in Devin Desktop: https://app.devin.ai/desktop/session/5b81b3515c894260be307f18c9b21e02?variant=devin
Requested by: @kenneth-berri
TLDR
Problem this solves:
nabove 1nentirely, evenn=1How it solves it:
nsingle-image requests in parallelnis no longer forwarded to Google ascandidateCountnaboveMAX_IMAGE_FAN_OUT_REQUESTS(default 10) is a 400 before any upstream call/v1/images/generationsand/v1/images/editsnUser Flow
Before: a developer asking a Gemini image model for two images gets an error instead of images
"n": 2n=2fails the same way, and on Vertex AI it fails forn=1tooAfter: the same request returns the two images that were asked for
"n": 2data, andusageholds the tokens of both imagesn=2also returns two images, on Google AI Studio and on Vertex AILinear ticket
Resolves LIT-10824
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Live proxy with real Google AI Studio and Vertex AI calls, model
gemini-3.1-flash-lite-image. Two workers sharing one dedicated Redis on port 6399, with two worker PIDs serving on each proxy. I dropped--reloadbecause it keeps a single worker. Before and After used the same command and config, Before on port 4100 from amaincheckout and After on port 4101 from this branch.Env vars:
GEMINI_API_KEY,VERTEXAI_PROJECT,VERTEX_AI_DEVIN_SERVICE_ACCOUNT_JSON.$Misstudio-gemini-3.1-flash-lite-imageorvertex-gemini-3.1-flash-lite-image, andin.pngis any small PNG.Before (2ab5597)
Google AI Studio
n=2returns 400Multiple candidates is not enabled for this modeln=2returns 400Multiple candidates is not enabled for this modeln=2returns 400Multiple candidates is not enabled for this modelVertex AI
n=2returns 400Request contains an invalid argument.n=2returns 400UnsupportedParamsError: The following parameters are not supported for model gemini-3.1-flash-lite-image: n, andn=1returns the same errorn=2returns 200 with 2 choices, one image eachAfter (a840f17)
Google AI Studio
n=2returns 200 with 2 images,usageinput_tokens: 16,output_tokens: 2990,total_tokens: 3006(one image was 8 / 1468 / 1476)n=2returns 200 with 2 images,usageinput_tokens: 2256,output_tokens: 2487,total_tokens: 4743(one image was 1128 / 1270 / 2398)n=2returns the same 400 as before, unchanged by this PRVertex AI
n=2returns 200 with 2 images,usageinput_tokens: 16,output_tokens: 2240,total_tokens: 2256(one image was 8 / 1120 / 1128)n=2returns 200 with 2 images,usageinput_tokens: 2256,output_tokens: 2240,total_tokens: 4496, andn=1returns 200 with 1 imagen=2returns 200 with 2 choices, one image each, unchangedn=11returns 400n=11 is above the maximum of 10 images per request.One of three calls fails (a840f17)
A third two-worker proxy on the same Redis, with Postgres for spend logs,
num_retries: 0, and the AI Studio model'sapi_basepointed at a local relay. The relay forwards every request to the realhttps://generativelanguage.googleapis.com/v1betaand answers every third one with a 429 itself, so two of the three calls are real provider calls and one failure is injected.n=3returns 429. The relay log shows two 200s from Google and one injected 429. TheLiteLLM_SpendLogsrow isaimage_edit,failure,spend: 0.068236,prompt_tokens: 2256,completion_tokens: 2555,total_tokens: 4811n=3returns 429 with two 200s from Google and one injected 429. The row isaimage_generation,failure,spend: 0.068306,prompt_tokens: 16,completion_tokens: 2975,total_tokens: 2991. At 600a98d the same request wrotespend: 0and zero tokensn=2with no injected failure writes asuccessrow withspend: 0.0684375,total_tokens: 3070Tests:
LITELLM_LOCAL_MODEL_COST_MAP=True uv run --no-sync pytest tests/unit/llms/custom_httpx/test_llm_http_handler.py tests/unit/proxy/image_endpoints tests/unit/images tests/unit/llms/gemini/image_generation tests/unit/llms/gemini/image_edit tests/unit/llms/vertex_ai/image_edit tests/unit/llms/vertex_ai/image_generationgives 808 passed, andmake checkpasses. The new pricing, hidden params and generations failure spend row tests fail with thelitellm/changes of their commits stashed.Type
🐛 Bug Fix
Caveats (if any)
Medium
/v1/images/generationsnow hands the router one logging object per request, like edits and chat, so the failure spend row carries that usage. A request that fails after retries now fires one failure callback, where it used to fire one per attempt. Deployment failure counts for cooldowns still count every attemptnimages now meannupstream requests against Google rate limitsnabove 10 is now a 400 on these routes, configurable withMAX_IMAGE_FAN_OUT_REQUESTSLow
/v1/chat/completionsis untouched, so AI Studio chatn=2still returns Google's 400candidateCountwas sent and were updatedsampleCountin one requestFinal Attestation
Note
Medium Risk
Changes core image HTTP handling, concurrent upstream load, and billing/partial-failure logging; proxy image-generation callback behavior on retries also shifts slightly.
Overview
When Gemini/Vertex image routes cannot honor OpenAI-style
nin a single upstream call, LiteLLM now fans out that many parallel single-image requests, mergesdataandusage, and sums per-call pricing instead of forwardingcandidateCount.A new
litellm/images/fan_out.pymodule drives sync/async handlers inllm_http_handler, capsnviaMAX_IMAGE_FAN_OUT_REQUESTS(default 10), and on partial failure records spend for successful images before surfacing the error. Provider configs exposeget_request_count()(Gemini/Vertex); Vertex Gemini image edit now acceptsn. The proxy image generation path builds alitellm_logging_objso failure rows include billed usage.Reviewed by Cursor Bugbot for commit 90425e8. Bugbot is set up for automated code reviews on this repo. Configure here.