Skip to content

fix(gemini): return an error instead of an empty 200 when a Gemini image request gets no image on lts/1.108.x - #53429

Merged
mateo-berri merged 48 commits into
BerriAI:lts/1.108.xfrom
izzybn:litellm_lts_gemini_image_finish_reason
Nov 25, 2026
Merged

mateo-berri merged 48 commits into
BerriAI:lts/1.108.xfrom
izzybn:litellm_lts_gemini_image_finish_reason

Conversation

@izzybn

@izzybn izzybn commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

On lts/1.108.x, Gemini image refusals and answers with no image now return an error saying why, not an empty 200, like #29125 on main

Details

TLDR

Problem this solves:

  • On lts/1.108.x a Gemini image refusal on AI Studio or Vertex answers 200 with data: [] and no reason, and is still billed

How it solves it:

  • A refused image or blocked prompt answers 400 with Gemini's reason
  • Any other answer without an image answers 422 naming its finishReason
  • Refusals and empty answers bill their tokens on the failure row and cost header, except IMAGE_RECITATION at $0
  • A configured fallback now serves a refused image and also bills the attempt it replaced
  • After a 5xx, a fallback's refusal now reaches the client
  • Billed image health probes now log a failure spend row

User Flow

Before: a refused Gemini image comes back as a 200 with no image or reason, and is still billed

  1. They send POST https://litellm-domain/v1/images/generations with a Gemini image model and a prompt, or POST /v1/images/edits with an image
  2. Gemini refuses with IMAGE_RECITATION, and the proxy answers 200 with "data": []
  3. The x-litellm-response-cost header and https://litellm-domain/spend/logs show a charge

After: the same refusal comes back as an error that says why, at $0

  1. They send the same request
  2. The proxy answers 400 with a ContentPolicyViolationError naming finishReason=IMAGE_RECITATION and Google's "You will not be charged for this request" message
  3. https://litellm-domain/spend/logs shows a failure at $0

Relevant issues

Backport of #29125, for the empty image answer reported in #28989, which is closed as not planned

Picks

Pick table

Picked in order with git cherry-pick -x, original author kept, except where the table says otherwise. Four picks apply verbatim, two with a one-line conflict, and eighteen are adapted. 7d727945194, 4472b4c8677, cfd3899f3e1, 982b99c8469, 71bb099f896, bfaff0b1e80 and 9a46606880e are main only, and #29125's merges of main are not picked

main commit Commit on this branch Change Applied
80257675c89 f1563317379 finishReason on generation safety blocks verbatim
93161b54dc2 3343bcb2fe5 blocked prompts and edit safety blocks verbatim
c299b71c152 43c1f5262d4 error instead of an empty 200 one-line conflict, see below
903c646c35d db85ae41aab bill a no-image answer's tokens one-line conflict, see below
6da062156e6 6e4189e4182 422 for OTHER and LANGUAGE adapted, see below
9adec36a89c 5ecb0d628e1 bill refusals Google charges for adapted, see below
1c7f26ae39c 0e3edfa3249 cost header on errors, healthy refused probes adapted, see below
7d727945194 none return served images beside an answer without one main only, see below
bb44ced6e8f 9560d7b0249, 50a92354748 failure spend row for billed health probes adapted, see below
3697ccd589c 9d26d75688b bill the failed attempt a fallback replaced adapted, see below
3d2105db227 4963e99e595 keep a failed attempt's charge on unpriced fallbacks and collector rows adapted, see below
8ad5e268496 1e448c2fd8d keep billing, alerts and errors right when Gemini answers without an image adapted, see below
476eeb59914 eb2c026cf7f, 8a58030368a count billed refusals in budgets once and never as deployment failures adapted, see below
1f5e8bdc5df 4ba734e90cd, 336aceed4d2, 83ead6faaf9 bill refusals once in Prometheus and token columns, and ignore request fields named after billing fields adapted, see below
f7b07f812cb fad3daaf875 keep a deployment that answered without an image marked healthy verbatim
489f685d47a 8b0a4635633 count an answer without an image as a deployment success verbatim
198d52b027e da9679d3f85, f497f2c9738 answer a fallback's refusal instead of an earlier failure, keep custom labels, and skip no-log spend adapted, see below
1277be6ffa1 0c596b95b10 log a fallback's refusal on the deployment that answered adapted, see below
20fadb7af28 0e27c22c9ee count an answer without an image toward deployment tpm limits, and keep refusals out of the Slack failed-request report adapted, see below
f15270604c8 14c77add780 count a refusal toward deployment tpm limits on sync calls adapted, see below
4472b4c8677 none store the Rust router's answered tokens as a 32-bit count main only, see below
4a2c4cc0d77 28da7e2f760, abf685bdf22 count a billed refusal toward key tpm limits, and only a fallback's own tokens toward deployment tpm adapted, see below
cfd3899f3e1 and 9a46606880e none store the Rust router's exception classes as a boxed slice main only, see below
1970a317131 e9c3e1da857 count every billed refusal of a fallback chain toward key tpm limits adapted, see below
428644572b6 c4e3e6fbcd2 annotate the new tests' bindings as Final adapted, tests only
982b99c8469 none bill every refused answer of an n fan-out toward model group usage main only, see below
cc572bd45c6 66e10121f9d keep custom labels off a no-log refusal's request counters adapted, see below
7cebd6ab113 706f674356a count a billed refusal toward key tpm with reservation off, and give back a recitation's reservation adapted, see below
71bb099f896 and bfaff0b1e80 none count a billed refusal's input tokens toward project itpm on every fallback attempt under an output limit main only, see below
none 4496778bfad, 7f9df4f1e00, 16291f02afd, 81527aff254, 78355a583ac key logging callbacks, usage after a fallback, deployment log settings, retried refusals, per-attempt failure logs, refused attempts on a client disconnect this line only, see below
Four commits copy prerequisites from main
main PR Commit on this branch What it brings
#49079 ec9f88acd7c error_response_without_credentials and its three private helpers, verbatim
#52103 f977f2b78bf the generations route putting its logging object on the request
#47741 b94967d8319 failure spend rows raising the live budget counters, all but one unit test
#53271 965eeb76e64 billed failure spend rows and budget counters with disable_error_logs on, all but the Rust spend ledger test
Where the picks differ from main

In the Gemini edit transformation the parsed response is named response_json on this line and payload on main, so c299b71c152 and 903c646c35d each call empty_image_response_error with response_json. Every other changed line in those two picks matches main

This line has no image fan-out (#52103), so one request is one upstream call. 6da062156e6 and 9adec36a89c also change the fan-out and its tests, and those parts are dropped. Here 9adec36a89c's refusal billing goes through the failure-usage hook the transformation already calls for a no-image answer

Without the #52103 route change, the generations route here had no logging object on the request, so its failure spend row read $0 even after the transformation billed it. Edits already had one. Main's route logs one failure event per request, while this line still logs one per router attempt, as its base does

This line's Gemini image usage parser does not read cachedContentTokenCount (main got that from #52572 and #52857), so the reasoning-token test here drops main's cached-token assertion

This line has no failure_row_response_cost, so 0e3edfa3249 moves the failure spend row's inline cost into a function with that name, without main's finalized-cost branch, which this line does not have. This line's empty-answer 422 was a plain UnprocessableEntityError, so it becomes an UnservedImageError subclass for the health probe to recognize. The agentic follow-up test change has no counterpart here. 7d727945194 changes only main's n fan-out, and this line has none, since it sends n to Gemini as candidateCount in one call

4496778bfad has no main commit. It makes the generations route keep the request data function_setup returns, as #52103 does on main, so a key's logging callbacks never reach the provider's params. It also sets a failed attempt's billed usage aside before each fallback, as main's carry_failed_attempt_usage does, so the refused attempt's usage goes on the failure row when the fallback fails too. A stream logs a failed attempt in the background, where that could bill the broken stream at $0, so 7f9df4f1e00 skips it for streams

9d26d75688b ports 3697ccd589c by hand. This line has no way to carry a failed attempt's cost to the attempt that serves the request, so it adds a narrow one with main's names. The set-aside skips streams, and every chat writer of partial usage is a stream, so chat billing does not change

9560d7b0249 ports bb44ced6e8f by hand. This line has no Rust spend ledger, so a billed health probe's failure row goes only through the legacy spend logger, and main's retyping of two reads in that logger's failure hook is left out, since it adds a type error here. That logger failed to write a row whose call never got a first token, so 50a92354748 dates that row at its end time, as it already did when the time was missing

4963e99e595 ports 3d2105db227 and keeps request fields named like function_setup's own parameters, such as is_async_call, out of that call. It also made the router cool down later failed image attempts, which 81527aff254 replaces by logging each attempt

16291f02afd has no main commit. The generations route shares one logging object across router attempts, which skips function_setup for each deployment, so the router now applies each attempt's own redaction, Langfuse keys and callbacks to it. Same-group retries also set a refused attempt's charge aside, as main's carry_superseded_attempt_usage does, so the row that ends the request bills every attempt

81527aff254 has no main commit. Each router attempt now runs the failure log again, so retries count in metrics, cooldowns and latency routing. Callbacks bound to one request survive the per-deployment reset, so a least-busy override releases its count. A private deployment's failure row drops its prompt, and image generation stays out of the timeout estimate this line's base never applied to it

1e448c2fd8d ports 8ad5e268496 by hand. It brings the fixes this line can use, for the error cost header, the billed timeout header, edit fallback tokens, refusal text with logging off, Prometheus refusal spend, Slack alerts and cooldowns on refusals, and a scoped key's view of other groups. Main's fixes for a retry after a partial n=2 answer, mixed n=2 answers and failed fallback token estimates are left out, because this line has no fan-out and does not estimate image tokens

78355a583ac has no main commit. A client that disconnects while a refused image request falls back cancels the restore path, so the refused attempt's charge was never written. The failure row now bills any attempt still set aside

eb2c026cf7f ports 476eeb59914 by hand. On both lines a billed refusal now counts once toward deployment, provider, tag, key model and session budgets, stays out of the deployment failure counter, and is not billed again when a post-call hook rejects a success that was already logged. This line runs the failure log on every router attempt, so its budget limiters charge each refused attempt from that log, where main opts them in per attempt. This line also skips the Slack exception alert for these answers and names the failed attempt's api_base in its failure log, two gaps main does not have. 8a58030368a gives image edits the same per-attempt logging reset image generations get, so an edit refused again on a retry in the same group also counts toward those budgets

4ba734e90cd and 336aceed4d2 port 1f5e8bdc5df by hand, and 83ead6faaf9 moves one line-only test to the bare label. A request field named failed_attempts_billed_on_success or image_answers_billed_on_failure no longer reaches logging, so a request cannot change what it is billed. Prometheus skips a billed failure that cost $0 and labels one that did not with the bare model name, and a refusal no longer marks the deployment partly down or counts as a deployment failure. A spend row after a billed image failure now sums the tokens of every billed attempt. Main's fix for the stream cost header is left out, because this line does not stream images

The same two commits close a gap only this line has. Each router attempt runs the failure log here, so a failed image fallback was counted twice toward allowed_fails and cooled the backup after one request. The fallback handler now adds its own cooldown only when the router's failure callback did not count the attempt already, which is the case for a no-log request

b94967d8319 picks #47741, which this PR needs because it moves billed refusals onto the failure spend row. Without it a burst of refusals ran past a key, team or tag max_budget until the database reseeded the live counters. It conflicted only where main's failure hook has a finalized-cost branch, which this line does not have, so that branch and its unit test are left out. Its 15 integration tests pass on this line

965eeb76e64 picks #53271, which this PR needs for the same reason, since with disable_error_logs on a billed refusal skipped its spend row and budget counters. This line has no Rust spend ledger, so that test is left out, and the billed check joins the hook's own disable_error_logs gate

da9679d3f85 picks 198d52b027e's Prometheus half, so refused and empty answers keep the request's custom metadata labels and a no-log refusal adds nothing to the spend and token counters. Its router half is in main's Rust router, which this line does not have, so f497f2c9738 makes this line's Python router raise a fallback's refusal or 422 when the earlier error was something else, where it raised the earlier 5xx

0c596b95b10 ports 1277be6ffa1. This line's failure hook already lifts the last attempt's logging object, so when that attempt is the fallback that refused, the port copies its group and id onto the request metadata, which the spend row and Prometheus read first. Main looks the deployment up in the router from the attempt the client saw, which this line does not record, so when every model refuses this line names the last one and main the first. The per-attempt Prometheus counters are left out, since this line runs the failure log on every attempt

0e27c22c9ee ports 20fadb7af28 by hand. This line has no Rust router, so the billed tokens go to the model group usage counter in this line's Python router, and this line has no tpd limit. Main's choice of the first refusal in a chain lives in its Rust router and is left out, since this line's Python router already answers the first refusal. The Slack daily report skips these answers as on main. When a refused attempt's fallback then fails another way, Prometheus labels the refusal's billed spend with the fallback's group as requested_model and the refused deployment as model_id

14c77add780 picks f15270604c8's sync half. Its fallback half is in main's Rust router, and a fallback attempt here already runs the async failure hook. This line runs the sync failure hook for an async image edit too, so both hooks skip the async image call types, which the async hook counts already

4472b4c8677 only narrows the Rust router's answered_tokens field for clippy, and this line has no Rust router

28da7e2f760 and abf685bdf22 port 4a2c4cc0d77 by hand. Main counts a billed refusal's tokens toward key, team and user tpm in its Rust limiter, and this line has none, so abf685bdf22 does it in the Python limiter, also when the refusal has no output tokens. 28da7e2f760 counts only a served fallback's own tokens toward its deployment's tpm, as main does. Two gaps only this line has are fixed in abf685bdf22 too. A served fallback no longer gives back the key's tpm reservation a second time, which left the key 1040 tokens short, and a refused edit through the proxy now counts toward its model group usage, since this line's router read only metadata and edits carry litellm_metadata

cfd3899f3e1 only stores the Rust router's exception classes as a boxed slice for clippy, and this line has no Rust router

e9c3e1da857 ports 1970a317131 by hand. Main fixes it in its Rust limiter, and this line has none, so the Python limiter counts a refused attempt's tokens toward the key tpm limit even after an earlier attempt of the same request settled the key's reservation. c4e3e6fbcd2 annotates the new tests' bindings as Final, as 428644572b6 does on main

982b99c8469 changes only main's n fan-out, and this line has none

66e10121f9d picks cc572bd45c6 and fixes a gap only this line has. On a sync call, a fallback served after a refusal counted the refused tokens again toward its own deployment's tpm, since only the async failure log set them aside. The sync failure log now does it too

706f674356a ports 7cebd6ab113 by hand. Main settles a billed refusal like a served answer in its Rust limiter, and this line has none, so with token reservation off the Python limiter now counts it toward the key, team and user tpm limits. An IMAGE_RECITATION refusal bills nothing, so it gives back its otpm reservation instead of settling as a billed answer with no tokens. A sync image refusal also counts toward its model group usage now, a gap only this line had

71bb099f896 fixes main's Rust limiter, which skipped a later fallback attempt's input tokens under token_rate_limit_type: output when the refusal had no output tokens. This line's Python limiter already counts every billed refusal toward project itpm under any limit type

#29125 also merged main after #54238, which counts every billed failure toward budgets there. That merge keeps main's budget limiters counting each refused attempt once after a served fallback. This line does not have #54238 and keeps eb2c026cf7f's own way of doing that

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

Last updated: f646616, where what 66e1012 and 706f674 fix ran against c4e3e6f. e9c3e1d's key tpm cases carry to c4e3e6f, a tests-only commit. The table below ran at abf685b and base 2818be7 against a scripted Gemini, from before and after, with older legs in the gist

Case Before (2818be7) After (abf685b)
5xx, then a fallback refusal 200, 1 call each 400, 1 call each
Its spend row on refused-backup success failure
Custom label on a refusal alpha alpha
no-log refusal 200, no row 400, failure row, no spend metric
3 refusals under tpm: 1000 200, 429, 429 400, 429, 429
5xx, refusal, refusal 200, 2 calls 400, first refusal, 3 calls
What 66e1012 and 706f674 fix, against c4e3e6f

Each side ran on its own proxy, database and Redis against a scripted refusal that bills 1110 tokens, with token reservation on and off. Counts are Redis deltas, from the k3-l0, k3-l2 and k3-b0r files in the gist, and the sync rows from sync-sync-live-v2.out

Case c4e3e6f f646616
Key tpm, reservation off, one refusal 1 1111
Refused generation on its model, reservation off not counted 1110
5 IMAGE_RECITATION generations, otpm: 40000 400, then 4 429s 5 400s
5 IMAGE_RECITATION edits, otpm: 40000 429, 400, then 3 429s 5 400s
no-log refusal, custom label on counters present absent
Sync refusal, model group usage not counted 1110 tpm, 1 rpm

Base 2818be7 answered the first recitation generation 200 and every edit 429. At f646616 a real Gemini fallback served a refused edit after a 5xx, with reservation on and off

The same counting on team, user and model limits, and on a real Vertex refusal

Both sides ran with token reservation off, the team and user cases on the scripted refusal and the Vertex cases on a real Vertex refusal of "turn this person into Yoda", from before and after. The NO_IMAGE answer carries no usage, and at c4e3e6f one such answer left the model's otpm counter at 65536, so the next four never reached Gemini. Team PTU limits take the same path as the team case and were traced, not run

Case c4e3e6f f646616
3 refused generations, team tpm: 1000 3 400s 400, 429, 429
3 refused edits, team tpm: 1000 3 400s 400, 429, 429
3 refused generations, user tpm: 1000 3 400s 400, 429, 429
5 NO_IMAGE generations, model otpm: 40000 422, then 4 429s 5 422s
5 NO_IMAGE edits, model otpm: 40000 422, then 4 429s 5 422s
3 real Vertex refused generations, key tpm: 100 3 400s 400, 429, 429
3 real Vertex refused edits, key tpm: 100 3 400s 400, 429, 429
What 28da7e2, abf685b and e9c3e1d fix, against 09b1d48

Each case refuses on a scripted Gemini and then a real Gemini fallback serves the image, from key tpm and router usage. The key's count should be the served tokens plus the refusal's tokens

Case 09b1d48 abf685b
Key tokens, refusal then served generation 1040 short exact
Key tokens, refusal then served edit 1 short exact
Key tokens, refusal with no output tokens, generation 1040 short exact
Key tokens, refusal with no output tokens, edit 1 short exact
Key tokens, served with no refusal exact exact
Refused edit in model group usage not counted 1110 tpm, 1 rpm

In e9c3e1d's cases a key's count should be the served tokens plus every refusal's 1110 tokens, from k2-e9c3e1d.out

Case, generation and edit abf685b e9c3e1d
5xx, refusal, then served 1110 short exact
Refusal, refusal, then served 1110 short exact
Refusal, refusal, none served not run exact
One refusal, no fallback not run exact

These key limits and chains ran at abf685b, from a and w, and gave the same answers as main

Case Answers Upstream calls
Key tpm: 2000, 3 refusals of 1110 tokens 400, 400, 429 2
Key tpm: 1000, refusal with no output tokens, generation or edit 400, 429, 429 1
Key tpm: 8, real Gemini refusal 400, 429, 429 1
No image, then a fallback refusal 422, $0.007326 2
Context window 400, then two fallback refusals 400 3
Rate limit, sync and chain cases at 2818be7 and abf685b

The deployment has tpm: 1000 and each refusal bills 1110 tokens. Each request ran within one minute of the last, from the tpm, ftpm, sync and chain outputs in the gist

Case Before (2818be7) After (abf685b)
enforce_model_rate_limits, 3 requests 200, then 2 429s, 1 call 400, then 2 429s, 1 call
usage-based-routing-v2, 3 requests 200, then 2 429s, 1 call 400, then 2 429s, 1 call
Same, deployment priced at $0 200, then 2 429s 400, then 2 429s
Same, IMAGE_RECITATION 200, then 2 429s 3 400s, 3 calls
Refusal as a 5xx's fallback, then a direct call, both limits 200, then 429 400, then 429
Sync Router, both limits 2 empty answers, 2 calls refusal, then 429, 1 call
5xx, refusal, refusal row refuser-a success, $0.003663 refuser-b failure, $0.004163
Slack daily keys for refusals latency none
Fallback counter for a refusing fallback successful failed
Budget smoke at 2818be7, 8b0a463 and 09b1d48

With disable_error_logs on, 5 refusals on a key with max_budget $0.008 answered 200 three times and then went over budget twice at 2818be7, were all refused at 8b0a463, and at 09b1d48 3 were refused and 2 went over budget, from base, before and after. Team and tag budgets matched, and the refused deployment's state stayed 0 with 3 successes on both 2818be7 and 09b1d48

The smoke below ran at 8b0a463 and at 83ead6f, the head before that round's three picks, each on its own proxy and database against a scripted Gemini that refuses every image at $0.003663, from before and after

Case Before (83ead6f) After (8b0a463)
5 refusals on a key with max_budget $0.008 5 refused 3 refused, 2 over budget
Same on a team budget 5 refused 3 refused, 2 over budget
Same on a tag budget 5 refused 3 refused, 2 over budget
Refused deployment state no sample 0
Refused deployment success count none 3 per budget
Real Gemini and Vertex at 2818be7 and abf685b

These ran on their own proxy and database with num_retries: 0, from before and after. On every row the cost header, spend row and key spend agree

Case Before (2818be7) After (abf685b) After spend
Gemini, Yoda 200, 0 images, success row 400, PROHIBITED_CONTENT, failure row $0.0000075
Vertex, Yoda 200, 0 images, success row 400, IMAGE_PROHIBITED_CONTENT, failure row $0.0037575
Gemini, Yoda, fallback serves 200, 0 images 200, 1 image $0.1371055
Vertex, Yoda, fallback serves 200, 0 images 200, 1 image $0.1428505
Vertex edit, fallback refuses too 200, 0 images 400 $0.0108575
Gemini edit, Yoda not run 400, PROHIBITED_CONTENT $0.0016875
Served Gemini generation 1 image 1 image $0.0403995
Served Vertex generation 1 image 1 image $0.039267
Served Gemini edit 1 image 1 image $0.0384555
Served Vertex edit 1 image 1 image $0.038478
Real Gemini and Vertex at 336acee

These ran on their own proxy and database with num_retries: 0, from t336ac-real.out, and the before column is base 60280ca from 34175f7's QA. On every tip row the cost header, spend row and key spend agree

Case Before (60280ca) After (336acee) After spend
Gemini, Yoda 200, 0 images 400, PROHIBITED_CONTENT $0.0000075
Vertex, Yoda 200, 0 images 400, IMAGE_PROHIBITED_CONTENT $0.00168
Gemini, Yoda, fallback refuses too 200, 0 images 400 $0.0000175
Vertex, Yoda, fallback serves 200, 0 images 200, 1 image $0.143587
Vertex edit, fallback refuses too 200, 0 images 400 $0.0056705
Served Gemini generation 1 image 1 image $0.0415845
Served Vertex generation 1 image 1 image $0.038322
Served Gemini edit 1 image 1 image $0.0387255
Served Vertex edit 1 image 1 image $0.0378855
What 4ba734e and 336acee fix, against 60280ca

These ran on a local scripted upstream, each side on its own proxy and database, with a refused request tried three times, from t336ac-scripted.out

Case 60280ca 4ba734e 336acee
Refused generation or edit 200, $0.003663 400, $0.010989 400, $0.010989
Request names a billing field $0.0387135 $0.0387135 $0.0387135
Refused, then served fallback 200, no fallback, $0.003663 200, $0.0497025 200, $0.0497025
Refused deployment state 0 1 no sample
Refused deployment failure count none 3 none
Refusal spend model label in Prometheus bare gemini/ prefix bare
Down host, spend and tokens $0, none $0, none $0, none
Down host state and failure count 1, 1 1, 1 1, 1
Failed edit fallback, third try 429, cooled 429, cooled 429, cooled
Failed no-log generation fallback, third try 500 500 500
Recitation, SDK and served fallback rows at 81527af

The before column comes from base 1f7098c on one or two workers, except the SDK row, which ran again at 16291f0's QA

Case Before (1f7098c) After (81527af) After spend
Vertex generation, red dot 200, 0 images 400, IMAGE_RECITATION $0
Gemini edit, red dot 200, 0 images 400, IMAGE_RECITATION $0
Vertex edit, red dot 200, 0 images 400, IMAGE_RECITATION $0
Gemini, Yoda 200, 0 images 400, PROHIBITED_CONTENT $0.0000075
Vertex, Yoda 200, 0 images 400, IMAGE_PROHIBITED_CONTENT $0.0041625
Python SDK, 6 calls 6 return 0 images 6 raise 400
Gemini refusal, fallback serves 200, 0 images 200, 1 image $0.1370575
Vertex refusal, fallback serves 200, 0 images 200, 1 image $0.1395265
Served Gemini generation 1 image 1 image $0.043407
Served Vertex generation 1 image 1 image $0.041847
Served Gemini edit 1 image 1 image $0.0377355
Served Vertex edit 1 image 1 image $0.0367455
Commands and output at 81527af

The real provider rows come from t81527-output.out, printed by the real leg, and this round's legs are in t81527-legs.txt. Each case makes a new key and sends this request

$ curl -s -o out.json -D headers.txt http://127.0.0.1:$port/v1/images/generations \
    -H "Authorization: Bearer $key" -H 'content-type: application/json' \
    -d '{"model": "vertex-image", "prompt": "turn this person into Yoda"}'
lfr7 refusal-vertex http=400 images=0 cost_header=0.0041624999999999995 key_spend=0.0041625 rows=[failure:vertex_ai/gemini-nano-banana-2.1:0.0041625:5+554]

The reporter's SDK call, three times per model, from before and after

$ python sdk_leg.py gemini/gemini-2.5-flash-image gemini/gemini-nano-banana-2.1
1f7098c gemini/gemini-2.5-flash-image 1 returned images=0
1f7098c gemini/gemini-nano-banana-2.1 1 returned images=0
81527af gemini/gemini-2.5-flash-image 1 raised ImageRefusalError status=400
81527af gemini/gemini-nano-banana-2.1 1 raised ImageRefusalError status=400
What 81527af fixes, against 16291f0

These ran on a local scripted upstream and in-process router probes, from t81527-output.out

Case 1f7098c 16291f0 81527af
Prometheus failures, 20 failed calls 20 10 20
Latency penalties, 20 timeouts 20 10 20
Least-busy count after failed retries 0 1 per deployment 0
Least-busy override, served 0 1 0
Least-busy override, failed 0 1 0
Private refusal row stores prompt no yes no
Private 500 row stores prompt yes yes no
Image read timeout row $0 $0.000055 $0

Real Gemini and Vertex also ran the two paths that were scripted before. A refusal retried in its group billed both attempts, at 10 prompt tokens and $0.000015 on Gemini, and $0.0089025 to $0.0118125 on Vertex. A deployment's callbacks and Langfuse key applied on a real served image and a real refusal

What 16291f0 fixes, against 4963e99

Retries and logging ran on a local scripted upstream, from t16291-scripted.out and the callback output at 4963e99 and 16291f0

Case 4963e99 16291f0
Refused, retry served $0.0387135 $0.0423765
Refused twice $0.003663 $0.007326
turn_off_message_logging, success prompt logged redacted
turn_off_message_logging, failure prompt logged redacted
Deployment callbacks do not fire fire
Deployment Langfuse key None deployment's key
Three broken deployments 500, 429, 429 500, 429, 429
Upstream calls 1 per deployment 1 per deployment
Fallback billing on a scripted upstream at 81527af
Case Generation Edit
Text-only answer, then served $0.038832 $0.038832
Blocked prompt, then served $0.038727 $0.038727
Recitation refusal, then served $0.0387135 not run
Served with no failure $0.0387135 $0.0387135
Two failed attempts, then served $0.0388455 $0.0388455
No fallback left 422, $0.000132 422, $0.000132
Real refused edits with a fallback at 16291f0

All 32 refused edits with a fallback configured ended 400, from these, these and these rows. The fallback ran and refused too. OpenAI answered moderation_blocked, and Gemini to Vertex failure rows bill both attempts, at 2252 prompt tokens for two 1126 token attempts. At f646616 a real Gemini fallback served one, in the 66e1012 and 706f674 cases above

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • IMAGE_RECITATION now logs $0, undoing fix(vertex_ai): bill gemini image edits by token usage #51038's billed input tokens, backed only by Google's per-request message
  • Gemini image refusals through OpenRouter still answer an empty 200, which is tracked separately, and Imagen has the same gap
  • With fallbacks set, a refused or empty answer now runs the next fallback, an upstream call the base never made
  • After a fallback, a billed refusal's cost lands on the served model's row, so per-model spend shifts

Low

  • OpenAI SDK clients will not retry the new 422, since the SDK retries only 408, 409, 429 and 5xx
  • A refused image generation health probe now counts as healthy, as edit probes did, except OpenAI's moderation_blocked
  • The blockReason answer is proven only against a scripted Gemini, since real Gemini never sent one
  • A refused attempt that a same-group retry then serves is proven only on a scripted upstream, while real refusals retried twice billed both attempts
  • An image timeout logs $0 on this line and an estimated input cost on main
  • The base's empty Vertex generation hides its finish reason, so that before row is not proven to be the same recitation refusal
  • Gemini served the recitation prompt at 81527af, so its generation refusal was last seen at 4963e99
  • As on the base, a deployment's callbacks join the process-wide callback lists
  • Main has the same deployment logging gap before and after fix(gemini): return an error instead of an empty 200 when a Gemini image request gets no image #29125, and it is tracked separately
  • A failed request from a no-log key still stores its prompt on the failure spend row, as on the base, and that is tracked separately. Refusals now reach that row too, since they are failures
  • A logging callback that sums response_cost over failure and success events counts a refused attempt twice after a served fallback, as on main, and the fix is tracked separately in shared logging
  • When a refused image's fallback then fails another way, its failure row and Prometheus spend can name a deployment that billed nothing, though the total is right
  • A refused image through a pass-through route to another LiteLLM proxy still bills the outer key what the inner proxy's cost header reports, now on a failure row
  • A pre-existing gap went to security engineering
  • A failed image fallback's failure row names the backup's model, and on edits its group, where the base named the first, since each attempt applies its own deployment's settings
  • A billed refusal no longer raises a model access group's live spend counter on this line, and a follow-up is filed
  • With token reservation on, a fallback's tokens count toward the requested model's limit on the key, and with it off an edit fallback's count toward none, and that is tracked separately
Decisions
  • Refusals are a blockReason or any finishReason litellm already maps to content_filter for chat, which is IMAGE_RECITATION, IMAGE_SAFETY, IMAGE_PROHIBITED_CONTENT, SAFETY, RECITATION, PROHIBITED_CONTENT, BLOCKLIST, SPII and ESCALATION, and they answer 400
    • NO_IMAGE, IMAGE_OTHER, OTHER and LANGUAGE carry no policy verdict, so they get the 422
    • The 400 and 422 carry the call id and cost headers, but not x-litellm-model-id, the other deployment headers or an edit's rate limit headers, which the base's 200 carried
    • Every blockReason, OTHER included, counts as a refusal, since Google documents each value as a reason the prompt was blocked
  • No image without a refusal answers 422, not 502 or 400
    • The router retries a 502 twice by default, so one empty answer becomes three upstream calls
    • A 400 would label it a policy refusal it is not
    • OpenAI SDK clients do not retry a 422 either. A 5xx would make the SDK and the router each retry, and every retry bills its tokens again
  • Every answer without an image bills its tokens on the failure log, except an IMAGE_RECITATION refusal, which logs $0
    • Google's billing page waives only requests that fail with HTTP 400 or 500, and these answers come back as HTTP 200
    • Only the IMAGE_RECITATION message says the request is not charged. The IMAGE_SAFETY message says only that blocked images are not charged, and the billed tokens hold no image
    • So every other answer keeps the billing main already gave it
    • The alternative was $0 for every refusal, which drops a charge Google still makes
    • This undoes fix(vertex_ai): bill gemini image edits by token usage #51038, which billed IMAGE_RECITATION at its input tokens. Google's answer says "You will not be charged for this request", and this run had no Cloud Billing export to check one request by its labels, so that message is the evidence used
    • The alternative was to keep fix(vertex_ai): bill gemini image edits by token usage #51038's charge, which bills a request Google says it does not charge
    • When a configured fallback then serves the request, its success row also bills any attempt Google charged for, on the header, the spend row and the key
    • Billing only the served answer would hide a charge Google made
  • An image generation failure now gets a failure spend row, and an image timeout stays at $0 on this line, as on its base
    • The generations route now carries its logging object, which the refusal billing needs
    • Main logs LiteLLM's prompt estimate for the same timeout. The alternative was to match main, which would start charging keys on this line for timeouts that were free before the upgrade
  • An IMAGE_RECITATION failure row shows LiteLLM's own prompt estimate at $0 on generations and 0 tokens on edits, not Gemini's token counts
    • Failure rows take Gemini's usage only for work that is billed, like a cut-off stream
    • The alternative was Gemini's counts at $0, which no other failure row does
  • Configured fallbacks run on a refusal or a 422 like on any other error
    • Fallbacks are opt-in, so the operator already chose to send a failed request to another model
    • The router's default retries are not opt-in, which is why neither error is retried
    • The alternative was to skip fallbacks for these errors, which ignores the operator's config
  • This line sends n to Gemini as candidateCount in one call, with no image fan-out, so a request fails only when no candidate holds an image
  • The 422 names only the finishReason, and its response body keeps only finishReason and finishMessage, so the model's text never reaches the error or the logs
    • The alternative was to echo the text, which can carry the prompt into logs and alerts
  • An image next to a refused candidate is still returned, so only an answer with no image at all fails
  • An error answer's x-litellm-response-cost header reports what its failure spend row bills, on every route that goes through the shared error handler, where it used to say 0 unless the call had a finalized cost
    • The alternative was to keep 0, which tells a client that a billed failure was free
    • Image generations used to send no cost header on an error. They now send one only when the failure billed more than $0, and image edits keep their existing header
  • An image health probe that gets a refusal or an answer without an image counts as healthy, since the deployment answered, as edit probes already did on this line. An OpenAI moderation_blocked refusal still counts as unhealthy, as on main
    • The alternative was unhealthy, which takes a working deployment out of routing because of the probe's prompt
  • A refusal or an answer without an image never cools a deployment, never counts toward its failure rate or the Slack daily report's failed requests, and sends no Slack exception alert, whatever allowed_fails_policy says, since the deployment answered
    • It also drops out of the Slack daily report's latency section, which reads only successes, where the base counted these answers as 200s
    • The alternative was the rule for other content policy 400s, where a few refusals plus a timeout cool every healthy deployment and turn on dynamic rate limits
  • A billed refusal counts once toward the deployment, provider, tag, key model and session budgets of the model that refused, and a fallback's success row counts only its own cost there
    • The alternative was counting budgets only on success, which lets refused requests run past a budget while Google bills them
  • An answer without an image also counts its tokens toward the deployment's tpm and itpm limits under usage-based-routing-v2 and enforce_model_rate_limits, and toward the router's model group usage, as the base did when these answers were 200s
    • Under enforce_model_rate_limits its itpm counts the refusal's real prompt tokens, while a served image counts only the pre-call estimate, as on the base, since this line cannot read an image response's usage there
    • That holds on a deployment priced at $0 too, since a limit counts tokens, not cost, and on sync calls and fallback attempts
    • An IMAGE_RECITATION refusal logs no Gemini usage, so it counts no tokens and gives back its token reservation, where the base counted Google's token counts
    • The alternative was counting only successes, which keeps sending billed calls past the limit the operator set
  • A billed refusal also counts its tokens toward the key, team and user tpm and itpm limits, with or without token reservation and also when it has no output tokens, as on main, and a served fallback counts only its own tokens toward its deployment's tpm
    • The alternative was counting only the served answer, which lets a key send billed refusals past its limit
  • Every failed image edit through the proxy now counts 1 request toward its model group's rpm usage, as failed generations already did, since the router now reads the edit's litellm_metadata
  • A refusal follows content_policy_fallbacks like every content policy error, so when that setting names only other groups, generic fallbacks do not run
  • A refused image through a pass-through route to another LiteLLM proxy still bills the outer key what the inner proxy's cost header reports, now on a failure row
    • The alternative was to skip billing every pass-through 4xx, which changes billing for every provider's client errors
  • An image router 429 now runs the failure log, as chat does, and a refusal is not cached, like every error
  • A failed image health probe that the provider billed writes a failure spend row under the health check key, through the legacy spend logger, this line's only spend writer, with the same cost a caller's request logs
    • This line logged these answers as a success row, and a healthy probe with no row would hide what Google charged
    • An IMAGE_RECITATION probe costs $0, so it writes no row, and a deployment priced only by its litellm_params still prices its probe at $0, as on main
  • When a fallback serves the request, a billed attempt's cost and tokens go on the served model's success row
    • Total spend is right, and per-model spend moves to the served model
    • The alternative was a separate row per failed attempt, but the existing separate rows serve only failure rows for timed-out attempts
  • The spend collector reads those billed tokens from the event's existing usage field
    • The alternative was a new event field, which an older collector rejects during a rolling upgrade because SpendEvent forbids unknown fields
  • A fallback with no price keeps the failed attempt's charge
    • The alternative was to bill the request as unpriced, which hides a charge Google made
  • When a fallback refuses or answers without an image after an earlier model failed another way, the client gets that refusal or 422, not the earlier error
    • The alternative was the earlier 5xx, which the OpenAI SDK retries, so the whole chain ran and billed 3 times
  • That fallback's failure row, Prometheus spend and request labels go on the fallback deployment that answered, and its own success and total deployment counters count it
  • When more than one model in a chain refuses or answers without an image, the client gets the first refusal or 422, and its row carries every billed attempt's charge, under the last model that failed, since this line logs the last attempt where main logs the one the client saw
  • A fallback that refuses or answers without an image counts in litellm_deployment_failed_fallbacks_total, where the base counted it as successful, since the client gets an error. A fallback that serves the request still counts as successful
  • A refusal or an answer without an image keeps the request's custom Prometheus metadata labels on its counters, as the base did when these answers were 200s, except for a no-log request
  • A no-log request's billed refusal writes its failure row and charges the key, as any billed failure does, where the base wrote no row and charged nothing for its 200
    • It adds nothing to the Prometheus spend and token counters, as the base did when these answers were 200s, and its request and failure counters still count it, as for any failed no-log request
  • With disable_error_logs on, a failure the provider billed still writes its failure spend row and raises the budget counters, as on main since fix(spend): retain billed failure accounting when error logs are disabled #53271
    • That covers a billed refusal, a chat timeout's prompt estimate and a cut stream's recovered usage, which the base charged only with error logs on
    • The alternative was to keep those failures free when error logs are off, which lets billed requests run past a budget
  • A refusal while Redis is down leaves the key's live spend counter at the request's budget reservation until that reservation expires, as every other failed request does on this line, since releasing it needs Redis
  • Each router attempt on the shared logging object follows its own deployment's turn_off_message_logging, Langfuse keys and callbacks, and settings from the request or key still win
    • The alternative was one setting per request, which logs a private deployment's prompt after a fallback from an open one
  • Each router attempt runs the failure log again, so retries still count in metrics, cooldowns and latency routing, as on the base
    • The alternative was one failure event per request, as on main, which would halve those counts on a stable line
  • A failure spend row takes only turn_off_message_logging: true from the attempt's deployment
    • The alternative was lifting all of the deployment's logging settings, which would pass its callback credentials to every failure hook
  • A same-group retry keeps each refused attempt's charge, as main does, so the row that ends the request bills every attempt
    • The alternative was billing only the last attempt, which hides charges Google made
  • Each charged failure row with a cost raises the live key, team, user, end-user, org, project and tag spend counters, as on main since fix(proxy): raise live budget counters for failure spend rows #47741, and the error waits at most a second for them
    • The alternative was to leave them to the database reseed, which let a burst of billed refusals run past a key, team or tag max_budget
  • A refusal or an answer without an image sets the deployment's litellm_deployment_state to 0 and counts in litellm_deployment_success_responses_total, as the base did when these answers were 200s, so success plus failure still adds up to the deployment's total
    • litellm_proxy_total_requests_metric_total now labels these requests with the error's status code where the base labeled them 200, since that is what the client gets
    • Like any failed request, they count in the LLM API failed request counter and no longer in litellm_requests_metric_total, and their deployment success sample has no api_provider label
    • They no longer set the deployment's litellm_remaining_requests_metric and litellm_remaining_tokens_metric gauges, which only a success sets. The alternative was to set them from these failures, which no other failure does
  • Imagen (predictions) responses and Gemini chat answers are unchanged, apart from the error cost header
Refuted bot findings
  • A served fallback image with no usage, like DALL-E's, still adds the refused attempt's spend to its success row, since ImageResponse turns a missing usage into a zero one, see utils.py and the thread
  • A deployment's callbacks join the process-wide lists on the base too, see utils.py and the thread

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
Bugbot summary

[!NOTE]
High Risk
Touches end-to-end billing, budget and rate-limit settlement, router fallbacks, and metrics—mis-counting or double-billing would affect production spend enforcement.

Overview
Gemini and Vertex image generation/edit now raise ImageRefusalError (400) or UnservedImageError (422) when the provider returns no image, instead of a 200 with data: []. A new empty_image_response path parses Gemini blockReason / finishReason, bills usage on the failure path where Google still charges (except IMAGE_RECITATION at $0), and wires that through the Gemini and Vertex image transformations.

Proxy and routing behavior changes broadly: failure responses can include cost headers and failure spend rows (including when disable_error_logs is on), fallbacks surface the refusal/422 after an earlier 5xx, and failed router attempts can roll billing into the attempt that finally serves. IMAGE_ANSWER_ERRORS are treated as client errors—not deployment outages—so cooldowns, many Slack alerts, and deployment failure metrics skip them while TPM/RPM, budgets, and Prometheus still account for billed tokens where appropriate. Per-attempt logging and deployment callback settings apply on shared image router attempts; health probes treat refusals as healthy but can log billed probe failures.

Reviewed by Cursor Bugbot for commit f646616. Bugbot is set up for automated code reviews on this repo. Configure here.

hclsys and others added 14 commits November 20, 2026 16:19
Image-gen transforms iterated candidates[].content.parts[] for inlineData
and ignored finishReason, so an IMAGE_SAFETY / IMAGE_PROHIBITED_CONTENT
block returned an empty ImageResponse with no exception. The chat path
already surfaces these (get_flagged_finish_reasons + ContentPolicyViolationError);
mirror that for image gen by raising on a flagged finishReason when no image
data was produced. Covers gemini/ and vertex_ai/ via one shared helper.

Fixes BerriAI#28989

(cherry picked from commit 8025767)
promptFeedback.blockReason with no candidates now raises
ContentPolicyViolationError like a flagged finishReason, and the gemini/
and vertex_ai/ image-edit transforms use the same check when they return
no image.

(cherry picked from commit 93161b5)
…i image errors

The Gemini image fix picked next builds its 400 and 422 responses with
error_response_without_credentials, which main added in BerriAI#49079 and the LTS line
does not have. This copies that helper and its three private helpers verbatim from
main's litellm/exceptions.py, without the rest of BerriAI#49079, so the error's
response.request keeps no api key query param, userinfo or auth headers
…age request gets no image

A refused image or a blocked prompt answers 400 content_policy_violation with
Gemini's finishReason and finishMessage, or its blockReason. Any other answer
without an image answers 422 with the model's text. Both cover AI Studio and
Vertex on image generations and image edits, and neither is billed or retried

(cherry picked from commit c299b71)
…of the 422

A Gemini or Vertex image answer without an image and without a refusal still bills its tokens on the failure log, as main billed the empty 200. Refusals and blocked prompts stay at $0. The 422 message names only the finishReason, so model output never reaches the exception text or logs

(cherry picked from commit 903c646)
…ext out of the 422 body

This takes the parts of the source commit that apply to the LTS line. OTHER and
LANGUAGE now answer 422 like IMAGE_OTHER, the 422's response body keeps only
finishReason and finishMessage, and UnprocessableEntityError's params are typed

The n above 1 fan-out billing (litellm/images/fan_out.py and its four handler
sites) is left out because the LTS image handlers send one upstream call. The
transformation keeps billing a no-image answer through logging_obj as before

(cherry picked from commit 6da0621)
…le charges for

Google charges for an image refusal or a blocked prompt that comes back
as HTTP 200, except IMAGE_RECITATION, whose answer says the request is
not charged. The transformation now bills those tokens on the failure
log through logging_obj, the way it already bills a no-image answer, and
the refusal still raises a 400 ContentPolicyViolationError

This adapts the source commit to the LTS line. LTS has no n above 1
fan-out, so ChargedImageRefusalError, the litellm/images/fan_out.py
change and the fan-out test cases are left out. LTS image usage does not
read cachedContentTokenCount, so the token details test checks reasoning
tokens only

(cherry picked from commit 9adec36)
… 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.
…mage health probes healthy

A failed image request that bills tokens now answers with an
x-litellm-response-cost header that matches its failure spend row. The
generations route sent no cost header on errors, and errors that went
through the shared error handler reported 0 unless the logging object
had a finalized cost

The image_generation health probe now counts a refusal or a Gemini
answer without an image as healthy, like the image_edit probe already
did for refusals, so a refused probe prompt does not mark the
deployment unhealthy

This adapts the source commit to the LTS line. LTS has no
failure_row_response_cost, so the failure spend row's inline cost moves
into one with that name, without main's finalized-cost branch, which
LTS does not have. LTS's empty-answer 422 was a plain
UnprocessableEntityError, so it becomes an UnservedImageError subclass
for the health probe to recognize, without main's billed_answer, since
LTS bills the answer through the logging object. The agentic follow-up
test change has no LTS counterpart

(cherry picked from commit 1c7f26a)
… refused attempt's usage off its fallback's success log
A health probe that the provider billed but that ends in an image error now writes a failure spend row under the internal health check key, and the text-only Vertex integration cases expect 422 with the same spend
… log when falling back

A stream request logs a failed attempt in the background, so setting that attempt's usage aside before the fallback raced the log and could bill the broken attempt at $0. Only non-stream requests, whose failure log has already run, set the usage aside.
@izzybn
izzybn requested a review from a team November 21, 2026 21:32
@veria-ai

veria-ai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

This PR updates the lts/1.108.x Gemini image request path to return an error instead of an empty HTTP 200 when no image is produced, with related changes to failure handling, callbacks, and usage accounting.

Six issues have been addressed, but three remain open. Deployment-specific callbacks can receive other deployments’ request events, potentially exposing data to unintended logging destinations. Accounting gaps also let callers avoid spend-budget consumption on billed image timeouts and token-limit consumption on recitation refusals with reported usage.

Open issues (3)

Fixed/addressed: 6 · PR risk: 7/10

Reviews

@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

…s the request

A billed text-only or blocked answer was dropped from spend once a fallback returned the image. The line has no way to carry that cost to the served attempt, so this adds a narrow one for the cost header, spend row and key spend
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@greptile-apps

greptile-apps Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[High impact] The reviewed changes appear safe to merge, with no new blocking finding

Summary

Gemini and Vertex image calls now return a policy error or a 422 when no image is returned. The changes also carry billed usage through retries and fallbacks, update spend and token counters, and keep answered refusals from marking deployments unhealthy

No new reportable issue was established. The previous-review merge bases differ, so the full PR diff was reviewed. No tests or live requests were run during this review

  • Gemini image calls return a refusal or no-image error when no image is produced.
  • Configured fallbacks can replace image errors, and their billed attempts stay accounted for.
  • Failure spend rows and error headers include the cost of billed image attempts.
  • Billed image refusals count toward the limits and budgets that track provider usage.
  • Image answers without images stay visible as provider responses, not deployment outages.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Gemini or Vertex image answer] --> B{Contains an image?}
    B -->|Yes| C[Return image]
    B -->|No| D{Policy refusal?}
    D -->|Yes| E[400 error]
    D -->|No| F[422 error]
    E --> G[Record billed usage except IMAGE_RECITATION]
    F --> G
    G --> H{Configured fallback?}
    H -->|Yes| I[Try fallback and retain earlier charges]
    H -->|No| J[Return error with billed cost]
Loading

Reviews (17) · Last reviewed commit: "Merge remote-tracking branch 'origin/lts..." · Reviewed by Greptile

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…efusal charges

A Logging object shared across router attempts now applies each deployment's redaction, Langfuse keys and callbacks. A same-group retry keeps the refused attempt's charge on the served or failed row
return deployment_fields
deployment_callbacks: Final = configured_callbacks(deployment_fields.get("callbacks"))
if deployment_callbacks is not None:
register_dynamic_callbacks(deployment_callbacks)

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.

Medium: Deployment callbacks become process-wide

With litellm_params.callbacks=[logger_for_A] on deployment A, this call permanently adds that logger to the global input, success, and failure callback lists; subsequent requests to deployment B also reach it through the global callback dispatch, even when B configures no such logger. Keep deployment callbacks on the current attempt's Logging object rather than registering them globally, so deployment-specific logging destinations remain isolated.

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.

The LTS base does the same, since function_setup at 1f7098c adds deployment callbacks to all five global lists, so this PR changes nothing here

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.

Base evidence: function_setup adds each request's callbacks to all five global lists here, so this PR changes nothing

litellm/litellm/utils.py

Lines 1051 to 1075 in 1e96f26

dynamic_callbacks: Final[list[str | Callable | CustomLogger] | None] = kwargs.pop("callbacks", None)
all_callbacks: Final = get_dynamic_callbacks(dynamic_callbacks=dynamic_callbacks)
if len(all_callbacks) > 0:
for callback in all_callbacks:
# check if callback is a string - e.g. "lago", "openmeter"
if isinstance(callback, str):
callback = litellm.litellm_core_utils.litellm_logging._init_custom_logger_compatible_class(
callback,
internal_usage_cache=None,
llm_router=None,
)
if callback is None or any(
type(cb) is type(callback) for cb in litellm._async_success_callback
): # don't double add a callback
continue
if callback not in litellm.input_callback:
litellm.input_callback.append(callback)
if callback not in litellm.success_callback:
litellm.logging_callback_manager.add_litellm_success_callback(callback)
if callback not in litellm.failure_callback:
litellm.logging_callback_manager.add_litellm_failure_callback(callback)
if callback not in litellm._async_success_callback:
litellm.logging_callback_manager.add_litellm_async_success_callback(callback)
if callback not in litellm._async_failure_callback:

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…meouts out of billed rows

Each router attempt now runs its own failure log, so retries count toward metrics, cooldowns and latency penalties. Request-bound routing callbacks survive the per-deployment reset, failure rows honor a private deployment, and image timeouts stay at $0 as on the base.
… tpm limits, log refusal spend under the requested model, and keep refusals out of the Slack failed-request report
…ync calls

A billed image refusal on a sync call now counts its answered tokens
toward the deployment's tpm limit under enforce_model_rate_limits and
usage-based-routing-v2, as the async path already did.

Adapted for lts/1.108.x. This line has no Rust router, so the fallback
half of the main commit has no counterpart, since a fallback attempt here
already runs the async failure hook. This line runs the sync failure hook
for an async image edit too, so both hooks skip the async image call
types, which the async hook counts already.

(cherry picked from commit f152706)
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

# Conflicts:
#	litellm/proxy/spend_tracking/spend_event.py

def _bill_refusal(reason: str, billing: FailedImageBilling, answer: ImageResponse) -> None:
if reason in _REFUSALS_GOOGLE_DOES_NOT_CHARGE:
return

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.

Medium: Uncharged refusals skip TPM accounting

When IMAGE_RECITATION includes nonzero usageMetadata, this return discards the tokens along with the charge. The failure logging payload consequently reports total_tokens=0, so the new rate-limit hooks never debit deployment TPM limits for these requests; preserve the reported usage with a zero response cost so repeated recitation refusals still consume the token allowance.

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.

Google says IMAGE_RECITATION is not charged, so it logs no usage and counts no tokens, as on main, which the body's Decisions record

…usage and keep a served fallback's reservation
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

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.

response_cost: Final[float] = success_cost_without_failed_image_answers(
kwargs, # pyright: ignore[reportUnknownArgumentType] # callback kwargs are untyped
standard_logging_payload.get("response_cost", 0),
)

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.

Refusals skip key model budgets

Medium Severity

A billed Gemini image refusal no longer raises model_max_budget. The success path subtracts image_answers_billed_on_failure, but unlike the deployment, tag, and session limiters this hook never charges that cost on failure. Refusals used to count as 200s; they now miss the key's per-model budget entirely.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit c4e3e6f. Configure here.

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.

This subclass inherits RouterBudgetLimiting.async_log_failure_event, which charges billed refusals, see

async def async_log_failure_event(
self, kwargs: Mapping[str, object], response_obj: object, start_time: object, end_time: object
) -> None:
if image_answer_cost_on_failure(kwargs) > 0:
await self.async_log_success_event( # pyright: ignore[reportUnknownMemberType] # legacy callback signature is untyped
kwargs, response_obj, start_time, end_time
)
, and test_a_billed_image_refusal_counts_once_toward_the_key_budget_of_the_model_that_refused fails when the subclass overrides it

pass
else:
self.model_call_details["response_cost"] = self.response_cost_calculator(result=logging_result)
self._add_failed_attempts_spend(logging_result, image_usage)

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.

Priced success drops owed attempt spend

Medium Severity

_add_failed_attempts_spend runs after cache hits, hidden-param costs, and freshly calculated costs, but not when a non-zero response_cost is already on the logging object. A served fallback that already priced itself (the pass-through path this branch calls out) never merges the refused attempt into response_cost or combined_usage_object, so the spend row under-bills while the cost header can still include the owed amount.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit c4e3e6f. Configure here.

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.

A refused attempt's spend is carried only for non-streamed image refusals, see

def _set_aside_failed_attempt_spend(logging_obj: Logging | None) -> _FailedAttemptSpend | None:
if logging_obj is None or _failure_logged_in_background(logging_obj):
return None
usage: Final = logging_obj.model_call_details.get("combined_usage_object")
if not isinstance(usage, Usage):
return None
response_cost: Final = logging_obj.model_call_details.get("response_cost")
logging_obj.model_call_details.pop("combined_usage_object")
logging_obj.model_call_details.pop("response_cost", None)
spend: Final = _FailedAttemptSpend(usage, _known_cost(response_cost))
logging_obj.owe_failed_attempt_on_success(spend.usage, spend.response_cost)
return spend
, and their image fallback is priced by branches that add it

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…tion off, count a sync refusal toward model group usage, and give back an unbilled recitation's reservation

Ports 7cebd6a by hand, since this line has no Rust limiter. With token
reservation off the Python limiter now counts a billed refusal's tokens toward the
key, team and user tpm limits the way it counts a served answer. A recitation bills
nothing, so it no longer settles as a billed answer and gives back its deployment
otpm reservation. A sync image refusal now also counts toward its model group usage,
which only the async failure hook did before.
# Conflicts:
#	litellm/proxy/utils.py
#	litellm/router_utils/fallback_event_handlers.py
#	tests/unit/router_utils/test_fallback_event_handlers.py
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

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.

return
own_usage: Final = image_usage or get_usage_object(completion_response=served_response)
if own_usage is None:
return

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.

Served fallback can drop refused spend

Medium Severity

_add_failed_attempts_spend returns immediately when the serving response has no usable usage, so billed Gemini refusals set aside for a later fallback never land on the success spend row. A fallback that serves an image without usage, such as DALL-E, keeps the header path able to add owed cost while the spend row, key spend, and combined token columns omit the refused attempt.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit f646616. Configure here.

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.

False positive. ImageResponse turns a missing usage into a zero ImageUsage, so a served DALL-E image still adds the refused attempt's spend:

litellm/litellm/types/utils.py

Lines 2829 to 2837 in f646616

_usage: Final = usage or ImageUsage(
input_tokens=0,
input_tokens_details=ImageUsageInputTokensDetails(
image_tokens=0,
text_tokens=0,
),
output_tokens=0,
total_tokens=0,
)

@mateo-berri

Copy link
Copy Markdown
Contributor

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.

✅ Bugbot reviewed your changes and found no new issues!

3 issues from previous reviews remain unresolved.

Fix All in Cursor

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit f646616. Configure here.

@mateo-berri mateo-berri 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.

LGTM

@mateo-berri
mateo-berri merged commit db8e36e into BerriAI:lts/1.108.x Nov 25, 2026
65 checks passed
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.

5 participants