Repository navigation
fix(gemini): return an error instead of an empty 200 when a Gemini image request gets no image on lts/1.108.x - #53429
Conversation
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)
…mini_image_finish_reason
… 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.
PR overviewThis 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 Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
…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
[High impact] The reviewed changes appear safe to merge, with no new blocking finding
|
…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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Base evidence: function_setup adds each request's callbacks to all five global lists here, so this PR changes nothing
Lines 1051 to 1075 in 1e96f26
…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)
# Conflicts: # litellm/proxy/spend_tracking/spend_event.py
… after a billed image refusal
|
|
||
| def _bill_refusal(reason: str, billing: FailedImageBilling, answer: ImageResponse) -> None: | ||
| if reason in _REFUSALS_GOOGLE_DOES_NOT_CHARGE: | ||
| return |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
… earlier hop settled the reservation
|
bugbot 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), | ||
| ) |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit c4e3e6f. Configure here.
There was a problem hiding this comment.
This subclass inherits RouterBudgetLimiting.async_log_failure_event, which charges billed refusals, see
litellm/litellm/router_strategy/budget_limiter.py
Lines 577 to 583 in c4e3e6f
| pass | ||
| else: | ||
| self.model_call_details["response_cost"] = self.response_cost_calculator(result=logging_result) | ||
| self._add_failed_attempts_spend(logging_result, image_usage) |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit c4e3e6f. Configure here.
There was a problem hiding this comment.
A refused attempt's spend is carried only for non-streamed image refusals, see
litellm/litellm/router_utils/fallback_event_handlers.py
Lines 80 to 91 in c4e3e6f
…ep no-log labels off its counters
…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
|
bugbot run |
| return | ||
| own_usage: Final = image_usage or get_usage_object(completion_response=served_response) | ||
| if own_usage is None: | ||
| return |
There was a problem hiding this comment.
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.
Reviewed by Cursor Bugbot for commit f646616. Configure here.
There was a problem hiding this comment.
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
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
3 issues from previous reviews remain unresolved.
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit f646616. Configure here.


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:
data: []and no reason, and is still billedHow it solves it:
finishReasonIMAGE_RECITATIONat $0User Flow
Before: a refused Gemini image comes back as a 200 with no image or reason, and is still billed
IMAGE_RECITATION, and the proxy answers 200 with"data": []x-litellm-response-costheader and https://litellm-domain/spend/logs show a chargeAfter: the same refusal comes back as an error that says why, at $0
ContentPolicyViolationErrornamingfinishReason=IMAGE_RECITATIONand Google's "You will not be charged for this request" messageRelevant 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,bfaff0b1e80and9a46606880eare main only, and #29125's merges ofmainare not picked80257675c89f1563317379finishReasonon generation safety blocks93161b54dc23343bcb2fe5c299b71c15243c1f5262d4903c646c35ddb85ae41aab6da062156e66e4189e4182OTHERandLANGUAGE9adec36a89c5ecb0d628e11c7f26ae39c0e3edfa32497d727945194bb44ced6e8f9560d7b0249,50a923547483697ccd589c9d26d75688b3d2105db2274963e99e5958ad5e2684961e448c2fd8d476eeb59914eb2c026cf7f,8a58030368a1f5e8bdc5df4ba734e90cd,336aceed4d2,83ead6faaf9f7b07f812cbfad3daaf875489f685d47a8b0a4635633198d52b027eda9679d3f85,f497f2c9738no-logspend1277be6ffa10c596b95b1020fadb7af280e27c22c9eef15270604c814c77add7804472b4c86774a2c4cc0d7728da7e2f760,abf685bdf22cfd3899f3e1and9a46606880e1970a317131e9c3e1da857428644572b6c4e3e6fbcd2Final982b99c8469nfan-out toward model group usagecc572bd45c666e10121f9dno-logrefusal's request counters7cebd6ab113706f674356atpmwith reservation off, and give back a recitation's reservation71bb099f896andbfaff0b1e80itpmon every fallback attempt under an output limit4496778bfad,7f9df4f1e00,16291f02afd,81527aff254,78355a583acFour commits copy prerequisites from main
ec9f88acd7cerror_response_without_credentialsand its three private helpers, verbatimf977f2b78bfb94967d8319965eeb76e64disable_error_logson, all but the Rust spend ledger testWhere the picks differ from main
In the Gemini edit transformation the parsed response is named
response_jsonon this line andpayloadonmain, soc299b71c152and903c646c35deach callempty_image_response_errorwithresponse_json. Every other changed line in those two picks matchesmainThis line has no image fan-out (#52103), so one request is one upstream call.
6da062156e6and9adec36a89calso change the fan-out and its tests, and those parts are dropped. Here9adec36a89c's refusal billing goes through the failure-usage hook the transformation already calls for a no-image answerWithout 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 assertionThis line has no
failure_row_response_cost, so0e3edfa3249moves 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 plainUnprocessableEntityError, so it becomes anUnservedImageErrorsubclass for the health probe to recognize. The agentic follow-up test change has no counterpart here.7d727945194changes only main'snfan-out, and this line has none, since it sendsnto Gemini ascandidateCountin one call4496778bfadhas no main commit. It makes the generations route keep the request datafunction_setupreturns, 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'scarry_failed_attempt_usagedoes, 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, so7f9df4f1e00skips it for streams9d26d75688bports3697ccd589cby 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 change9560d7b0249portsbb44ced6e8fby 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, so50a92354748dates that row at its end time, as it already did when the time was missing4963e99e595ports3d2105db227and keeps request fields named likefunction_setup's own parameters, such asis_async_call, out of that call. It also made the router cool down later failed image attempts, which81527aff254replaces by logging each attempt16291f02afdhas no main commit. The generations route shares one logging object across router attempts, which skipsfunction_setupfor 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'scarry_superseded_attempt_usagedoes, so the row that ends the request bills every attempt81527aff254has 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 it1e448c2fd8dports8ad5e268496by 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 tokens78355a583achas 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 asideeb2c026cf7fports476eeb59914by 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.8a58030368agives 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 budgets4ba734e90cdand336aceed4d2port1f5e8bdc5dfby hand, and83ead6faaf9moves one line-only test to the bare label. A request field namedfailed_attempts_billed_on_successorimage_answers_billed_on_failureno 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 imagesThe 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_failsand 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 ano-logrequestb94967d8319picks #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 tagmax_budgetuntil 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 line965eeb76e64picks #53271, which this PR needs for the same reason, since withdisable_error_logson 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 owndisable_error_logsgateda9679d3f85picks198d52b027e's Prometheus half, so refused and empty answers keep the request's custom metadata labels and ano-logrefusal adds nothing to the spend and token counters. Its router half is in main's Rust router, which this line does not have, sof497f2c9738makes this line's Python router raise a fallback's refusal or 422 when the earlier error was something else, where it raised the earlier 5xx0c596b95b10ports1277be6ffa1. 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 attempt0e27c22c9eeports20fadb7af28by 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 notpdlimit. 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 asrequested_modeland the refused deployment asmodel_id14c77add780picksf15270604c8'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 already4472b4c8677only narrows the Rust router'sanswered_tokensfield for clippy, and this line has no Rust router28da7e2f760andabf685bdf22port4a2c4cc0d77by hand. Main counts a billed refusal's tokens toward key, team and usertpmin its Rust limiter, and this line has none, soabf685bdf22does it in the Python limiter, also when the refusal has no output tokens.28da7e2f760counts only a served fallback's own tokens toward its deployment'stpm, as main does. Two gaps only this line has are fixed inabf685bdf22too. A served fallback no longer gives back the key'stpmreservation 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 onlymetadataand edits carrylitellm_metadatacfd3899f3e1only stores the Rust router's exception classes as a boxed slice for clippy, and this line has no Rust routere9c3e1da857ports1970a317131by 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 keytpmlimit even after an earlier attempt of the same request settled the key's reservation.c4e3e6fbcd2annotates the new tests' bindings asFinal, as428644572b6does on main982b99c8469changes only main'snfan-out, and this line has none66e10121f9dpickscc572bd45c6and 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'stpm, since only the async failure log set them aside. The sync failure log now does it too706f674356aports7cebd6ab113by 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 usertpmlimits. AnIMAGE_RECITATIONrefusal bills nothing, so it gives back itsotpmreservation 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 had71bb099f896fixes main's Rust limiter, which skipped a later fallback attempt's input tokens undertoken_rate_limit_type: outputwhen the refusal had no output tokens. This line's Python limiter already counts every billed refusal toward projectitpmunder any limit type#29125 also merged
mainafter #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 keepseb2c026cf7f's own way of doing thatPre-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
Last updated: f646616, where what 66e1012 and 706f674 fix ran against c4e3e6f. e9c3e1d's key
tpmcases 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 gistrefused-backupalphaalphano-logrefusaltpm: 1000What 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-l2andk3-b0rfiles in the gist, and the sync rows from sync-sync-live-v2.outtpm, reservation off, one refusalIMAGE_RECITATIONgenerations,otpm: 40000IMAGE_RECITATIONedits,otpm: 40000no-logrefusal, custom label on countersBase 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_IMAGEanswer carries no usage, and at c4e3e6f one such answer left the model'sotpmcounter at 65536, so the next four never reached Gemini. Team PTU limits take the same path as the team case and were traced, not runtpm: 1000tpm: 1000tpm: 1000NO_IMAGEgenerations, modelotpm: 40000NO_IMAGEedits, modelotpm: 40000tpm: 100tpm: 100What 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
In e9c3e1d's cases a key's count should be the served tokens plus every refusal's 1110 tokens, from k2-e9c3e1d.out
These key limits and chains ran at abf685b, from a and w, and gave the same answers as main
tpm: 2000, 3 refusals of 1110 tokenstpm: 1000, refusal with no output tokens, generation or edittpm: 8, real Gemini refusalRate limit, sync and chain cases at 2818be7 and abf685b
The deployment has
tpm: 1000and each refusal bills 1110 tokens. Each request ran within one minute of the last, from thetpm,ftpm,syncandchainoutputs in the gistenforce_model_rate_limits, 3 requestsusage-based-routing-v2, 3 requestsIMAGE_RECITATIONRouter, both limitsrefuser-asuccess, $0.003663refuser-bfailure, $0.004163Budget smoke at 2818be7, 8b0a463 and 09b1d48
With
disable_error_logson, 5 refusals on a key withmax_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 09b1d48The 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
max_budget$0.008Real 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 agreePROHIBITED_CONTENT, failure rowIMAGE_PROHIBITED_CONTENT, failure rowPROHIBITED_CONTENTReal 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 agreePROHIBITED_CONTENTIMAGE_PROHIBITED_CONTENTWhat 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
gemini/prefixno-loggeneration fallback, third tryRecitation, 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
IMAGE_RECITATIONIMAGE_RECITATIONIMAGE_RECITATIONPROHIBITED_CONTENTIMAGE_PROHIBITED_CONTENTCommands 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
The reporter's SDK call, three times per model, from before and after
What 81527af fixes, against 16291f0
These ran on a local scripted upstream and in-process router probes, from t81527-output.out
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
turn_off_message_logging, successturn_off_message_logging, failureNoneFallback billing on a scripted upstream at 81527af
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 aboveType
🐛 Bug Fix
Caveats (if any)
Medium
IMAGE_RECITATIONnow 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 messagefallbacksset, a refused or empty answer now runs the next fallback, an upstream call the base never madeLow
moderation_blockedblockReasonanswer is proven only against a scripted Gemini, since real Gemini never sent onecallbacksjoin the process-wide callback listsno-logkey 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 failuresresponse_costover failure and success events counts a refused attempt twice after a served fallback, as on main, and the fix is tracked separately in shared loggingDecisions
blockReasonor anyfinishReasonlitellm already maps tocontent_filterfor chat, which isIMAGE_RECITATION,IMAGE_SAFETY,IMAGE_PROHIBITED_CONTENT,SAFETY,RECITATION,PROHIBITED_CONTENT,BLOCKLIST,SPIIandESCALATION, and they answer 400NO_IMAGE,IMAGE_OTHER,OTHERandLANGUAGEcarry no policy verdict, so they get the 422x-litellm-model-id, the other deployment headers or an edit's rate limit headers, which the base's 200 carriedblockReason,OTHERincluded, counts as a refusal, since Google documents each value as a reason the prompt was blockedIMAGE_RECITATIONrefusal, which logs $0IMAGE_RECITATIONmessage says the request is not charged. TheIMAGE_SAFETYmessage says only that blocked images are not charged, and the billed tokens hold no imageIMAGE_RECITATIONat 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 usedIMAGE_RECITATIONfailure row shows LiteLLM's own prompt estimate at $0 on generations and 0 tokens on edits, not Gemini's token countsfallbacksrun on a refusal or a 422 like on any other errornto Gemini ascandidateCountin one call, with no image fan-out, so a request fails only when no candidate holds an imagefinishReason, and its response body keeps onlyfinishReasonandfinishMessage, so the model's text never reaches the error or the logsx-litellm-response-costheader 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 costmoderation_blockedrefusal still counts as unhealthy, as on mainallowed_fails_policysays, since the deployment answeredtpmanditpmlimits underusage-based-routing-v2andenforce_model_rate_limits, and toward the router's model group usage, as the base did when these answers were 200senforce_model_rate_limitsitsitpmcounts 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 thereIMAGE_RECITATIONrefusal logs no Gemini usage, so it counts no tokens and gives back its token reservation, where the base counted Google's token countstpmanditpmlimits, 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'stpmrpmusage, as failed generations already did, since the router now reads the edit'slitellm_metadatacontent_policy_fallbackslike every content policy error, so when that setting names only other groups, genericfallbacksdo not runIMAGE_RECITATIONprobe costs $0, so it writes no row, and a deployment priced only by itslitellm_paramsstill prices its probe at $0, as on mainusagefieldSpendEventforbids unknown fieldslitellm_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 successfulno-logrequestno-logrequest'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 200no-logrequestdisable_error_logson, 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 #53271turn_off_message_logging, Langfuse keys and callbacks, and settings from the request or key still winturn_off_message_logging: truefrom the attempt's deploymentmax_budgetlitellm_deployment_stateto 0 and counts inlitellm_deployment_success_responses_total, as the base did when these answers were 200s, so success plus failure still adds up to the deployment's totallitellm_proxy_total_requests_metric_totalnow labels these requests with the error's status code where the base labeled them 200, since that is what the client getslitellm_requests_metric_total, and their deployment success sample has noapi_providerlabellitellm_remaining_requests_metricandlitellm_remaining_tokens_metricgauges, which only a success sets. The alternative was to set them from these failures, which no other failure doespredictions) responses and Gemini chat answers are unchanged, apart from the error cost headerRefuted bot findings
ImageResponseturns a missing usage into a zero one, see utils.py and the threadcallbacksjoin the process-wide lists on the base too, see utils.py and the threadFinal Attestation
Bugbot summary