Repository navigation
fix(budget-limiter): derive custom_llm_provider for /v1/messages and /v1/embeddings routes - #32180
Conversation
Greptile SummaryThis PR fixes silent budget-tracking failures on
Confidence Score: 4/5The change is narrowly scoped to a fallback path that only activates when custom_llm_provider is absent, so the existing /v1/chat/completions flow is untouched. The fix mirrors the pattern already used by _get_llm_provider_for_deployment, the tests cover the reported regression and the happy path, and the bare except Exception swallows derivation failures silently — making misconfiguration harder to diagnose but not introducing incorrect behavior. No files require special attention beyond the minor logging gap in the exception handler in budget_limiter.py.
|
| Filename | Overview |
|---|---|
| litellm/router_strategy/budget_limiter.py | Adds a fallback provider derivation step in async_log_success_event when custom_llm_provider is absent from litellm_params. Uses the same get_llm_provider helper already used by _get_llm_provider_for_deployment. Logic is sound; exception suppression lacks a log line. |
| tests/test_litellm/router_strategy/test_budget_limiter_provider_derivation.py | New mock-only test file with three focused regression tests. Correctly patches cache/DB calls with AsyncMock, asserts the increment path fires on provider match, and verifies the no-op path for an unconfigured provider. No real network calls. |
Reviews (1): Last reviewed commit: "fix(budget-limiter): derive custom_llm_p..." | Re-trigger Greptile
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 1 · PR risk: 0/10 |
… key
LoggedLiteLLMParams for /v1/messages and /v1/embeddings does not populate
the model field, so litellm_params.get('model') returns ''. This caused
get_llm_provider to fail silently and budget enforcement to be skipped
entirely — meaning API key holders could exhaust provider budgets via those
routes with no cap enforced.
Fix: extend the fallback chain to kwargs['model'] and then
standard_logging_payload['model'] before giving up.
Addresses review feedback from veria-ai on BerriAI#32180.
|
We hit this independently on v1.83.14-stable routing Claude Code traffic ( We backported this PR's change as a build-time patch and can confirm it fixes both: Redis counters accrue on |
|
Linking related issue #30276 which hits the same root cause (custom_llm_provider missing in async_log_success_event) via the embedding path. Also, @henricook has independently confirmed this fix resolves the issue on production with Claude Code traffic on /v1/messages. Happy to extend the fix to cover the embedding path as well if preferred. |
…ider
`/v1/chat/completions` injects `custom_llm_provider` into `litellm_params`, but
`/v1/messages` and `/v1/embeddings` do not. `RouterBudgetLimiting.async_log_success_event`
read it only from `litellm_params` and raised `ValueError("custom_llm_provider is
required")` before incrementing any spend counter, so provider budgets never
accrued on those routes. Deployment-level `max_budget` sits below the same guard,
so it was silently disabled too.
The standard logging payload already carries `custom_llm_provider` for every
route -- it is built from the top-level call details rather than from
`litellm_params` -- so fall back to it. `litellm_params` keeps precedence, and
the `ValueError` is preserved when neither source has a provider.
Fixes BerriAI#26701
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015ftJdiLtpTbjoZaNuqX6dq
242e96c to
60c8b3d
Compare
|
Rebased onto current The old revision would not have passed CI. The branch was 6887 commits behind. Git reported the merge as clean, which hid two real breakages introduced upstream since July:
Simpler fix. While reworking it I found the derivation was unnecessary: custom_llm_provider: Final[str | None] = (
kwargs.get("litellm_params", {}).get("custom_llm_provider", None)
or standard_logging_payload["custom_llm_provider"]
)
Verification:
@henricook — the mechanism you described is exactly it: the raise happens before any counter increments, which is why deployment-level Ready for review whenever someone has a moment — this has been open since 5 July and silently disables provider budgets on two routes. |
Summary
/v1/chat/completionsinjectscustom_llm_providerintolitellm_params, but/v1/messagesand/v1/embeddingsdo not.RouterBudgetLimiting.async_log_success_eventread it only fromlitellm_params, so on those routes it raisedValueError("custom_llm_provider is required")before incrementing any spend counter — provider budgets silently never accrued. Deployment-levelmax_budgetsits below the same guard, so it was disabled too.@henricook independently hit this in production on
v1.83.14-stablerouting Claude Code traffic through a Vertex+Azure router withprovider_budget_config.Fixes #26701. Same root cause as #30276.
What changed since the first revision
This PR originally derived the provider from the model string via
litellm.get_llm_provider(...)wrapped in try/except (+31 lines). While rebasing onto currentlitellm_internal_stagingI found thatStandardLoggingPayloadalready carriescustom_llm_provider, and that it is populated for every route — it is built from the top-level call details (litellm_logging.py,kwargs.get("custom_llm_provider")) rather than fromlitellm_params. All threeupdate_environment_variablescall sites inmain.pypass it through.So the derivation was unnecessary. The fix is now three lines:
litellm_paramskeeps precedence, and theValueErroris preserved when neither source has a provider.Subscript rather than
.get()is deliberate:StandardLoggingPayloadis a totalTypedDictin whichcustom_llm_provider: str | Noneis a required key, and the subscript form is the one that type-checks cleanly under the current strict config.Rebase notes
The branch was 6887 commits behind. Git reported the merge as clean, but the old revision no longer builds against current staging:
custom_llm_provideris now declaredFinal[str], and the previous revision reassigned it twice — +15 new basedpyright errors, including two"custom_llm_provider" is declared as Final and cannot be reassigned.typing.castis now banned byruff-strict.toml(TID251), ruling out the obvious workaround.The current revision is a single commit on top of
litellm_internal_staging.Tests
Rewrote the regression tests around the payload fallback and verified they actually fail without the fix.
.venv/bin/python -m pytest tests/test_litellm/router_strategy/test_budget_limiter_provider_derivation.py -q→ 4 passedValueError: custom_llm_provider is required(the two/v1/messagesand/v1/embeddingscases); the precedence and still-raises cases pass in both, as they assert unchanged behaviour.venv/bin/python -m pytest tests/test_litellm/router_strategy/test_budget_limiter_hotpath.py tests/test_litellm/router_strategy/test_budget_limiter_provider_derivation.py -q→ 13 passedbasedpyright litellm/router_strategy/budget_limiter.py→ 144 diagnostics, identical to staging (zero delta, no rule regressed)ruff check --config ruff-strict.toml→ zero delta vs staging;ruff format --checkcleanModel evals
Not run. This is a spend-accounting fix in a router callback and does not change model outputs.
Assistance
Claude Code was used to rebase this PR, investigate why the original approach no longer type-checked, find the simpler payload-based fix, and rewrite the tests. The human submitter reviewed the changed lines and the test results.