Skip to content

fix(budget-limiter): derive custom_llm_provider for /v1/messages and /v1/embeddings routes - #32180

Closed
jagjeet-singh-23 wants to merge 1 commit into
BerriAI:mainfrom
jagjeet-singh-23:fix/budget-limiter-custom-provider-messages-embeddings
Closed

jagjeet-singh-23 wants to merge 1 commit into
BerriAI:mainfrom
jagjeet-singh-23:fix/budget-limiter-custom-provider-messages-embeddings

Conversation

@jagjeet-singh-23

@jagjeet-singh-23 jagjeet-singh-23 commented Jul 5, 2026 •

Copy link
Copy Markdown

Summary

/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, so on those routes it raised ValueError("custom_llm_provider is required") before incrementing any spend counter — provider budgets silently never accrued. Deployment-level max_budget sits below the same guard, so it was disabled too.

@henricook independently hit this in production on v1.83.14-stable routing Claude Code traffic through a Vertex+Azure router with provider_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 current litellm_internal_staging I found that StandardLoggingPayload already carries custom_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 from litellm_params. All three update_environment_variables call sites in main.py pass it through.

So the derivation was unnecessary. The fix is now three lines:

custom_llm_provider: Final[str | None] = (
    kwargs.get("litellm_params", {}).get("custom_llm_provider", None)
    or standard_logging_payload["custom_llm_provider"]
)

litellm_params keeps precedence, and the ValueError is preserved when neither source has a provider.

Subscript rather than .get() is deliberate: StandardLoggingPayload is a total TypedDict in which custom_llm_provider: str | None is 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_provider is now declared Final[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.cast is now banned by ruff-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 passed
  • Same file against unpatched staging → 2 failed with exactly ValueError: custom_llm_provider is required (the two /v1/messages and /v1/embeddings cases); 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 passed
  • basedpyright 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 --check clean

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

@greptile-apps

greptile-apps Bot commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes silent budget-tracking failures on /v1/messages and /v1/embeddings routes when provider_budget_config is enabled. Unlike /v1/chat/completions, those routes do not inject custom_llm_provider into litellm_params, causing async_log_success_event to raise ValueError on every request.

  • Core fix: adds a fallback in async_log_success_event that calls litellm.get_llm_provider() (already used by _get_llm_provider_for_deployment) to derive the provider from the model string when custom_llm_provider is absent, then raises only if both paths fail.
  • Tests: three new pytest.mark.asyncio tests reproduce the exact bug for Anthropic and OpenAI models, plus a regression guard for the existing chat-completions path; all calls are properly mocked — no real network traffic.

Confidence Score: 4/5

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

Important Files Changed

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

codecov Bot commented Jul 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@veria-ai

veria-ai Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

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

Security review

No open security issues remain on this pull request.

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

jagjeet-singh-23 added a commit to jagjeet-singh-23/litellm that referenced this pull request Jul 5, 2026
… 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.
@henricook

henricook commented Jul 7, 2026 •

Copy link
Copy Markdown

We hit this independently on v1.83.14-stable routing Claude Code traffic (/v1/messages) through a Vertex+Azure router with provider_budget_config - budgets silently never accrue because async_log_success_event raises on the missing custom_llm_provider before any counter increments. Note this kills deployment-level budgets too (litellm_params.max_budget), since they sit below the same guard.

We backported this PR's change as a build-time patch and can confirm it fixes both: Redis counters accrue on /v1/messages and the router correctly fails over to the fallback provider once the budget trips. The same test on /chat/completions passes with and without the patch, confirming the bug is passthrough-path-specific. Would love to see this merged - happy to provide repro details.

@jagjeet-singh-23

Copy link
Copy Markdown
Author

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
@jagjeet-singh-23
jagjeet-singh-23 force-pushed the fix/budget-limiter-custom-provider-messages-embeddings branch from 242e96c to 60c8b3d Compare September 5, 2026 08:27
@jagjeet-singh-23
jagjeet-singh-23 requested a review from a team September 5, 2026 08:27
@jagjeet-singh-23

Copy link
Copy Markdown
Author

Rebased onto current litellm_internal_staging and substantially simplified — the diff on budget_limiter.py is now +9/-1 instead of +31.

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:

  • custom_llm_provider is now declared Final[str], and the old revision reassigned it twice → +15 new basedpyright errors, two of them "custom_llm_provider" is declared as Final and cannot be reassigned.
  • typing.cast is now banned by ruff-strict.toml (TID251), which rules out the obvious workaround.

Simpler fix. While reworking it I found the derivation was unnecessary: StandardLoggingPayload already carries custom_llm_provider, and it is populated on every route, because it is built from the top-level call details (litellm_logging.py: kwargs.get("custom_llm_provider")) rather than from litellm_params. All three update_environment_variables call sites in main.py pass it through. So no get_llm_provider call, no dict view, no try/except:

custom_llm_provider: Final[str | None] = (
    kwargs.get("litellm_params", {}).get("custom_llm_provider", None)
    or standard_logging_payload["custom_llm_provider"]
)

litellm_params keeps precedence; the ValueError still fires when neither source has a provider.

Verification:

  • The two /v1/messages and /v1/embeddings regression tests fail against unpatched staging with exactly ValueError: custom_llm_provider is required, and pass with the fix. The precedence and still-raises tests pass in both, since they assert unchanged behaviour.
  • tests/test_litellm/router_strategy/ → 1266 passed. The 14 failures in test_complexity_router.py are a missing optional semantic_router dep in my local env and reproduce identically on unpatched staging.
  • basedpyright on budget_limiter.py: 144 diagnostics, byte-identical to staging — no rule regressed. ruff --config ruff-strict.toml and ruff format --check: zero delta.

@henricook — the mechanism you described is exactly it: the raise happens before any counter increments, which is why deployment-level max_budget dies with it. If you are able to re-test against this revision, that would be useful; the observable behaviour should be the same as the version you ran, just arrived at differently.

Ready for review whenever someone has a moment — this has been open since 5 July and silently disables provider budgets on two routes.

@codspeed

codspeed Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing jagjeet-singh-23:fix/budget-limiter-custom-provider-messages-embeddings (60c8b3d) with litellm_internal_staging (29ac88e)

Open in CodSpeed

@yuneng-berri
yuneng-berri deleted the branch BerriAI:main September 13, 2026 04:28
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 15:51
@github-actions

Copy link
Copy Markdown
Contributor

#26701 was fixed by #38172 on main, so this pull request is closed. Reopen it if something was missed.

@github-actions github-actions Bot closed this Sep 25, 2026
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.

[Bug] custom_llm_provider not propagated to budget_limiter.async_log_success_event for /v1/messages + /v1/embeddings

3 participants