Skip to content

fix(gemini): return n images for image generations and edits when n > 1 - #52103

Merged
kerry-berri merged 6 commits into
BerriAI:mainfrom
kenneth-berri:litellm_lit-10824-gemini-image-n-fan-out
Nov 16, 2026
Merged

kerry-berri merged 6 commits into
BerriAI:mainfrom
kenneth-berri:litellm_lit-10824-gemini-image-n-fan-out

Conversation

@kenneth-berri

@kenneth-berri kenneth-berri commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

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:

  • Gemini image generations and edits fail with n above 1
  • Google rejects more than one candidate on these routes
  • Vertex AI Gemini image edits reject n entirely, even n=1

How it solves it:

  • LiteLLM sends n single-image requests in parallel
  • Images and token usage are merged into one response
  • n is no longer forwarded to Google as candidateCount
  • n above MAX_IMAGE_FAN_OUT_REQUESTS (default 10) is a 400 before any upstream call
  • Each call is priced on its own usage and the costs are summed, so summed tokens never cross a pricing tier no call reached
  • If one call fails, the calls that succeeded are still logged with their usage and cost, on both /v1/images/generations and /v1/images/edits
  • Vertex AI Gemini image edits now accept n

User Flow

Before: a developer asking a Gemini image model for two images gets an error instead of images

  1. They send POST https://litellm-domain/v1/images/generations with a Gemini image model and "n": 2
  2. The response is a 400, "Multiple candidates is not enabled for this model" on Google AI Studio or "Request contains an invalid argument" on Vertex AI
  3. POST https://litellm-domain/v1/images/edits with n=2 fails the same way, and on Vertex AI it fails for n=1 too

After: the same request returns the two images that were asked for

  1. They send POST https://litellm-domain/v1/images/generations with a Gemini image model and "n": 2
  2. The response is a 200 with two entries in data, and usage holds the tokens of both images
  3. POST https://litellm-domain/v1/images/edits with n=2 also returns two images, on Google AI Studio and on Vertex AI

Linear ticket

Resolves LIT-10824

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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 more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays 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 --reload because it keeps a single worker. Before and After used the same command and config, Before on port 4100 from a main checkout and After on port 4101 from this branch.

Env vars: GEMINI_API_KEY, VERTEXAI_PROJECT, VERTEX_AI_DEVIN_SERVICE_ACCOUNT_JSON.

python litellm/proxy/proxy_cli.py --config config.yaml --port 4100 --num_workers 2 --detailed_debug --use_v2_migration_resolver
model_list:
  - model_name: vertex-gemini-3.1-flash-lite-image
    litellm_params:
      model: vertex_ai/gemini-3.1-flash-lite-image
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: global
      vertex_credentials: os.environ/VERTEX_AI_DEVIN_SERVICE_ACCOUNT_JSON
  - model_name: studio-gemini-3.1-flash-lite-image
    litellm_params:
      model: gemini/gemini-3.1-flash-lite-image
      api_key: os.environ/GEMINI_API_KEY
router_settings:
  redis_host: 127.0.0.1
  redis_port: 6399
general_settings:
  master_key: sk-lit10824-local-qa-key
  coordination_redis:
    host: 127.0.0.1
    port: 6399

$M is studio-gemini-3.1-flash-lite-image or vertex-gemini-3.1-flash-lite-image, and in.png is any small PNG.

H="Authorization: Bearer sk-lit10824-local-qa-key"
curl -s localhost:4100/v1/images/generations -H "$H" -H "Content-Type: application/json" \
  -d "{\"model\":\"$M\",\"prompt\":\"A watercolor painting of a lighthouse at dawn\",\"n\":2}"
curl -s localhost:4100/v1/images/edits -H "$H" -F model=$M -F image=@in.png \
  -F "prompt=Add a small blue circle in the center" -F n=2
curl -s localhost:4100/v1/chat/completions -H "$H" -H "Content-Type: application/json" \
  -d "{\"model\":\"$M\",\"messages\":[{\"role\":\"user\",\"content\":\"Generate a watercolor painting of a lighthouse at dawn\"}],\"n\":2}"

Before (2ab5597)

Google AI Studio

  1. Generations n=2 returns 400 Multiple candidates is not enabled for this model
  2. Edits n=2 returns 400 Multiple candidates is not enabled for this model
  3. Chat n=2 returns 400 Multiple candidates is not enabled for this model

Vertex AI

  1. Generations n=2 returns 400 Request contains an invalid argument.
  2. Edits n=2 returns 400 UnsupportedParamsError: The following parameters are not supported for model gemini-3.1-flash-lite-image: n, and n=1 returns the same error
  3. Chat n=2 returns 200 with 2 choices, one image each

After (a840f17)

Google AI Studio

  1. Generations n=2 returns 200 with 2 images, usage input_tokens: 16, output_tokens: 2990, total_tokens: 3006 (one image was 8 / 1468 / 1476)
  2. Edits n=2 returns 200 with 2 images, usage input_tokens: 2256, output_tokens: 2487, total_tokens: 4743 (one image was 1128 / 1270 / 2398)
  3. Chat n=2 returns the same 400 as before, unchanged by this PR

Vertex AI

  1. Generations n=2 returns 200 with 2 images, usage input_tokens: 16, output_tokens: 2240, total_tokens: 2256 (one image was 8 / 1120 / 1128)
  2. Edits n=2 returns 200 with 2 images, usage input_tokens: 2256, output_tokens: 2240, total_tokens: 4496, and n=1 returns 200 with 1 image
  3. Chat n=2 returns 200 with 2 choices, one image each, unchanged
  4. Generations n=11 returns 400 n=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's api_base pointed at a local relay. The relay forwards every request to the real https://generativelanguage.googleapis.com/v1beta and answers every third one with a 429 itself, so two of the three calls are real provider calls and one failure is injected.

  1. Edits n=3 returns 429. The relay log shows two 200s from Google and one injected 429. The LiteLLM_SpendLogs row is aimage_edit, failure, spend: 0.068236, prompt_tokens: 2256, completion_tokens: 2555, total_tokens: 4811
  2. Generations n=3 returns 429 with two 200s from Google and one injected 429. The row is aimage_generation, failure, spend: 0.068306, prompt_tokens: 16, completion_tokens: 2975, total_tokens: 2991. At 600a98d the same request wrote spend: 0 and zero tokens
  3. Generations n=2 with no injected failure writes a success row with spend: 0.0684375, total_tokens: 3070

Tests: 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_generation gives 808 passed, and make check passes. The new pricing, hidden params and generations failure spend row tests fail with the litellm/ changes of their commits stashed.

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • One failed upstream call fails the whole request
    • Images from the calls that succeeded are still billed by Google, and LiteLLM logs their usage and cost on the failure
    • /v1/images/generations now 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 attempt
  • n images now mean n upstream requests against Google rate limits
  • n above 10 is now a 400 on these routes, configurable with MAX_IMAGE_FAN_OUT_REQUESTS

Low

  • /v1/chat/completions is untouched, so AI Studio chat n=2 still returns Google's 400
  • Three existing tests asserted candidateCount was sent and were updated
  • Response headers in hidden params come from the first upstream call only
  • Not tested live: Imagen models, which keep sending sampleCount in one request

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

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 n in a single upstream call, LiteLLM now fans out that many parallel single-image requests, merges data and usage, and sums per-call pricing instead of forwarding candidateCount.

A new litellm/images/fan_out.py module drives sync/async handlers in llm_http_handler, caps n via MAX_IMAGE_FAN_OUT_REQUESTS (default 10), and on partial failure records spend for successful images before surfacing the error. Provider configs expose get_request_count() (Gemini/Vertex); Vertex Gemini image edit now accepts n. The proxy image generation path builds a litellm_logging_obj so 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.

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>
@veria-ai

veria-ai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Fixed/addressed: 2 · PR risk: 0/10

Reviews

Comment thread litellm/images/fan_out.py Resolved
@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

@greptile

@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

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
@greptile-apps

greptile-apps Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge with no outstanding findings.

Summary

Gemini image generations and edits now send one upstream request per requested image, then merge the images and usage.

  • Gemini image routes return the number of images callers request.
  • Failed image batches still record the work providers completed.
  • Imagen edit test assertions keep the same checks with cleaner line breaks.

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

Comment thread litellm/images/fan_out.py Resolved
Comment thread litellm/images/fan_out.py Resolved

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread litellm/images/fan_out.py Resolved
…t fails

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

@greptile

@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

bugbot run

Comment thread litellm/images/fan_out.py Resolved
Comment thread litellm/images/fan_out.py Resolved

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

…ive the merged response its own hidden params

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

@greptileai

@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

…fails

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

@greptileai

@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@codspeed

codspeed Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 2 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 45 untouched benchmarks


Comparing kenneth-berri:litellm_lit-10824-gemini-image-n-fan-out (90425e8) with main (7363ffd)

Open in CodSpeed

…test

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

@greptile

@kenneth-berri

Copy link
Copy Markdown
Collaborator Author

bugbot run

@codecov

codecov Bot commented Nov 16, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.57534% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/images/fan_out.py 95.83% 3 Missing ⚠️
litellm/llms/custom_httpx/llm_http_handler.py 95.34% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@kerry-berri
kerry-berri merged commit 113766d into BerriAI:main Nov 16, 2026
154 of 157 checks passed
yuneng-berri added a commit that referenced this pull request Nov 23, 2026
…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)
mateo-berri added a commit to norkelbyte/litellm that referenced this pull request Nov 26, 2026
… 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants