From 691ca03266539c7278c88a4d10eb161fc7e68e2b Mon Sep 17 00:00:00 2001
From: nate-berri
Date: Sat, 10 Oct 2026 13:20:31 -0700
Subject: [PATCH 01/40] fix(sdk): resolve litellm.proxy lazily on attribute
access (#45845)
The layer cleanup stopped import litellm from loading any proxy module, so litellm.proxy was no longer bound and litellm.proxy._types.X raised AttributeError. The module __getattr__ now imports litellm.proxy on first access, which keeps import litellm free of proxy._types and fixes the docs and code-quality checks on main
---
litellm/__init__.py | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/litellm/__init__.py b/litellm/__init__.py
index 4196912488f..a6bbd132cbf 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -2386,6 +2386,11 @@ def __getattr__(name: str) -> Any:
handler_func: Final = registry[name]
return handler_func(name)
+ if name == "proxy":
+ import importlib
+
+ return importlib.import_module("litellm.proxy")
+
if name == "harness" or name in _AGENT_EXPORTS:
import importlib
From c397b57f2b8685d05e7c5ffc5bdacef6a310f33f Mon Sep 17 00:00:00 2001
From: nate-berri
Date: Sat, 10 Oct 2026 13:32:34 -0700
Subject: [PATCH 02/40] refactor(anthropic): move prompt cache pricing helper
out of the proxy package (#45753)
* refactor(anthropic): move prompt cache pricing helper out of the proxy package
Part of LIT-9423
* fix(sdk): resolve litellm.proxy lazily on attribute access
The layer cleanup stopped import litellm from loading any proxy module, so litellm.proxy was no longer bound and litellm.proxy._types.X raised AttributeError. The module __getattr__ now imports litellm.proxy on first access, which keeps import litellm free of proxy._types and fixes the docs and code-quality checks on main
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
litellm/llms/anthropic/cache_aware_routing.py | 2 +-
.../llms/anthropic/prompt_cache_pricing.py | 100 +++++++++++++++++
.../common_utils/prompt_cache_pricing.py | 101 +-----------------
.../test_anthropic_prompt_cache_pricing.py} | 2 +-
4 files changed, 104 insertions(+), 101 deletions(-)
create mode 100644 litellm/llms/anthropic/prompt_cache_pricing.py
rename tests/unit/{proxy/common_utils/test_prompt_cache_pricing.py => llms/anthropic/test_anthropic_prompt_cache_pricing.py} (97%)
diff --git a/litellm/llms/anthropic/cache_aware_routing.py b/litellm/llms/anthropic/cache_aware_routing.py
index f049e4ac187..515373448f4 100644
--- a/litellm/llms/anthropic/cache_aware_routing.py
+++ b/litellm/llms/anthropic/cache_aware_routing.py
@@ -24,7 +24,7 @@ from litellm.llms.anthropic.prompt_cache_prediction import (
resolve_prediction_target,
supported_prediction_headers,
)
-from litellm.proxy.common_utils.prompt_cache_pricing import price_cache_tokens
+from litellm.llms.anthropic.prompt_cache_pricing import price_cache_tokens
from litellm.types.llms.base import LiteLLMBaseModel
from litellm.types.management_endpoints.prompt_cache_prediction import (
CacheCostScenario,
diff --git a/litellm/llms/anthropic/prompt_cache_pricing.py b/litellm/llms/anthropic/prompt_cache_pricing.py
new file mode 100644
index 00000000000..b07873db510
--- /dev/null
+++ b/litellm/llms/anthropic/prompt_cache_pricing.py
@@ -0,0 +1,100 @@
+from collections.abc import Mapping
+from datetime import datetime, timezone
+from math import isfinite
+from typing import Final
+
+from pydantic import TypeAdapter
+
+import litellm
+from litellm.cost_calculator import (
+ completion_cost, # pyright: ignore[reportUnknownVariableType] # legacy optional parameters are untyped
+ select_model_name_for_cost_calc,
+)
+from litellm.litellm_core_utils.litellm_logging import Logging
+from litellm.types.management_endpoints.prompt_cache_prediction import CacheTokenBuckets
+from litellm.types.utils import CacheCreationTokenDetails, ModelResponse, PromptTokensDetailsWrapper, Usage
+
+_PRICE_ENTRY: Final = TypeAdapter(Mapping[str, object])
+
+
+def _valid_price(value: object) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and isfinite(value) and value >= 0
+
+
+def _has_required_prices(prices: Mapping[str, object], tokens: CacheTokenBuckets, completion_tokens: int = 0) -> bool:
+ required: Final = (
+ ("input_cost_per_token", True),
+ ("cache_read_input_token_cost", tokens.cache_read_input_tokens > 0),
+ ("cache_creation_input_token_cost", tokens.cache_creation_5m_input_tokens > 0),
+ ("cache_creation_input_token_cost_above_1hr", tokens.cache_creation_1h_input_tokens > 0),
+ ("output_cost_per_token", completion_tokens > 0),
+ )
+ if any(needed and not _valid_price(prices.get(key)) for key, needed in required):
+ return False
+ return all(
+ _valid_price(value)
+ for key, value in prices.items()
+ if value is not None and any(needed and key.startswith(f"{base}_above_") for base, needed in required)
+ )
+
+
+def price_cache_tokens(
+ model: str, deployment_id: str, tokens: CacheTokenBuckets, completion_tokens: int = 0
+) -> float | None:
+ try:
+ selected_model: Final = select_model_name_for_cost_calc(
+ model=model,
+ completion_response=None,
+ custom_pricing=True,
+ custom_llm_provider="anthropic",
+ router_model_id=deployment_id,
+ )
+ if selected_model is None:
+ return None
+ model_info: Final = litellm.get_model_info(model=selected_model, custom_llm_provider="anthropic")
+ registry: Final = _PRICE_ENTRY.validate_python(litellm.model_cost) # pyright: ignore[reportUnknownMemberType] # legacy registry is validated at this boundary
+ price_entry: Final = registry.get(model_info["key"])
+ if price_entry is None:
+ return None
+ prices: Final = _PRICE_ENTRY.validate_python(price_entry)
+ if completion_tokens < 0 or not _has_required_prices(prices, tokens, completion_tokens):
+ return None
+ usage: Final = Usage(
+ prompt_tokens=tokens.total_tokens,
+ completion_tokens=completion_tokens,
+ total_tokens=tokens.total_tokens + completion_tokens,
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ cached_tokens=tokens.cache_read_input_tokens,
+ cache_creation_tokens=tokens.cache_creation_5m_input_tokens + tokens.cache_creation_1h_input_tokens,
+ cache_creation_token_details=CacheCreationTokenDetails(
+ ephemeral_5m_input_tokens=tokens.cache_creation_5m_input_tokens,
+ ephemeral_1h_input_tokens=tokens.cache_creation_1h_input_tokens,
+ ),
+ ),
+ )
+ logging_obj: Final = Logging(
+ model=model,
+ messages=[],
+ stream=False,
+ call_type="completion",
+ start_time=datetime.now(timezone.utc),
+ litellm_call_id="prompt-cache-prediction",
+ function_id="prompt-cache-prediction",
+ )
+ completion_cost(
+ completion_response=ModelResponse(model=model, usage=usage),
+ model=model,
+ custom_llm_provider="anthropic",
+ custom_pricing=True,
+ router_model_id=deployment_id,
+ litellm_logging_obj=logging_obj,
+ )
+ breakdown: Final = logging_obj.cost_breakdown
+ input_cost: Final = breakdown.get("input_cost") if breakdown is not None else None
+ output_cost: Final = breakdown.get("output_cost") if breakdown is not None else None
+ if input_cost is None or output_cost is None:
+ return None
+ cost: Final = input_cost + output_cost
+ return cost if _valid_price(cost) else None
+ except Exception: # noqa: BLE001 # the shared pricing owners raise plain Exception for unpriceable models
+ return None
diff --git a/litellm/proxy/common_utils/prompt_cache_pricing.py b/litellm/proxy/common_utils/prompt_cache_pricing.py
index b07873db510..55682ba872c 100644
--- a/litellm/proxy/common_utils/prompt_cache_pricing.py
+++ b/litellm/proxy/common_utils/prompt_cache_pricing.py
@@ -1,100 +1,3 @@
-from collections.abc import Mapping
-from datetime import datetime, timezone
-from math import isfinite
-from typing import Final
+from litellm.llms.anthropic.prompt_cache_pricing import price_cache_tokens
-from pydantic import TypeAdapter
-
-import litellm
-from litellm.cost_calculator import (
- completion_cost, # pyright: ignore[reportUnknownVariableType] # legacy optional parameters are untyped
- select_model_name_for_cost_calc,
-)
-from litellm.litellm_core_utils.litellm_logging import Logging
-from litellm.types.management_endpoints.prompt_cache_prediction import CacheTokenBuckets
-from litellm.types.utils import CacheCreationTokenDetails, ModelResponse, PromptTokensDetailsWrapper, Usage
-
-_PRICE_ENTRY: Final = TypeAdapter(Mapping[str, object])
-
-
-def _valid_price(value: object) -> bool:
- return isinstance(value, (int, float)) and not isinstance(value, bool) and isfinite(value) and value >= 0
-
-
-def _has_required_prices(prices: Mapping[str, object], tokens: CacheTokenBuckets, completion_tokens: int = 0) -> bool:
- required: Final = (
- ("input_cost_per_token", True),
- ("cache_read_input_token_cost", tokens.cache_read_input_tokens > 0),
- ("cache_creation_input_token_cost", tokens.cache_creation_5m_input_tokens > 0),
- ("cache_creation_input_token_cost_above_1hr", tokens.cache_creation_1h_input_tokens > 0),
- ("output_cost_per_token", completion_tokens > 0),
- )
- if any(needed and not _valid_price(prices.get(key)) for key, needed in required):
- return False
- return all(
- _valid_price(value)
- for key, value in prices.items()
- if value is not None and any(needed and key.startswith(f"{base}_above_") for base, needed in required)
- )
-
-
-def price_cache_tokens(
- model: str, deployment_id: str, tokens: CacheTokenBuckets, completion_tokens: int = 0
-) -> float | None:
- try:
- selected_model: Final = select_model_name_for_cost_calc(
- model=model,
- completion_response=None,
- custom_pricing=True,
- custom_llm_provider="anthropic",
- router_model_id=deployment_id,
- )
- if selected_model is None:
- return None
- model_info: Final = litellm.get_model_info(model=selected_model, custom_llm_provider="anthropic")
- registry: Final = _PRICE_ENTRY.validate_python(litellm.model_cost) # pyright: ignore[reportUnknownMemberType] # legacy registry is validated at this boundary
- price_entry: Final = registry.get(model_info["key"])
- if price_entry is None:
- return None
- prices: Final = _PRICE_ENTRY.validate_python(price_entry)
- if completion_tokens < 0 or not _has_required_prices(prices, tokens, completion_tokens):
- return None
- usage: Final = Usage(
- prompt_tokens=tokens.total_tokens,
- completion_tokens=completion_tokens,
- total_tokens=tokens.total_tokens + completion_tokens,
- prompt_tokens_details=PromptTokensDetailsWrapper(
- cached_tokens=tokens.cache_read_input_tokens,
- cache_creation_tokens=tokens.cache_creation_5m_input_tokens + tokens.cache_creation_1h_input_tokens,
- cache_creation_token_details=CacheCreationTokenDetails(
- ephemeral_5m_input_tokens=tokens.cache_creation_5m_input_tokens,
- ephemeral_1h_input_tokens=tokens.cache_creation_1h_input_tokens,
- ),
- ),
- )
- logging_obj: Final = Logging(
- model=model,
- messages=[],
- stream=False,
- call_type="completion",
- start_time=datetime.now(timezone.utc),
- litellm_call_id="prompt-cache-prediction",
- function_id="prompt-cache-prediction",
- )
- completion_cost(
- completion_response=ModelResponse(model=model, usage=usage),
- model=model,
- custom_llm_provider="anthropic",
- custom_pricing=True,
- router_model_id=deployment_id,
- litellm_logging_obj=logging_obj,
- )
- breakdown: Final = logging_obj.cost_breakdown
- input_cost: Final = breakdown.get("input_cost") if breakdown is not None else None
- output_cost: Final = breakdown.get("output_cost") if breakdown is not None else None
- if input_cost is None or output_cost is None:
- return None
- cost: Final = input_cost + output_cost
- return cost if _valid_price(cost) else None
- except Exception: # noqa: BLE001 # the shared pricing owners raise plain Exception for unpriceable models
- return None
+__all__ = ("price_cache_tokens",)
diff --git a/tests/unit/proxy/common_utils/test_prompt_cache_pricing.py b/tests/unit/llms/anthropic/test_anthropic_prompt_cache_pricing.py
similarity index 97%
rename from tests/unit/proxy/common_utils/test_prompt_cache_pricing.py
rename to tests/unit/llms/anthropic/test_anthropic_prompt_cache_pricing.py
index 01b18c1ed71..4f424224012 100644
--- a/tests/unit/proxy/common_utils/test_prompt_cache_pricing.py
+++ b/tests/unit/llms/anthropic/test_anthropic_prompt_cache_pricing.py
@@ -3,7 +3,7 @@ from typing import Final
import pytest
import litellm
-from litellm.proxy.common_utils.prompt_cache_pricing import price_cache_tokens
+from litellm.llms.anthropic.prompt_cache_pricing import price_cache_tokens
from litellm.types.management_endpoints.prompt_cache_prediction import CacheTokenBuckets
From 4e44b382fd3a2e42d56b67d5092d023a82d1899c Mon Sep 17 00:00:00 2001
From: Marcus Greer
Date: Sat, 10 Oct 2026 13:32:54 -0700
Subject: [PATCH 03/40] fix(terraform): stop sending blocked on litellm_user
updates (#45410)
* fix(terraform): stop sending blocked on litellm_user updates
/user/update writes blocked into the user table upsert, but blocked only
exists as a column on keys, so every litellm_user update failed with a 400
from Prisma. Updates no longer send it. Create sends it only when set to
true, since /user/new applies it to the auto-created key
blocked only applies at creation; litellm_key_block covers changes after that
* fix(terraform): always send blocked on litellm_user create
/user/new fills an omitted blocked from default_internal_user_params, so
leaving it out on create let a proxy-side blocked=true default block the
auto-created key. Create sends the configured value again, including
false, while updates still never send it
* chore(terraform): drop comment on litellm_user create blocked
* fix(terraform): keep litellm_user blocked undeprecated
Create sends blocked again, so it still controls the auto-created key.
Whether to deprecate it in favor of litellm_key_block is left to the
provider maintainers; the docs describe it as creation-only instead
---
terraform/provider/CHANGELOG.md | 1 +
terraform/provider/docs/resources/user.md | 2 +-
terraform/provider/litellm/resource_user.go | 7 +-
.../provider/litellm/resource_user_test.go | 78 +++++++++++++++++++
4 files changed, 83 insertions(+), 5 deletions(-)
diff --git a/terraform/provider/CHANGELOG.md b/terraform/provider/CHANGELOG.md
index d8c53e1432c..b948db2b231 100644
--- a/terraform/provider/CHANGELOG.md
+++ b/terraform/provider/CHANGELOG.md
@@ -49,6 +49,7 @@ longer signal it.
### Fixed
+- **user**: `litellm_user` updates no longer send `blocked`, which `/user/update` writes into the user table where no such column exists, so every update failed with a 400 (`Could not find field at upsertOneLiteLLM_UserTable.create.blocked`). Create still sends `blocked`, including `false`, so a `default_internal_user_params.blocked` on the proxy cannot block the auto-created key. Changing `blocked` after creation has no effect, since the proxy has no user-level block; use `litellm_key_block` instead
- **model**: `litellm_model` refresh now reads the `{"data": [...]}` envelope `/model/info` returns, so `model_info` fields changed outside Terraform show up as drift instead of silently keeping the previous state
- **key**: An update that changes `team_id` and fails because the key was already cascade-deleted along with its previous team now recovers by recreating the key under the new team, instead of aborting the apply. The key's absence is confirmed against the proxy first, so an unrelated failure still errors out, and a `team_id` change between two teams that both still exist stays a plain in-place update
- **credential**: create now reports a `credential_name` collision as a clear error naming the `terraform import` command that adopts the existing credential, instead of surfacing the proxy's raw 500 with a Prisma `Unique constraint failed` message. New `adopt_existing` argument (default `false`) opts into taking the existing credential over during create, which makes `apply` idempotent again once state loses track of a credential that still exists on the proxy. Requires a proxy that answers 409 on the collision; older proxies are still detected by their 500 message
diff --git a/terraform/provider/docs/resources/user.md b/terraform/provider/docs/resources/user.md
index 9b537292d54..19fa8b68f14 100644
--- a/terraform/provider/docs/resources/user.md
+++ b/terraform/provider/docs/resources/user.md
@@ -50,7 +50,7 @@ resource "litellm_user" "alice" {
- `permissions` (Optional) - Map of permission values for the user
- `model_max_budget` (Optional) - JSON string of per-model budget config, e.g. `jsonencode({"gpt-4o" = {max_budget = 10.0}})`
- `guardrails` (Optional) - List of guardrails applied to the user's requests
-- `blocked` (Optional, Default `false`) - Whether the user is blocked from making requests
+- `blocked` (Optional, Default `false`) - Whether to block the key auto-created with the user. Only sent on creation, so changing it afterwards has no effect. The proxy has no user-level block; use `litellm_key_block` to block keys
## Attribute Reference
diff --git a/terraform/provider/litellm/resource_user.go b/terraform/provider/litellm/resource_user.go
index c1aa9d7e9fa..76420d1f9bf 100644
--- a/terraform/provider/litellm/resource_user.go
+++ b/terraform/provider/litellm/resource_user.go
@@ -164,7 +164,7 @@ func resourceLiteLLMUser() *schema.Resource {
Type: schema.TypeBool,
Optional: true,
Default: false,
- Description: "Whether the user is blocked from making requests",
+ Description: "Whether to block the key auto-created with the user. Only sent on creation; use litellm_key_block to change it afterwards",
},
"key": {
Type: schema.TypeString,
@@ -195,6 +195,7 @@ func resourceLiteLLMUserCreate(d *schema.ResourceData, m interface{}) error {
}
userData["auto_create_key"] = d.Get("auto_create_key").(bool)
userData["send_invite_email"] = d.Get("send_invite_email").(bool)
+ userData["blocked"] = d.Get("blocked").(bool)
log.Printf("[DEBUG] Create user request payload: %+v", userData)
@@ -337,9 +338,7 @@ func resourceLiteLLMUserDelete(d *schema.ResourceData, m interface{}) error {
}
func buildUserData(d *schema.ResourceData) map[string]interface{} {
- userData := map[string]interface{}{
- "blocked": d.Get("blocked").(bool),
- }
+ userData := map[string]interface{}{}
for _, key := range []string{
"user_email", "user_alias", "user_role", "teams", "models", "max_budget",
diff --git a/terraform/provider/litellm/resource_user_test.go b/terraform/provider/litellm/resource_user_test.go
index c254c0c5929..046cef91954 100644
--- a/terraform/provider/litellm/resource_user_test.go
+++ b/terraform/provider/litellm/resource_user_test.go
@@ -239,3 +239,81 @@ func TestResourceUserDelete_SendsUserIDs(t *testing.T) {
t.Fatalf("expected ID to be cleared after delete, got %q", d.Id())
}
}
+
+func TestResourceUserUpdate_NeverSendsBlocked(t *testing.T) {
+ for name, config := range map[string]map[string]interface{}{
+ "unset": {"user_role": "internal_user"},
+ "true": {"user_role": "internal_user", "blocked": true},
+ "false": {"user_role": "internal_user", "blocked": false},
+ } {
+ t.Run(name, func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/user/update":
+ var payload map[string]interface{}
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatalf("failed to decode update payload: %v", err)
+ }
+ if _, ok := payload["blocked"]; ok {
+ w.WriteHeader(http.StatusBadRequest)
+ w.Write([]byte(`{"error": "Could not find field at upsertOneLiteLLM_UserTable.create.blocked"}`))
+ return
+ }
+ w.Write([]byte(`{"user_id": "u-7"}`))
+ case "/user/info":
+ w.Write(userInfoBody("u-7", map[string]interface{}{"user_role": "internal_user"}))
+ default:
+ t.Errorf("unexpected request to %s", r.URL.Path)
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ defer srv.Close()
+
+ d := schema.TestResourceDataRaw(t, resourceLiteLLMUser().Schema, config)
+ d.SetId("u-7")
+
+ if err := resourceLiteLLMUserUpdate(d, NewClient(srv.URL, "test-key", true)); err != nil {
+ t.Fatalf("update failed: %v", err)
+ }
+ })
+ }
+}
+
+func TestResourceUserCreate_AlwaysSendsBlocked(t *testing.T) {
+ for name, tc := range map[string]struct {
+ config map[string]interface{}
+ wantBlocked interface{}
+ }{
+ "unset": {config: map[string]interface{}{}, wantBlocked: false},
+ "false": {config: map[string]interface{}{"blocked": false}, wantBlocked: false},
+ "true": {config: map[string]interface{}{"blocked": true}, wantBlocked: true},
+ } {
+ t.Run(name, func(t *testing.T) {
+ var createPayload map[string]interface{}
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/user/new":
+ if err := json.NewDecoder(r.Body).Decode(&createPayload); err != nil {
+ t.Fatalf("failed to decode create payload: %v", err)
+ }
+ w.Write([]byte(`{"user_id": "u-1", "key": "sk-generated"}`))
+ case "/user/info":
+ w.Write(userInfoBody("u-1", map[string]interface{}{"user_role": "internal_user"}))
+ default:
+ t.Errorf("unexpected request to %s", r.URL.Path)
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ defer srv.Close()
+
+ d := schema.TestResourceDataRaw(t, resourceLiteLLMUser().Schema, tc.config)
+
+ if err := resourceLiteLLMUserCreate(d, NewClient(srv.URL, "test-key", true)); err != nil {
+ t.Fatalf("create failed: %v", err)
+ }
+ if got := createPayload["blocked"]; got != tc.wantBlocked {
+ t.Errorf("expected blocked %v in create payload, got %v", tc.wantBlocked, got)
+ }
+ })
+ }
+}
From 3a0803aaa1c4329e3687389ae2dc0b2b53eeffbc Mon Sep 17 00:00:00 2001
From: Yassin Kortam
Date: Sat, 10 Oct 2026 13:33:03 -0700
Subject: [PATCH 04/40] fix(ui): store SSO exchange token via storeLoginToken
to keep Secure flag (#45840)
Co-authored-by: Nabil Ameena
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
.../src/components/networking.test.ts | 34 +++++++++++++++++++
.../src/components/networking.tsx | 2 +-
.../src/utils/cookieUtils.test.ts | 23 +++++++++++++
3 files changed, 58 insertions(+), 1 deletion(-)
diff --git a/ui/litellm-dashboard/src/components/networking.test.ts b/ui/litellm-dashboard/src/components/networking.test.ts
index e60c0356751..1aa003750d7 100644
--- a/ui/litellm-dashboard/src/components/networking.test.ts
+++ b/ui/litellm-dashboard/src/components/networking.test.ts
@@ -118,6 +118,40 @@ describe("loginCall - storeLoginToken integration", () => {
});
});
+describe("exchangeLoginCode - storeLoginToken integration", () => {
+ const originalFetch = global.fetch;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ global.fetch = originalFetch;
+ });
+
+ it("calls storeLoginToken when exchange response includes token", async () => {
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ token: "sso-jwt" }),
+ }) as unknown as typeof global.fetch;
+ const { storeLoginToken } = await import("@/utils/cookieUtils");
+ const token = await Networking.exchangeLoginCode("some-login-code");
+ expect(token).toBe("sso-jwt");
+ expect(storeLoginToken).toHaveBeenCalledWith("sso-jwt");
+ });
+
+ it("does not call storeLoginToken when exchange response has no token", async () => {
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({}),
+ }) as unknown as typeof global.fetch;
+ const { storeLoginToken } = await import("@/utils/cookieUtils");
+ const token = await Networking.exchangeLoginCode("some-login-code");
+ expect(token).toBeUndefined();
+ expect(storeLoginToken).not.toHaveBeenCalled();
+ });
+});
+
describe("modelInfoCall", () => {
let currentFetch: typeof global.fetch;
diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx
index 2b38da75411..54b2066c9c5 100644
--- a/ui/litellm-dashboard/src/components/networking.tsx
+++ b/ui/litellm-dashboard/src/components/networking.tsx
@@ -7102,7 +7102,7 @@ export const exchangeLoginCode = async (code: string, workerBaseUrl?: string | n
const data = await response.json();
if (data.token) {
- document.cookie = `token=${data.token}; path=/; SameSite=Lax`;
+ storeLoginToken(data.token);
}
return data.token;
};
diff --git a/ui/litellm-dashboard/src/utils/cookieUtils.test.ts b/ui/litellm-dashboard/src/utils/cookieUtils.test.ts
index a38b96e74c2..a1bf827560b 100644
--- a/ui/litellm-dashboard/src/utils/cookieUtils.test.ts
+++ b/ui/litellm-dashboard/src/utils/cookieUtils.test.ts
@@ -174,6 +174,29 @@ describe("cookieUtils", () => {
expect(cookieSpy).toHaveBeenCalledWith(expect.stringContaining("path=/ui"));
vi.restoreAllMocks();
});
+
+ it("should write the cookie with Secure on an https page", () => {
+ vi.stubGlobal("location", { ...window.location, protocol: "https:" });
+ const cookieSpy = vi.spyOn(document, "cookie", "set");
+
+ storeLoginToken("https-jwt");
+
+ expect(cookieSpy).toHaveBeenCalledWith(expect.stringMatching(/^token=https-jwt; .*; Secure$/));
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ it("should write the cookie without Secure on an http page", () => {
+ vi.stubGlobal("location", { ...window.location, protocol: "http:" });
+ const cookieSpy = vi.spyOn(document, "cookie", "set");
+
+ storeLoginToken("http-jwt");
+
+ expect(cookieSpy).toHaveBeenCalledWith(expect.stringMatching(/^token=http-jwt; /));
+ expect(cookieSpy).not.toHaveBeenCalledWith(expect.stringContaining("Secure"));
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
});
describe("getCookie", () => {
From 7383f59ad2719ee0edf7725f5fa50e2f7f326919 Mon Sep 17 00:00:00 2001
From: nate-berri
Date: Sat, 10 Oct 2026 13:33:16 -0700
Subject: [PATCH 05/40] refactor(skills): move NewSkillRequest to
litellm.models.skills (#45768)
* refactor(skills): move NewSkillRequest to litellm.models.skills
Part of LIT-9423
* fix(sdk): resolve litellm.proxy lazily on attribute access
The layer cleanup stopped import litellm from loading any proxy module, so litellm.proxy was no longer bound and litellm.proxy._types.X raised AttributeError. The module __getattr__ now imports litellm.proxy on first access, which keeps import litellm free of proxy._types and fixes the docs and code-quality checks on main
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
litellm/llms/litellm_proxy/skills/handler.py | 4 ++--
.../llms/litellm_proxy/skills/transformation.py | 2 +-
litellm/models/skills.py | 15 +++++++++++++++
litellm/proxy/_types.py | 16 +++-------------
4 files changed, 21 insertions(+), 16 deletions(-)
diff --git a/litellm/llms/litellm_proxy/skills/handler.py b/litellm/llms/litellm_proxy/skills/handler.py
index a86301d9a79..0dbe47791fb 100644
--- a/litellm/llms/litellm_proxy/skills/handler.py
+++ b/litellm/llms/litellm_proxy/skills/handler.py
@@ -15,8 +15,8 @@ from litellm.llms.litellm_proxy.skills.constants import (
LITELLM_SKILL_ID_PREFIX,
MAX_SKILLS_PER_SEARCH,
)
-from litellm.models.skills import LiteLLM_SkillsTable
-from litellm.proxy._types import NewSkillRequest, UserAPIKeyAuth
+from litellm.models.skills import LiteLLM_SkillsTable, NewSkillRequest
+from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.common_utils.resource_ownership import (
get_primary_resource_owner_scope,
get_resource_owner_scopes,
diff --git a/litellm/llms/litellm_proxy/skills/transformation.py b/litellm/llms/litellm_proxy/skills/transformation.py
index 834b6e65e02..4cbd9f50301 100644
--- a/litellm/llms/litellm_proxy/skills/transformation.py
+++ b/litellm/llms/litellm_proxy/skills/transformation.py
@@ -137,7 +137,7 @@ class LiteLLMSkillsTransformationHandler:
"""Async implementation of create_skill."""
# Lazy import to avoid SDK dependency on proxy
from litellm.llms.litellm_proxy.skills.handler import LiteLLMSkillsHandler
- from litellm.proxy._types import NewSkillRequest
+ from litellm.models.skills import NewSkillRequest
skill_request: Final = NewSkillRequest(
display_title=display_title,
diff --git a/litellm/models/skills.py b/litellm/models/skills.py
index f56dcfff49a..e03e62fa731 100644
--- a/litellm/models/skills.py
+++ b/litellm/models/skills.py
@@ -28,3 +28,18 @@ class LiteLLM_SkillsTable(LiteLLMPydanticObjectBase):
created_by: str | None = None
updated_at: datetime | None = None
updated_by: str | None = None
+
+
+class NewSkillRequest(LiteLLMPydanticObjectBase):
+ """Request to create a new skill in LiteLLM database"""
+
+ display_title: str | None = None
+ description: str | None = None
+ instructions: str | None = None
+ file_content: bytes | None = None # Binary content of skill files (zip)
+ file_name: str | None = None # Original filename
+ file_type: str | None = None # MIME type (e.g., "application/zip")
+ metadata: dict[str, Any] | None = None
+ authorization_url: str | None = None
+ token_url: str | None = None
+ registration_url: str | None = None
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index b1a7d3671fc..26d9e0e1b44 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -1809,19 +1809,9 @@ class MCPSubmissionsSummary(LiteLLMPydanticObjectBase):
######## Skills API Types ########
-class NewSkillRequest(LiteLLMPydanticObjectBase):
- """Request to create a new skill in LiteLLM database"""
-
- display_title: str | None = None
- description: str | None = None
- instructions: str | None = None
- file_content: bytes | None = None # Binary content of skill files (zip)
- file_name: str | None = None # Original filename
- file_type: str | None = None # MIME type (e.g., "application/zip")
- metadata: dict[str, Any] | None = None
- authorization_url: str | None = None
- token_url: str | None = None
- registration_url: str | None = None
+from litellm.models.skills import ( # noqa: E402 # public re-export
+ NewSkillRequest as NewSkillRequest, # noqa: PLC0414 # public re-export
+)
class UpdateSkillRequest(LiteLLMPydanticObjectBase):
From 5325c4a236610099c5f06d22a65ed57ccdcf33d0 Mon Sep 17 00:00:00 2001
From: "devin-ai-integration[bot]"
<158243242+devin-ai-integration[bot]@users.noreply.github.com>
Date: Sat, 10 Oct 2026 20:33:55 +0000
Subject: [PATCH 06/40] feat(proxy): per-model team member budgets with router
fallback (#43887)
Co-authored-by: yassin
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
.../context_management/editors/compact.py | 66 +-
litellm/proxy/_types.py | 11 +
litellm/proxy/auth/auth_checks.py | 3 +
litellm/proxy/auth/fallback_budget.py | 72 +-
litellm/proxy/auth/user_api_key_auth.py | 709 +++++-
litellm/proxy/common_request_processing.py | 76 +-
.../proxy/hooks/model_max_budget_limiter.py | 60 +-
litellm/proxy/litellm_pre_call_utils.py | 3 +
.../budget_management_endpoints.py | 9 +-
.../management_endpoints/common_utils.py | 55 +-
.../management_endpoints/team_endpoints.py | 67 +-
.../pass_through_endpoints.py | 1 +
litellm/proxy/proxy_server.py | 12 +-
litellm/router_utils/common_utils.py | 27 +
.../context_management/test_compact.py | 132 +-
...st_auth_checks_object_access_and_lookup.py | 41 +
tests/unit/proxy/auth/test_fallback_budget.py | 270 ++-
.../test_user_api_key_auth_request_flow.py | 2135 ++++++++++++++++-
.../test_upsert_budget_membership.py | 167 +-
.../hooks/test_model_max_budget_limiter.py | 123 +-
.../management_v1/test_teams.py | 8 +-
.../test_budget_endpoints.py | 41 +
.../management_endpoints/test_common_utils.py | 136 +-
.../test_team_endpoints.py | 362 ++-
.../test_management_helpers_utils.py | 9 +-
.../test_pass_through_endpoints.py | 9 +-
.../proxy/test_common_request_processing.py | 153 +-
.../unit/proxy/test_litellm_pre_call_utils.py | 5 +
.../test_router_utils_common_utils.py | 20 +
.../src/components/Teams.integration.test.tsx | 83 +
ui/litellm-dashboard/src/components/Teams.tsx | 14 +
.../key_team_helpers/ModelMaxBudgetEditor.tsx | 12 +-
.../src/components/networking.tsx | 5 +
.../team/EditMembership.integration.test.tsx | 129 +
.../src/components/team/EditMembership.tsx | 18 +-
.../team/TeamInfo.integration.test.tsx | 94 +
.../src/components/team/TeamInfo.tsx | 58 +-
.../components/team/TeamMemberTab.test.tsx | 21 +
.../src/components/team/TeamMemberTab.tsx | 16 +-
.../src/components/team/memberFormValues.ts | 27 +-
ui/litellm-dashboard/src/lib/http/schema.d.ts | 25 +
41 files changed, 5039 insertions(+), 245 deletions(-)
create mode 100644 ui/litellm-dashboard/src/components/Teams.integration.test.tsx
diff --git a/litellm/llms/anthropic/pass_through/context_management/editors/compact.py b/litellm/llms/anthropic/pass_through/context_management/editors/compact.py
index f743320b702..85a20ea4435 100644
--- a/litellm/llms/anthropic/pass_through/context_management/editors/compact.py
+++ b/litellm/llms/anthropic/pass_through/context_management/editors/compact.py
@@ -84,6 +84,7 @@ _PROPAGATED_METADATA_KEYS: Final = (
"user_api_key_model_max_budget",
"user_api_key_team_model_max_budget",
"user_api_key_user_model_max_budget",
+ "user_api_key_team_member_model_max_budget",
"user_api_key_end_user_model_max_budget",
"litellm_call_id",
"litellm_parent_otel_span",
@@ -125,6 +126,23 @@ class _SummaryAcompletion(Protocol):
) -> "Awaitable[ModelResponse | CustomStreamWrapper]": ...
+class _SummaryModelBudgetLimiter(Protocol):
+ async def is_team_member_within_model_budget(
+ self,
+ user_id: str,
+ team_id: str,
+ team_member_model_max_budget: Mapping[str, object],
+ model: str,
+ ) -> bool: ...
+
+ async def is_end_user_within_model_budget(
+ self,
+ end_user_id: str,
+ end_user_model_max_budget: Mapping[str, object],
+ model: str,
+ ) -> bool: ...
+
+
class _CreateRateLimitDescriptors(Protocol):
def __call__(
self,
@@ -392,6 +410,42 @@ async def _check_summary_model_access(
return True
+async def _check_summary_team_member_model_budget(
+ user_api_key_auth: "UserAPIKeyAuth",
+ model_max_budget_limiter: _SummaryModelBudgetLimiter,
+ summary_model: str,
+) -> bool:
+ team_member_model_max_budget: Final = user_api_key_auth.team_member_model_max_budget
+ user_id: Final = user_api_key_auth.user_id
+ team_id: Final = user_api_key_auth.team_id
+ if (
+ not isinstance(team_member_model_max_budget, Mapping)
+ or not team_member_model_max_budget
+ or not isinstance(user_id, str)
+ or not isinstance(team_id, str)
+ ):
+ return True
+
+ try:
+ await model_max_budget_limiter.is_team_member_within_model_budget(
+ user_id=user_id,
+ team_id=team_id,
+ team_member_model_max_budget=team_member_model_max_budget,
+ model=summary_model,
+ )
+ except litellm.BudgetExceededError:
+ return False
+ except Exception as e: # noqa: BLE001 # unexpected budget-check errors must deny compaction
+ verbose_logger.warning(
+ "compact_20260112: unexpected error during team member model-budget "
+ "check for summary_model=%s; denying: %s",
+ summary_model,
+ e,
+ )
+ return False
+ return True
+
+
async def _check_summary_model_budget(
user_api_key_auth: Optional["UserAPIKeyAuth"],
summary_model: str,
@@ -407,9 +461,9 @@ async def _check_summary_model_budget(
per-model budget is configured.
Every scope is checked because the summary's spend is charged to every
- scope: this file propagates the key, team, user and end-user budgets into the
- subrequest's metadata, so skipping one of them would let compaction
- increment a counter it can never be refused by.
+ scope: this file propagates the key, team, user, team-member and end-user
+ budgets into the subrequest's metadata, so skipping one of them would let
+ compaction increment a counter it can never be refused by.
"""
if user_api_key_auth is None:
return True
@@ -497,7 +551,11 @@ async def _check_summary_model_budget(
)
return False
- return True
+ return await _check_summary_team_member_model_budget(
+ user_api_key_auth=user_api_key_auth,
+ model_max_budget_limiter=model_max_budget_limiter,
+ summary_model=summary_model,
+ )
def _without_parallel_request_gauges(
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 26d9e0e1b44..7ac8b1f8538 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -2106,6 +2106,7 @@ class NewTeamRequest(TeamBase):
team_member_tpm_limit: int | None = None # allow user to set TPM limit for all team members
team_member_key_duration: str | None = None # e.g. "1d", "1w", "1m"
team_member_budget_duration: str | None = None # e.g. "30d", "1mo"
+ team_member_model_max_budget: GenericBudgetConfigType | None = None
allowed_vector_store_indexes: list[AllowedVectorStoreIndexItem] | None = None
enforced_batch_output_expires_after: dict | None = None
enforced_file_expires_after: dict | None = None
@@ -2165,6 +2166,7 @@ class UpdateTeamRequest(LiteLLMPydanticObjectBase):
require_trace_id: bool | None = None
team_member_budget: float | None = None
team_member_budget_duration: str | None = None
+ team_member_model_max_budget: GenericBudgetConfigType | None = None
team_member_rpm_limit: int | None = None
team_member_tpm_limit: int | None = None
team_member_key_duration: str | None = None
@@ -3363,6 +3365,7 @@ class UserAPIKeyAuth(LiteLLM_VerificationTokenView): # the expected response ob
# and validating it here would make one malformed row fail auth outright.
# resolve_model_budget validates the single entry a request actually needs.
user_model_max_budget: Mapping[str, object] | None = None
+ team_member_model_max_budget: Mapping[str, object] | None = Field(default=None, exclude=True)
request_route: str | None = None
is_session_token: bool = False
# Server-only marker set exclusively by the MCP gateway admission path
@@ -4651,6 +4654,13 @@ class TeamMemberUpdateRequest(TeamMemberDeleteRequest):
default=None,
description="UTC expiry for temp_budget_increase",
)
+ model_max_budget: GenericBudgetConfigType | None = Field(
+ default=None,
+ description=(
+ "Per-model spend caps for this team member, each with its own budget_duration. "
+ "Overrides the team's default per-model member budget. Pass an empty dict to fall back to the team default."
+ ),
+ )
@model_validator(mode="after")
def validate_temp_budget(self) -> "TeamMemberUpdateRequest":
@@ -4669,6 +4679,7 @@ class TeamMemberUpdateResponse(MemberUpdateResponse):
allowed_models: list[str] | None = None
temp_budget_increase: float | None = None
temp_budget_expiry: datetime | None = None
+ model_max_budget: GenericBudgetConfigType | None = None
class TeamModelAddRequest(LiteLLMBaseModel):
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.py
index 7c62e4f4147..d687b2ad7a0 100644
--- a/litellm/proxy/auth/auth_checks.py
+++ b/litellm/proxy/auth/auth_checks.py
@@ -1739,6 +1739,7 @@ async def get_team_member_default_budget(
budget_id: str,
prisma_client: PrismaClient | None,
user_api_key_cache: UserApiKeyCache,
+ raise_on_lookup_error: bool = False,
) -> LiteLLM_BudgetTable | None:
"""
Fetches the team-level default per-member budget referenced by team.metadata["team_member_budget_id"].
@@ -1773,6 +1774,8 @@ async def get_team_member_default_budget(
)
except Exception:
verbose_proxy_logger.exception("Error fetching team-default member budget %s", budget_id)
+ if raise_on_lookup_error:
+ raise
return None
if budget_record is None:
diff --git a/litellm/proxy/auth/fallback_budget.py b/litellm/proxy/auth/fallback_budget.py
index 5aa28a08bb8..a126a53821b 100644
--- a/litellm/proxy/auth/fallback_budget.py
+++ b/litellm/proxy/auth/fallback_budget.py
@@ -11,13 +11,13 @@ attempted, mirroring `fallback_model_access.py`. It deliberately leaves the prim
a zero-cost model is never blocked by budget, and only the paid fallback is refused. On by default;
set `general_settings.enforce_fallback_budget: false` to restore the unguarded behaviour.
-Scope: the key's and the user's `max_budget`. Not covered yet, and each needs a read-only evaluation
-path before it can be: team, team-member, end-user, org, global and per-model budgets, whose
-auth-path functions enforce rather than report (they raise), so reusing them would fire threshold
-alerts and take spend reservations for a target that is then skipped; and the key's rolling
-`budget_limits` windows, whose accumulated spend lives only in per-window counters
-(`spend:key:{token}:window:{budget_duration}`), so enforcing them means more counter reads on the
-fallback path rather than reusing state auth already loaded.
+Scope: the key's and the user's `max_budget`, plus the team member's per-model caps. Not covered yet,
+and each needs a read-only evaluation path before it can be: team and team-member overall, end-user,
+org, global and other per-model budgets, whose auth-path functions enforce rather than report (they
+raise), so reusing them would fire threshold alerts and take spend reservations for a target that is
+then skipped; and the key's rolling `budget_limits` windows, whose accumulated spend lives only in
+per-window counters (`spend:key:{token}:window:{budget_duration}`), so enforcing them means more
+counter reads on the fallback path rather than reusing state auth already loaded.
Two known limitations of that narrow scope, both shared with `fallback_model_access.py`:
@@ -33,10 +33,11 @@ Two known limitations of that narrow scope, both shared with `fallback_model_acc
from collections.abc import Callable, Mapping
from dataclasses import dataclass
-from typing import Final
+from typing import Final, Protocol
from pydantic import ValidationError
+import litellm
from litellm._logging import verbose_proxy_logger
from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.auth.auth_checks import ( # noqa: F401 # legacy module exports
@@ -55,6 +56,16 @@ class _FallbackBudgetSettings(LiteLLMBaseModel):
enforce_fallback_budget: bool = True
+class _TeamMemberModelBudgetLimiter(Protocol):
+ async def is_team_member_within_model_budget(
+ self,
+ user_id: str,
+ team_id: str,
+ team_member_model_max_budget: Mapping[str, object],
+ model: str,
+ ) -> bool: ...
+
+
def _token_in_metadata(metadata: object) -> UserAPIKeyAuth | None:
try:
return _RequestMetadata.model_validate(metadata).user_api_key_auth
@@ -103,7 +114,13 @@ async def _counter_spend(counter_key: str, fallback_spend: float, max_budget: fl
)
-async def is_token_within_budget_for_model(*, model: str, valid_token: UserAPIKeyAuth, llm_router: Router) -> bool:
+async def is_token_within_budget_for_model(
+ *,
+ model: str,
+ valid_token: UserAPIKeyAuth,
+ llm_router: Router,
+ team_member_model_budget_limiter: _TeamMemberModelBudgetLimiter | None = None,
+) -> bool:
"""
True when the key and the user behind it can still pay for `model`.
@@ -139,6 +156,23 @@ async def is_token_within_budget_for_model(*, model: str, valid_token: UserAPIKe
if user_spend >= user_budget:
return False
+ team_member_model_max_budget: Final = valid_token.team_member_model_max_budget
+ if (
+ team_member_model_budget_limiter is not None
+ and team_member_model_max_budget
+ and isinstance(valid_token.user_id, str)
+ and isinstance(valid_token.team_id, str)
+ ):
+ try:
+ await team_member_model_budget_limiter.is_team_member_within_model_budget(
+ user_id=valid_token.user_id,
+ team_id=valid_token.team_id,
+ team_member_model_max_budget=team_member_model_max_budget,
+ model=model,
+ )
+ except litellm.BudgetExceededError:
+ return False
+
return True
@@ -151,6 +185,7 @@ class RouterFallbackBudgetCheck:
"""
is_enforced: Callable[[], bool]
+ team_member_model_budget_limiter: _TeamMemberModelBudgetLimiter | None = None
async def __call__(self, *, model: str, request_kwargs: Mapping[str, object], llm_router: Router) -> bool:
if not self.is_enforced():
@@ -158,11 +193,20 @@ class RouterFallbackBudgetCheck:
valid_token: Final = _user_api_key_auth_from_request(request_kwargs)
if valid_token is None:
return True
- try:
- return await is_token_within_budget_for_model(model=model, valid_token=valid_token, llm_router=llm_router)
- except Exception as e: # noqa: BLE001 # fail closed: a spend lookup failure must not bill the caller
- verbose_proxy_logger.warning("Skipping fallback to model=%s: budget lookup failed: %s", model, e)
- return False
+ budget_models: Final = tuple(dict.fromkeys((model, llm_router.routable_model_group(model))))
+ for budget_model in budget_models:
+ try:
+ if not await is_token_within_budget_for_model(
+ model=budget_model,
+ valid_token=valid_token,
+ llm_router=llm_router,
+ team_member_model_budget_limiter=self.team_member_model_budget_limiter,
+ ):
+ return False
+ except Exception as e: # noqa: BLE001 # fail closed: a spend lookup failure must not bill the caller
+ verbose_proxy_logger.warning("Skipping fallback to model=%s: budget lookup failed: %s", model, e)
+ return False
+ return True
router_fallback_budget_check: Final = RouterFallbackBudgetCheck(is_enforced=_enforced_by_general_settings)
diff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.py
index d6a51bc2fc9..2231706b282 100644
--- a/litellm/proxy/auth/user_api_key_auth.py
+++ b/litellm/proxy/auth/user_api_key_auth.py
@@ -11,12 +11,11 @@ import asyncio
import fnmatch
import re
import secrets
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from datetime import datetime, timezone
from typing import Final, NamedTuple, Protocol, Union, cast
import fastapi
-import orjson
from fastapi import HTTPException, Request, WebSocket, status
from fastapi.security.api_key import APIKeyHeader
from starlette.exceptions import WebSocketException
@@ -51,13 +50,18 @@ from litellm.proxy.auth.auth_checks import ( # noqa: F401 # legacy module expo
_get_user_role, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
_is_model_cost_zero, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
_is_user_proxy_admin, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
+ _model_access_group_max_budget_check, # pyright: ignore[reportPrivateUsage] # reuse common-check group budget enforcement
_team_member_max_budget_alert_check, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
+ _unpriced_models_in_request, # pyright: ignore[reportPrivateUsage] # reuse common-check pricing enforcement
_virtual_key_max_budget_alert_check, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
_virtual_key_max_budget_check, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
_virtual_key_soft_budget_check, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
cache_key_object,
+ can_customer_access_model,
can_key_call_model,
can_object_call_model,
+ can_project_access_model,
+ can_team_access_model,
check_end_user_budget,
common_checks,
delete_cache_key_object,
@@ -67,6 +71,7 @@ from litellm.proxy.auth.auth_checks import ( # noqa: F401 # legacy module expo
get_object_permission,
get_org_object_for_request,
get_project_object,
+ get_team_member_default_budget,
get_team_membership,
get_team_object,
get_user_object,
@@ -76,9 +81,12 @@ from litellm.proxy.auth.auth_checks import ( # noqa: F401 # legacy module expo
is_user_proxy_admin,
is_valid_fallback_model,
jwt_key_mapping_cache_key,
+ key_access_group_grants_model,
key_model_aliases_for_auth_check,
resolve_and_validate_end_user_id,
resolve_default_end_user_budget,
+ route_skips_budget_checks,
+ stamp_matched_model_access_groups,
team_member_max_budget_alert_check,
virtual_key_max_budget_alert_check,
virtual_key_max_budget_check,
@@ -169,7 +177,13 @@ from litellm.proxy.utils import (
)
from litellm.repositories.table_repositories import JWTKeyMappingRepository, TeamMembershipRepository
from litellm.repositories.verification_token_repository import VerificationTokenRepository
-from litellm.router_utils.common_utils import resolve_model_group_alias
+from litellm.router_utils.common_utils import resolve_model_group_alias, resolve_served_model
+from litellm.router_utils.fallback_event_handlers import (
+ PROVIDER_SCOPED_RESOURCE_KEYS,
+ fallback_lookup_groups,
+ fallbacks_disabled_for_request,
+ get_fallback_model_group_for_lookup_groups,
+)
from litellm.secret_managers.main import get_secret_bool
from litellm.types.services import ServiceTypes
@@ -332,6 +346,18 @@ def _get_model_names_for_budget_checks(
return model
+def _budget_fallback_target_model(target: object) -> str | None:
+ if isinstance(target, str):
+ return target
+ if not isinstance(target, Mapping):
+ return None
+ target_mapping: Final = cast(Mapping[str, object], target) # cast-ok: isinstance cannot type the container's items
+ if set(target_mapping) != {"model"}:
+ return None
+ model: Final = target_mapping.get("model")
+ return model if isinstance(model, str) else None
+
+
class _KeyModelBudgetLimiter(Protocol):
async def is_key_within_model_budget(self, user_api_key_dict: UserAPIKeyAuth, model: str) -> bool: ...
@@ -354,6 +380,34 @@ class _TeamModelBudgetLimiter(Protocol):
) -> bool: ...
+class _EveryModelBudgetLimiter(Protocol):
+ async def is_key_within_model_budget(self, user_api_key_dict: UserAPIKeyAuth, model: str) -> bool: ...
+
+ async def is_user_within_model_budget(
+ self, user_id: str, user_model_max_budget: Mapping[str, object], model: str
+ ) -> bool: ...
+
+ async def is_end_user_within_model_budget(
+ self, end_user_id: str, end_user_model_max_budget: Mapping[str, object], model: str
+ ) -> bool: ...
+
+ async def is_team_within_model_budget(
+ self,
+ team_id: str,
+ team_model_max_budget: Mapping[str, object],
+ key_model_max_budget: Mapping[str, object] | None,
+ model: str,
+ ) -> bool: ...
+
+ async def is_team_member_within_model_budget(
+ self,
+ user_id: str,
+ team_id: str,
+ team_member_model_max_budget: Mapping[str, object],
+ model: str,
+ ) -> bool: ...
+
+
class _TokenTeamModels(Protocol):
@property
def team_models(self) -> list[str]: ...
@@ -374,6 +428,30 @@ def _token_team_models(valid_token: _TokenTeamModels) -> list[str]:
return valid_token.team_models
+class _TokenModelBudgetFields(Protocol):
+ @property
+ def model_max_budget(self) -> Mapping[str, object] | None: ...
+
+ @property
+ def end_user_model_max_budget(self) -> Mapping[str, object] | None: ...
+
+ @property
+ def team_model_aliases(self) -> dict[str, str] | None: ... # mutable-ok: mirrors _can_object_call_model's contract
+
+
+def _token_model_budget_fields(valid_token: _TokenModelBudgetFields) -> _TokenModelBudgetFields:
+ return valid_token
+
+
+class _RouterFallbacks(Protocol):
+ @property
+ def fallbacks(self) -> Sequence[object] | None: ...
+
+
+def _router_fallbacks(router: _RouterFallbacks) -> Sequence[object] | None:
+ return router.fallbacks
+
+
async def _read_user_model_max_budget(
user_id: str | None,
prisma_client: PrismaClient | None,
@@ -443,13 +521,455 @@ async def _check_team_model_budget(
)
+async def _is_within_every_model_budget(
+ valid_token: UserAPIKeyAuth,
+ model_max_budget_limiter: _EveryModelBudgetLimiter,
+ model: str,
+) -> bool:
+ budget_fields: Final = _token_model_budget_fields(valid_token)
+ key_model_max_budget: Final = budget_fields.model_max_budget
+ user_model_max_budget: Final = valid_token.user_model_max_budget
+ end_user_model_max_budget: Final = budget_fields.end_user_model_max_budget
+ team_model_max_budget: Final = valid_token.team_model_max_budget
+ team_member_model_max_budget: Final = valid_token.team_member_model_max_budget
+ try:
+ if valid_token.token is not None and isinstance(key_model_max_budget, Mapping) and key_model_max_budget:
+ await model_max_budget_limiter.is_key_within_model_budget(
+ user_api_key_dict=valid_token,
+ model=model,
+ )
+ if valid_token.user_id is not None and isinstance(user_model_max_budget, Mapping) and user_model_max_budget:
+ await model_max_budget_limiter.is_user_within_model_budget(
+ user_id=valid_token.user_id,
+ user_model_max_budget=user_model_max_budget,
+ model=model,
+ )
+ if (
+ valid_token.end_user_id is not None
+ and isinstance(end_user_model_max_budget, Mapping)
+ and end_user_model_max_budget
+ ):
+ await model_max_budget_limiter.is_end_user_within_model_budget(
+ end_user_id=valid_token.end_user_id,
+ end_user_model_max_budget=end_user_model_max_budget,
+ model=model,
+ )
+ if valid_token.team_id is not None and isinstance(team_model_max_budget, Mapping) and team_model_max_budget:
+ await model_max_budget_limiter.is_team_within_model_budget(
+ team_id=valid_token.team_id,
+ team_model_max_budget=team_model_max_budget,
+ key_model_max_budget=key_model_max_budget,
+ model=model,
+ )
+ if (
+ valid_token.user_id is not None
+ and valid_token.team_id is not None
+ and isinstance(team_member_model_max_budget, Mapping)
+ and team_member_model_max_budget
+ ):
+ await model_max_budget_limiter.is_team_member_within_model_budget(
+ user_id=valid_token.user_id,
+ team_id=valid_token.team_id,
+ team_member_model_max_budget=team_member_model_max_budget,
+ model=model,
+ )
+ except litellm.BudgetExceededError:
+ return False
+ return True
+
+
+async def _is_fallback_model_authorized(
+ model: str,
+ valid_token: UserAPIKeyAuth,
+ llm_model_list: Sequence[object] | None,
+ llm_router: litellm.Router | None,
+ prisma_client: PrismaClient | None = None,
+ team_membership: LiteLLM_TeamMembership | None = None,
+ project_object: LiteLLM_ProjectTableCachedObj | None = None,
+ refuse_agent_keys: bool = False,
+ team_object: LiteLLM_TeamTable | None = None,
+) -> bool:
+ if refuse_agent_keys and valid_token.agent_id is not None:
+ return False
+ try:
+ await can_key_call_model(
+ model=model,
+ llm_model_list=llm_model_list,
+ valid_token=valid_token,
+ llm_router=llm_router,
+ prisma_client=prisma_client,
+ )
+ if team_object is not None:
+ try:
+ await can_team_access_model(
+ model=model,
+ team_object=team_object,
+ llm_router=llm_router,
+ team_model_aliases=_token_model_budget_fields(valid_token).team_model_aliases,
+ key_model_aliases=key_model_aliases_for_auth_check(valid_token),
+ prisma_client=prisma_client,
+ )
+ except ProxyException as team_denial:
+ if team_denial.type != ProxyErrorTypes.team_model_access_denied:
+ raise
+ if not await key_access_group_grants_model(
+ model=model,
+ valid_token=valid_token,
+ team_object=team_object,
+ llm_router=llm_router,
+ key_model_aliases=key_model_aliases_for_auth_check(valid_token),
+ ):
+ raise
+ else:
+ team_models: Final = _token_team_models(valid_token)
+ if team_models:
+ can_object_call_model(
+ model=model,
+ llm_router=llm_router,
+ models=team_models,
+ team_model_aliases=_token_model_budget_fields(valid_token).team_model_aliases,
+ team_id=valid_token.team_id,
+ key_model_aliases=key_model_aliases_for_auth_check(valid_token),
+ object_type="team",
+ )
+ member_allowed_models: Final = (
+ team_membership.litellm_budget_table.allowed_models
+ if team_membership is not None and team_membership.litellm_budget_table is not None
+ else None
+ )
+ if member_allowed_models:
+ can_object_call_model(
+ model=model,
+ llm_router=llm_router,
+ models=member_allowed_models,
+ team_id=valid_token.team_id,
+ key_model_aliases=key_model_aliases_for_auth_check(valid_token),
+ object_type="team",
+ )
+ if project_object is not None and len(project_object.models) > 0:
+ can_project_access_model(
+ model=model,
+ project_object=project_object,
+ llm_router=llm_router,
+ key_model_aliases=key_model_aliases_for_auth_check(valid_token),
+ )
+ except ProxyException:
+ return False
+ return True
+
+
+async def _is_within_all_fallback_model_budgets(
+ valid_token: UserAPIKeyAuth,
+ model_max_budget_limiter: _EveryModelBudgetLimiter,
+ models: Sequence[str],
+) -> bool:
+ for model in models:
+ if not await _is_within_every_model_budget(
+ valid_token=valid_token,
+ model_max_budget_limiter=model_max_budget_limiter,
+ model=model,
+ ):
+ return False
+ return True
+
+
+async def _check_team_member_model_budget_with_fallback(
+ valid_token: UserAPIKeyAuth,
+ model_max_budget_limiter: _EveryModelBudgetLimiter,
+ models: Sequence[str],
+ request_data: dict[str, object], # mutable-ok: fallback rewrites the request body
+ request: Request,
+ llm_model_list: Sequence[object] | None,
+ llm_router: litellm.Router | None,
+ project_object: LiteLLM_ProjectTableCachedObj | None = None,
+ team_object: LiteLLM_TeamTable | None = None,
+ end_user_object: LiteLLM_EndUserTable | None = None,
+ route: str = "",
+ prisma_client: PrismaClient | None = None,
+ user_api_key_cache: UserApiKeyCache | None = None,
+ proxy_logging_obj: ProxyLogging | None = None,
+) -> None:
+ team_member_model_max_budget: Final = valid_token.team_member_model_max_budget
+ if (
+ valid_token.user_id is None
+ or valid_token.team_id is None
+ or not isinstance(team_member_model_max_budget, Mapping)
+ or not team_member_model_max_budget
+ ):
+ return
+
+ user_id: Final = valid_token.user_id
+ team_id: Final = valid_token.team_id
+ for model_name in models:
+ await _check_team_member_model_budget_for_model(
+ user_id=user_id,
+ team_id=team_id,
+ team_member_model_max_budget=team_member_model_max_budget,
+ model_name=model_name,
+ valid_token=valid_token,
+ model_max_budget_limiter=model_max_budget_limiter,
+ request_data=request_data,
+ request=request,
+ llm_model_list=llm_model_list,
+ llm_router=llm_router,
+ project_object=project_object,
+ team_object=team_object,
+ end_user_object=end_user_object,
+ route=route,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+
+async def _check_team_member_model_budget_for_model(
+ user_id: str,
+ team_id: str,
+ team_member_model_max_budget: Mapping[str, object],
+ model_name: str,
+ valid_token: UserAPIKeyAuth,
+ model_max_budget_limiter: _EveryModelBudgetLimiter,
+ request_data: dict[str, object], # mutable-ok: fallback rewrites the request body
+ request: Request,
+ llm_model_list: Sequence[object] | None,
+ llm_router: litellm.Router | None,
+ project_object: LiteLLM_ProjectTableCachedObj | None = None,
+ team_object: LiteLLM_TeamTable | None = None,
+ end_user_object: LiteLLM_EndUserTable | None = None,
+ route: str = "",
+ prisma_client: PrismaClient | None = None,
+ user_api_key_cache: UserApiKeyCache | None = None,
+ proxy_logging_obj: ProxyLogging | None = None,
+) -> None:
+ try:
+ await model_max_budget_limiter.is_team_member_within_model_budget(
+ user_id=user_id,
+ team_id=team_id,
+ team_member_model_max_budget=team_member_model_max_budget,
+ model=model_name,
+ )
+ except litellm.BudgetExceededError:
+ if (
+ request_data.get("model") != model_name
+ or llm_router is None
+ or fallbacks_disabled_for_request(kwargs=request_data)
+ ):
+ raise
+ fallback_succeeded: Final = await _try_team_member_model_budget_fallback(
+ user_id=user_id,
+ team_id=team_id,
+ model_name=model_name,
+ valid_token=valid_token,
+ model_max_budget_limiter=model_max_budget_limiter,
+ request_data=request_data,
+ request=request,
+ llm_model_list=llm_model_list,
+ llm_router=llm_router,
+ project_object=project_object,
+ team_object=team_object,
+ end_user_object=end_user_object,
+ route=route,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+ if not fallback_succeeded:
+ raise
+
+
+async def _try_team_member_model_budget_fallback(
+ user_id: str,
+ team_id: str,
+ model_name: str,
+ valid_token: UserAPIKeyAuth,
+ model_max_budget_limiter: _EveryModelBudgetLimiter,
+ request_data: dict[str, object], # mutable-ok: fallback rewrites the request body
+ request: Request,
+ llm_model_list: Sequence[object] | None,
+ llm_router: litellm.Router,
+ project_object: LiteLLM_ProjectTableCachedObj | None = None,
+ team_object: LiteLLM_TeamTable | None = None,
+ end_user_object: LiteLLM_EndUserTable | None = None,
+ route: str = "",
+ prisma_client: PrismaClient | None = None,
+ user_api_key_cache: UserApiKeyCache | None = None,
+ proxy_logging_obj: ProxyLogging | None = None,
+) -> bool:
+ if request.headers.get("content-type", "").lower().startswith("multipart/form-data") or any(
+ request_data.get(key) for key in PROVIDER_SCOPED_RESOURCE_KEYS
+ ):
+ return False
+
+ from litellm.proxy import proxy_server
+ from litellm.proxy.proxy_server import proxy_config
+
+ resolved_prisma_client: Final = prisma_client if prisma_client is not None else proxy_server.prisma_client
+ resolved_user_api_key_cache: Final = (
+ user_api_key_cache if user_api_key_cache is not None else proxy_server.user_api_key_cache
+ )
+ resolved_proxy_logging_obj: Final = (
+ proxy_logging_obj if proxy_logging_obj is not None else proxy_server.proxy_logging_obj
+ )
+
+ try:
+ router_settings: Final[dict[str, object] | None] = (
+ cast( # cast-ok: proxy settings return an unparameterized dict
+ dict[str, object] | None,
+ await proxy_config.get_hierarchical_router_settings(
+ user_api_key_dict=valid_token,
+ prisma_client=resolved_prisma_client,
+ proxy_logging_obj=resolved_proxy_logging_obj,
+ ),
+ )
+ )
+ except Exception: # noqa: BLE001 # Settings lookup failures must not authorize a fallback.
+ return False
+
+ configured_fallbacks: Final[object] = router_settings.get("fallbacks") if router_settings is not None else None
+ router_fallbacks: Final[Sequence[object] | None] = (
+ cast(Sequence[object], configured_fallbacks) # cast-ok: guarded by the list check below
+ if isinstance(configured_fallbacks, list)
+ else _router_fallbacks(llm_router)
+ )
+ if router_fallbacks is None:
+ return False
+
+ fallback_models, _ = get_fallback_model_group_for_lookup_groups(
+ fallbacks=list(router_fallbacks),
+ lookup_groups=fallback_lookup_groups(kwargs=request_data, model_group=model_name),
+ )
+ fallback_targets: Final[Sequence[object]] = fallback_models or ()
+ fallback_candidates: Final[tuple[str, ...]] = tuple(
+ model for target in fallback_targets if (model := _budget_fallback_target_model(target)) is not None
+ )
+ if not fallback_candidates:
+ return False
+
+ model_group_aliases: Final[object] = (
+ router_settings.get("model_group_alias") if router_settings is not None else None
+ )
+ key_aliases: Final[object] = cast( # cast-ok: auth aliases are dynamically typed at runtime
+ object, valid_token.aliases
+ )
+ resolved_fallback_candidates: Final[tuple[tuple[str, str], ...]] = tuple(
+ (
+ candidate,
+ target if (target := resolve_model_group_alias(model_group_aliases, candidate)) is not None else candidate,
+ )
+ for candidate in fallback_candidates
+ )
+ fallback_candidates_with_served_models: Final = (
+ (
+ fallback_candidate,
+ fallback_model,
+ resolve_served_model(
+ fallback_model,
+ litellm.model_alias_map,
+ key_aliases,
+ model_group_aliases,
+ ),
+ )
+ for fallback_candidate, fallback_model in resolved_fallback_candidates
+ )
+
+ try:
+ team_membership: Final = await get_team_membership(
+ user_id=user_id,
+ team_id=team_id,
+ prisma_client=resolved_prisma_client,
+ user_api_key_cache=resolved_user_api_key_cache,
+ proxy_logging_obj=resolved_proxy_logging_obj,
+ )
+ except Exception: # noqa: BLE001 # membership lookup failures must not authorize a fallback
+ return False
+
+ for fallback_candidate, fallback_model, served_model in fallback_candidates_with_served_models:
+ if fallback_model == model_name:
+ continue
+ try:
+ if (
+ litellm.block_requests_for_models_without_pricing
+ and RouteChecks.is_llm_api_route(route=route)
+ and _unpriced_models_in_request(model=served_model, llm_router=llm_router)
+ ):
+ continue
+ if end_user_object is not None and end_user_object.models:
+ can_customer_access_model(
+ model=fallback_model,
+ end_user_object=end_user_object,
+ llm_router=llm_router,
+ valid_token=valid_token,
+ )
+ if not is_model_cost_zero(
+ model=served_model, llm_router=llm_router
+ ) and not await _is_within_all_fallback_model_budgets(
+ valid_token=valid_token,
+ model_max_budget_limiter=model_max_budget_limiter,
+ models=tuple(
+ dict.fromkeys(
+ (
+ fallback_candidate,
+ fallback_model,
+ served_model,
+ llm_router.routable_model_group(served_model),
+ )
+ )
+ ),
+ ):
+ continue
+ if not await _is_fallback_model_authorized(
+ model=fallback_model,
+ valid_token=valid_token,
+ llm_model_list=llm_model_list,
+ llm_router=llm_router,
+ prisma_client=prisma_client,
+ team_object=team_object,
+ team_membership=team_membership,
+ project_object=project_object,
+ refuse_agent_keys=True,
+ ):
+ continue
+ valid_token.matched_model_access_groups = [] # rebind-ok: clear prior groups before evaluating this candidate
+ matched_groups = await stamp_matched_model_access_groups(
+ model=fallback_model,
+ valid_token=valid_token,
+ team_object=team_object,
+ project_object=project_object,
+ llm_router=llm_router,
+ prisma_client=resolved_prisma_client,
+ user_api_key_cache=resolved_user_api_key_cache,
+ proxy_logging_obj=resolved_proxy_logging_obj,
+ team_membership=team_membership,
+ team_membership_loaded=True,
+ )
+ valid_token.matched_model_access_groups = list(matched_groups) # rebind-ok: spend uses the candidate groups
+ if matched_groups:
+ await _model_access_group_max_budget_check(
+ matched_model_access_groups=list(matched_groups),
+ prisma_client=resolved_prisma_client,
+ user_api_key_cache=resolved_user_api_key_cache,
+ )
+ except Exception: # noqa: BLE001 # A candidate check failure must not escape the fail-closed walk.
+ verbose_proxy_logger.warning(
+ "Skipping fallback candidate %s after a budget or authorization check error",
+ fallback_model.replace("\r", "").replace("\n", ""),
+ exc_info=True,
+ )
+ continue
+ rewrite_request_model(request_data=request_data, request=request, model=fallback_model)
+ if "path_params" in request.scope:
+ request.scope["path_params"]["model"] = fallback_model # rebind-ok: route handlers use the fallback model
+ return True
+ return False
+
+
async def _check_key_model_budget_with_fallback(
valid_token: UserAPIKeyAuth,
model_max_budget_limiter: _KeyModelBudgetLimiter,
model_name: str,
- request_data: dict,
+ request_data: dict[str, object], # mutable-ok: fallback rewrites the request body
request: Request,
- llm_model_list: list | None = None,
+ llm_model_list: Sequence[object] | None = None,
llm_router: litellm.Router | None = None,
) -> None:
"""
@@ -489,32 +1009,16 @@ async def _check_key_model_budget_with_fallback(
)
if fallback_model is None:
raise e
- try:
- await can_key_call_model(
- model=fallback_model,
- llm_model_list=llm_model_list,
- valid_token=valid_token,
- llm_router=llm_router,
- )
- if valid_token.team_models:
- can_object_call_model(
- model=fallback_model,
- llm_router=llm_router,
- models=valid_token.team_models,
- team_model_aliases=valid_token.team_model_aliases,
- team_id=valid_token.team_id,
- key_model_aliases=key_model_aliases_for_auth_check(valid_token),
- object_type="team",
- )
- except ProxyException:
- raise e
- request_data["model"] = fallback_model
- safe_set_request_parsed_body(request=request, parsed_body=request_data)
- request._json = request_data # pyright: ignore[reportPrivateUsage] # Starlette JSON cache
- request._body = orjson.dumps(request_data) # pyright: ignore[reportPrivateUsage] # Starlette body cache
- path_params: Final = request.scope.get("path_params")
- if isinstance(path_params, dict) and "model" in path_params:
- path_params["model"] = fallback_model
+ if not await _is_fallback_model_authorized(
+ model=fallback_model,
+ valid_token=valid_token,
+ llm_model_list=llm_model_list,
+ llm_router=llm_router,
+ ):
+ raise
+ rewrite_request_model(request_data=request_data, request=request, model=fallback_model)
+ if "path_params" in request.scope:
+ request.scope["path_params"]["model"] = fallback_model # rebind-ok: route handlers use the fallback model
def _get_bearer_token_or_received_api_key(api_key: str) -> str:
@@ -2543,7 +3047,9 @@ async def validate_resolved_virtual_key( # noqa: C901 # Preserve ordering of e
model_name=model_name,
request_data=request_data,
request=request,
- llm_model_list=llm_model_list,
+ llm_model_list=cast( # cast-ok: router model lists are deployment sequences
+ Sequence[object] | None, llm_model_list
+ ),
llm_router=llm_router,
)
@@ -2836,6 +3342,79 @@ def is_no_auth_dev_mode(master_key: str | None, general_settings: Mapping[str, o
)
+async def _load_team_member_default_model_budget(
+ user_api_key_auth_obj: UserAPIKeyAuth,
+ team_object: LiteLLM_TeamTable | None,
+ prisma_client: PrismaClient | None,
+ user_api_key_cache: UserApiKeyCache,
+ skip_budget_checks: bool,
+ proxy_logging_obj: ProxyLogging | None,
+) -> None:
+ team_metadata_value: Final[object] = getattr(team_object, "metadata", None) if team_object is not None else None
+ team_metadata: Final[Mapping[str, object] | None] = (
+ cast( # cast-ok: team metadata is a string-keyed JSON object
+ Mapping[str, object], team_metadata_value
+ )
+ if isinstance(team_metadata_value, Mapping)
+ else None
+ )
+ team_member_budget_id: Final[object | None] = (
+ team_metadata.get("team_member_budget_id") if isinstance(team_metadata, Mapping) else None
+ )
+ if (
+ not isinstance(user_api_key_auth_obj.user_id, str)
+ or not isinstance(user_api_key_auth_obj.team_id, str)
+ or prisma_client is None
+ ):
+ return
+
+ try:
+ membership: Final = await get_team_membership(
+ user_id=user_api_key_auth_obj.user_id,
+ team_id=user_api_key_auth_obj.team_id,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+ member_budget_row: Final = membership.litellm_budget_table if membership is not None else None
+ member_budget_value: Final[object] = (
+ getattr(member_budget_row, "model_max_budget", None) if member_budget_row is not None else None
+ )
+ if (
+ membership is not None
+ and membership.budget_id is not None
+ and membership.budget_id != team_member_budget_id
+ and isinstance(member_budget_value, Mapping)
+ and member_budget_value
+ ):
+ user_api_key_auth_obj.team_member_model_max_budget = ( # rebind-ok: auth context carries member budget downstream
+ member_budget_value
+ )
+ return
+ if not isinstance(team_member_budget_id, str):
+ return
+ team_member_default_budget: Final = await get_team_member_default_budget(
+ budget_id=team_member_budget_id,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ raise_on_lookup_error=True,
+ )
+ except Exception:
+ if not skip_budget_checks:
+ raise
+ verbose_proxy_logger.warning("Skipping team-member model budget lookup after a lookup error", exc_info=True)
+ return
+
+ default_budget_value: Final[object] = (
+ getattr(team_member_default_budget, "model_max_budget", None)
+ if team_member_default_budget is not None
+ else None
+ )
+ user_api_key_auth_obj.team_member_model_max_budget = ( # rebind-ok: auth context carries default budget downstream
+ default_budget_value if isinstance(default_budget_value, Mapping) else None
+ )
+
+
@tracer.wrap()
async def run_centralized_common_checks(
user_api_key_auth_obj: UserAPIKeyAuth,
@@ -2864,6 +3443,7 @@ async def run_centralized_common_checks(
from litellm.proxy.proxy_server import (
general_settings,
litellm_proxy_admin_name,
+ llm_model_list, # pyright: ignore[reportUnknownVariableType] # proxy global has untyped deployment entries
llm_router,
master_key,
model_max_budget_limiter,
@@ -3124,6 +3704,17 @@ async def run_centralized_common_checks(
llm_router=llm_router,
team_id=user_api_key_auth_obj.team_id,
)
+ typed_team_object: Final[LiteLLM_TeamTable | None] = (
+ team_object if isinstance(team_object, LiteLLM_TeamTable) else None
+ )
+ await _load_team_member_default_model_budget(
+ user_api_key_auth_obj=user_api_key_auth_obj,
+ team_object=typed_team_object,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ skip_budget_checks=skip_budget_checks or route_skips_budget_checks(route=route),
+ proxy_logging_obj=proxy_logging_obj,
+ )
# Pin the metadata variable name (litellm_metadata vs metadata) before
# any tag merge runs. Without this, header tags from
@@ -3164,19 +3755,42 @@ async def run_centralized_common_checks(
project_object=project_object,
)
if not skip_budget_checks:
+ models: Final = _get_model_names_for_budget_checks(
+ model=_get_model_from_request_context(
+ request_data=request_data,
+ route=route,
+ request=request,
+ llm_router=llm_router,
+ team_id=user_api_key_auth_obj.team_id,
+ )
+ )
await _check_team_model_budget(
valid_token=user_api_key_auth_obj,
model_max_budget_limiter=model_max_budget_limiter,
- models=_get_model_names_for_budget_checks(
- model=_get_model_from_request_context(
- request_data=request_data,
- route=route,
- request=request,
- llm_router=llm_router,
- team_id=user_api_key_auth_obj.team_id,
- )
- ),
+ models=models,
)
+ typed_project_object: Final[LiteLLM_ProjectTableCachedObj | None] = (
+ project_object if isinstance(project_object, LiteLLM_ProjectTableCachedObj) else None
+ )
+ if not route_skips_budget_checks(route=route):
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=user_api_key_auth_obj,
+ model_max_budget_limiter=model_max_budget_limiter,
+ models=models,
+ request_data=request_data,
+ request=request,
+ llm_model_list=cast( # cast-ok: router model lists are deployment sequences
+ Sequence[object] | None, llm_model_list
+ ),
+ llm_router=llm_router,
+ project_object=typed_project_object,
+ team_object=typed_team_object,
+ end_user_object=end_user_object if isinstance(end_user_object, LiteLLM_EndUserTable) else None,
+ route=route,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ proxy_logging_obj=proxy_logging_obj,
+ )
await _reserve_budget_after_common_checks(
user_api_key_auth_obj=user_api_key_auth_obj,
@@ -3184,7 +3798,10 @@ async def run_centralized_common_checks(
request_data=request_data,
route=route,
llm_router=llm_router,
- team_object=team_object,
+ team_object=cast( # cast-ok: preserve plain team-table objects through reservation
+ LiteLLM_TeamTableCachedObj | None,
+ team_object,
+ ),
user_object=user_object,
end_user_id=end_user_id,
end_user_object=end_user_object,
@@ -3855,13 +4472,13 @@ async def enforce_key_and_fallback_model_access(
)
-_enforce_key_and_fallback_model_access: Final = enforce_key_and_fallback_model_access
+_enforce_key_and_fallback_model_access: Final = enforce_key_and_fallback_model_access # pyright: ignore[reportUnknownVariableType] # existing tests use this alias
async def _run_post_custom_auth_checks(
valid_token: UserAPIKeyAuth,
request: Request,
- request_data: dict,
+ request_data: dict[str, object],
route: str,
parent_otel_span: Span | None,
) -> UserAPIKeyAuth:
@@ -3956,7 +4573,9 @@ async def _run_post_custom_auth_checks(
model_name=model_name,
request_data=request_data,
request=request,
- llm_model_list=llm_model_list,
+ llm_model_list=cast( # cast-ok: router model lists are deployment sequences
+ Sequence[object] | None, llm_model_list
+ ),
llm_router=llm_router,
)
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.py
index 7f0e0b1fc87..ed9ac258e16 100644
--- a/litellm/proxy/common_request_processing.py
+++ b/litellm/proxy/common_request_processing.py
@@ -83,6 +83,7 @@ from litellm.litellm_core_utils.streaming_handler import (
from litellm.proxy._types import LiteLLMRoutes, ProxyErrorTypes, ProxyException, UserAPIKeyAuth
from litellm.proxy.auth.auth_checks import (
can_key_call_resolved_model,
+ is_model_cost_zero,
request_skips_budget_checks,
tag_max_budget_check_for_tags,
)
@@ -127,7 +128,7 @@ from litellm.proxy.utils import ( # noqa: F401 # legacy module exports
)
from litellm.router import Router
from litellm.router_utils.add_retry_fallback_headers import get_hidden_params_dict
-from litellm.router_utils.common_utils import resolve_model_group_alias
+from litellm.router_utils.common_utils import resolve_model_group_alias, resolve_served_model
from litellm.types.guardrails import GuardrailEventHooks
from litellm.types.router import RouterRateLimitError
from litellm.types.router_weights import validate_router_weights
@@ -250,6 +251,7 @@ from litellm.proxy.litellm_pre_call_utils import (
add_litellm_data_to_request,
refresh_proxy_server_request_body_snapshot,
reject_url_valued_destination,
+ sanitize_for_log,
)
from litellm.proxy.policy_engine.response_retrieval import attach_post_call_pipelines_to_retrieval
from litellm.types.utils import (
@@ -737,6 +739,7 @@ async def _resolve_per_request_model_group_alias(
_REQUEST_MODEL: Final[TypeAdapter[str | list[str] | None]] = TypeAdapter(str | list[str] | None)
+_ROUTER_SETTINGS_ADAPTER: Final[TypeAdapter[Mapping[str, object] | None]] = TypeAdapter(Mapping[str, object] | None)
def _request_model(data: Mapping[str, object]) -> str | list[str] | None:
@@ -1733,6 +1736,69 @@ def _timing_values(
return getattr(logging_obj, "response_timing_metrics", None) or {}
+async def _team_member_within_fallback_model_budget(
+ user_api_key_dict: UserAPIKeyAuth,
+ model: str,
+ llm_router: Router | None,
+ proxy_config: ProxyConfig | None,
+ proxy_logging_obj: ProxyLogging,
+) -> bool:
+ member_caps: Final = user_api_key_dict.team_member_model_max_budget
+ user_id: Final = user_api_key_dict.user_id
+ team_id: Final = user_api_key_dict.team_id
+ if not isinstance(member_caps, Mapping) or not member_caps or user_id is None or team_id is None:
+ return True
+ from litellm.proxy.proxy_server import model_max_budget_limiter
+
+ try:
+ from litellm.proxy.proxy_server import prisma_client
+
+ router_settings: Final = (
+ _ROUTER_SETTINGS_ADAPTER.validate_python(
+ await proxy_config.get_hierarchical_router_settings( # pyright: ignore[reportUnknownMemberType] # legacy bare-dict return
+ user_api_key_dict=user_api_key_dict,
+ prisma_client=prisma_client,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+ )
+ if proxy_config is not None and llm_router is not None
+ else None
+ )
+ raw_aliases: Final[object] = cast( # cast-ok: auth aliases are dynamically typed at runtime
+ object, user_api_key_dict.aliases
+ )
+ served_model: Final = resolve_served_model(
+ model,
+ litellm.model_alias_map,
+ raw_aliases,
+ router_settings.get("model_group_alias") if router_settings is not None else None,
+ )
+ if is_model_cost_zero(model=served_model, llm_router=llm_router):
+ return True
+ budget_models: Final = (
+ tuple(dict.fromkeys((model, served_model, llm_router.routable_model_group(served_model))))
+ if llm_router is not None
+ else tuple(dict.fromkeys((model, served_model)))
+ )
+ for budget_model in budget_models:
+ await model_max_budget_limiter.is_team_member_within_model_budget(
+ user_id=user_id,
+ team_id=team_id,
+ team_member_model_max_budget=member_caps,
+ model=budget_model,
+ )
+ except litellm.BudgetExceededError:
+ return False
+ except Exception as e: # noqa: BLE001 # fail closed: a spend lookup failure must not bill the member
+ verbose_proxy_logger.warning(
+ "Skipping rate limit fallback to model=%s: member budget lookup failed: %s",
+ sanitize_for_log(model),
+ sanitize_for_log(e),
+ )
+ return False
+ return True
+
+
class ProxyBaseLLMRequestProcessing:
def __init__(self, data: dict):
self.data = data
@@ -2371,6 +2437,14 @@ class ProxyBaseLLMRequestProcessing:
for fallback_model in fallback_models:
if fallback_model == original_model:
continue
+ if not await _team_member_within_fallback_model_budget(
+ user_api_key_dict=user_api_key_dict,
+ model=fallback_model,
+ llm_router=llm_router,
+ proxy_config=proxy_config,
+ proxy_logging_obj=proxy_logging_obj,
+ ):
+ continue
self.data = independent_snapshot(pristine)
self.data["model"] = fallback_model
try:
diff --git a/litellm/proxy/hooks/model_max_budget_limiter.py b/litellm/proxy/hooks/model_max_budget_limiter.py
index 8bca51784f2..eaa185917e5 100644
--- a/litellm/proxy/hooks/model_max_budget_limiter.py
+++ b/litellm/proxy/hooks/model_max_budget_limiter.py
@@ -4,7 +4,7 @@ import time
from collections.abc import Iterable, Mapping, Sequence
from dataclasses import dataclass
from types import MappingProxyType
-from typing import Final
+from typing import Final, cast # noqa: TID251 # untyped callback payload requires explicit narrowing
from openai.types import Batch
@@ -25,6 +25,7 @@ VIRTUAL_KEY_SPEND_CACHE_KEY_PREFIX: Final = "virtual_key_spend"
END_USER_SPEND_CACHE_KEY_PREFIX: Final = "end_user_model_spend"
USER_SPEND_CACHE_KEY_PREFIX: Final = "user_model_spend"
TEAM_SPEND_CACHE_KEY_PREFIX: Final = "team_model_spend"
+TEAM_MEMBER_SPEND_CACHE_KEY_PREFIX: Final = "team_member_model_spend"
_SPEND_CACHE_KEY_PREFIXES: Final = MappingProxyType(
{
@@ -32,6 +33,7 @@ _SPEND_CACHE_KEY_PREFIXES: Final = MappingProxyType(
Litellm_EntityType.USER: USER_SPEND_CACHE_KEY_PREFIX,
Litellm_EntityType.END_USER: END_USER_SPEND_CACHE_KEY_PREFIX,
Litellm_EntityType.TEAM: TEAM_SPEND_CACHE_KEY_PREFIX,
+ Litellm_EntityType.TEAM_MEMBER: TEAM_MEMBER_SPEND_CACHE_KEY_PREFIX,
}
)
@@ -45,6 +47,7 @@ _BUDGET_START_TIME_KEY_PREFIXES: Final = MappingProxyType(
Litellm_EntityType.USER: "user_model_budget_start_time",
Litellm_EntityType.END_USER: "end_user_budget_start_time",
Litellm_EntityType.TEAM: "team_model_budget_start_time",
+ Litellm_EntityType.TEAM_MEMBER: "team_member_model_budget_start_time",
}
)
@@ -63,6 +66,10 @@ class ResolvedModelBudget:
budget_config: BudgetConfig
+def team_member_budget_entity_id(user_id: str, team_id: str) -> str:
+ return f"{len(user_id)}:{user_id}:{team_id}"
+
+
def model_budget_spend_cache_key(
entity_type: Litellm_EntityType,
entity_id: str | None,
@@ -290,6 +297,18 @@ def _resolve_entity_model_budgets(
)
+def _metadata_value(metadata: object, key: str) -> object | None:
+ metadata_mapping: Final[Mapping[str, object]] = cast( # cast-ok: callback metadata has string keys
+ Mapping[str, object], metadata
+ )
+ return metadata_mapping.get(key)
+
+
+def _metadata_string_value(metadata: object, key: str) -> str | None:
+ value: Final = _metadata_value(metadata, key)
+ return value if isinstance(value, str) else None
+
+
class _PROXY_VirtualKeyModelMaxBudgetLimiter(RouterBudgetLimiting):
"""
Handles budgets for model + virtual key
@@ -410,6 +429,24 @@ class _PROXY_VirtualKeyModelMaxBudgetLimiter(RouterBudgetLimiting):
exceeded_message=f"LiteLLM Team: {team_id}, exceeded budget for model={model}",
)
+ @with_service_target("model_budgets")
+ async def is_team_member_within_model_budget(
+ self,
+ user_id: str,
+ team_id: str,
+ team_member_model_max_budget: Mapping[str, object],
+ model: str,
+ ) -> bool:
+ return await self._is_entity_within_model_budget(
+ entity_type=Litellm_EntityType.TEAM_MEMBER,
+ entity_id=team_member_budget_entity_id(user_id=user_id, team_id=team_id),
+ model_max_budget=team_member_model_max_budget,
+ model=model,
+ exceeded_message=(
+ f"LiteLLM Team Member: user={user_id}, team={team_id}, exceeded budget for model={model}"
+ ),
+ )
+
async def _is_entity_within_model_budget(
self,
entity_type: Litellm_EntityType,
@@ -523,6 +560,19 @@ class _PROXY_VirtualKeyModelMaxBudgetLimiter(RouterBudgetLimiting):
response_cost: Final[float] = standard_logging_payload.get("response_cost", 0)
key_model_max_budget: Final = _metadata.get("user_api_key_model_max_budget")
+ team_member_user_id: Final = _metadata_string_value(
+ payload_metadata, # pyright: ignore[reportUnknownArgumentType] # callback metadata is partially untyped
+ "user_api_key_user_id",
+ )
+ team_member_team_id: Final = _metadata_string_value(
+ payload_metadata, # pyright: ignore[reportUnknownArgumentType] # callback metadata is partially untyped
+ "user_api_key_team_id",
+ )
+ team_member_entity_id: Final = (
+ team_member_budget_entity_id(user_id=team_member_user_id, team_id=team_member_team_id)
+ if team_member_user_id is not None and team_member_team_id is not None
+ else None
+ )
entity_budgets: Final = (
(
Litellm_EntityType.KEY,
@@ -553,6 +603,14 @@ class _PROXY_VirtualKeyModelMaxBudgetLimiter(RouterBudgetLimiting):
standard_logging_payload.get("end_user") or payload_metadata.get("user_api_key_end_user_id"),
_metadata.get("user_api_key_end_user_model_max_budget"),
),
+ (
+ Litellm_EntityType.TEAM_MEMBER,
+ team_member_entity_id,
+ _metadata_value(
+ _metadata, # pyright: ignore[reportUnknownArgumentType] # callback metadata is partially untyped
+ "user_api_key_team_member_model_max_budget",
+ ),
+ ),
)
resolved_budgets: Final = _resolve_entity_model_budgets(model=model, entity_budgets=entity_budgets)
diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.py
index 913310952cd..0d693b85ce8 100644
--- a/litellm/proxy/litellm_pre_call_utils.py
+++ b/litellm/proxy/litellm_pre_call_utils.py
@@ -2508,6 +2508,9 @@ async def add_litellm_data_to_request(
data[_metadata_variable_name]["user_api_key_user_max_budget"] = user_api_key_dict.user_max_budget
user_model_budget: Final = user_api_key_dict.user_model_max_budget
data[_metadata_variable_name]["user_api_key_user_model_max_budget"] = user_model_budget # rebind-ok: out-param
+ data[_metadata_variable_name][ # rebind-ok: adds member budget for spend tracking
+ "user_api_key_team_member_model_max_budget"
+ ] = user_api_key_dict.team_member_model_max_budget
data[_metadata_variable_name].update(carried_budget_metadata(user_api_key_dict))
data[_metadata_variable_name]["user_api_key_metadata"] = strip_callback_config(user_api_key_dict.metadata)
diff --git a/litellm/proxy/management_endpoints/budget_management_endpoints.py b/litellm/proxy/management_endpoints/budget_management_endpoints.py
index d001dc666af..b3f372327dc 100644
--- a/litellm/proxy/management_endpoints/budget_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/budget_management_endpoints.py
@@ -19,6 +19,8 @@ from typing import Final
from fastapi import APIRouter, Depends, HTTPException
+from litellm._internal_context import service_target
+from litellm._logging import verbose_proxy_logger
from litellm.proxy._types import *
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.common_utils.timezone_utils import get_budget_reset_time
@@ -141,7 +143,7 @@ async def update_budget(
- model_max_budget: Optional[dict] - Specify max budget for a given model. Example: {"openai/gpt-4o-mini": {"max_budget": 100.0, "budget_duration": "1d", "tpm_limit": 100000, "rpm_limit": 100000}}
- budget_reset_at: Optional[datetime] - Update the Datetime when the budget was last reset.
"""
- from litellm.proxy.proxy_server import litellm_proxy_admin_name, prisma_client
+ from litellm.proxy.proxy_server import litellm_proxy_admin_name, prisma_client, user_api_key_cache
if prisma_client is None:
raise HTTPException(
@@ -199,6 +201,11 @@ async def update_budget(
where={"budget_id": budget_obj.budget_id},
data=budget_obj_jsonified,
)
+ with service_target("team_member_budgets"):
+ try:
+ await user_api_key_cache.async_delete_cache(key=f"team_member_default_budget:{budget_obj.budget_id}")
+ except Exception: # noqa: BLE001 # Cache failure must not fail a committed budget update.
+ verbose_proxy_logger.warning("Failed to evict the team member default budget cache", exc_info=True)
return response
diff --git a/litellm/proxy/management_endpoints/common_utils.py b/litellm/proxy/management_endpoints/common_utils.py
index 6a70a0137a4..adf89c29279 100644
--- a/litellm/proxy/management_endpoints/common_utils.py
+++ b/litellm/proxy/management_endpoints/common_utils.py
@@ -1,3 +1,4 @@
+import json
import math
from collections.abc import Mapping
from types import MappingProxyType
@@ -580,21 +581,31 @@ MEMBER_BUDGET_PATCH_FIELDS: Final = MappingProxyType(
"allowed_models": "allowed_models",
"temp_budget_increase": "temp_budget_increase",
"temp_budget_expiry": "temp_budget_expiry",
+ "model_max_budget": "model_max_budget",
}
)
-def _prisma_value(value: object) -> object:
+_JSON_BUDGET_COLUMNS: Final = frozenset({"model_max_budget"})
+
+
+def _prisma_value(column: str, value: object) -> object:
+ if column in _JSON_BUDGET_COLUMNS:
+ return json.dumps(value if value is not None else {})
return list(value) if isinstance(value, tuple) else value
+def _prisma_payload(data: Mapping[str, object]) -> dict[str, object]:
+ return {column: _prisma_value(column, value) for column, value in data.items()}
+
+
def member_budget_patch(source: BaseModel) -> Mapping[str, object]:
"""Map the per-member limit fields a request actually set to their budget-table
columns (merge-patch: a sent value updates, an explicit null clears, an absent
field is left untouched)."""
provided: Final = source.model_dump(exclude_unset=True)
return {
- column: _prisma_value(provided[request_field])
+ column: provided[request_field]
for request_field, column in MEMBER_BUDGET_PATCH_FIELDS.items()
if request_field in provided
}
@@ -603,7 +614,7 @@ def member_budget_patch(source: BaseModel) -> Mapping[str, object]:
def _is_set_budget_value(value: object) -> bool:
if value is None:
return False
- if isinstance(value, list) and len(value) == 0:
+ if isinstance(value, (list, dict)) and len(value) == 0:
return False
return True
@@ -645,10 +656,26 @@ async def upsert_budget_and_membership(
A patch that only touches the temporary budget pair never copies permanent
limits into a new row, so the member keeps inheriting the live team default.
"""
- if not budget_patch:
+ ignore_default_model_budget_clear: Final = (
+ existing_budget_id is not None
+ and existing_budget_id == team_default_budget_id
+ and "model_max_budget" in budget_patch
+ and (
+ budget_patch["model_max_budget"] is None
+ or (isinstance(budget_patch["model_max_budget"], Mapping) and not budget_patch["model_max_budget"])
+ )
+ )
+ effective_patch: Final = MappingProxyType(
+ {
+ field: value
+ for field, value in budget_patch.items()
+ if not (ignore_default_model_budget_clear and field == "model_max_budget")
+ }
+ )
+ if not effective_patch:
return
- write_data: Final = dict(budget_patch)
+ write_data: Final = dict(effective_patch)
if "budget_duration" in write_data:
duration: Final = write_data["budget_duration"]
write_data["budget_reset_at"] = (
@@ -675,7 +702,7 @@ async def upsert_budget_and_membership(
return
await tx.litellm_budgettable.update(
where={"budget_id": existing_budget_id},
- data={"updated_by": user_api_key_dict.user_id or "", **write_data},
+ data={"updated_by": user_api_key_dict.user_id or "", **_prisma_payload(write_data)},
)
return
@@ -689,14 +716,24 @@ async def upsert_budget_and_membership(
create_data: Final[dict[str, object]] = { # mutable-ok: Prisma create payloads are dict-shaped
"created_by": user_api_key_dict.user_id or "",
"updated_by": user_api_key_dict.user_id or "",
+ "model_max_budget": {},
**MappingProxyType(
- {f: source[f] for f in _TEAM_MEMBER_BUDGET_LIMIT_FIELDS if _is_set_budget_value(source.get(f))}
+ {
+ f: source[f]
+ for f in _TEAM_MEMBER_BUDGET_LIMIT_FIELDS
+ if (
+ f != "model_max_budget"
+ or team_default_budget_id is None
+ or source.get("budget_id") != team_default_budget_id
+ )
+ and _is_set_budget_value(source.get(f))
+ }
),
**write_data,
}
# Restarting an inherited window on an unrelated edit hands the member a free period.
- carried: Final = source.get("budget_reset_at") if "budget_duration" not in budget_patch else None
+ carried: Final = source.get("budget_reset_at") if "budget_duration" not in effective_patch else None
if carried is not None:
create_data["budget_reset_at"] = carried
if create_data.get("budget_reset_at") is None:
@@ -708,7 +745,7 @@ async def upsert_budget_and_membership(
return
new_budget: Final = await tx.litellm_budgettable.create(
- data=create_data,
+ data=_prisma_payload(create_data),
include={"team_membership": True},
)
await tx.litellm_teammembership.upsert(
diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.py
index c78434eda83..544bc471ce5 100644
--- a/litellm/proxy/management_endpoints/team_endpoints.py
+++ b/litellm/proxy/management_endpoints/team_endpoints.py
@@ -37,6 +37,7 @@ from pydantic import BaseModel, Field, JsonValue, TypeAdapter, ValidationError
from typing_extensions import ReadOnly, TypedDict, assert_never
import litellm
+from litellm._internal_context import with_service_target
from litellm._logging import verbose_proxy_logger
from litellm._uuid import uuid
from litellm.integrations.prometheus import PrometheusLogger
@@ -228,7 +229,7 @@ from litellm.types.proxy.management_endpoints.team_endpoints import (
TeamUserSpendRow,
UpdateTeamMemberPermissionsRequest,
)
-from litellm.types.utils import BudgetConfig
+from litellm.types.utils import BudgetConfig, GenericBudgetConfigType
if TYPE_CHECKING:
from prisma import Prisma
@@ -547,6 +548,7 @@ class TeamMemberBudgetHandler:
team_member_rpm_limit: int | None = None,
team_member_tpm_limit: int | None = None,
team_member_budget_duration: str | None = None,
+ team_member_model_max_budget: GenericBudgetConfigType | None = None,
) -> bool:
"""Check if any team member limits are provided"""
return any(
@@ -555,9 +557,22 @@ class TeamMemberBudgetHandler:
team_member_rpm_limit is not None,
team_member_tpm_limit is not None,
team_member_budget_duration is not None,
+ team_member_model_max_budget is not None,
]
)
+ @staticmethod
+ @with_service_target("team_member_budgets")
+ async def _evict_default_budget_cache(
+ budget_id: str,
+ user_api_key_cache: UserApiKeyCache | None,
+ ) -> None:
+ if user_api_key_cache is not None:
+ try:
+ await user_api_key_cache.async_delete_cache(key=f"team_member_default_budget:{budget_id}")
+ except Exception: # noqa: BLE001 # Cache failure must not fail a committed budget update.
+ verbose_proxy_logger.warning("Failed to evict the team member default budget cache", exc_info=True)
+
@staticmethod
async def create_team_member_budget_table(
data: NewTeamRequest | _TeamAliasBudgetRow,
@@ -567,6 +582,8 @@ class TeamMemberBudgetHandler:
team_member_rpm_limit: int | None = None,
team_member_tpm_limit: int | None = None,
team_member_budget_duration: str | None = None,
+ team_member_model_max_budget: GenericBudgetConfigType | None = None,
+ user_api_key_cache: UserApiKeyCache | None = None,
explicitly_set_fields: AbstractSet[str] = frozenset(),
) -> dict:
"""Create team member budget table with provided limits.
@@ -602,11 +619,17 @@ class TeamMemberBudgetHandler:
budget_request.tpm_limit = team_member_tpm_limit
if team_member_budget_duration is not None:
budget_request.budget_duration = team_member_budget_duration
+ if team_member_model_max_budget is not None:
+ budget_request.model_max_budget = team_member_model_max_budget
team_member_budget_table: Final = await _as_budget_write(new_budget)(
budget_obj=budget_request,
user_api_key_dict=user_api_key_dict,
)
+ await TeamMemberBudgetHandler._evict_default_budget_cache(
+ budget_id=team_member_budget_table.budget_id,
+ user_api_key_cache=user_api_key_cache,
+ )
# Add team_member_budget_id as metadata field to team table
if new_team_data_json.get("metadata") is None:
@@ -627,6 +650,8 @@ class TeamMemberBudgetHandler:
team_member_rpm_limit: int | None = None,
team_member_tpm_limit: int | None = None,
team_member_budget_duration: str | None = None,
+ team_member_model_max_budget: GenericBudgetConfigType | None = None,
+ user_api_key_cache: UserApiKeyCache | None = None,
explicitly_set_fields: AbstractSet[str] = frozenset(),
) -> dict:
"""Upsert team member budget table with provided limits.
@@ -657,11 +682,19 @@ class TeamMemberBudgetHandler:
budget_request.budget_duration = team_member_budget_duration
if team_member_budget_duration is None:
budget_request.budget_reset_at = None
+ if team_member_model_max_budget is not None or "team_member_model_max_budget" in explicitly_set_fields:
+ budget_request.model_max_budget = (
+ {} if team_member_model_max_budget is None else team_member_model_max_budget
+ )
budget_row: Final = await _as_budget_write(update_budget)(
budget_obj=budget_request,
user_api_key_dict=user_api_key_dict,
)
+ await TeamMemberBudgetHandler._evict_default_budget_cache(
+ budget_id=team_member_budget_id,
+ user_api_key_cache=user_api_key_cache,
+ )
verbose_proxy_logger.info(
"Updated team member budget table: %s, with team_member_budget=%s, team_member_rpm_limit=%s, team_member_tpm_limit=%s",
budget_row.budget_id,
@@ -682,6 +715,8 @@ class TeamMemberBudgetHandler:
team_member_rpm_limit=team_member_rpm_limit,
team_member_tpm_limit=team_member_tpm_limit,
team_member_budget_duration=team_member_budget_duration,
+ team_member_model_max_budget=team_member_model_max_budget,
+ user_api_key_cache=user_api_key_cache,
explicitly_set_fields=explicitly_set_fields,
)
@@ -696,6 +731,9 @@ class TeamMemberBudgetHandler:
data_dict.pop("team_member_budget_duration", None)
data_dict.pop("team_member_rpm_limit", None)
data_dict.pop("team_member_tpm_limit", None)
+ data_dict.pop( # pyright: ignore[reportUnknownMemberType] # legacy raw dict lacks key typing
+ "team_member_model_max_budget", None
+ )
_clean_team_member_fields = clean_team_member_fields
@@ -705,6 +743,7 @@ class TeamMemberBudgetHandler:
user_api_key_dict: "UserAPIKeyAuth",
updated_kv: dict,
explicitly_set_fields: set,
+ user_api_key_cache: UserApiKeyCache | None = None,
) -> dict:
"""Clear explicitly-nulled fields on the team member budget row."""
from litellm.proxy._types import BudgetNewRequest
@@ -727,10 +766,16 @@ class TeamMemberBudgetHandler:
budget_request.rpm_limit = None
if "team_member_tpm_limit" in explicitly_set_fields:
budget_request.tpm_limit = None
+ if "team_member_model_max_budget" in explicitly_set_fields:
+ budget_request.model_max_budget = {}
await update_budget(
budget_obj=budget_request,
user_api_key_dict=user_api_key_dict,
)
+ await TeamMemberBudgetHandler._evict_default_budget_cache(
+ budget_id=team_member_budget_id,
+ user_api_key_cache=user_api_key_cache,
+ )
TeamMemberBudgetHandler.clean_team_member_fields(updated_kv)
return updated_kv
@@ -1420,6 +1465,7 @@ async def new_team(
- object_permission: Optional[LiteLLM_ObjectPermissionBase] - team-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "agents": ["agent_1", "agent_2"], "agent_access_groups": ["dev_group"]}. IF null or {} then no object permission.
- team_member_budget: Optional[float] - The maximum budget allocated to an individual team member.
- team_member_budget_duration: Optional[str] - The duration of the budget for the team member. Doc [here](https://docs.litellm.ai/docs/proxy/team_budgets)
+ - team_member_model_max_budget: Optional[dict] - Per-model budgets shared by team members without an override.
- team_member_rpm_limit: Optional[int] - The RPM (Requests Per Minute) limit for individual team members.
- team_member_tpm_limit: Optional[int] - The TPM (Tokens Per Minute) limit for individual team members.
- team_member_key_duration: Optional[str] - The duration for a team member's key. e.g. "1d", "1w", "1mo"
@@ -1508,6 +1554,10 @@ async def new_team(
validate_budget_duration(data.budget_duration)
validate_budget_duration(data.team_member_budget_duration)
validate_team_model_max_budget(model_max_budget=data.model_max_budget, premium_user=premium_user)
+ validate_team_model_max_budget(
+ model_max_budget=data.team_member_model_max_budget,
+ premium_user=premium_user,
+ )
if data.soft_budget is not None:
if data.max_budget is not None:
@@ -1702,6 +1752,7 @@ async def new_team(
team_member_rpm_limit=data.team_member_rpm_limit,
team_member_tpm_limit=data.team_member_tpm_limit,
team_member_budget_duration=data.team_member_budget_duration,
+ team_member_model_max_budget=data.team_member_model_max_budget,
):
data_json = await TeamMemberBudgetHandler.create_team_member_budget_table(
data=data,
@@ -1711,6 +1762,8 @@ async def new_team(
team_member_rpm_limit=data.team_member_rpm_limit,
team_member_tpm_limit=data.team_member_tpm_limit,
team_member_budget_duration=data.team_member_budget_duration,
+ team_member_model_max_budget=data.team_member_model_max_budget,
+ user_api_key_cache=user_api_key_cache,
explicitly_set_fields=data.model_fields_set,
)
@@ -2190,6 +2243,7 @@ async def update_team(
- object_permission: Optional[LiteLLM_ObjectPermissionBase] - team-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "agents": ["agent_1", "agent_2"], "agent_access_groups": ["dev_group"]}. IF null or {} then no object permission.
- team_member_budget: Optional[float] - The maximum budget allocated to an individual team member.
- team_member_budget_duration: Optional[str] - The duration of the budget for the team member. Doc [here](https://docs.litellm.ai/docs/proxy/team_budgets)
+ - team_member_model_max_budget: Optional[dict] - Per-model budgets shared by team members without an override.
- team_member_rpm_limit: Optional[int] - The RPM (Requests Per Minute) limit for individual team members.
- team_member_tpm_limit: Optional[int] - The TPM (Tokens Per Minute) limit for individual team members.
- team_member_key_duration: Optional[str] - The duration for a team member's key. e.g. "1d", "1w", "1mo"
@@ -2276,6 +2330,10 @@ async def update_team(
validate_budget_duration(data.budget_duration)
validate_budget_duration(data.team_member_budget_duration)
validate_team_model_max_budget(model_max_budget=data.model_max_budget, premium_user=premium_user)
+ validate_team_model_max_budget(
+ model_max_budget=data.team_member_model_max_budget,
+ premium_user=premium_user,
+ )
existing_team_row = await _raw_team_db(TeamRepository(prisma_client)).find_unique(
where={"team_id": data.team_id}
@@ -2495,6 +2553,7 @@ async def update_team(
"team_member_rpm_limit",
"team_member_tpm_limit",
"team_member_budget_duration",
+ "team_member_model_max_budget",
]
if field in updated_kv
}
@@ -2524,6 +2583,7 @@ async def update_team(
team_member_rpm_limit=data.team_member_rpm_limit,
team_member_tpm_limit=data.team_member_tpm_limit,
team_member_budget_duration=data.team_member_budget_duration,
+ team_member_model_max_budget=data.team_member_model_max_budget,
):
updated_kv = await TeamMemberBudgetHandler.upsert_team_member_budget_table(
team_table=existing_team_row,
@@ -2533,6 +2593,8 @@ async def update_team(
team_member_rpm_limit=data.team_member_rpm_limit,
team_member_tpm_limit=data.team_member_tpm_limit,
team_member_budget_duration=data.team_member_budget_duration,
+ team_member_model_max_budget=data.team_member_model_max_budget,
+ user_api_key_cache=user_api_key_cache,
explicitly_set_fields=_team_member_fields_in_request,
)
# Backfill team_memberships for members who joined before the
@@ -2556,6 +2618,7 @@ async def update_team(
user_api_key_dict=user_api_key_dict,
updated_kv=updated_kv,
explicitly_set_fields=_team_member_fields_in_request,
+ user_api_key_cache=user_api_key_cache,
)
else:
TeamMemberBudgetHandler.clean_team_member_fields(updated_kv)
@@ -3866,6 +3929,7 @@ async def team_member_update(
)
validate_budget_duration(data.budget_duration)
+ validate_team_model_max_budget(data.model_max_budget, premium_user=premium_user)
_existing_team_row: Final = await _team_db(prisma_client).find_unique(where={"team_id": data.team_id})
@@ -3982,6 +4046,7 @@ async def team_member_update(
allowed_models=data.allowed_models,
temp_budget_increase=data.temp_budget_increase,
temp_budget_expiry=data.temp_budget_expiry,
+ model_max_budget=data.model_max_budget,
)
diff --git a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
index 5d73a04f9e0..d6358c638e7 100644
--- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
+++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py
@@ -677,6 +677,7 @@ class HttpPassThroughEndpointHelpers(BasePassthroughUtils):
_metadata["user_api_key_model_max_budget"] = user_api_key_dict.model_max_budget
_metadata["user_api_key_team_model_max_budget"] = user_api_key_dict.team_model_max_budget
_metadata["user_api_key_user_model_max_budget"] = user_api_key_dict.user_model_max_budget
+ _metadata["user_api_key_team_member_model_max_budget"] = user_api_key_dict.team_member_model_max_budget
_metadata["user_api_key_end_user_model_max_budget"] = user_api_key_dict.end_user_model_max_budget
else:
for field in (
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index dac46855fd6..089647c6297 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -359,7 +359,7 @@ from litellm.proxy.auth.auth_utils import (
log_once_if_budget_reservation_disabled,
warn_once_if_custom_auth_skips_common_checks,
)
-from litellm.proxy.auth.fallback_budget import router_fallback_budget_check
+from litellm.proxy.auth.fallback_budget import RouterFallbackBudgetCheck, router_fallback_budget_check
from litellm.proxy.auth.fallback_model_access import router_fallback_access_check
from litellm.proxy.auth.handle_jwt import JWTHandler
from litellm.proxy.auth.litellm_license import AUTO_ROUTER_LICENSE_REMEDY, LicenseCheck
@@ -7196,7 +7196,10 @@ class ProxyConfig:
),
ignore_invalid_deployments=True, # don't raise an error if a deployment is invalid
fallback_access_check=router_fallback_access_check,
- fallback_budget_check=router_fallback_budget_check,
+ fallback_budget_check=RouterFallbackBudgetCheck(
+ is_enforced=router_fallback_budget_check.is_enforced,
+ team_member_model_budget_limiter=model_max_budget_limiter,
+ ),
auto_router_capability_limit=_license_check.auto_router_capability_limit,
)
@@ -7691,7 +7694,10 @@ class ProxyConfig:
search_tools=search_tools,
ignore_invalid_deployments=True,
fallback_access_check=router_fallback_access_check,
- fallback_budget_check=router_fallback_budget_check,
+ fallback_budget_check=RouterFallbackBudgetCheck(
+ is_enforced=router_fallback_budget_check.is_enforced,
+ team_member_model_budget_limiter=model_max_budget_limiter,
+ ),
auto_router_capability_limit=_license_check.auto_router_capability_limit,
)
verbose_proxy_logger.debug("updated llm_router: %s", llm_router)
diff --git a/litellm/router_utils/common_utils.py b/litellm/router_utils/common_utils.py
index 4d6af710bb9..6976a64ef39 100644
--- a/litellm/router_utils/common_utils.py
+++ b/litellm/router_utils/common_utils.py
@@ -4,6 +4,8 @@ from collections.abc import Mapping, Sequence
from types import MappingProxyType
from typing import TYPE_CHECKING, Final, TypeVar
+from pydantic import TypeAdapter
+
if TYPE_CHECKING:
from litellm.types.llms.openai import OpenAIFileObject
@@ -19,6 +21,7 @@ from litellm.types.utils import LlmProviders
_V = TypeVar("_V")
ROUTER_ONLY_CALL_KWARGS: Final = frozenset({"silent_model", "include_fallback_errors"})
+_OBJECT_MAPPING_ADAPTER: Final[TypeAdapter[Mapping[object, object]]] = TypeAdapter(Mapping[object, object])
def without_router_only_kwargs(kwargs: Mapping[str, _V]) -> dict[str, _V]:
@@ -72,6 +75,30 @@ def resolve_model_group_alias(model_group_alias: object, model: str) -> str | No
return target
+def resolve_served_model(
+ model: str,
+ model_alias_map: object,
+ key_aliases: object,
+ model_group_alias: object,
+) -> str:
+ """Model the request preparation serves for `model`.
+
+ Apply the global alias map, then key aliases, then `router_settings.model_group_alias`.
+ """
+ global_aliases: Final = (
+ _OBJECT_MAPPING_ADAPTER.validate_python(model_alias_map) if isinstance(model_alias_map, Mapping) else None
+ )
+ global_target: Final = global_aliases.get(model) if global_aliases is not None else None
+ after_global: Final = global_target if isinstance(global_target, str) else model
+ key_alias_mapping: Final = (
+ _OBJECT_MAPPING_ADAPTER.validate_python(key_aliases) if isinstance(key_aliases, Mapping) else None
+ )
+ key_target: Final = key_alias_mapping.get(after_global) if key_alias_mapping is not None else None
+ after_key: Final = key_target if isinstance(key_target, str) else after_global
+ router_target: Final = resolve_model_group_alias(model_group_alias, after_key)
+ return router_target if router_target is not None else after_key
+
+
def truncate_fallback_error_detail(detail: str) -> str:
"""
Bound a fallback failure detail before it is logged or appended to an exception message.
diff --git a/tests/unit/llms/anthropic/pass_through/context_management/test_compact.py b/tests/unit/llms/anthropic/pass_through/context_management/test_compact.py
index ced53794cc2..494e742e426 100644
--- a/tests/unit/llms/anthropic/pass_through/context_management/test_compact.py
+++ b/tests/unit/llms/anthropic/pass_through/context_management/test_compact.py
@@ -13,7 +13,7 @@ Coverage:
"""
import json
-from typing import Any, Dict, List
+from typing import Any, Dict, Final, List
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
@@ -1198,6 +1198,7 @@ def _fake_user_api_key_auth(
end_user_model_max_budget=None,
end_user_id=None,
user_model_max_budget=None,
+ team_member_model_max_budget=None,
user_id=None,
token=None,
):
@@ -1219,6 +1220,7 @@ def _fake_user_api_key_auth(
auth.end_user_model_max_budget = end_user_model_max_budget
auth.end_user_id = end_user_id
auth.user_model_max_budget = user_model_max_budget
+ auth.team_member_model_max_budget = team_member_model_max_budget
auth.user_id = user_id
auth.token = token
return auth
@@ -1659,6 +1661,120 @@ async def test_summary_model_denied_when_user_over_model_budget():
assert kwarg in real_params, f"compact.py passes {kwarg}=, which the limiter no longer accepts"
+async def test_summary_model_denied_when_team_member_over_model_budget(monkeypatch: pytest.MonkeyPatch):
+ from litellm.caching.dual_cache import DualCache
+ from litellm.llms.anthropic.pass_through.context_management.constants import COMPACT_SUMMARY_MODEL_SETTING_KEY
+ from litellm.models.team_membership import LiteLLM_TeamMembership
+ from litellm.proxy._types import (
+ LiteLLM_BudgetTable,
+ LiteLLM_TeamTableCachedObj,
+ LitellmUserRoles,
+ UserAPIKeyAuth,
+ )
+ from litellm.proxy.auth.auth_checks import get_team_member_default_budget
+ from litellm.proxy.auth.user_api_key_auth import _load_team_member_default_model_budget
+ from litellm.proxy.common_utils.user_api_key_cache import (
+ UserApiKeyCache,
+ team_membership_reservation_cache_key,
+ )
+ from litellm.proxy.hooks.model_max_budget_limiter import PROXY_VirtualKeyModelMaxBudgetLimiter
+ from litellm.proxy.proxy_server import general_settings
+
+ import litellm.proxy.proxy_server as proxy_server
+
+ budget_id: Final = "summary-budget"
+ member_budget: Final = {"claude-haiku-4-5": {"max_budget": 0.0, "budget_duration": "1d"}}
+ user_id: Final = "member-over-budget"
+ team_id: Final = "team-1"
+ user_api_key_cache: Final = UserApiKeyCache()
+ prisma_client: Final = MagicMock()
+ team_object: Final = LiteLLM_TeamTableCachedObj(
+ team_id=team_id,
+ models=["all-proxy-models"],
+ metadata={"team_member_budget_id": budget_id},
+ )
+ membership: Final = LiteLLM_TeamMembership(
+ user_id=user_id,
+ team_id=team_id,
+ budget_id=budget_id,
+ litellm_budget_table=LiteLLM_BudgetTable(budget_id=budget_id, model_max_budget={}),
+ )
+ await user_api_key_cache.async_set_cache(
+ key=team_membership_reservation_cache_key(user_id=user_id, team_id=team_id),
+ value=membership,
+ model_type=LiteLLM_TeamMembership,
+ )
+ await user_api_key_cache.async_set_cache(
+ key=f"team_member_default_budget:{budget_id}",
+ value=LiteLLM_BudgetTable(budget_id=budget_id, model_max_budget=member_budget),
+ model_type=LiteLLM_BudgetTable,
+ )
+ await user_api_key_cache.async_set_cache(
+ key=f"team_id:{team_id}",
+ value=team_object,
+ model_type=LiteLLM_TeamTableCachedObj,
+ )
+
+ auth: Final = UserAPIKeyAuth(
+ token="hashed-token",
+ user_id=user_id,
+ team_id=team_id,
+ user_role=LitellmUserRoles.INTERNAL_USER,
+ models=["all-proxy-models"],
+ )
+ await _load_team_member_default_model_budget(
+ user_api_key_auth_obj=auth,
+ team_object=team_object,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ skip_budget_checks=False,
+ proxy_logging_obj=None,
+ )
+ assert auth.team_member_model_max_budget == member_budget
+ assert (
+ await get_team_member_default_budget(
+ budget_id=budget_id,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ raise_on_lookup_error=True,
+ )
+ ).model_max_budget == member_budget
+
+ router: Final = litellm.Router(
+ model_list=[
+ {"model_name": MODEL, "litellm_params": {"model": MODEL}},
+ {
+ "model_name": "claude-haiku-4-5",
+ "litellm_params": {
+ "model": "claude-haiku-4-5",
+ "mock_response": "x",
+ },
+ },
+ ]
+ )
+ limiter: Final = PROXY_VirtualKeyModelMaxBudgetLimiter(dual_cache=DualCache())
+ monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)
+ monkeypatch.setattr(proxy_server, "user_api_key_cache", user_api_key_cache)
+ monkeypatch.setattr(proxy_server, "llm_router", router)
+ monkeypatch.setattr(proxy_server, "model_max_budget_limiter", limiter)
+ monkeypatch.setattr(proxy_server, "proxy_logging_obj", MagicMock())
+ monkeypatch.setitem(general_settings, COMPACT_SUMMARY_MODEL_SETTING_KEY, "claude-haiku-4-5")
+ messages: Final = [{"role": "user", "content": "hello " * 60_000}]
+
+ result: Final = await apply_compact_20260112(
+ model=MODEL,
+ messages=messages,
+ tools=None,
+ system=None,
+ edit_spec={"type": "compact_20260112", "trigger": {"type": "input_tokens", "value": 50_000}},
+ user_api_key_auth=auth,
+ llm_router=router,
+ )
+
+ assert result.applied_edits[0].get("error") == "summary_model_budget_exceeded"
+ assert result.compaction_block is None
+
+
async def test_summary_model_denied_when_end_user_over_model_budget():
"""End-user per-model budget is enforced for the summary subrequest too."""
import litellm
@@ -2022,9 +2138,7 @@ async def test_summary_model_denied_when_team_over_model_budget():
limiter = MagicMock()
limiter.is_key_within_model_budget = AsyncMock(return_value=True)
limiter.is_team_within_model_budget = AsyncMock(
- side_effect=litellm.BudgetExceededError(
- message="over budget", current_cost=10, max_budget=5
- )
+ side_effect=litellm.BudgetExceededError(message="over budget", current_cost=10, max_budget=5)
)
with (
@@ -2064,9 +2178,7 @@ async def test_summary_model_denied_when_team_over_model_budget():
PROXY_VirtualKeyModelMaxBudgetLimiter,
)
- real_params = inspect.signature(
- PROXY_VirtualKeyModelMaxBudgetLimiter.is_team_within_model_budget
- ).parameters
+ real_params = inspect.signature(PROXY_VirtualKeyModelMaxBudgetLimiter.is_team_within_model_budget).parameters
for kwarg in ("team_id", "team_model_max_budget", "key_model_max_budget", "model"):
assert kwarg in real_params, f"compact.py passes {kwarg}=, which the limiter does not accept"
@@ -2585,6 +2697,9 @@ async def test_prepare_context_managed_request_forwards_proxy_litellm_metadata()
"user_api_key": "sk-parent",
"user_api_key_team_id": "team-abc",
"user_api_key_user_id": "user-xyz",
+ "user_api_key_team_member_model_max_budget": {
+ "claude-haiku-4-5": {"budget_limit": 4.0, "time_period": "1d"}
+ },
"litellm_call_id": "call-1",
},
additional_drop_params=None,
@@ -2595,6 +2710,9 @@ async def test_prepare_context_managed_request_forwards_proxy_litellm_metadata()
assert captured_summary_metadata.get("user_api_key") == "sk-parent"
assert captured_summary_metadata.get("user_api_key_team_id") == "team-abc"
assert captured_summary_metadata.get("user_api_key_user_id") == "user-xyz"
+ assert captured_summary_metadata.get("user_api_key_team_member_model_max_budget") == {
+ "claude-haiku-4-5": {"budget_limit": 4.0, "time_period": "1d"}
+ }
assert captured_summary_metadata.get("litellm_call_id") == "call-1"
# Anthropic-shape ``metadata.user_id`` must not leak in as a propagated field.
assert "user_id" not in captured_summary_metadata
diff --git a/tests/unit/proxy/auth/test_auth_checks_object_access_and_lookup.py b/tests/unit/proxy/auth/test_auth_checks_object_access_and_lookup.py
index e26845e5b2a..8b712772230 100644
--- a/tests/unit/proxy/auth/test_auth_checks_object_access_and_lookup.py
+++ b/tests/unit/proxy/auth/test_auth_checks_object_access_and_lookup.py
@@ -7703,6 +7703,47 @@ async def test_get_team_member_default_budget_caches_json_safe_payload():
mock_prisma_client.db.litellm_budgettable.find_unique.assert_awaited_once()
+@pytest.mark.asyncio
+async def test_get_team_member_default_budget_reraises_lookup_error_when_requested() -> None:
+ from litellm.proxy.auth.auth_checks import get_team_member_default_budget
+
+ lookup_error: Final = RuntimeError("budget database unavailable")
+ cache: Final = MagicMock()
+ cache.async_get_cache = AsyncMock(return_value=None)
+ prisma_client: Final = MagicMock()
+ prisma_client.db.litellm_budgettable.find_unique = AsyncMock(side_effect=lookup_error)
+
+ with pytest.raises(RuntimeError) as exc_info:
+ await get_team_member_default_budget(
+ budget_id="default-budget",
+ prisma_client=prisma_client,
+ user_api_key_cache=cache,
+ raise_on_lookup_error=True,
+ )
+
+ assert exc_info.value is lookup_error
+
+
+@pytest.mark.asyncio
+async def test_get_team_member_default_budget_returns_none_on_lookup_error_by_default() -> None:
+ from litellm.proxy.auth.auth_checks import get_team_member_default_budget
+
+ prisma_client: Final = MagicMock()
+ prisma_client.db.litellm_budgettable.find_unique = AsyncMock(
+ side_effect=RuntimeError("budget database unavailable")
+ )
+ cache: Final = MagicMock()
+ cache.async_get_cache = AsyncMock(return_value=None)
+
+ budget: Final = await get_team_member_default_budget(
+ budget_id="default-budget",
+ prisma_client=prisma_client,
+ user_api_key_cache=cache,
+ )
+
+ assert budget is None
+
+
@pytest.mark.asyncio
async def test_get_end_user_object_db_fetch_returns_validated_end_user():
from litellm.proxy.auth.auth_checks import get_end_user_object
diff --git a/tests/unit/proxy/auth/test_fallback_budget.py b/tests/unit/proxy/auth/test_fallback_budget.py
index 00c1a7cdefc..3d31f1e0c78 100644
--- a/tests/unit/proxy/auth/test_fallback_budget.py
+++ b/tests/unit/proxy/auth/test_fallback_budget.py
@@ -1,12 +1,23 @@
+from collections.abc import Mapping, Sequence
+from typing import Final
+from unittest.mock import AsyncMock, MagicMock
+
+import litellm
import pytest
from litellm import Router
-from litellm.proxy._types import UserAPIKeyAuth
+from litellm.caching.dual_cache import DualCache
+from litellm.proxy._types import Litellm_EntityType, UserAPIKeyAuth
from litellm.proxy.auth.fallback_budget import (
RouterFallbackBudgetCheck,
is_token_within_budget_for_model,
router_fallback_budget_check,
)
+from litellm.proxy.hooks.model_max_budget_limiter import (
+ PROXY_VirtualKeyModelMaxBudgetLimiter,
+ model_budget_spend_cache_key,
+ team_member_budget_entity_id,
+)
FREE_MODEL = {
"model_name": "free-model",
@@ -48,6 +59,41 @@ def _token(**overrides) -> UserAPIKeyAuth:
return UserAPIKeyAuth(**fields)
+async def _team_member_limiter(
+ spend_by_model: Mapping[str, float] | None = None,
+) -> tuple[PROXY_VirtualKeyModelMaxBudgetLimiter, MagicMock]:
+ entity_id: Final = team_member_budget_entity_id(user_id="u1", team_id="t1")
+ spend_by_key: Final = {
+ model_budget_spend_cache_key(
+ entity_type=Litellm_EntityType.TEAM_MEMBER,
+ entity_id=entity_id,
+ budget_model=model,
+ budget_duration="1d",
+ ): spend
+ for model, spend in (spend_by_model or {}).items()
+ }
+ redis_cache: Final = MagicMock()
+
+ async def get_spend(*, key: str) -> object | None:
+ return spend_by_key.get(key)
+
+ redis_cache.async_get_cache = AsyncMock(side_effect=get_spend)
+ return PROXY_VirtualKeyModelMaxBudgetLimiter(dual_cache=DualCache(redis_cache=redis_cache)), redis_cache
+
+
+def _member_budget_spend_keys(models: Sequence[str]) -> tuple[str, ...]:
+ entity_id: Final = team_member_budget_entity_id(user_id="u1", team_id="t1")
+ return tuple(
+ model_budget_spend_cache_key(
+ entity_type=Litellm_EntityType.TEAM_MEMBER,
+ entity_id=entity_id,
+ budget_model=model,
+ budget_duration="1d",
+ )
+ for model in models
+ )
+
+
ENFORCED = RouterFallbackBudgetCheck(is_enforced=lambda: True)
NOT_ENFORCED = RouterFallbackBudgetCheck(is_enforced=lambda: False)
@@ -70,6 +116,201 @@ async def test_paid_target_refused_when_over_user_budget():
assert await is_token_within_budget_for_model(model="paid-model", valid_token=token, llm_router=_router()) is False
+@pytest.mark.asyncio
+async def test_team_member_budget_refuses_an_exhausted_paid_target() -> None:
+ member_caps: Final = {"paid-model": {"max_budget": 5.0, "budget_duration": "1d"}}
+ token: Final = _token(
+ user_id="u1",
+ team_id="t1",
+ team_member_model_max_budget=member_caps,
+ )
+ limiter, redis_cache = await _team_member_limiter(spend_by_model={"paid-model": 10.0})
+
+ within_budget: Final = await is_token_within_budget_for_model(
+ model="paid-model",
+ valid_token=token,
+ llm_router=_router(),
+ team_member_model_budget_limiter=limiter,
+ )
+
+ assert within_budget is False
+ assert tuple(call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list) == (
+ _member_budget_spend_keys(("paid-model",))
+ )
+
+
+@pytest.mark.asyncio
+async def test_router_fallback_budget_check_resolves_model_group_alias_before_member_cap_check() -> None:
+ expensive_model: Final = {
+ **PAID_MODEL,
+ "model_name": "expensive",
+ "model_info": {"id": "expensive-model-id"},
+ }
+ router: Final = Router(
+ model_list=[FREE_MODEL, expensive_model],
+ model_group_alias={"backup": "expensive"},
+ )
+ member_caps: Final = {
+ "backup": {"max_budget": 100.0, "budget_duration": "1d"},
+ "expensive": {"max_budget": 5.0, "budget_duration": "1d"},
+ }
+ token: Final = _token(user_id="u1", team_id="t1", team_member_model_max_budget=member_caps)
+ limiter, redis_cache = await _team_member_limiter(spend_by_model={"backup": 1.0, "expensive": 10.0})
+ budget_check: Final = RouterFallbackBudgetCheck(
+ is_enforced=lambda: True,
+ team_member_model_budget_limiter=limiter,
+ )
+
+ within_budget: Final = await budget_check(
+ model="backup",
+ request_kwargs={"metadata": {"user_api_key_auth": token}},
+ llm_router=router,
+ )
+
+ assert within_budget is False
+ assert tuple(call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list) == (
+ _member_budget_spend_keys(("backup", "expensive"))
+ )
+
+
+@pytest.mark.asyncio
+async def test_router_fallback_budget_check_refuses_an_exhausted_alias_cap() -> None:
+ expensive_model: Final = {
+ **PAID_MODEL,
+ "model_name": "expensive",
+ "model_info": {"id": "expensive-model-id"},
+ }
+ router: Final = Router(
+ model_list=[FREE_MODEL, expensive_model],
+ model_group_alias={"backup": "expensive"},
+ )
+ member_caps: Final = {"backup": {"max_budget": 5.0, "budget_duration": "1d"}}
+ token: Final = _token(user_id="u1", team_id="t1", team_member_model_max_budget=member_caps)
+ limiter, redis_cache = await _team_member_limiter(spend_by_model={"backup": 10.0})
+ budget_check: Final = RouterFallbackBudgetCheck(
+ is_enforced=lambda: True,
+ team_member_model_budget_limiter=limiter,
+ )
+
+ within_budget: Final = await budget_check(
+ model="backup",
+ request_kwargs={"metadata": {"user_api_key_auth": token}},
+ llm_router=router,
+ )
+
+ assert within_budget is False
+ assert tuple(call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list) == (
+ _member_budget_spend_keys(("backup",))
+ )
+
+
+@pytest.mark.asyncio
+async def test_router_fallback_budget_check_allows_alias_when_both_names_are_within_cap() -> None:
+ expensive_model: Final = {
+ **PAID_MODEL,
+ "model_name": "expensive",
+ "model_info": {"id": "expensive-model-id"},
+ }
+ router: Final = Router(
+ model_list=[FREE_MODEL, expensive_model],
+ model_group_alias={"backup": "expensive"},
+ )
+ member_caps: Final = {
+ "backup": {"max_budget": 5.0, "budget_duration": "1d"},
+ "expensive": {"max_budget": 5.0, "budget_duration": "1d"},
+ }
+ token: Final = _token(user_id="u1", team_id="t1", team_member_model_max_budget=member_caps)
+ limiter, redis_cache = await _team_member_limiter(spend_by_model={"backup": 1.0, "expensive": 1.0})
+ budget_check: Final = RouterFallbackBudgetCheck(
+ is_enforced=lambda: True,
+ team_member_model_budget_limiter=limiter,
+ )
+
+ within_budget: Final = await budget_check(
+ model="backup",
+ request_kwargs={"metadata": {"user_api_key_auth": token}},
+ llm_router=router,
+ )
+
+ assert within_budget is True
+ assert tuple(call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list) == (
+ _member_budget_spend_keys(("backup", "expensive"))
+ )
+
+
+@pytest.mark.asyncio
+async def test_router_fallback_budget_check_deduplicates_non_alias_target() -> None:
+ router: Final = _router()
+ member_caps: Final = {"paid-model": {"max_budget": 5.0, "budget_duration": "1d"}}
+ token: Final = _token(user_id="u1", team_id="t1", team_member_model_max_budget=member_caps)
+ limiter, redis_cache = await _team_member_limiter(spend_by_model={"paid-model": 1.0})
+ budget_check: Final = RouterFallbackBudgetCheck(
+ is_enforced=lambda: True,
+ team_member_model_budget_limiter=limiter,
+ )
+
+ within_budget: Final = await budget_check(
+ model="paid-model",
+ request_kwargs={"metadata": {"user_api_key_auth": token}},
+ llm_router=router,
+ )
+
+ assert within_budget is True
+ assert tuple(call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list) == (
+ _member_budget_spend_keys(("paid-model",))
+ )
+
+
+@pytest.mark.asyncio
+async def test_team_member_budget_allows_a_paid_target_when_under_cap() -> None:
+ member_caps: Final = {"paid-model": {"max_budget": 5.0, "budget_duration": "1d"}}
+ token: Final = _token(
+ user_id="u1",
+ team_id="t1",
+ team_member_model_max_budget=member_caps,
+ )
+ limiter, redis_cache = await _team_member_limiter(spend_by_model={"paid-model": 1.0})
+
+ within_budget: Final = await is_token_within_budget_for_model(
+ model="paid-model",
+ valid_token=token,
+ llm_router=_router(),
+ team_member_model_budget_limiter=limiter,
+ )
+
+ assert within_budget is True
+ assert tuple(call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list) == (
+ _member_budget_spend_keys(("paid-model",))
+ )
+
+
+@pytest.mark.asyncio
+async def test_team_member_caps_are_not_evaluated_without_a_limiter() -> None:
+ token: Final = _token(
+ user_id="u1",
+ team_id="t1",
+ team_member_model_max_budget={"paid-model": {"max_budget": 5.0, "budget_duration": "1d"}},
+ )
+
+ assert await is_token_within_budget_for_model(model="paid-model", valid_token=token, llm_router=_router()) is True
+
+
+@pytest.mark.asyncio
+async def test_team_member_limiter_is_not_called_without_member_caps() -> None:
+ token: Final = _token(user_id="u1", team_id="t1")
+ limiter, redis_cache = await _team_member_limiter()
+
+ within_budget: Final = await is_token_within_budget_for_model(
+ model="paid-model",
+ valid_token=token,
+ llm_router=_router(),
+ team_member_model_budget_limiter=limiter,
+ )
+
+ assert within_budget is True
+ assert redis_cache.async_get_cache.call_args_list == []
+
+
@pytest.mark.asyncio
async def test_zero_cost_target_allowed_even_when_over_budget():
"""Refusing a free target would deny a request on spend some other model accrued."""
@@ -123,6 +364,33 @@ async def test_enforced_check_reads_the_key_from_request_metadata(metadata_field
assert await ENFORCED(model="paid-model", request_kwargs=under, llm_router=_router()) is True
+@pytest.mark.asyncio
+async def test_router_check_passes_member_limiter_from_request_metadata() -> None:
+ member_caps: Final = {"paid-model": {"max_budget": 5.0, "budget_duration": "1d"}}
+ token: Final = _token(
+ user_id="u1",
+ team_id="t1",
+ team_member_model_max_budget=member_caps,
+ )
+ limiter, redis_cache = await _team_member_limiter(spend_by_model={"paid-model": 10.0})
+ budget_check: Final = RouterFallbackBudgetCheck(
+ is_enforced=lambda: True,
+ team_member_model_budget_limiter=limiter,
+ )
+ request_kwargs: Final = {"metadata": {"user_api_key_auth": token}}
+
+ within_budget: Final = await budget_check(
+ model="paid-model",
+ request_kwargs=request_kwargs,
+ llm_router=_router(),
+ )
+
+ assert within_budget is False
+ assert tuple(call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list) == (
+ _member_budget_spend_keys(("paid-model",))
+ )
+
+
@pytest.mark.asyncio
async def test_a_stale_low_counter_still_refuses_a_paid_target(monkeypatch):
"""
diff --git a/tests/unit/proxy/auth/test_user_api_key_auth_request_flow.py b/tests/unit/proxy/auth/test_user_api_key_auth_request_flow.py
index 1a636e28fb9..492ab408fc8 100644
--- a/tests/unit/proxy/auth/test_user_api_key_auth_request_flow.py
+++ b/tests/unit/proxy/auth/test_user_api_key_auth_request_flow.py
@@ -5,10 +5,11 @@ import os
import subprocess
import sys
import time
-from collections.abc import Mapping
-from contextlib import contextmanager
+from collections.abc import Mapping, Sequence
+from contextlib import contextmanager, nullcontext
from datetime import datetime, timedelta, timezone
from functools import partial
+from io import BytesIO
from pathlib import Path
from textwrap import dedent
from types import SimpleNamespace
@@ -16,13 +17,24 @@ from typing import Final
from unittest.mock import ANY, AsyncMock, MagicMock, patch
+import orjson
import pytest
-from fastapi import HTTPException, status
+from fastapi import HTTPException, Request, status
+from starlette.datastructures import UploadFile
import litellm
import litellm.proxy.proxy_server
from litellm.caching.dual_cache import DualCache
-from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+from litellm.proxy.common_utils.user_api_key_cache import (
+ NO_TEAM_MEMBERSHIP_SENTINEL,
+ UserApiKeyCache,
+ team_membership_reservation_cache_key,
+)
+from litellm.proxy.hooks.model_max_budget_limiter import (
+ PROXY_VirtualKeyModelMaxBudgetLimiter,
+ model_budget_spend_cache_key,
+ team_member_budget_entity_id,
+)
from litellm.proxy._types import (
LiteLLMRoutes,
LiteLLM_JWTAuth,
@@ -30,6 +42,9 @@ from litellm.proxy._types import (
LiteLLM_EndUserTable,
LiteLLM_ObjectPermissionTable,
LiteLLM_OrganizationTable,
+ LiteLLM_ProjectTableCachedObj,
+ LiteLLM_TeamMembership,
+ LiteLLM_TeamTable,
LiteLLM_TeamTableCachedObj,
LiteLLM_UserTable,
Litellm_EntityType,
@@ -52,8 +67,10 @@ from litellm.proxy.auth.route_checks import RouteChecks
from litellm.proxy.common_utils.http_parsing_utils import get_client_requested_model
from litellm.proxy.auth.user_api_key_auth import (
_check_key_model_budget_with_fallback,
+ _check_team_member_model_budget_with_fallback,
_ensure_litellm_received_at_on_request_state,
_ensure_parent_otel_span_on_request_state,
+ _load_team_member_default_model_budget,
_PendingAutoRegister,
_matches_routing_override,
_reserve_budget_after_common_checks,
@@ -78,6 +95,82 @@ class _RoutingRequest:
self.state = SimpleNamespace()
+async def _real_model_budget_limiter(
+ *,
+ member_spend: Mapping[str, float] | None = None,
+ key_spend: Mapping[str, float] | None = None,
+ member_errors: Mapping[str, Exception] | None = None,
+) -> tuple[PROXY_VirtualKeyModelMaxBudgetLimiter, MagicMock]:
+ member_entity_id: Final = team_member_budget_entity_id(user_id="user-1", team_id="team-1")
+ scope_spend: Final = (
+ *(
+ (Litellm_EntityType.TEAM_MEMBER, member_entity_id, model, spend)
+ for model, spend in (member_spend or {}).items()
+ ),
+ *((Litellm_EntityType.KEY, "test-key", model, spend) for model, spend in (key_spend or {}).items()),
+ )
+ scope_errors: Final = tuple(
+ (Litellm_EntityType.TEAM_MEMBER, member_entity_id, model, error)
+ for model, error in (member_errors or {}).items()
+ )
+ spend_by_key: Final = {
+ model_budget_spend_cache_key(
+ entity_type=entity_type,
+ entity_id=entity_id,
+ budget_model=model,
+ budget_duration="1d",
+ ): spend
+ for entity_type, entity_id, model, spend in scope_spend
+ }
+ errors_by_key: Final = {
+ model_budget_spend_cache_key(
+ entity_type=entity_type,
+ entity_id=entity_id,
+ budget_model=model,
+ budget_duration="1d",
+ ): error
+ for entity_type, entity_id, model, error in scope_errors
+ }
+ redis_cache: Final = MagicMock()
+
+ async def get_spend(*, key: str) -> object | None:
+ if key in errors_by_key:
+ raise errors_by_key[key]
+ return spend_by_key.get(key)
+
+ redis_cache.async_get_cache = AsyncMock(side_effect=get_spend)
+ return PROXY_VirtualKeyModelMaxBudgetLimiter(dual_cache=DualCache(redis_cache=redis_cache)), redis_cache
+
+
+def _model_budget_spend_keys(
+ entity_type: Litellm_EntityType,
+ entity_id: str,
+ models: Sequence[str],
+) -> list[str]:
+ return [
+ model_budget_spend_cache_key(
+ entity_type=entity_type,
+ entity_id=entity_id,
+ budget_model=model,
+ budget_duration="1d",
+ )
+ for model in models
+ ]
+
+
+def _team_member_model_budget_spend_keys(models: Sequence[str]) -> list[str]:
+ return _model_budget_spend_keys(
+ Litellm_EntityType.TEAM_MEMBER,
+ team_member_budget_entity_id(user_id="user-1", team_id="team-1"),
+ models,
+ )
+
+
+def _assert_budget_exceeded_values(error: litellm.BudgetExceededError) -> None:
+ assert error.current_cost == 10
+ assert error.max_budget == 5
+
+
def test_get_api_key():
bearer_token = "Bearer sk-98765678"
api_key = "sk-98765678"
@@ -4730,9 +4823,11 @@ async def test_centralized_common_checks_carries_team_and_user_budget_state_on_t
)
proxy_logging_obj = MagicMock()
proxy_logging_obj.service_logging_obj.async_service_success_hook = AsyncMock()
+ database = MagicMock()
+ database.db.litellm_teammembership.find_unique = AsyncMock(return_value=None)
attrs = {
**_proxy_attrs_for_centralized_checks(user_custom_auth=None),
- "prisma_client": MagicMock(),
+ "prisma_client": database,
"user_api_key_cache": user_api_key_cache,
"proxy_logging_obj": proxy_logging_obj,
}
@@ -5011,6 +5106,503 @@ async def test_centralized_common_checks_enforces_team_model_max_budget_from_the
assert limiter.calls == [("t1", team_caps, key_caps, "gpt-4o")]
+@pytest.mark.asyncio
+async def test_centralized_common_checks_loads_member_budget_and_exempts_discovery_routes():
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+ from litellm.proxy.hooks.model_max_budget_limiter import PROXY_VirtualKeyModelMaxBudgetLimiter
+ import litellm.proxy.proxy_server as _proxy_server_mod
+
+ budget_id: Final = "member-budget-1"
+ member_caps: Final = {"gpt-4o": {"max_budget": 0.0, "budget_duration": "1d"}}
+ membership: Final = LiteLLM_TeamMembership(
+ user_id="u1",
+ team_id="t1",
+ budget_id=budget_id,
+ litellm_budget_table=LiteLLM_BudgetTable(
+ budget_id=budget_id,
+ model_max_budget={"gpt-4o": {"max_budget": 100.0, "budget_duration": "1d"}},
+ ),
+ )
+ user_api_key_cache: Final = UserApiKeyCache()
+ await user_api_key_cache.async_set_cache(
+ key=team_membership_reservation_cache_key(user_id="u1", team_id="t1"),
+ value=membership,
+ model_type=LiteLLM_TeamMembership,
+ )
+ await user_api_key_cache.async_set_cache(
+ key="team_id:t1",
+ value=LiteLLM_TeamTableCachedObj(
+ team_id="t1",
+ models=["gpt-4o"],
+ metadata={"team_member_budget_id": budget_id},
+ ),
+ model_type=LiteLLM_TeamTableCachedObj,
+ )
+ await user_api_key_cache.async_set_cache(
+ key=f"team_member_default_budget:{budget_id}",
+ value=LiteLLM_BudgetTable(budget_id=budget_id, model_max_budget=member_caps),
+ model_type=LiteLLM_BudgetTable,
+ )
+ await user_api_key_cache.async_set_cache(
+ key="u1",
+ value=LiteLLM_UserTable(user_id="u1", user_role=LitellmUserRoles.INTERNAL_USER),
+ model_type=LiteLLM_UserTable,
+ )
+ router: Final = litellm.Router(
+ model_list=[{"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o"}}],
+ )
+ limiter: Final = PROXY_VirtualKeyModelMaxBudgetLimiter(dual_cache=DualCache())
+ attrs: Final = {
+ "general_settings": {"disable_budget_reservation": True},
+ "litellm_proxy_admin_name": "admin",
+ "llm_model_list": router.model_list,
+ "llm_router": router,
+ "master_key": "sk-master-key",
+ "prisma_client": MagicMock(),
+ "user_api_key_cache": user_api_key_cache,
+ "proxy_logging_obj": MagicMock(),
+ "model_max_budget_limiter": limiter,
+ "user_custom_auth": None,
+ }
+ originals: Final = {attribute: getattr(_proxy_server_mod, attribute, None) for attribute in attrs}
+
+ try:
+ for attribute, value in attrs.items():
+ setattr(_proxy_server_mod, attribute, value)
+ token: Final = UserAPIKeyAuth(
+ api_key="sk-test",
+ token="hashed",
+ user_id="u1",
+ team_id="t1",
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ )
+ request: Final = Request(
+ scope={
+ "type": "http",
+ "method": "POST",
+ "path": "/v1/models",
+ "raw_path": b"/v1/models",
+ "query_string": b"",
+ "headers": [],
+ "server": ("test", 80),
+ "client": ("test", 1),
+ "scheme": "http",
+ }
+ )
+ await run_centralized_common_checks(
+ user_api_key_auth_obj=token,
+ request=request,
+ request_data={"model": "gpt-4o"},
+ route="/v1/models",
+ )
+
+ assert token.team_member_model_max_budget == member_caps
+
+ non_exempt_token: Final = UserAPIKeyAuth(
+ api_key="sk-test",
+ token="hashed",
+ user_id="u1",
+ team_id="t1",
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ )
+ non_exempt_request: Final = Request(
+ scope={
+ "type": "http",
+ "method": "POST",
+ "path": "/v1/chat/completions",
+ "raw_path": b"/v1/chat/completions",
+ "query_string": b"",
+ "headers": [],
+ "server": ("test", 80),
+ "client": ("test", 1),
+ "scheme": "http",
+ }
+ )
+ with pytest.raises(litellm.BudgetExceededError):
+ await run_centralized_common_checks(
+ user_api_key_auth_obj=non_exempt_token,
+ request=non_exempt_request,
+ request_data={"model": "gpt-4o"},
+ route="/v1/chat/completions",
+ )
+ finally:
+ for attribute, value in originals.items():
+ setattr(_proxy_server_mod, attribute, value)
+
+
+@pytest.mark.parametrize(
+ ("route", "path", "must_raise"),
+ [
+ pytest.param("/v1/models", "/v1/models", False, id="budget-exempt-discovery-route"),
+ pytest.param("/chat/completions", "/v1/chat/completions", True, id="paid-model-route"),
+ ],
+)
+@pytest.mark.asyncio
+async def test_centralized_common_checks_skips_default_member_budget_lookup_errors_on_exempt_routes(
+ route: str,
+ path: str,
+ must_raise: bool,
+):
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
+ from litellm.proxy.hooks.model_max_budget_limiter import PROXY_VirtualKeyModelMaxBudgetLimiter
+ import litellm.proxy.proxy_server as _proxy_server_mod
+
+ budget_id: Final = "member-budget-lookup-fails"
+ membership: Final = LiteLLM_TeamMembership(
+ user_id="u1",
+ team_id="t1",
+ budget_id=budget_id,
+ litellm_budget_table=LiteLLM_BudgetTable(
+ budget_id=budget_id,
+ model_max_budget={"gpt-4o": {"max_budget": 100.0, "budget_duration": "1d"}},
+ ),
+ )
+ user_api_key_cache: Final = UserApiKeyCache()
+ await user_api_key_cache.async_set_cache(
+ key=team_membership_reservation_cache_key(user_id="u1", team_id="t1"),
+ value=membership,
+ model_type=LiteLLM_TeamMembership,
+ )
+ await user_api_key_cache.async_set_cache(
+ key="team_id:t1",
+ value=LiteLLM_TeamTableCachedObj(
+ team_id="t1",
+ models=["gpt-4o"],
+ metadata={"team_member_budget_id": budget_id},
+ ),
+ model_type=LiteLLM_TeamTableCachedObj,
+ )
+ await user_api_key_cache.async_set_cache(
+ key="u1",
+ value=LiteLLM_UserTable(user_id="u1", user_role=LitellmUserRoles.INTERNAL_USER),
+ model_type=LiteLLM_UserTable,
+ )
+ prisma_client: Final = MagicMock()
+ prisma_client.db.litellm_budgettable.find_unique = AsyncMock(
+ side_effect=RuntimeError("budget database unavailable")
+ )
+ router: Final = litellm.Router(
+ model_list=[{"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o"}}],
+ )
+ limiter: Final = PROXY_VirtualKeyModelMaxBudgetLimiter(dual_cache=DualCache())
+ attrs: Final = {
+ "general_settings": {"disable_budget_reservation": True},
+ "litellm_proxy_admin_name": "admin",
+ "llm_model_list": router.model_list,
+ "llm_router": router,
+ "master_key": "sk-master-key",
+ "prisma_client": prisma_client,
+ "user_api_key_cache": user_api_key_cache,
+ "proxy_logging_obj": MagicMock(),
+ "model_max_budget_limiter": limiter,
+ "user_custom_auth": None,
+ }
+ originals: Final = {attribute: getattr(_proxy_server_mod, attribute, None) for attribute in attrs}
+
+ try:
+ for attribute, value in attrs.items():
+ setattr(_proxy_server_mod, attribute, value)
+ token: Final = UserAPIKeyAuth(
+ api_key="sk-test",
+ token="hashed",
+ user_id="u1",
+ team_id="t1",
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ )
+ request: Final = Request(
+ scope={
+ "type": "http",
+ "method": "POST",
+ "path": path,
+ "raw_path": path.encode(),
+ "query_string": b"",
+ "headers": [],
+ "server": ("test", 80),
+ "client": ("test", 1),
+ "scheme": "http",
+ }
+ )
+ with pytest.raises(RuntimeError, match="budget database unavailable") if must_raise else nullcontext():
+ await run_centralized_common_checks(
+ user_api_key_auth_obj=token,
+ request=request,
+ request_data={"model": "gpt-4o"},
+ route=route,
+ )
+
+ assert token.team_member_model_max_budget is None
+ prisma_client.db.litellm_budgettable.find_unique.assert_awaited_once_with(where={"budget_id": budget_id})
+ finally:
+ for attribute, value in originals.items():
+ setattr(_proxy_server_mod, attribute, value)
+
+
+def _team_member_model_budget_load_inputs() -> tuple[
+ UserAPIKeyAuth, LiteLLM_TeamTableCachedObj, MagicMock, UserApiKeyCache
+]:
+ token: Final = UserAPIKeyAuth(user_id="member-1", team_id="team-1")
+ team_object: Final = LiteLLM_TeamTableCachedObj(
+ team_id="team-1",
+ metadata={"team_member_budget_id": "default-budget"},
+ )
+ prisma_client: Final = MagicMock()
+ prisma_client.db.litellm_budgettable.find_unique = AsyncMock()
+ user_api_key_cache: Final = UserApiKeyCache()
+ return token, team_object, prisma_client, user_api_key_cache
+
+
+@pytest.mark.asyncio
+async def test_member_model_budget_load_prefers_override_row() -> None:
+ token, team_object, prisma_client, user_api_key_cache = _team_member_model_budget_load_inputs()
+ member_caps: Final = {"claude-sonnet-4-6": {"max_budget": 2.0, "budget_duration": "1d"}}
+ membership: Final = LiteLLM_TeamMembership(
+ user_id="member-1",
+ team_id="team-1",
+ budget_id="member-budget",
+ litellm_budget_table=LiteLLM_BudgetTable(budget_id="member-budget", model_max_budget=member_caps),
+ )
+ await user_api_key_cache.async_set_cache(
+ key=team_membership_reservation_cache_key(user_id="member-1", team_id="team-1"),
+ value=membership,
+ model_type=LiteLLM_TeamMembership,
+ )
+
+ await _load_team_member_default_model_budget(
+ user_api_key_auth_obj=token,
+ team_object=team_object,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ skip_budget_checks=False,
+ proxy_logging_obj=None,
+ )
+
+ assert token.team_member_model_max_budget == member_caps
+ prisma_client.db.litellm_budgettable.find_unique.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+async def test_member_model_budget_load_uses_override_without_team_default_id() -> None:
+ token, team_object, prisma_client, user_api_key_cache = _team_member_model_budget_load_inputs()
+ team_object = LiteLLM_TeamTableCachedObj(team_id=team_object.team_id, metadata={})
+ member_caps: Final = {"claude-sonnet-4-6": {"max_budget": 2.0, "budget_duration": "1d"}}
+ membership: Final = LiteLLM_TeamMembership(
+ user_id="member-1",
+ team_id="team-1",
+ budget_id="member-budget",
+ litellm_budget_table=LiteLLM_BudgetTable(budget_id="member-budget", model_max_budget=member_caps),
+ )
+ await user_api_key_cache.async_set_cache(
+ key=team_membership_reservation_cache_key(user_id="member-1", team_id="team-1"),
+ value=membership,
+ model_type=LiteLLM_TeamMembership,
+ )
+
+ await _load_team_member_default_model_budget(
+ user_api_key_auth_obj=token,
+ team_object=team_object,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ skip_budget_checks=False,
+ proxy_logging_obj=None,
+ )
+
+ assert token.team_member_model_max_budget == member_caps
+ prisma_client.db.litellm_budgettable.find_unique.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+async def test_member_model_budget_load_reads_current_default_for_plain_team_object() -> None:
+ from litellm.proxy.common_utils.user_api_key_cache import team_membership_reservation_cache_key
+
+ token: Final = UserAPIKeyAuth(user_id="member-1", team_id="team-1")
+ team_object: Final = LiteLLM_TeamTable(
+ team_id="team-1",
+ metadata={"team_member_budget_id": "default-budget"},
+ )
+ prisma_client: Final = MagicMock()
+ user_api_key_cache: Final = UserApiKeyCache()
+ stale_caps: Final = {"claude-sonnet-4-6": {"max_budget": 3.0, "budget_duration": "1d"}}
+ current_caps: Final = {"claude-sonnet-4-6": {"max_budget": 1.0, "budget_duration": "1d"}}
+ membership: Final = LiteLLM_TeamMembership(
+ user_id="member-1",
+ team_id="team-1",
+ budget_id="default-budget",
+ litellm_budget_table=LiteLLM_BudgetTable(budget_id="default-budget", model_max_budget=stale_caps),
+ )
+ await user_api_key_cache.async_set_cache(
+ key=team_membership_reservation_cache_key(user_id="member-1", team_id="team-1"),
+ value=membership,
+ model_type=LiteLLM_TeamMembership,
+ )
+ await user_api_key_cache.async_set_cache(
+ key="team_member_default_budget:default-budget",
+ value=LiteLLM_BudgetTable(budget_id="default-budget", model_max_budget=current_caps),
+ model_type=LiteLLM_BudgetTable,
+ )
+
+ await _load_team_member_default_model_budget(
+ user_api_key_auth_obj=token,
+ team_object=team_object,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ skip_budget_checks=False,
+ proxy_logging_obj=None,
+ )
+
+ assert token.team_member_model_max_budget == current_caps
+
+
+@pytest.mark.asyncio
+async def test_member_model_budget_load_overall_only_override_keeps_default_caps() -> None:
+ token, team_object, prisma_client, user_api_key_cache = _team_member_model_budget_load_inputs()
+ default_caps: Final = {"claude-sonnet-4-6": {"max_budget": 3.0, "budget_duration": "1d"}}
+ membership: Final = LiteLLM_TeamMembership(
+ user_id="member-1",
+ team_id="team-1",
+ budget_id="member-budget",
+ litellm_budget_table=LiteLLM_BudgetTable(budget_id="member-budget", max_budget=5.0, model_max_budget=None),
+ )
+ await user_api_key_cache.async_set_cache(
+ key=team_membership_reservation_cache_key(user_id="member-1", team_id="team-1"),
+ value=membership,
+ model_type=LiteLLM_TeamMembership,
+ )
+ await user_api_key_cache.async_set_cache(
+ key="team_member_default_budget:default-budget",
+ value=LiteLLM_BudgetTable(budget_id="default-budget", model_max_budget=default_caps),
+ model_type=LiteLLM_BudgetTable,
+ )
+
+ await _load_team_member_default_model_budget(
+ user_api_key_auth_obj=token,
+ team_object=team_object,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ skip_budget_checks=False,
+ proxy_logging_obj=None,
+ )
+
+ assert token.team_member_model_max_budget == default_caps
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("cleared_member_caps", [None, {}], ids=["null", "empty"])
+async def test_member_model_budget_load_falls_back_when_override_has_no_model_caps(
+ cleared_member_caps: dict[str, object] | None,
+) -> None:
+ token, team_object, prisma_client, user_api_key_cache = _team_member_model_budget_load_inputs()
+ default_caps: Final = {"claude-sonnet-4-6": {"max_budget": 3.0, "budget_duration": "1d"}}
+ membership: Final = LiteLLM_TeamMembership(
+ user_id="member-1",
+ team_id="team-1",
+ budget_id="member-budget",
+ litellm_budget_table=LiteLLM_BudgetTable(budget_id="member-budget", model_max_budget=cleared_member_caps),
+ )
+ default_budget: Final = LiteLLM_BudgetTable(budget_id="default-budget", model_max_budget=default_caps)
+ await user_api_key_cache.async_set_cache(
+ key=team_membership_reservation_cache_key(user_id="member-1", team_id="team-1"),
+ value=membership,
+ model_type=LiteLLM_TeamMembership,
+ )
+ await user_api_key_cache.async_set_cache(
+ key="team_member_default_budget:default-budget",
+ value=default_budget,
+ model_type=LiteLLM_BudgetTable,
+ )
+
+ await _load_team_member_default_model_budget(
+ user_api_key_auth_obj=token,
+ team_object=team_object,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ skip_budget_checks=False,
+ proxy_logging_obj=None,
+ )
+
+ assert token.team_member_model_max_budget == default_caps
+
+
+@pytest.mark.asyncio
+async def test_member_model_budget_load_uses_default_without_membership() -> None:
+ token, team_object, prisma_client, user_api_key_cache = _team_member_model_budget_load_inputs()
+ default_caps: Final = {"claude-sonnet-4-6": {"max_budget": 3.0, "budget_duration": "1d"}}
+ default_budget: Final = LiteLLM_BudgetTable(budget_id="default-budget", model_max_budget=default_caps)
+ prisma_client.db.litellm_teammembership.find_unique = AsyncMock(return_value=None)
+ await user_api_key_cache.async_set_cache(
+ key="team_member_default_budget:default-budget",
+ value=default_budget,
+ model_type=LiteLLM_BudgetTable,
+ )
+
+ await _load_team_member_default_model_budget(
+ user_api_key_auth_obj=token,
+ team_object=team_object,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ skip_budget_checks=False,
+ proxy_logging_obj=None,
+ )
+
+ assert token.team_member_model_max_budget == default_caps
+
+
+@pytest.mark.asyncio
+async def test_member_model_budget_load_fails_closed_on_default_lookup_error() -> None:
+ token, team_object, prisma_client, user_api_key_cache = _team_member_model_budget_load_inputs()
+ prisma_client.db.litellm_teammembership.find_unique = AsyncMock(return_value=None)
+ prisma_client.db.litellm_budgettable.find_unique = AsyncMock(
+ side_effect=RuntimeError("budget database unavailable")
+ )
+
+ with pytest.raises(RuntimeError, match="budget database unavailable"):
+ await _load_team_member_default_model_budget(
+ user_api_key_auth_obj=token,
+ team_object=team_object,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ skip_budget_checks=False,
+ proxy_logging_obj=None,
+ )
+
+
+@pytest.mark.asyncio
+async def test_member_model_budget_load_skips_default_lookup_error_when_checks_are_skipped() -> None:
+ token, team_object, prisma_client, user_api_key_cache = _team_member_model_budget_load_inputs()
+ prisma_client.db.litellm_teammembership.find_unique = AsyncMock(return_value=None)
+ prisma_client.db.litellm_budgettable.find_unique = AsyncMock(
+ side_effect=RuntimeError("budget database unavailable")
+ )
+
+ await _load_team_member_default_model_budget(
+ user_api_key_auth_obj=token,
+ team_object=team_object,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ skip_budget_checks=True,
+ proxy_logging_obj=None,
+ )
+
+ assert token.team_member_model_max_budget is None
+
+
+@pytest.mark.asyncio
+async def test_member_model_budget_load_allows_missing_default_row() -> None:
+ token, team_object, prisma_client, user_api_key_cache = _team_member_model_budget_load_inputs()
+ prisma_client.db.litellm_teammembership.find_unique = AsyncMock(return_value=None)
+ prisma_client.db.litellm_budgettable.find_unique = AsyncMock(return_value=None)
+
+ await _load_team_member_default_model_budget(
+ user_api_key_auth_obj=token,
+ team_object=team_object,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ skip_budget_checks=False,
+ proxy_logging_obj=None,
+ )
+
+ assert token.team_member_model_max_budget is None
+
+
@pytest.mark.asyncio
async def test_centralized_common_checks_skipped_for_custom_auth_without_flag():
"""Existing RPS guarantee: custom-auth deployments without
@@ -5331,11 +5923,13 @@ async def test_team_key_vector_store_access_when_team_cannot_be_resolved(
request._url = URL(url="/v1/rag/query")
database: Final = MagicMock()
database.db.litellm_objectpermissiontable.find_unique = AsyncMock(
- side_effect=lambda where: LiteLLM_ObjectPermissionTable(
- object_permission_id=where["object_permission_id"], vector_stores=["KBSTOREA"]
+ side_effect=lambda where: (
+ LiteLLM_ObjectPermissionTable(
+ object_permission_id=where["object_permission_id"], vector_stores=["KBSTOREA"]
+ )
+ if where["object_permission_id"] == "key-permission"
+ else None
)
- if where["object_permission_id"] == "key-permission"
- else None
)
attrs: Final = {
**_proxy_attrs_for_centralized_checks(),
@@ -5387,6 +5981,7 @@ async def test_keyless_team_member_vector_store_access_uses_only_the_resolved_te
):
from fastapi import Request
from starlette.datastructures import URL
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
token: Final = UserAPIKeyAuth(
user_id="user-1",
@@ -5408,9 +6003,27 @@ async def test_keyless_team_member_vector_store_access_uses_only_the_resolved_te
object_permission_id=where["object_permission_id"], vector_stores=grants[where["object_permission_id"]]
)
)
+ database.db.litellm_teammembership.find_unique = AsyncMock(return_value=None)
+ if isinstance(team_lookup, Exception):
+ database.db.litellm_teamtable.find_unique = AsyncMock(side_effect=team_lookup)
+ else:
+ database.db.litellm_teamtable.find_unique = AsyncMock(
+ side_effect=lambda where, **_: LiteLLM_TeamTable(
+ team_id=where["team_id"],
+ models=["gpt-4o-mini"],
+ object_permission_id=team_lookup[where["team_id"]],
+ )
+ )
+ user_api_key_cache: Final = UserApiKeyCache()
+ await user_api_key_cache.async_set_cache(
+ key="user-1",
+ value=LiteLLM_UserTable(user_id="user-1", teams=["team-1", "team-2"], object_permission_id="user-grants-a"),
+ model_type=LiteLLM_UserTable,
+ )
attrs: Final = {
**_proxy_attrs_for_centralized_checks(),
"prisma_client": database,
+ "user_api_key_cache": user_api_key_cache,
"proxy_logging_obj": MagicMock(service_logging_obj=MagicMock(async_service_success_hook=AsyncMock())),
"general_settings": {"vector_store_deny_by_default": True},
}
@@ -5418,22 +6031,6 @@ async def test_keyless_team_member_vector_store_access_uses_only_the_resolved_te
monkeypatch.setattr(litellm.proxy.proxy_server, name, value)
monkeypatch.setattr(litellm, "vector_store_registry", None)
- async def get_team(team_id: str, **_: object) -> LiteLLM_TeamTableCachedObj:
- if isinstance(team_lookup, Exception):
- raise team_lookup
- return LiteLLM_TeamTableCachedObj(team_id=team_id, models=["gpt-4o-mini"], object_permission_id=team_lookup[team_id])
-
- monkeypatch.setattr("litellm.proxy.auth.user_api_key_auth.get_team_object", get_team)
- monkeypatch.setattr("litellm.proxy.auth.auth_checks.get_team_membership", AsyncMock(return_value=None))
- monkeypatch.setattr(
- "litellm.proxy.auth.user_api_key_auth.get_user_object",
- AsyncMock(
- return_value=LiteLLM_UserTable(
- user_id="user-1", teams=["team-1", "team-2"], object_permission_id="user-grants-a"
- )
- ),
- )
-
checks: Final = run_centralized_common_checks(
user_api_key_auth_obj=token,
request=request,
@@ -6683,6 +7280,7 @@ async def test_centralized_common_checks_inherits_org_identity(
attrs = _proxy_attrs_for_centralized_checks(user_custom_auth=None)
attrs["prisma_client"] = MagicMock()
+ attrs["prisma_client"].db.litellm_teammembership.find_unique = AsyncMock(return_value=None)
attrs["general_settings"] = {"allow_requests_on_db_unavailable": allow_db_unavailable}
originals = {a: getattr(_proxy_server_mod, a, None) for a in attrs}
try:
@@ -7690,7 +8288,8 @@ async def _authenticate_session_token_against_db(
from starlette.datastructures import URL
attrs = _proxy_attrs_for_db_lookup()
- attrs["prisma_client"].db.litellm_teammembership.find_first = AsyncMock(return_value=None)
+ attrs["prisma_client"].db.litellm_teammembership.find_unique = AsyncMock(return_value=membership_row)
+ attrs["prisma_client"].db.litellm_teammembership.find_first = AsyncMock(return_value=membership_row)
originals = {a: getattr(_proxy_server_mod, a, None) for a in attrs}
assemble = AsyncMock(return_value=UserAPIKeyAuth(user_id=SESSION_USER_ID, is_session_token=True))
try:
@@ -7710,10 +8309,6 @@ async def _authenticate_session_token_against_db(
"litellm.proxy.auth.user_api_key_auth.get_team_object",
AsyncMock(return_value=team_row, side_effect=team_error),
),
- patch( # test-quality-ok: the builder reads its DB row loaders off module globals
- "litellm.proxy.auth.user_api_key_auth.get_team_membership",
- AsyncMock(return_value=membership_row),
- ),
):
await user_api_key_auth_builder(
request=request,
@@ -8226,25 +8821,16 @@ class TestCheckKeyModelBudgetWithFallback:
request_data = {"model": "gpt-4o"}
request = self._make_request()
- with patch(
- "litellm.proxy.auth.user_api_key_auth.can_key_call_model",
- side_effect=ProxyException(
- message="model not allowed",
- type=ProxyErrorTypes.budget_exceeded,
- param="model",
- code=status.HTTP_403_FORBIDDEN,
- ),
- ):
- with pytest.raises(litellm.BudgetExceededError) as exc_info:
- await _check_key_model_budget_with_fallback(
- valid_token=valid_token,
- model_max_budget_limiter=limiter,
- model_name="gpt-4o",
- request_data=request_data,
- request=request,
- llm_model_list=None,
- llm_router=None,
- )
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_key_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ model_name="gpt-4o",
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=None,
+ )
assert exc_info.value is original_error
assert request_data["model"] == "gpt-4o"
@@ -8264,19 +8850,15 @@ class TestCheckKeyModelBudgetWithFallback:
request_data = {"model": "gpt-4o"}
request = self._make_request()
- with patch(
- "litellm.proxy.auth.user_api_key_auth.can_key_call_model",
- return_value=True,
- ):
- await _check_key_model_budget_with_fallback(
- valid_token=valid_token,
- model_max_budget_limiter=limiter,
- model_name="gpt-4o",
- request_data=request_data,
- request=request,
- llm_model_list=None,
- llm_router=None,
- )
+ await _check_key_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ model_name="gpt-4o",
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=None,
+ )
assert request_data["model"] == "gpt-4o-mini"
@@ -8298,20 +8880,16 @@ class TestCheckKeyModelBudgetWithFallback:
request_data = {"model": "gpt-4o"}
request = self._make_request()
- with patch(
- "litellm.proxy.auth.user_api_key_auth.can_key_call_model",
- return_value=True,
- ):
- with pytest.raises(litellm.BudgetExceededError) as exc_info:
- await _check_key_model_budget_with_fallback(
- valid_token=valid_token,
- model_max_budget_limiter=limiter,
- model_name="gpt-4o",
- request_data=request_data,
- request=request,
- llm_model_list=None,
- llm_router=None,
- )
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_key_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ model_name="gpt-4o",
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=None,
+ )
assert exc_info.value is original_error
assert request_data["model"] == "gpt-4o"
@@ -8333,19 +8911,15 @@ class TestCheckKeyModelBudgetWithFallback:
request = self._make_request()
request.scope["path_params"] = {"model": "gpt-4o"}
- with patch(
- "litellm.proxy.auth.user_api_key_auth.can_key_call_model",
- return_value=True,
- ):
- await _check_key_model_budget_with_fallback(
- valid_token=valid_token,
- model_max_budget_limiter=limiter,
- model_name="gpt-4o",
- request_data=request_data,
- request=request,
- llm_model_list=None,
- llm_router=None,
- )
+ await _check_key_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ model_name="gpt-4o",
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=None,
+ )
assert request_data["model"] == "gpt-4o-mini"
assert request.scope["path_params"]["model"] == "gpt-4o-mini"
@@ -8379,6 +8953,1287 @@ class TestCheckKeyModelBudgetWithFallback:
assert "model" not in request_data
+class TestCheckTeamMemberModelBudgetWithFallback:
+ @pytest.fixture(autouse=True)
+ async def _seed_auth_cache(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ import litellm.proxy.proxy_server as proxy_server
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache, team_membership_reservation_cache_key
+
+ user_api_key_cache: Final = UserApiKeyCache()
+ await user_api_key_cache.async_set_cache(
+ key=team_membership_reservation_cache_key(user_id="user-1", team_id="team-1"),
+ value=NO_TEAM_MEMBERSHIP_SENTINEL,
+ )
+ await user_api_key_cache.async_set_cache(
+ key="team_id:team-1",
+ value=LiteLLM_TeamTableCachedObj(team_id="team-1"),
+ model_type=LiteLLM_TeamTableCachedObj,
+ )
+ prisma_client: Final = MagicMock()
+ prisma_client.db.litellm_teammembership.find_unique = AsyncMock(return_value=None)
+ prisma_client.db.litellm_teammembership.find_first = AsyncMock(return_value=None)
+ monkeypatch.setattr(proxy_server, "user_api_key_cache", user_api_key_cache)
+ monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)
+ monkeypatch.setattr(proxy_server, "proxy_logging_obj", MagicMock())
+
+ def _router(
+ self,
+ fallbacks: list[dict[str, object]] | None,
+ model_group_alias: dict[str, str] | None = None,
+ free_models: frozenset[str] = frozenset(),
+ ) -> litellm.Router:
+ model_list: Final = [
+ {
+ "model_name": model,
+ "litellm_params": {"model": "gpt-4o"},
+ **(
+ {"model_info": {"input_cost_per_token": 0, "output_cost_per_token": 0}}
+ if model in free_models
+ else {}
+ ),
+ }
+ for model in (
+ "gpt-4o",
+ "gpt-4o-mini",
+ "restricted-model",
+ "backup",
+ "backup-unavailable",
+ "backup-valid",
+ "claude-sonnet-4-6",
+ "claude-haiku-4-5",
+ "claude-haiku",
+ "expensive",
+ *sorted(free_models),
+ )
+ ]
+ return litellm.Router(model_list=model_list, fallbacks=fallbacks, model_group_alias=model_group_alias)
+
+ def _request(self, model: str) -> Request:
+ return Request(scope={"type": "http", "path_params": {"model": model}, "headers": []})
+
+ @pytest.mark.asyncio
+ async def test_within_budget_does_not_rewrite_request(self):
+ budget: Final = {"gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"}}
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget=budget,
+ )
+ limiter, _ = await _real_model_budget_limiter()
+ request_data: Final = {"model": "gpt-4o"}
+ request: Final = self._request("gpt-4o")
+
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"gpt-4o": ["gpt-4o-mini"]}]),
+ )
+
+ assert request_data["model"] == "gpt-4o"
+ assert request.scope["path_params"]["model"] == "gpt-4o"
+ assert "parsed_body" not in request.scope
+
+ @pytest.mark.asyncio
+ async def test_generic_fallback_rewrites_every_request_view(self):
+ budget: Final = {"gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"}}
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ models=["gpt-4o", "gpt-4o-mini"],
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={**budget, "gpt-4o-mini": {"max_budget": 100.0, "budget_duration": "1d"}},
+ )
+ limiter, _ = await _real_model_budget_limiter(member_spend={"gpt-4o": 10.0})
+ request_data: Final = {"model": "gpt-4o", "auth_injected_metadata": {"internal": "value"}}
+ request: Final = self._request("gpt-4o")
+ client_body: Final = {"model": "gpt-4o", "messages": [{"role": "user", "content": "hello"}]}
+ request.scope["parsed_body"] = (tuple(client_body), client_body)
+
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"*": ["gpt-4o-mini"]}]),
+ )
+
+ assert request_data["model"] == "gpt-4o-mini"
+ expected_body: Final = {"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "hello"}]}
+ assert request._json == expected_body
+ assert orjson.loads(request._body) == expected_body
+ assert request.scope["parsed_body"][1] == expected_body
+ assert "auth_injected_metadata" not in request._json
+ assert request.scope["path_params"]["model"] == "gpt-4o-mini"
+
+ @pytest.mark.asyncio
+ async def test_specific_fallback_rewrites_requested_model(self):
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={
+ "gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"},
+ "gpt-4o-mini": {"max_budget": 100.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, _ = await _real_model_budget_limiter(member_spend={"gpt-4o": 10.0})
+ request_data: Final = {"model": "gpt-4o"}
+ request: Final = self._request("gpt-4o")
+
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"gpt-4o": ["gpt-4o-mini"]}]),
+ )
+
+ assert request_data["model"] == "gpt-4o-mini"
+ assert request.scope["path_params"]["model"] == "gpt-4o-mini"
+
+ @pytest.mark.asyncio
+ async def test_multipart_request_keeps_member_budget_error_without_rewriting(self) -> None:
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ models=["claude-sonnet-4-6", "claude-haiku-4-5"],
+ user_id="user-1",
+ team_id="team-1",
+ router_settings={"fallbacks": [{"claude-sonnet-4-6": ["claude-haiku-4-5"]}]},
+ team_member_model_max_budget={"claude-sonnet-4-6": {"max_budget": 5.0, "budget_duration": "1d"}},
+ )
+ limiter, redis_cache = await _real_model_budget_limiter(member_spend={"claude-sonnet-4-6": 10.0})
+ user_api_key_cache: Final = UserApiKeyCache()
+ await user_api_key_cache.async_set_cache(
+ key=team_membership_reservation_cache_key(user_id="user-1", team_id="team-1"),
+ value=NO_TEAM_MEMBERSHIP_SENTINEL,
+ )
+ uploaded_file: Final = UploadFile(filename="audio.wav", file=BytesIO(b"audio"))
+ request_data: Final = {"model": "claude-sonnet-4-6", "file": uploaded_file}
+ request: Final = Request(
+ scope={
+ "type": "http",
+ "path_params": {"model": "claude-sonnet-4-6"},
+ "headers": [(b"content-type", b"Multipart/Form-Data; boundary=test")],
+ }
+ )
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["claude-sonnet-4-6"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=litellm.Router(
+ model_list=[],
+ fallbacks=[{"claude-sonnet-4-6": ["claude-haiku-4-5"]}],
+ ),
+ user_api_key_cache=user_api_key_cache,
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == "claude-sonnet-4-6"
+ assert request_data["file"] is uploaded_file
+ assert request.scope["path_params"]["model"] == "claude-sonnet-4-6"
+ assert getattr(request, "_body", None) is None
+ assert [
+ call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list
+ ] == _team_member_model_budget_spend_keys(["claude-sonnet-4-6"])
+
+ @pytest.mark.asyncio
+ async def test_provider_scoped_resource_keeps_member_budget_error_without_fallback(self) -> None:
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ models=["claude-sonnet-4-6", "claude-haiku-4-5"],
+ user_id="user-1",
+ team_id="team-1",
+ router_settings={"fallbacks": [{"claude-sonnet-4-6": ["claude-haiku-4-5"]}]},
+ team_member_model_max_budget={"claude-sonnet-4-6": {"max_budget": 5.0, "budget_duration": "1d"}},
+ )
+ limiter, redis_cache = await _real_model_budget_limiter(member_spend={"claude-sonnet-4-6": 10.0})
+ request_data: Final[dict[str, object]] = {
+ "model": "claude-sonnet-4-6",
+ "input_file_id": "file-123",
+ }
+ request: Final = self._request("claude-sonnet-4-6")
+ user_api_key_cache: Final = UserApiKeyCache()
+ await user_api_key_cache.async_set_cache(
+ key=team_membership_reservation_cache_key(user_id="user-1", team_id="team-1"),
+ value=NO_TEAM_MEMBERSHIP_SENTINEL,
+ )
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["claude-sonnet-4-6"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=litellm.Router(
+ model_list=[],
+ fallbacks=[{"claude-sonnet-4-6": ["claude-haiku-4-5"]}],
+ ),
+ user_api_key_cache=user_api_key_cache,
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data == {
+ "model": "claude-sonnet-4-6",
+ "input_file_id": "file-123",
+ }
+ assert request.scope["path_params"]["model"] == "claude-sonnet-4-6"
+ assert [
+ call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list
+ ] == _team_member_model_budget_spend_keys(["claude-sonnet-4-6"])
+
+ @pytest.mark.asyncio
+ async def test_fallback_prefers_hierarchical_router_settings_fallbacks(self) -> None:
+ import litellm.proxy.proxy_server as proxy_server
+
+ router_settings: Final = {"fallbacks": [{"claude-sonnet-4-6": ["claude-haiku-4-5"]}]}
+ await proxy_server.user_api_key_cache.async_set_cache(
+ key="team_id:team-1",
+ value=LiteLLM_TeamTableCachedObj(team_id="team-1", router_settings=router_settings),
+ model_type=LiteLLM_TeamTableCachedObj,
+ )
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={
+ "claude-sonnet-4-6": {"max_budget": 5.0, "budget_duration": "1d"},
+ "claude-haiku-4-5": {"max_budget": 100.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, redis_cache = await _real_model_budget_limiter(member_spend={"claude-sonnet-4-6": 10.0})
+ request_data: Final = {"model": "claude-sonnet-4-6"}
+ request: Final = self._request("claude-sonnet-4-6")
+ router: Final = self._router([{"claude-sonnet-4-6": ["global-backup"]}])
+
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["claude-sonnet-4-6"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=router,
+ )
+
+ assert request_data["model"] == "claude-haiku-4-5"
+ assert request.scope["path_params"]["model"] == "claude-haiku-4-5"
+ assert [
+ call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list
+ ] == _team_member_model_budget_spend_keys(["claude-sonnet-4-6", "claude-haiku-4-5"])
+
+ @pytest.mark.asyncio
+ async def test_fallback_resolves_router_alias_before_budget_check(self) -> None:
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ user_id="user-1",
+ team_id="team-1",
+ router_settings={"model_group_alias": {"backup": "expensive"}},
+ team_member_model_max_budget={
+ "claude-sonnet-4-6": {"max_budget": 5.0, "budget_duration": "1d"},
+ "backup": {"max_budget": 100.0, "budget_duration": "1d"},
+ "expensive": {"max_budget": 5.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, redis_cache = await _real_model_budget_limiter(
+ member_spend={"claude-sonnet-4-6": 10.0, "expensive": 10.0}
+ )
+ request_data: Final = {"model": "claude-sonnet-4-6"}
+ request: Final = self._request("claude-sonnet-4-6")
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["claude-sonnet-4-6"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"claude-sonnet-4-6": ["backup"]}]),
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == "claude-sonnet-4-6"
+ assert [
+ call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list
+ ] == _team_member_model_budget_spend_keys(["claude-sonnet-4-6", "backup", "expensive"])
+
+ @pytest.mark.asyncio
+ async def test_fallback_checks_global_router_alias_budget_before_rerouting(self) -> None:
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={
+ "claude-sonnet-4-6": {"max_budget": 5.0, "budget_duration": "1d"},
+ "backup": {"max_budget": 100.0, "budget_duration": "1d"},
+ "expensive": {"max_budget": 5.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, redis_cache = await _real_model_budget_limiter(
+ member_spend={"claude-sonnet-4-6": 10.0, "expensive": 10.0}
+ )
+ request_data: Final[dict[str, object]] = {"model": "claude-sonnet-4-6"}
+ request: Final = self._request("claude-sonnet-4-6")
+ router: Final = self._router(
+ [{"claude-sonnet-4-6": ["backup"]}],
+ model_group_alias={"backup": "expensive"},
+ )
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["claude-sonnet-4-6"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=router,
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == "claude-sonnet-4-6"
+ assert [
+ call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list
+ ] == _team_member_model_budget_spend_keys(["claude-sonnet-4-6", "backup", "expensive"])
+
+ @pytest.mark.asyncio
+ async def test_fallback_checks_key_team_alias_budget_before_rerouting(self) -> None:
+ model_group_alias: Final = {"backup": "expensive"}
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ user_id="user-1",
+ team_id="team-1",
+ router_settings={"model_group_alias": model_group_alias},
+ team_member_model_max_budget={
+ "claude-sonnet-4-6": {"max_budget": 5.0, "budget_duration": "1d"},
+ "backup": {"max_budget": 5.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, redis_cache = await _real_model_budget_limiter(
+ member_spend={"claude-sonnet-4-6": 10.0, "backup": 10.0}
+ )
+ request_data: Final[dict[str, object]] = {"model": "claude-sonnet-4-6"}
+ request: Final = self._request("claude-sonnet-4-6")
+ router: Final = self._router([{"claude-sonnet-4-6": ["backup"]}])
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["claude-sonnet-4-6"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=router,
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == "claude-sonnet-4-6"
+ assert [
+ call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list
+ ] == _team_member_model_budget_spend_keys(["claude-sonnet-4-6", "backup"])
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "key_aliases, global_alias_map",
+ [
+ pytest.param({"backup": "expensive"}, {}, id="key_aliases"),
+ pytest.param({}, {"backup": "expensive"}, id="global_alias_map"),
+ ],
+ )
+ async def test_fallback_aliased_to_spent_member_model_budget_is_skipped(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ key_aliases: dict[str, str],
+ global_alias_map: dict[str, str],
+ ) -> None:
+ primary_model: Final = "claude-sonnet-4-6"
+ fallback_model: Final = "backup"
+ expensive_model: Final = "expensive"
+ monkeypatch.setattr(litellm, "model_alias_map", global_alias_map)
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ user_id="user-1",
+ team_id="team-1",
+ aliases=key_aliases,
+ team_member_model_max_budget={
+ primary_model: {"max_budget": 5.0, "budget_duration": "1d"},
+ expensive_model: {"max_budget": 5.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, redis_cache = await _real_model_budget_limiter(
+ member_spend={primary_model: 10.0, expensive_model: 10.0}
+ )
+ request_data: Final[dict[str, object]] = {"model": primary_model}
+ request: Final = self._request(primary_model)
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=[primary_model],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{primary_model: [fallback_model]}]),
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == primary_model
+ assert request.scope["path_params"]["model"] == primary_model
+ assert [
+ call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list
+ ] == _team_member_model_budget_spend_keys([primary_model, expensive_model])
+
+ @pytest.mark.asyncio
+ async def test_free_fallback_aliased_to_spent_paid_model_is_skipped(self) -> None:
+ primary_model: Final = "claude-sonnet-4-6"
+ fallback_model: Final = "free-backup"
+ expensive_model: Final = "expensive"
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ user_id="user-1",
+ team_id="team-1",
+ aliases={fallback_model: expensive_model},
+ team_member_model_max_budget={
+ primary_model: {"max_budget": 5.0, "budget_duration": "1d"},
+ expensive_model: {"max_budget": 5.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, redis_cache = await _real_model_budget_limiter(
+ member_spend={primary_model: 10.0, expensive_model: 10.0}
+ )
+ request_data: Final[dict[str, object]] = {"model": primary_model}
+ request: Final = self._request(primary_model)
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=[primary_model],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router(
+ [{primary_model: [fallback_model]}],
+ free_models=frozenset({fallback_model}),
+ ),
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == primary_model
+ assert request.scope["path_params"]["model"] == primary_model
+ assert [
+ call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list
+ ] == _team_member_model_budget_spend_keys([primary_model, expensive_model])
+
+ @pytest.mark.asyncio
+ async def test_fallback_rewrites_router_alias_to_budget_checked_target(self) -> None:
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ user_id="user-1",
+ team_id="team-1",
+ router_settings={"model_group_alias": {"backup": "expensive"}},
+ team_member_model_max_budget={
+ "claude-sonnet-4-6": {"max_budget": 5.0, "budget_duration": "1d"},
+ "backup": {"max_budget": 100.0, "budget_duration": "1d"},
+ "expensive": {"max_budget": 100.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, redis_cache = await _real_model_budget_limiter(member_spend={"claude-sonnet-4-6": 10.0})
+ request_data: Final[dict[str, object]] = {"model": "claude-sonnet-4-6"}
+ request: Final = self._request("claude-sonnet-4-6")
+
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["claude-sonnet-4-6"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"claude-sonnet-4-6": ["backup"]}]),
+ )
+
+ assert request_data["model"] == "expensive"
+ assert request.scope["path_params"]["model"] == "expensive"
+ assert [
+ call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list
+ ] == _team_member_model_budget_spend_keys(["claude-sonnet-4-6", "backup", "expensive"])
+
+ @pytest.mark.asyncio
+ async def test_zero_cost_fallback_skips_spent_member_model_budget(self) -> None:
+ primary_model: Final = "claude-sonnet-4-6"
+ fallback_model: Final = "free-backup"
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={
+ primary_model: {"max_budget": 5.0, "budget_duration": "1d"},
+ fallback_model: {"max_budget": 5.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, redis_cache = await _real_model_budget_limiter(
+ member_spend={primary_model: 10.0, fallback_model: 10.0}
+ )
+ request_data: Final[dict[str, object]] = {"model": primary_model}
+ request: Final = self._request(primary_model)
+
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=[primary_model],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router(
+ [{primary_model: [fallback_model]}],
+ free_models=frozenset({fallback_model}),
+ ),
+ )
+
+ assert request_data["model"] == fallback_model
+ assert request.scope["path_params"]["model"] == fallback_model
+ assert [
+ call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list
+ ] == _team_member_model_budget_spend_keys([primary_model])
+
+ @pytest.mark.asyncio
+ async def test_fallback_settings_lookup_error_keeps_original_budget_error(self) -> None:
+ import litellm.proxy.proxy_server as proxy_server
+
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={"claude-sonnet-4-6": {"max_budget": 5.0, "budget_duration": "1d"}},
+ )
+ limiter, redis_cache = await _real_model_budget_limiter(member_spend={"claude-sonnet-4-6": 10.0})
+ request_data: Final = {"model": "claude-sonnet-4-6"}
+ request: Final = self._request("claude-sonnet-4-6")
+ await proxy_server.user_api_key_cache.async_delete_cache(key="team_id:team-1")
+ proxy_server.prisma_client.db.litellm_teamtable.find_unique = AsyncMock(
+ side_effect=RuntimeError("settings unavailable")
+ )
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["claude-sonnet-4-6"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router(None),
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == "claude-sonnet-4-6"
+ assert [
+ call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list
+ ] == _team_member_model_budget_spend_keys(["claude-sonnet-4-6"])
+ proxy_server.prisma_client.db.litellm_teamtable.find_unique.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_fallback_skips_candidate_after_budget_check_error(self) -> None:
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ user_id="user-1",
+ team_id="team-1",
+ router_settings={"model_group_alias": {}},
+ team_member_model_max_budget={
+ "claude-sonnet-4-6": {"max_budget": 5.0, "budget_duration": "1d"},
+ "backup-unavailable": {"max_budget": 100.0, "budget_duration": "1d"},
+ "backup-valid": {"max_budget": 100.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, redis_cache = await _real_model_budget_limiter(
+ member_spend={"claude-sonnet-4-6": 10.0},
+ member_errors={"backup-unavailable": RuntimeError("budget counter unavailable")},
+ )
+ request_data: Final = {"model": "claude-sonnet-4-6"}
+ request: Final = self._request("claude-sonnet-4-6")
+
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["claude-sonnet-4-6"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"claude-sonnet-4-6": ["backup-unavailable", "backup-valid"]}]),
+ )
+
+ assert request_data["model"] == "backup-valid"
+ assert request.scope["path_params"]["model"] == "backup-valid"
+ assert [
+ call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list
+ ] == _team_member_model_budget_spend_keys(["claude-sonnet-4-6", "backup-unavailable", "backup-valid"])
+
+ @pytest.mark.asyncio
+ async def test_fallback_candidate_check_errors_keep_original_budget_error(self) -> None:
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ user_id="user-1",
+ team_id="team-1",
+ router_settings={"model_group_alias": {}},
+ team_member_model_max_budget={
+ "claude-sonnet-4-6": {"max_budget": 5.0, "budget_duration": "1d"},
+ "backup-unavailable": {"max_budget": 100.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, _ = await _real_model_budget_limiter(
+ member_spend={"claude-sonnet-4-6": 10.0},
+ member_errors={"backup-unavailable": RuntimeError("budget counter unavailable")},
+ )
+ request_data: Final = {"model": "claude-sonnet-4-6"}
+ request: Final = self._request("claude-sonnet-4-6")
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["claude-sonnet-4-6"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"claude-sonnet-4-6": ["backup-unavailable"]}]),
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == "claude-sonnet-4-6"
+
+ @pytest.mark.asyncio
+ async def test_fallback_outside_project_models_raises_original_member_budget_error(
+ self,
+ ) -> None:
+ valid_token: Final = UserAPIKeyAuth(
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={
+ "claude-sonnet-4-6": {"max_budget": 5.0, "budget_duration": "1d"},
+ "claude-haiku-4-5": {"max_budget": 100.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, _ = await _real_model_budget_limiter(member_spend={"claude-sonnet-4-6": 10.0})
+ request_data: Final = {"model": "claude-sonnet-4-6"}
+ request: Final = self._request("claude-sonnet-4-6")
+ project_object: Final = LiteLLM_ProjectTableCachedObj(
+ project_id="project-1",
+ models=["claude-sonnet-4-6"],
+ )
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["claude-sonnet-4-6"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"claude-sonnet-4-6": ["claude-haiku-4-5"]}]),
+ project_object=project_object,
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == "claude-sonnet-4-6"
+
+ @pytest.mark.asyncio
+ async def test_fallback_within_project_models_rewrites_request(
+ self,
+ ) -> None:
+ valid_token: Final = UserAPIKeyAuth(
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={
+ "claude-sonnet-4-6": {"max_budget": 5.0, "budget_duration": "1d"},
+ "claude-haiku-4-5": {"max_budget": 100.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, _ = await _real_model_budget_limiter(member_spend={"claude-sonnet-4-6": 10.0})
+ request_data: Final = {"model": "claude-sonnet-4-6"}
+ request: Final = self._request("claude-sonnet-4-6")
+ project_object: Final = LiteLLM_ProjectTableCachedObj(
+ project_id="project-1",
+ models=["claude-sonnet-4-6", "claude-haiku-4-5"],
+ )
+
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["claude-sonnet-4-6"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"claude-sonnet-4-6": ["claude-haiku-4-5"]}]),
+ project_object=project_object,
+ )
+
+ assert request_data["model"] == "claude-haiku-4-5"
+ assert request.scope["path_params"]["model"] == "claude-haiku-4-5"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("grant_source", ["team", "key"])
+ async def test_fallback_uses_team_and_key_access_group_grants(
+ self, grant_source: str, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ import litellm.proxy.proxy_server as proxy_server
+ from litellm.proxy._types import LiteLLM_AccessGroupTable
+
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ user_id="user-1",
+ team_id="team-1",
+ team_models=["claude-sonnet-4-6"],
+ access_group_ids=["key-group"] if grant_source == "key" else [],
+ team_member_model_max_budget={
+ "claude-sonnet-4-6": {"max_budget": 5.0, "budget_duration": "1d"},
+ "claude-haiku-4-5": {"max_budget": 100.0, "budget_duration": "1d"},
+ },
+ )
+ team_object: Final = LiteLLM_TeamTable(
+ team_id="team-1",
+ models=["claude-sonnet-4-6"],
+ access_group_ids=["team-group"] if grant_source == "team" else [],
+ )
+ limiter, _ = await _real_model_budget_limiter(member_spend={"claude-sonnet-4-6": 10.0})
+ request_data: Final = {"model": "claude-sonnet-4-6"}
+ request: Final = self._request("claude-sonnet-4-6")
+ prisma_client: Final = MagicMock()
+ access_group_id: Final = "team-group" if grant_source == "team" else "key-group"
+ group_row: Final = LiteLLM_AccessGroupTable(
+ access_group_id=access_group_id,
+ access_group_name=access_group_id,
+ access_model_names=["claude-haiku-4-5"],
+ assigned_team_ids=["team-1"],
+ )
+ prisma_client.db.litellm_accessgrouptable.find_unique = AsyncMock(return_value=group_row)
+ monkeypatch.setattr(proxy_server, "prisma_client", prisma_client)
+
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["claude-sonnet-4-6"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"claude-sonnet-4-6": ["claude-haiku-4-5"]}]),
+ team_object=team_object,
+ prisma_client=prisma_client,
+ user_api_key_cache=proxy_server.user_api_key_cache,
+ proxy_logging_obj=proxy_server.proxy_logging_obj,
+ )
+
+ assert request_data["model"] == "claude-haiku-4-5"
+ prisma_client.db.litellm_accessgrouptable.find_unique.assert_awaited_once_with(
+ where={"access_group_id": access_group_id}
+ )
+
+ @pytest.mark.asyncio
+ async def test_fallback_without_team_or_key_access_group_grants_keeps_budget_error(self) -> None:
+ valid_token: Final = UserAPIKeyAuth(
+ user_id="user-1",
+ team_id="team-1",
+ team_models=["claude-sonnet-4-6"],
+ team_member_model_max_budget={
+ "claude-sonnet-4-6": {"max_budget": 5.0, "budget_duration": "1d"},
+ "claude-haiku-4-5": {"max_budget": 100.0, "budget_duration": "1d"},
+ },
+ )
+ team_object: Final = LiteLLM_TeamTable(team_id="team-1", models=["claude-sonnet-4-6"])
+ limiter, _ = await _real_model_budget_limiter(member_spend={"claude-sonnet-4-6": 10.0})
+ request_data: Final = {"model": "claude-sonnet-4-6"}
+ request: Final = self._request("claude-sonnet-4-6")
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["claude-sonnet-4-6"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"claude-sonnet-4-6": ["claude-haiku-4-5"]}]),
+ team_object=team_object,
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == "claude-sonnet-4-6"
+
+ @pytest.mark.asyncio
+ async def test_exhausted_fallback_raises_original_member_budget_error(self):
+ budget: Final = {
+ "gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"},
+ "gpt-4o-mini": {"max_budget": 5.0, "budget_duration": "1d"},
+ }
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget=budget,
+ )
+ limiter, _ = await _real_model_budget_limiter(member_spend={"gpt-4o": 10.0, "gpt-4o-mini": 10.0})
+ request_data: Final = {"model": "gpt-4o"}
+ request: Final = self._request("gpt-4o")
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"gpt-4o": ["gpt-4o-mini"]}]),
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == "gpt-4o"
+
+ @pytest.mark.asyncio
+ async def test_no_router_fallback_raises_original_member_budget_error(self):
+ valid_token: Final = UserAPIKeyAuth(
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={"gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"}},
+ )
+ limiter, _ = await _real_model_budget_limiter(member_spend={"gpt-4o": 10.0})
+ request_data: Final = {"model": "gpt-4o"}
+ request: Final = self._request("gpt-4o")
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=None,
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+
+ @pytest.mark.asyncio
+ async def test_router_without_fallbacks_raises_original_member_budget_error(self):
+ budget: Final = {"gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"}}
+ valid_token: Final = UserAPIKeyAuth(
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget=budget,
+ )
+ limiter, _ = await _real_model_budget_limiter(member_spend={"gpt-4o": 10.0})
+ request_data: Final = {"model": "gpt-4o"}
+ request: Final = self._request("gpt-4o")
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router(None),
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == "gpt-4o"
+
+ @pytest.mark.asyncio
+ async def test_fallback_exceeding_key_budget_is_rejected(self):
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ model_max_budget={"gpt-4o-mini": {"max_budget": 1.0, "budget_duration": "1d"}},
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={"gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"}},
+ )
+ limiter, redis_cache = await _real_model_budget_limiter(
+ member_spend={"gpt-4o": 10.0}, key_spend={"gpt-4o-mini": 2.0}
+ )
+ request_data: Final = {"model": "gpt-4o"}
+ request: Final = self._request("gpt-4o")
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"gpt-4o": ["gpt-4o-mini"]}]),
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert [
+ call.kwargs["key"]
+ for call in redis_cache.async_get_cache.call_args_list
+ if call.kwargs["key"].startswith("virtual_key_spend:")
+ ] == _model_budget_spend_keys(Litellm_EntityType.KEY, "test-key", ["gpt-4o-mini"])
+
+ @pytest.mark.asyncio
+ async def test_fallback_outside_key_models_is_rejected(self):
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ models=["gpt-4o"],
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={"gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"}},
+ )
+ limiter, _ = await _real_model_budget_limiter(member_spend={"gpt-4o": 10.0})
+ request_data: Final = {"model": "gpt-4o"}
+ request: Final = self._request("gpt-4o")
+ denied: Final = ProxyException(
+ message="model not allowed",
+ type=ProxyErrorTypes.budget_exceeded,
+ param="model",
+ code=status.HTTP_403_FORBIDDEN,
+ )
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"gpt-4o": ["gpt-4o-mini"]}]),
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == "gpt-4o"
+
+ @pytest.mark.asyncio
+ async def test_agent_key_does_not_reroute_to_fallback(self):
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ models=["gpt-4o", "gpt-4o-mini"],
+ user_id="user-1",
+ team_id="team-1",
+ agent_id="agent-1",
+ team_member_model_max_budget={
+ "gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"},
+ "gpt-4o-mini": {"max_budget": 100.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, _ = await _real_model_budget_limiter(member_spend={"gpt-4o": 10.0})
+ request_data: Final = {"model": "gpt-4o"}
+ request: Final = self._request("gpt-4o")
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"gpt-4o": ["gpt-4o-mini"]}]),
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == "gpt-4o"
+ assert getattr(request, "_json", None) is None
+
+ @pytest.mark.asyncio
+ async def test_agent_key_can_reroute_on_key_model_budget_fallback(self):
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ models=["gpt-4o", "gpt-4o-mini"],
+ agent_id="agent-1",
+ budget_fallbacks={"gpt-4o": ["gpt-4o-mini"]},
+ model_max_budget={
+ "gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"},
+ "gpt-4o-mini": {"max_budget": 100.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, _ = await _real_model_budget_limiter(key_spend={"gpt-4o": 10.0})
+ request_data: Final = {"model": "gpt-4o"}
+ request: Final = self._request("gpt-4o")
+
+ await _check_key_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ model_name="gpt-4o",
+ request_data=request_data,
+ request=request,
+ )
+
+ assert request_data["model"] == "gpt-4o-mini"
+
+ @pytest.mark.asyncio
+ async def test_fallback_outside_member_allowed_models_is_rejected(self):
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ models=["gpt-4o", "gpt-4o-mini"],
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={"gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"}},
+ )
+ limiter, _ = await _real_model_budget_limiter(member_spend={"gpt-4o": 10.0})
+ request_data: Final = {"model": "gpt-4o"}
+ request: Final = self._request("gpt-4o")
+ import litellm.proxy.proxy_server as proxy_server
+
+ membership: Final = LiteLLM_TeamMembership(
+ user_id="user-1",
+ team_id="team-1",
+ budget_id="member-budget",
+ litellm_budget_table=LiteLLM_BudgetTable(budget_id="member-budget", allowed_models=["gpt-4o"]),
+ )
+ await proxy_server.user_api_key_cache.async_set_cache(
+ key=team_membership_reservation_cache_key(user_id="user-1", team_id="team-1"),
+ value=membership,
+ model_type=LiteLLM_TeamMembership,
+ )
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"gpt-4o": ["gpt-4o-mini"]}]),
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("targets", "expected_model"),
+ [
+ ([{"model": "gpt-4o-mini"}], "gpt-4o-mini"),
+ ([{"model": "gpt-4o-mini", "temperature": 0.2}, {"model": "claude-haiku"}], "claude-haiku"),
+ ([{"model": "gpt-4o-mini", "temperature": 0.2}], None),
+ ],
+ )
+ async def test_dict_fallback_targets_only_reroute_model_only_entries(self, targets, expected_model):
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ models=["gpt-4o", "gpt-4o-mini", "claude-haiku"],
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={
+ "gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"},
+ "gpt-4o-mini": {"max_budget": 100.0, "budget_duration": "1d"},
+ "claude-haiku": {"max_budget": 100.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, _ = await _real_model_budget_limiter(member_spend={"gpt-4o": 10.0})
+ request_data: Final = {"model": "gpt-4o"}
+ request: Final = self._request("gpt-4o")
+
+ if expected_model is not None:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"gpt-4o": targets}]),
+ )
+ assert request_data["model"] == expected_model
+ else:
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"gpt-4o": targets}]),
+ )
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == "gpt-4o"
+
+ @pytest.mark.asyncio
+ async def test_fallback_skips_candidate_denied_to_end_user(self):
+ valid_token: Final = UserAPIKeyAuth(
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={
+ "gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"},
+ "gpt-4o-mini": {"max_budget": 100.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, _ = await _real_model_budget_limiter(member_spend={"gpt-4o": 10.0})
+ request_data: Final = {"model": "gpt-4o"}
+ request: Final = self._request("gpt-4o")
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=self._router([{"gpt-4o": ["gpt-4o-mini"]}]),
+ end_user_object=SimpleNamespace(models=["gpt-4o"]),
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == "gpt-4o"
+
+ @pytest.mark.asyncio
+ async def test_fallback_skips_candidates_without_pricing(self, monkeypatch: pytest.MonkeyPatch):
+ valid_token: Final = UserAPIKeyAuth(
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={"gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"}},
+ )
+ limiter, redis_cache = await _real_model_budget_limiter(member_spend={"gpt-4o": 10.0})
+ request_data: Final = {"model": "gpt-4o"}
+ request: Final = self._request("gpt-4o")
+ router: Final = litellm.Router(
+ model_list=[
+ {"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o"}},
+ {"model_name": "unpriced-model", "litellm_params": {"model": "openai/unpriced-model"}},
+ ],
+ fallbacks=[{"gpt-4o": ["unpriced-model"]}],
+ )
+ monkeypatch.setattr(litellm, "block_requests_for_models_without_pricing", True)
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=router,
+ route="/v1/chat/completions",
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert [
+ call.kwargs["key"] for call in redis_cache.async_get_cache.call_args_list
+ ] == _team_member_model_budget_spend_keys(["gpt-4o"])
+
+ @pytest.mark.asyncio
+ async def test_fallback_checks_candidate_access_group_budget_and_stamps_candidate_groups(self):
+ import litellm.proxy.proxy_server as proxy_server
+ from litellm.proxy.common_utils.user_api_key_cache import model_access_group_cache_key
+ from litellm.types.proxy.model_access_group_budget import ModelAccessGroupBudget
+
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ models=["gpt-4o", "gpt-4o-mini", "fallback-group"],
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={
+ "gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"},
+ "gpt-4o-mini": {"max_budget": 100.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, _ = await _real_model_budget_limiter(member_spend={"gpt-4o": 10.0})
+ request_data: Final = {"model": "gpt-4o"}
+ request: Final = self._request("gpt-4o")
+ await proxy_server.user_api_key_cache.async_set_cache(
+ key=model_access_group_cache_key("fallback-group"),
+ value=ModelAccessGroupBudget(access_group_name="fallback-group", spend=0.0, max_budget=10.0),
+ model_type=ModelAccessGroupBudget,
+ )
+ router: Final = litellm.Router(
+ model_list=[
+ {"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o"}},
+ {
+ "model_name": "gpt-4o-mini",
+ "litellm_params": {"model": "gpt-4o-mini"},
+ "model_info": {"access_groups": ["fallback-group"]},
+ },
+ ],
+ fallbacks=[{"gpt-4o": ["gpt-4o-mini"]}],
+ )
+
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=router,
+ )
+
+ assert request_data["model"] == "gpt-4o-mini"
+ assert request.scope["path_params"]["model"] == "gpt-4o-mini"
+ assert valid_token.matched_model_access_groups == ["fallback-group"]
+
+ @pytest.mark.asyncio
+ async def test_access_group_budget_exhaustion_skips_fallback_candidate(self):
+ import litellm.proxy.proxy_server as proxy_server
+ from litellm.proxy.common_utils.user_api_key_cache import model_access_group_cache_key
+ from litellm.types.proxy.model_access_group_budget import ModelAccessGroupBudget
+
+ valid_token: Final = UserAPIKeyAuth(
+ token="test-key",
+ models=["gpt-4o", "gpt-4o-mini", "fallback-group"],
+ user_id="user-1",
+ team_id="team-1",
+ team_member_model_max_budget={
+ "gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"},
+ "gpt-4o-mini": {"max_budget": 100.0, "budget_duration": "1d"},
+ },
+ )
+ limiter, _ = await _real_model_budget_limiter(member_spend={"gpt-4o": 10.0})
+ request_data: Final = {"model": "gpt-4o"}
+ request: Final = self._request("gpt-4o")
+ await proxy_server.user_api_key_cache.async_set_cache(
+ key=model_access_group_cache_key("fallback-group"),
+ value=ModelAccessGroupBudget(access_group_name="fallback-group", spend=5.0, max_budget=5.0),
+ model_type=ModelAccessGroupBudget,
+ )
+ router: Final = litellm.Router(
+ model_list=[
+ {"model_name": "gpt-4o", "litellm_params": {"model": "gpt-4o"}},
+ {
+ "model_name": "gpt-4o-mini",
+ "litellm_params": {"model": "gpt-4o-mini"},
+ "model_info": {"access_groups": ["fallback-group"]},
+ },
+ ],
+ fallbacks=[{"gpt-4o": ["gpt-4o-mini"]}],
+ )
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_team_member_model_budget_with_fallback(
+ valid_token=valid_token,
+ model_max_budget_limiter=limiter,
+ models=["gpt-4o"],
+ request_data=request_data,
+ request=request,
+ llm_model_list=None,
+ llm_router=router,
+ )
+
+ _assert_budget_exceeded_values(exc_info.value)
+ assert request_data["model"] == "gpt-4o"
+
+
@pytest.mark.asyncio
async def test_global_proxy_spend_reads_resettable_proxy_budget_row():
"""Regression for the global proxy budget ignoring budget_duration
@@ -10185,9 +12040,7 @@ async def test_managed_agent_cannot_bypass_grants_with_server_default(
monkeypatch.setattr(proxy_server, name, value)
data = {"messages": [{"role": "user", "content": "hi"}], **({"model": requested} if requested else {})}
auth = UserAPIKeyAuth(agent_id="managed")
- auth.managed_agent_context = ManagedAgentContext(
- agent_id="managed", binding_revision="revision", mode="autonomous"
- )
+ auth.managed_agent_context = ManagedAgentContext(agent_id="managed", binding_revision="revision", mode="autonomous")
if not grant_default:
with pytest.raises(ProxyException) as denied:
await _authorize_authenticated_request(auth, _alias_request(route, data), data, route, "persisted-key")
@@ -10217,12 +12070,21 @@ async def test_managed_jwt_cannot_be_downgraded_into_virtual_key_mapping(monkeyp
from litellm.types.proxy.agent_identity import AgentIdentityBinding
binding: Final = AgentIdentityBinding(
- agent_id="managed", provider="microsoft_entra", issuer="issuer", tenant_id="tenant",
- client_id="client", service_principal_id="principal", revision="current",
+ agent_id="managed",
+ provider="microsoft_entra",
+ issuer="issuer",
+ tenant_id="tenant",
+ client_id="client",
+ service_principal_id="principal",
+ revision="current",
)
agent: Final = AgentResponse(
- agent_id="managed", agent_name="Managed", agent_card_params={},
- identity_managed=True, identity=binding, execution_mode="autonomous",
+ agent_id="managed",
+ agent_name="Managed",
+ agent_card_params={},
+ identity_managed=True,
+ identity=binding,
+ execution_mode="autonomous",
)
client: Final = MagicMock()
client.writer_db.litellm_agentidentity.find_unique = AsyncMock(return_value=binding)
@@ -10230,22 +12092,35 @@ async def test_managed_jwt_cannot_be_downgraded_into_virtual_key_mapping(monkeyp
handler: Final = MagicMock()
handler.is_jwt.return_value = True
handler.litellm_jwtauth = LiteLLM_JWTAuth(virtual_key_claim_field="sub")
- handler.auth_jwt = AsyncMock(return_value={
- "iss": "issuer", "tid": "tenant", "azp": "client", "oid": "principal", "sub": "mapped-key",
- })
+ handler.auth_jwt = AsyncMock(
+ return_value={
+ "iss": "issuer",
+ "tid": "tenant",
+ "azp": "client",
+ "oid": "principal",
+ "sub": "mapped-key",
+ }
+ )
for name, value in {
**_proxy_attrs_for_centralized_checks(),
- "general_settings": {"enable_jwt_auth": True}, "premium_user": True,
- "prisma_client": client, "jwt_handler": handler, "user_api_key_cache": UserApiKeyCache(),
+ "general_settings": {"enable_jwt_auth": True},
+ "premium_user": True,
+ "prisma_client": client,
+ "jwt_handler": handler,
+ "user_api_key_cache": UserApiKeyCache(),
"proxy_logging_obj": MagicMock(post_call_failure_hook=AsyncMock(return_value=None)),
}.items():
monkeypatch.setattr(proxy_server, name, value)
for _ in range(2):
with pytest.raises(ProxyException) as failure:
await user_api_key_auth_builder(
- request=_alias_request("/v1/chat/completions", {}), api_key="Bearer verified.jwt.token",
- azure_api_key_header="", anthropic_api_key_header=None, google_ai_studio_api_key_header=None,
- azure_apim_header=None, request_data={},
+ request=_alias_request("/v1/chat/completions", {}),
+ api_key="Bearer verified.jwt.token",
+ azure_api_key_header="",
+ anthropic_api_key_header=None,
+ google_ai_studio_api_key_header=None,
+ azure_apim_header=None,
+ request_data={},
)
assert failure.value.code == "403"
assert "without virtual-key mapping" in failure.value.message
@@ -10262,9 +12137,17 @@ async def test_virtual_key_cannot_enter_checks_as_an_identity_managed_actor(monk
from litellm.types.proxy.agent_identity import AgentIdentityBinding
target: Final = AgentResponse(
- agent_id="bound", agent_name="Bound", agent_card_params={}, identity_managed=True,
+ agent_id="bound",
+ agent_name="Bound",
+ agent_card_params={},
+ identity_managed=True,
identity=AgentIdentityBinding(
- agent_id="bound", provider="microsoft_entra", tenant_id="tenant", client_id="client", issuer="issuer", revision="current"
+ agent_id="bound",
+ provider="microsoft_entra",
+ tenant_id="tenant",
+ client_id="client",
+ issuer="issuer",
+ revision="current",
),
)
client: Final = MagicMock()
@@ -10272,7 +12155,9 @@ async def test_virtual_key_cannot_enter_checks_as_an_identity_managed_actor(monk
monkeypatch.setattr(proxy_server, "prisma_client", client)
checks: Final = AsyncMock()
monkeypatch.setattr(auth_module, "run_centralized_common_checks", checks)
- monkeypatch.setattr(proxy_server, "proxy_logging_obj", MagicMock(post_call_failure_hook=AsyncMock(return_value=None)))
+ monkeypatch.setattr(
+ proxy_server, "proxy_logging_obj", MagicMock(post_call_failure_hook=AsyncMock(return_value=None))
+ )
data: Final = {"model": "allowed", "messages": [{"role": "user", "content": "hello"}]}
request: Final = _alias_request("/v1/chat/completions", data)
with pytest.raises(ProxyException):
@@ -10300,16 +12185,24 @@ async def test_custom_auth_grants_reach_managed_targets_without_a_virtual_key_ro
from litellm.types.proxy.agent_identity import AgentIdentityBinding
target: Final = AgentResponse(
- agent_id="target", agent_name="Target", agent_card_params={}, identity_managed=True,
+ agent_id="target",
+ agent_name="Target",
+ agent_card_params={},
+ identity_managed=True,
identity=AgentIdentityBinding(
- agent_id="target", provider="microsoft_entra", tenant_id="tenant", client_id="client",
- issuer="issuer", revision="current",
+ agent_id="target",
+ provider="microsoft_entra",
+ tenant_id="tenant",
+ client_id="client",
+ issuer="issuer",
+ revision="current",
),
)
registry: Final = AgentRegistry()
registry.register_agent(target)
trusted: Final = UserAPIKeyAuth(
- api_key=credential, object_permission={"object_permission_id": "custom", "agents": ["target"] if granted else ["other"]}
+ api_key=credential,
+ object_permission={"object_permission_id": "custom", "agents": ["target"] if granted else ["other"]},
)
custom: Final = AsyncMock(return_value=trusted)
database: Final = MagicMock()
@@ -10325,9 +12218,13 @@ async def test_custom_auth_grants_reach_managed_targets_without_a_virtual_key_ro
monkeypatch.setattr(agent_registry, "global_agent_registry", registry)
monkeypatch.setattr(litellm, "enable_post_custom_auth_checks", False, raising=False)
admitted: Final = await user_api_key_auth_builder(
- request=_alias_request("/a2a/target/message/send", {}), api_key=f"Bearer {credential}",
- azure_api_key_header="", anthropic_api_key_header=None, google_ai_studio_api_key_header=None,
- azure_apim_header=None, request_data={},
+ request=_alias_request("/a2a/target/message/send", {}),
+ api_key=f"Bearer {credential}",
+ azure_api_key_header="",
+ anthropic_api_key_header=None,
+ google_ai_studio_api_key_header=None,
+ azure_apim_header=None,
+ request_data={},
)
assert await AgentRequestHandler.is_agent_allowed("target", admitted) is granted
custom.assert_awaited_once()
@@ -10347,9 +12244,13 @@ async def test_enterprise_custom_auth_key_return_stays_a_proxy_validated_key(mon
module: Final = importlib.import_module("litellm.proxy.auth.user_api_key_auth")
monkeypatch.setattr(module, "enterprise_custom_auth", custom)
admitted: Final = await user_api_key_auth_builder(
- request=_alias_request("/v1/chat/completions", {}), api_key="Bearer external-credential",
- azure_api_key_header="", anthropic_api_key_header=None, google_ai_studio_api_key_header=None,
- azure_apim_header=None, request_data={},
+ request=_alias_request("/v1/chat/completions", {}),
+ api_key="Bearer external-credential",
+ azure_api_key_header="",
+ anthropic_api_key_header=None,
+ google_ai_studio_api_key_header=None,
+ azure_apim_header=None,
+ request_data={},
)
assert admitted.authenticated_by_custom_auth is False
assert admitted.via_virtual_key is True
diff --git a/tests/unit/proxy/common_utils/test_upsert_budget_membership.py b/tests/unit/proxy/common_utils/test_upsert_budget_membership.py
index 74d1748d4de..1f7154f0a74 100644
--- a/tests/unit/proxy/common_utils/test_upsert_budget_membership.py
+++ b/tests/unit/proxy/common_utils/test_upsert_budget_membership.py
@@ -1,6 +1,8 @@
# tests/litellm/proxy/common_utils/test_upsert_budget_membership.py
+import json
import types
from datetime import datetime, timedelta, timezone
+from typing import Final
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -230,7 +232,11 @@ async def test_create_from_temp_budget_pair_only(mock_tx, fake_user):
)
mock_tx.litellm_budgettable.create.assert_awaited_once()
- assert stored_budget_row(mock_tx) == {"temp_budget_increase": 5.0, "temp_budget_expiry": expiry}
+ assert stored_budget_row(mock_tx) == {
+ "model_max_budget": "{}",
+ "temp_budget_increase": 5.0,
+ "temp_budget_expiry": expiry,
+ }
mock_tx.litellm_teammembership.upsert.assert_awaited_once()
mock_tx.litellm_teammembership.update.assert_not_called()
@@ -252,7 +258,11 @@ async def test_create_from_temp_pair_never_snapshots_team_default(mock_tx, fake_
)
mock_tx.litellm_budgettable.find_unique.assert_not_awaited()
- assert stored_budget_row(mock_tx) == {"temp_budget_increase": 1.0, "temp_budget_expiry": expiry}
+ assert stored_budget_row(mock_tx) == {
+ "model_max_budget": "{}",
+ "temp_budget_increase": 1.0,
+ "temp_budget_expiry": expiry,
+ }
mock_tx.litellm_teammembership.upsert.assert_awaited_once()
@@ -274,7 +284,11 @@ async def test_temp_pair_on_shared_default_member_creates_bare_row(mock_tx, fake
mock_tx.litellm_budgettable.find_unique.assert_not_awaited()
mock_tx.litellm_budgettable.update.assert_not_called()
- assert stored_budget_row(mock_tx) == {"temp_budget_increase": 1.0, "temp_budget_expiry": expiry}
+ assert stored_budget_row(mock_tx) == {
+ "model_max_budget": "{}",
+ "temp_budget_increase": 1.0,
+ "temp_budget_expiry": expiry,
+ }
mock_tx.litellm_teammembership.upsert.assert_awaited_once()
@@ -296,6 +310,58 @@ async def test_clearing_temp_pair_on_shared_default_member_is_noop(mock_tx, fake
mock_tx.litellm_teammembership.upsert.assert_not_called()
+@pytest.mark.asyncio
+async def test_clearing_model_budget_to_none_on_shared_default_is_noop(mock_tx, fake_user):
+ await upsert_budget_and_membership(
+ mock_tx,
+ team_id="team-default",
+ user_id="user-on-default",
+ existing_budget_id="team-default-budget-1",
+ user_api_key_dict=fake_user,
+ budget_patch={"model_max_budget": None},
+ team_default_budget_id="team-default-budget-1",
+ )
+
+ mock_tx.litellm_budgettable.find_unique.assert_not_awaited()
+ mock_tx.litellm_budgettable.create.assert_not_called()
+ mock_tx.litellm_budgettable.update.assert_not_called()
+ mock_tx.litellm_teammembership.update.assert_not_called()
+ mock_tx.litellm_teammembership.upsert.assert_not_called()
+
+
+@pytest.mark.asyncio
+async def test_clearing_model_budget_to_none_with_tpm_clones_shared_default(mock_tx, fake_user):
+ shared_default_id: Final = "team-default-budget-1"
+ mock_tx.litellm_budgettable.find_unique = AsyncMock(
+ return_value=budget_row(
+ budget_id=shared_default_id,
+ max_budget=100.0,
+ model_max_budget={"claude-sonnet-4-6": {"max_budget": 5.0}},
+ )
+ )
+
+ await upsert_budget_and_membership(
+ mock_tx,
+ team_id="team-default",
+ user_id="user-on-default",
+ existing_budget_id=shared_default_id,
+ user_api_key_dict=fake_user,
+ budget_patch={"model_max_budget": None, "tpm_limit": 5},
+ team_default_budget_id=shared_default_id,
+ )
+
+ create_data: Final = mock_tx.litellm_budgettable.create.await_args.kwargs["data"]
+ assert create_data == {
+ "created_by": fake_user.user_id,
+ "updated_by": fake_user.user_id,
+ "model_max_budget": "{}",
+ "max_budget": 100.0,
+ "tpm_limit": 5,
+ }
+ mock_tx.litellm_budgettable.update.assert_not_called()
+ mock_tx.litellm_teammembership.upsert.assert_awaited_once()
+
+
@pytest.mark.asyncio
async def test_temp_pair_with_permanent_field_still_clones_shared_default(mock_tx, fake_user):
expiry = datetime(2100, 1, 1, tzinfo=timezone.utc)
@@ -337,7 +403,7 @@ async def test_create_from_plain_patch_does_not_snapshot_team_default(mock_tx, f
)
mock_tx.litellm_budgettable.find_unique.assert_not_awaited()
- assert stored_budget_row(mock_tx) == {"tpm_limit": 500}
+ assert stored_budget_row(mock_tx) == {"model_max_budget": "{}", "tpm_limit": 500}
mock_tx.litellm_teammembership.upsert.assert_awaited_once()
@@ -380,6 +446,7 @@ async def test_clone_on_write_from_shared_default(mock_tx, fake_user):
assert create_data == {
"created_by": fake_user.user_id,
"updated_by": fake_user.user_id,
+ "model_max_budget": "{}",
"max_budget": 50.0, # caller wins
"tpm_limit": 500, # cloned from default
"budget_duration": "1d", # cloned from default
@@ -401,6 +468,69 @@ async def test_clone_on_write_from_shared_default(mock_tx, fake_user):
)
+@pytest.mark.asyncio
+async def test_clone_on_write_preserves_model_caps_from_shared_nondefault_row(mock_tx, fake_user):
+ shared_budget_id: Final = "shared-member-budget"
+ model_caps: Final = {"gpt-4o": {"max_budget": 4.0, "budget_duration": "1d"}}
+ mock_tx.litellm_budgettable.find_unique = AsyncMock(
+ return_value=budget_row(
+ budget_id=shared_budget_id,
+ max_budget=100.0,
+ model_max_budget=model_caps,
+ )
+ )
+
+ await upsert_budget_and_membership(
+ mock_tx,
+ team_id="team-shared",
+ user_id="user-shared",
+ existing_budget_id=shared_budget_id,
+ user_api_key_dict=fake_user,
+ budget_patch={"tpm_limit": 1000},
+ team_default_budget_id="team-default-budget",
+ shared_budget_ids=frozenset({shared_budget_id}),
+ )
+
+ create_data: Final = mock_tx.litellm_budgettable.create.await_args.kwargs["data"]
+ persisted_model_caps: Final = create_data["model_max_budget"]
+ assert (
+ json.loads(persisted_model_caps) if isinstance(persisted_model_caps, str) else persisted_model_caps
+ ) == model_caps
+
+
+@pytest.mark.asyncio
+async def test_clearing_model_budget_to_none_clones_shared_nondefault_row(mock_tx, fake_user):
+ shared_budget_id: Final = "shared-member-budget"
+ mock_tx.litellm_budgettable.find_unique = AsyncMock(
+ return_value=budget_row(
+ budget_id=shared_budget_id,
+ max_budget=100.0,
+ model_max_budget={"gpt-4o": {"max_budget": 4.0}},
+ )
+ )
+
+ await upsert_budget_and_membership(
+ mock_tx,
+ team_id="team-shared",
+ user_id="user-shared",
+ existing_budget_id=shared_budget_id,
+ user_api_key_dict=fake_user,
+ budget_patch={"model_max_budget": None},
+ team_default_budget_id="team-default-budget",
+ shared_budget_ids=frozenset({shared_budget_id}),
+ )
+
+ create_data: Final = mock_tx.litellm_budgettable.create.await_args.kwargs["data"]
+ assert create_data == {
+ "created_by": fake_user.user_id,
+ "updated_by": fake_user.user_id,
+ "model_max_budget": "{}",
+ "max_budget": 100.0,
+ }
+ mock_tx.litellm_budgettable.update.assert_not_called()
+ mock_tx.litellm_teammembership.upsert.assert_awaited_once()
+
+
# TEST: forking the shared default while clearing its duration must drop the
# duration (and not carry a reset time) on the new private budget.
@pytest.mark.asyncio
@@ -431,6 +561,7 @@ async def test_clone_on_write_clears_duration(mock_tx, fake_user):
assert create_data == {
"created_by": fake_user.user_id,
"updated_by": fake_user.user_id,
+ "model_max_budget": "{}",
"max_budget": 200.0,
"tpm_limit": 500,
"budget_duration": None,
@@ -460,3 +591,31 @@ async def test_private_budget_updates_in_place(mock_tx, fake_user):
)
mock_tx.litellm_budgettable.create.assert_not_called()
mock_tx.litellm_teammembership.upsert.assert_not_called()
+
+
+@pytest.mark.asyncio
+async def test_clearing_model_budget_to_none_updates_private_row(mock_tx, fake_user):
+ mock_tx.litellm_budgettable.find_unique = AsyncMock(
+ return_value=budget_row(
+ max_budget=10.0,
+ model_max_budget={"gpt-4o": {"max_budget": 4.0}},
+ )
+ )
+
+ await upsert_budget_and_membership(
+ mock_tx,
+ team_id="team-mixed",
+ user_id="user-private",
+ existing_budget_id="private-budget-xyz",
+ user_api_key_dict=fake_user,
+ budget_patch={"model_max_budget": None},
+ team_default_budget_id="team-default-budget-1",
+ )
+
+ mock_tx.litellm_budgettable.update.assert_awaited_once_with(
+ where={"budget_id": "private-budget-xyz"},
+ data={"updated_by": fake_user.user_id, "model_max_budget": "{}"},
+ )
+ mock_tx.litellm_budgettable.create.assert_not_called()
+ mock_tx.litellm_teammembership.update.assert_not_called()
+ mock_tx.litellm_teammembership.upsert.assert_not_called()
diff --git a/tests/unit/proxy/hooks/test_model_max_budget_limiter.py b/tests/unit/proxy/hooks/test_model_max_budget_limiter.py
index 8de34e6391e..2678f4205d5 100644
--- a/tests/unit/proxy/hooks/test_model_max_budget_limiter.py
+++ b/tests/unit/proxy/hooks/test_model_max_budget_limiter.py
@@ -6,15 +6,20 @@ from typing import Final
import pytest
+import litellm
from litellm.caching.caching import DualCache
+from litellm.proxy._types import Litellm_EntityType
from litellm.proxy.hooks.model_max_budget_limiter import (
PROXY_VirtualKeyModelMaxBudgetLimiter,
+ model_budget_spend_cache_key,
+ team_member_budget_entity_id,
)
from litellm.types.caching import RedisPipelineIncrementOperation
from litellm.types.utils import LiteLLMBatch, Usage
KEY_HASH: Final = "key-hash-batch"
USER_ID: Final = "user-batch"
+TEAM_ID: Final = "team-batch"
MODEL_GROUP: Final = "batch-qa-primary"
BATCH_COST: Final = 2.925e-05
CHAT_COST: Final = 0.001
@@ -35,7 +40,13 @@ def _batch(batch_id: str, status: str) -> LiteLLMBatch:
)
-def _event(call_type: str, response_cost: float) -> dict[str, object]:
+def _event(
+ call_type: str,
+ response_cost: float,
+ team_member_model_max_budget: Mapping[str, object] | None = None,
+ user_id: str = USER_ID,
+ team_id: str = TEAM_ID,
+) -> dict[str, object]:
return {
"call_type": call_type,
"standard_logging_object": {
@@ -43,12 +54,21 @@ def _event(call_type: str, response_cost: float) -> dict[str, object]:
"response_cost": response_cost,
"model": "openai/gpt-5.4-mini",
"model_group": MODEL_GROUP,
- "metadata": {"user_api_key_hash": KEY_HASH, "user_api_key_user_id": USER_ID},
+ "metadata": {
+ "user_api_key_hash": KEY_HASH,
+ "user_api_key_user_id": user_id,
+ "user_api_key_team_id": team_id,
+ },
},
"litellm_params": {
"metadata": {
"user_api_key_model_max_budget": {MODEL_GROUP: {"budget_limit": 0.0001, "time_period": "1d"}},
"user_api_key_user_model_max_budget": {MODEL_GROUP: {"budget_limit": 0.0001, "time_period": "1d"}},
+ **(
+ {"user_api_key_team_member_model_max_budget": team_member_model_max_budget}
+ if team_member_model_max_budget is not None
+ else {}
+ ),
}
},
}
@@ -60,9 +80,23 @@ async def _poll(limiter: PROXY_VirtualKeyModelMaxBudgetLimiter, batch: LiteLLMBa
)
-async def _chat(limiter: PROXY_VirtualKeyModelMaxBudgetLimiter) -> None:
+async def _chat(
+ limiter: PROXY_VirtualKeyModelMaxBudgetLimiter,
+ team_member_model_max_budget: Mapping[str, object] | None = None,
+ user_id: str = USER_ID,
+ team_id: str = TEAM_ID,
+) -> None:
await limiter.async_log_success_event(
- _event("acompletion", CHAT_COST), response_obj=None, start_time=None, end_time=None
+ _event(
+ "acompletion",
+ CHAT_COST,
+ team_member_model_max_budget=team_member_model_max_budget,
+ user_id=user_id,
+ team_id=team_id,
+ ),
+ response_obj=None,
+ start_time=None,
+ end_time=None,
)
@@ -74,6 +108,87 @@ def _local_spend(limiter: PROXY_VirtualKeyModelMaxBudgetLimiter, spend_key: str)
return limiter.dual_cache.in_memory_cache.get_cache(key=spend_key) or 0.0
+@pytest.mark.asyncio
+async def test_team_member_budget_is_charged_and_enforced_after_success():
+ budget: Final = {MODEL_GROUP: {"max_budget": 0.0005, "budget_duration": "1d"}}
+ limiter: Final = PROXY_VirtualKeyModelMaxBudgetLimiter(dual_cache=DualCache())
+
+ await _chat(limiter, team_member_model_max_budget=budget)
+
+ entity_id: Final = team_member_budget_entity_id(user_id=USER_ID, team_id=TEAM_ID)
+ spend_key: Final = model_budget_spend_cache_key(
+ entity_type=Litellm_EntityType.TEAM_MEMBER,
+ entity_id=entity_id,
+ budget_model=MODEL_GROUP,
+ budget_duration="1d",
+ )
+ assert await _spend(limiter, spend_key) == CHAT_COST
+
+ with pytest.raises(litellm.BudgetExceededError, match="LiteLLM Team Member"):
+ await limiter.is_team_member_within_model_budget(
+ user_id=USER_ID,
+ team_id=TEAM_ID,
+ team_member_model_max_budget=budget,
+ model=MODEL_GROUP,
+ )
+
+
+def test_team_member_budget_entity_id_is_unambiguous():
+ first_entity_id: Final = team_member_budget_entity_id(user_id="a:b", team_id="c")
+ second_entity_id: Final = team_member_budget_entity_id(user_id="a", team_id="b:c")
+
+ assert first_entity_id == "3:a:b:c"
+ assert second_entity_id == "1:a:b:c"
+
+ first_spend_key: Final = model_budget_spend_cache_key(
+ entity_type=Litellm_EntityType.TEAM_MEMBER,
+ entity_id=first_entity_id,
+ budget_model=MODEL_GROUP,
+ budget_duration="1d",
+ )
+ second_spend_key: Final = model_budget_spend_cache_key(
+ entity_type=Litellm_EntityType.TEAM_MEMBER,
+ entity_id=second_entity_id,
+ budget_model=MODEL_GROUP,
+ budget_duration="1d",
+ )
+ assert first_spend_key != second_spend_key
+
+
+@pytest.mark.asyncio
+async def test_team_member_budget_spend_isolated_by_user_and_team():
+ budget: Final = {MODEL_GROUP: {"max_budget": CHAT_COST * 2, "budget_duration": "1d"}}
+ limiter: Final = PROXY_VirtualKeyModelMaxBudgetLimiter(dual_cache=DualCache())
+
+ await _chat(limiter, team_member_model_max_budget=budget)
+
+ assert await limiter.is_team_member_within_model_budget(
+ user_id="different-user",
+ team_id=TEAM_ID,
+ team_member_model_max_budget=budget,
+ model=MODEL_GROUP,
+ )
+ assert await limiter.is_team_member_within_model_budget(
+ user_id=USER_ID,
+ team_id="different-team",
+ team_member_model_max_budget=budget,
+ model=MODEL_GROUP,
+ )
+
+
+@pytest.mark.asyncio
+async def test_zero_team_member_model_budget_rejects_first_request():
+ limiter: Final = PROXY_VirtualKeyModelMaxBudgetLimiter(dual_cache=DualCache())
+
+ with pytest.raises(litellm.BudgetExceededError, match="LiteLLM Team Member"):
+ await limiter.is_team_member_within_model_budget(
+ user_id=USER_ID,
+ team_id=TEAM_ID,
+ team_member_model_max_budget={MODEL_GROUP: {"max_budget": 0, "budget_duration": "1d"}},
+ model=MODEL_GROUP,
+ )
+
+
class _Clock:
def __init__(self) -> None:
self.seconds = 0.0
diff --git a/tests/unit/proxy/management_endpoints/management_v1/test_teams.py b/tests/unit/proxy/management_endpoints/management_v1/test_teams.py
index 3f60384cfa7..5d1c658b143 100644
--- a/tests/unit/proxy/management_endpoints/management_v1/test_teams.py
+++ b/tests/unit/proxy/management_endpoints/management_v1/test_teams.py
@@ -85,6 +85,10 @@ def _matches(row: Mapping[str, object], where: Mapping[str, object]) -> bool:
return all((wanted := _wanted(where, field)) is not None and row.get(field) in wanted for field in where)
+def _as_stored(data: Mapping[str, object]) -> dict[str, object]:
+ return {k: json.loads(v) if k == "model_max_budget" and isinstance(v, str) else v for k, v in data.items()}
+
+
class _BudgetTable:
def __init__(self, budgets: Sequence[_BudgetRow]) -> None:
self.rows: dict[str, _BudgetRow] = {b.budget_id: b for b in budgets}
@@ -94,13 +98,13 @@ class _BudgetTable:
async def update(self, where: Mapping[str, str], data: Mapping[str, object]) -> _BudgetRow:
row: Final = self.rows[where["budget_id"]]
- updated: Final = row.model_copy(update=dict(data))
+ updated: Final = row.model_copy(update=_as_stored(data))
self.rows[row.budget_id] = updated
return updated
async def create(self, data: Mapping[str, object], include: Mapping[str, bool] | None = None) -> _BudgetRow:
budget_id: Final = f"new-budget-{len(self.rows) + 1}"
- row: Final = _BudgetRow.model_validate({**data, "budget_id": budget_id})
+ row: Final = _BudgetRow.model_validate({**_as_stored(data), "budget_id": budget_id})
self.rows[budget_id] = row
return row
diff --git a/tests/unit/proxy/management_endpoints/test_budget_endpoints.py b/tests/unit/proxy/management_endpoints/test_budget_endpoints.py
index 2f3be61d00f..24129488f21 100644
--- a/tests/unit/proxy/management_endpoints/test_budget_endpoints.py
+++ b/tests/unit/proxy/management_endpoints/test_budget_endpoints.py
@@ -11,6 +11,8 @@ from fastapi.testclient import TestClient
import litellm.proxy.proxy_server as ps
from litellm.proxy.proxy_server import app
from litellm.proxy._types import UserAPIKeyAuth, LitellmUserRoles, CommonProxyErrors
+from litellm.caching.in_memory_cache import InMemoryCache
+from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache
@@ -102,6 +104,25 @@ async def test_update_budget_rejects_a_duration_that_never_advances(client_and_m
mock_table.update.assert_not_awaited()
+@pytest.mark.asyncio
+async def test_update_budget_evicts_local_cache_when_redis_delete_fails(
+ client_and_mocks, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ client, _, _ = client_and_mocks
+ cache_key = "team_member_default_budget:budget_456"
+ cache = UserApiKeyCache(in_memory_cache=InMemoryCache())
+ cache.set_cache(cache_key, {"budget_id": "budget_456"}, local_only=True)
+ redis_cache = MagicMock()
+ redis_cache.async_delete_cache = AsyncMock(side_effect=RuntimeError("redis unavailable"))
+ cache.redis_cache = redis_cache
+ monkeypatch.setattr(ps, "user_api_key_cache", cache)
+
+ response = client.post("/budget/update", json={"budget_id": "budget_456", "max_budget": 10.0})
+
+ assert response.status_code == 200, response.text
+ assert cache.get_cache(cache_key, local_only=True) is None
+
+
@pytest.mark.asyncio
async def test_new_budget_db_not_connected(client_and_mocks, monkeypatch):
client, mock_prisma, mock_table = client_and_mocks
@@ -136,6 +157,26 @@ async def test_update_budget_success(client_and_mocks, monkeypatch):
assert body["updated_by"] == "test_user"
+@pytest.mark.asyncio
+async def test_update_budget_evicts_team_member_default_budget_cache(client_and_mocks, monkeypatch):
+ client, _, _ = client_and_mocks
+ cache: Final = UserApiKeyCache(in_memory_cache=InMemoryCache())
+ monkeypatch.setattr(ps, "user_api_key_cache", cache)
+ cache_key: Final = "team_member_default_budget:budget_456"
+ await cache.async_set_cache(key=cache_key, value={"budget_id": "budget_456"})
+ assert await cache.async_get_cache(key=cache_key) == {"budget_id": "budget_456"}
+
+ try:
+ response: Final = client.post(
+ "/budget/update",
+ json={"budget_id": "budget_456", "max_budget": 10.0},
+ )
+ assert response.status_code == 200, response.text
+ assert await cache.async_get_cache(key=cache_key) is None
+ finally:
+ await cache.async_delete_cache(key=cache_key)
+
+
@pytest.mark.asyncio
async def test_new_and_update_budget_persist_tpd_limit(client_and_mocks):
client, _, mock_table = client_and_mocks
diff --git a/tests/unit/proxy/management_endpoints/test_common_utils.py b/tests/unit/proxy/management_endpoints/test_common_utils.py
index d783f4c64f6..21d017addca 100644
--- a/tests/unit/proxy/management_endpoints/test_common_utils.py
+++ b/tests/unit/proxy/management_endpoints/test_common_utils.py
@@ -18,6 +18,7 @@ from pydantic import BaseModel
from litellm import Router
from litellm.proxy._types import (
+ LiteLLM_BudgetTable,
LiteLLM_OrganizationMembershipTable,
LiteLLM_TeamTable,
LiteLLM_UserTable,
@@ -35,25 +36,132 @@ from litellm.proxy.management_endpoints.common_utils import (
update_metadata_fields,
user_api_key_has_admin_view,
user_has_admin_privileges,
+ upsert_budget_and_membership,
)
from litellm.types.utils import BudgetConfig
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ "budget_patch",
+ [
+ {"tpm_limit": 200},
+ {"model_max_budget": {}, "tpm_limit": 5},
+ ],
+)
+async def test_shared_default_clone_keeps_inheriting_updated_team_model_caps(
+ budget_patch: dict[str, object],
+) -> None:
+ from litellm.proxy.auth.user_api_key_auth import _load_team_member_default_model_budget
+ from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache, team_membership_reservation_cache_key
+ from litellm.proxy._types import LiteLLM_TeamMembership
+
+ source_caps = {"claude-sonnet-4-6": {"max_budget": 3.0, "budget_duration": "1d"}}
+ default_caps = {"claude-sonnet-4-6": {"max_budget": 1.0, "budget_duration": "1d"}}
+ budget_table = SimpleNamespace(
+ find_unique=AsyncMock(
+ return_value=SimpleNamespace(
+ model_dump=MagicMock(
+ return_value={
+ "budget_id": "default-budget",
+ "model_max_budget": source_caps,
+ "tpm_limit": 100,
+ }
+ )
+ )
+ ),
+ create=AsyncMock(return_value=SimpleNamespace(budget_id="private-budget")),
+ )
+ membership_table = SimpleNamespace(upsert=AsyncMock())
+ tx = SimpleNamespace(litellm_budgettable=budget_table, litellm_teammembership=membership_table)
+ token = UserAPIKeyAuth(user_id="member-1", team_id="team-1")
+
+ await upsert_budget_and_membership(
+ tx,
+ team_id="team-1",
+ user_id="member-1",
+ existing_budget_id="default-budget",
+ user_api_key_dict=token,
+ budget_patch=budget_patch,
+ team_default_budget_id="default-budget",
+ )
+
+ budget_table.create.assert_awaited_once()
+ membership_table.upsert.assert_awaited_once()
+ assert budget_table.create.await_args.kwargs["data"]["tpm_limit"] == budget_patch["tpm_limit"]
+ model_max_budget: Final = budget_table.create.await_args.kwargs["data"]["model_max_budget"]
+ assert isinstance(model_max_budget, str)
+ assert model_max_budget == "{}"
+ membership = LiteLLM_TeamMembership(
+ user_id="member-1",
+ team_id="team-1",
+ budget_id="private-budget",
+ litellm_budget_table=LiteLLM_BudgetTable(budget_id="private-budget", model_max_budget={}),
+ )
+ user_api_key_cache: Final = UserApiKeyCache()
+ await user_api_key_cache.async_set_cache(
+ key=team_membership_reservation_cache_key(user_id="member-1", team_id="team-1"),
+ value=membership,
+ model_type=LiteLLM_TeamMembership,
+ )
+ await user_api_key_cache.async_set_cache(
+ key="team_member_default_budget:default-budget",
+ value=LiteLLM_BudgetTable(budget_id="default-budget", model_max_budget=default_caps),
+ model_type=LiteLLM_BudgetTable,
+ )
+ team_object = SimpleNamespace(
+ team_id="team-1",
+ metadata={"team_member_budget_id": "default-budget"},
+ )
+
+ await _load_team_member_default_model_budget(
+ user_api_key_auth_obj=token,
+ team_object=team_object,
+ prisma_client=MagicMock(),
+ user_api_key_cache=user_api_key_cache,
+ skip_budget_checks=False,
+ proxy_logging_obj=None,
+ )
+
+ assert token.team_member_model_max_budget == default_caps
+
+
+@pytest.mark.asyncio
+async def test_empty_model_budget_patch_on_team_default_keeps_membership_attached() -> None:
+ tx: Final = MagicMock()
+ tx.litellm_budgettable.find_unique = AsyncMock(
+ return_value=SimpleNamespace(
+ model_dump=MagicMock(
+ return_value={
+ "budget_id": "default-budget",
+ "max_budget": 10.0,
+ "model_max_budget": {"claude-sonnet-4-6": {"max_budget": 1.0}},
+ }
+ )
+ )
+ )
+ tx.litellm_budgettable.create = AsyncMock()
+ tx.litellm_budgettable.update = AsyncMock()
+ tx.litellm_teammembership.upsert = AsyncMock()
+ tx.litellm_teammembership.update = AsyncMock()
+
+ await upsert_budget_and_membership(
+ tx,
+ team_id="team-1",
+ user_id="member-1",
+ existing_budget_id="default-budget",
+ user_api_key_dict=UserAPIKeyAuth(user_id="admin"),
+ budget_patch={"model_max_budget": {}},
+ team_default_budget_id="default-budget",
+ )
+
+ tx.litellm_budgettable.create.assert_not_awaited()
+ tx.litellm_budgettable.update.assert_not_awaited()
+ tx.litellm_teammembership.upsert.assert_not_awaited()
+ tx.litellm_teammembership.update.assert_not_awaited()
+
+
class TestUpdateMetadataFieldsEmptyCollections:
- """
- Regression tests for issue #20304.
-
- The UI sends empty arrays (`[]`) for enterprise-only fields like
- guardrails, policies, and logging even when the user hasn't configured
- these features. The backend must not treat empty collections as an
- intent to use the feature, and therefore must not trigger the premium
- license check.
-
- However, empty collections must still be written into metadata so that
- users can intentionally clear a previously-set field (e.g. removing all
- guardrails by sending `guardrails: []`).
- """
-
@patch("litellm.proxy.management_endpoints.common_utils.premium_user_check")
def test_empty_list_does_not_trigger_premium_check(self, mock_premium_check):
"""Empty lists for premium fields must not trigger the premium check."""
diff --git a/tests/unit/proxy/management_endpoints/test_team_endpoints.py b/tests/unit/proxy/management_endpoints/test_team_endpoints.py
index b81c1c9f3d5..e921e4df5c1 100644
--- a/tests/unit/proxy/management_endpoints/test_team_endpoints.py
+++ b/tests/unit/proxy/management_endpoints/test_team_endpoints.py
@@ -2591,6 +2591,8 @@ async def test_update_team_team_member_budget_not_passed_to_db(
team_member_rpm_limit=None,
team_member_tpm_limit=None,
team_member_budget_duration=None,
+ team_member_model_max_budget=None,
+ user_api_key_cache=None,
explicitly_set_fields=frozenset(),
):
# Remove team_member_budget from updated_kv as the real function does
@@ -3159,6 +3161,8 @@ async def test_update_team_with_team_member_budget_duration(
team_member_rpm_limit=None,
team_member_tpm_limit=None,
team_member_budget_duration=None,
+ team_member_model_max_budget=None,
+ user_api_key_cache=None,
explicitly_set_fields=frozenset(),
):
result_kv = updated_kv.copy()
@@ -10891,6 +10895,7 @@ async def test_create_team_member_budget_table_with_duration():
team_alias="test-team",
team_member_budget=20.0,
team_member_budget_duration="30d",
+ team_member_model_max_budget={"gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"}},
)
with patch(
@@ -10904,15 +10909,181 @@ async def test_create_team_member_budget_table_with_duration():
user_api_key_dict=mock_admin,
team_member_budget=20.0,
team_member_budget_duration="30d",
+ team_member_model_max_budget=data.team_member_model_max_budget,
)
mock_new_budget.assert_awaited_once()
budget_request = mock_new_budget.call_args.kwargs["budget_obj"]
assert budget_request.budget_duration == "30d"
assert budget_request.max_budget == 20.0
+ assert budget_request.model_max_budget == data.team_member_model_max_budget
assert result["metadata"]["team_member_budget_id"] == "budget-abc"
+@pytest.mark.asyncio
+async def test_upsert_team_member_model_max_budget_updates_default_budget_and_evicts_cache():
+ from litellm.proxy.management_endpoints.team_endpoints import TeamMemberBudgetHandler
+
+ model_budget: Final = {"gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"}}
+ team_table: Final = LiteLLM_TeamTable(
+ team_id="test-team",
+ metadata={"team_member_budget_id": "member-budget-1"},
+ members_with_roles=[],
+ )
+ cache: Final = MagicMock()
+ cache.async_delete_cache = AsyncMock()
+ budget_cache: Final = MagicMock()
+ budget_cache.async_delete_cache = AsyncMock()
+ prisma: Final = MagicMock()
+ prisma.db.litellm_budgettable.update = AsyncMock(return_value=MagicMock(budget_id="member-budget-1"))
+
+ with (
+ patch("litellm.proxy.proxy_server.prisma_client", prisma),
+ patch("litellm.proxy.proxy_server.user_api_key_cache", budget_cache),
+ patch("litellm.proxy.proxy_server.premium_user", True),
+ ):
+ result: Final = await TeamMemberBudgetHandler.upsert_team_member_budget_table(
+ team_table=team_table,
+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin"),
+ updated_kv={"team_id": "test-team", "team_member_model_max_budget": model_budget},
+ team_member_model_max_budget=model_budget,
+ user_api_key_cache=cache,
+ explicitly_set_fields={"team_member_model_max_budget"},
+ )
+
+ budget_update: Final = prisma.db.litellm_budgettable.update.call_args.kwargs
+ assert budget_update["where"]["budget_id"] == "member-budget-1"
+ assert budget_update["data"]["budget_id"] == "member-budget-1"
+ assert json.loads(budget_update["data"]["model_max_budget"]) == model_budget
+ assert result["metadata"]["team_member_budget_id"] == "member-budget-1"
+ assert "team_member_model_max_budget" not in result
+ cache.async_delete_cache.assert_awaited_once_with(key="team_member_default_budget:member-budget-1")
+ budget_cache.async_delete_cache.assert_awaited_once_with(key="team_member_default_budget:member-budget-1")
+
+
+@pytest.mark.asyncio
+async def test_update_team_clears_explicitly_null_member_model_budget_and_evicts_cache(
+ disable_audit_logging_for_mocked_team,
+):
+ from fastapi import Request
+
+ from litellm.proxy._types import UpdateTeamRequest
+ from litellm.proxy.management_endpoints.team_endpoints import update_team
+
+ existing: Final = _existing_team_with_model_caps({})
+ existing.metadata = {"team_member_budget_id": "member-budget-1"}
+ existing.members_with_roles = []
+ existing.model_dump.return_value["metadata"] = existing.metadata
+ existing.model_dump.return_value["members_with_roles"] = []
+ cache: Final = MagicMock()
+ cache.async_get_cache = AsyncMock(return_value=None)
+ cache.async_set_cache = AsyncMock()
+ cache.async_delete_cache = AsyncMock()
+ updated: Final = _existing_team_with_model_caps({})
+ updated.metadata = {"team_member_budget_id": "member-budget-1"}
+ updated.model_dump.return_value.update({"metadata": updated.metadata, "members_with_roles": []})
+ updated.litellm_model_table = None
+ update_budget_response: Final = MagicMock(budget_id="member-budget-1")
+ prisma: Final = MagicMock()
+
+ with (
+ patch("litellm.proxy.proxy_server.prisma_client", prisma),
+ patch("litellm.proxy.proxy_server.user_api_key_cache", cache),
+ patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin"),
+ patch("litellm.proxy.proxy_server.premium_user", True),
+ ):
+ prisma.db.litellm_teamtable.find_unique = AsyncMock(return_value=existing)
+ prisma.jsonify_team_object = lambda db_data: db_data
+ prisma.db.litellm_teamtable.update = AsyncMock(return_value=updated)
+ prisma.db.litellm_budgettable.update = AsyncMock(return_value=update_budget_response)
+
+ request_data: Final = UpdateTeamRequest(team_id="standalone-team-123", team_member_model_max_budget=None)
+ await update_team(
+ data=request_data,
+ http_request=MagicMock(spec=Request),
+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin"),
+ )
+
+ budget_update: Final = prisma.db.litellm_budgettable.update.call_args.kwargs
+ assert budget_update["where"]["budget_id"] == "member-budget-1"
+ assert budget_update["data"]["budget_id"] == "member-budget-1"
+ assert budget_update["data"]["model_max_budget"] == "{}"
+ assert "team_member_model_max_budget" in request_data.model_fields_set
+ assert "model_max_budget" in budget_update["data"]
+ assert cache.async_delete_cache.await_args_list == [
+ call(key="team_member_default_budget:member-budget-1"),
+ call(key="team_member_default_budget:member-budget-1"),
+ ]
+
+
+@pytest.mark.asyncio
+async def test_update_team_persists_member_model_budget_to_default_budget_row(
+ disable_audit_logging_for_mocked_team,
+):
+ from fastapi import Request
+
+ from litellm.proxy._types import UpdateTeamRequest
+ from litellm.proxy.management_endpoints.team_endpoints import update_team
+
+ member_caps: Final = {"gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"}}
+ existing: Final = _existing_team_with_model_caps({})
+ existing.metadata = {"team_member_budget_id": "member-budget-1"}
+ existing.members_with_roles = []
+ existing.model_dump.return_value["metadata"] = existing.metadata
+ existing.model_dump.return_value["members_with_roles"] = []
+ cache: Final = MagicMock()
+ cache.async_get_cache = AsyncMock(return_value=None)
+ cache.async_set_cache = AsyncMock()
+ cache.async_delete_cache = AsyncMock()
+ updated: Final = _existing_team_with_model_caps({})
+ updated.metadata = {"team_member_budget_id": "member-budget-1"}
+ updated.model_dump.return_value.update({"metadata": updated.metadata, "members_with_roles": []})
+ updated.litellm_model_table = None
+ update_budget_response: Final = MagicMock(budget_id="member-budget-1")
+ prisma: Final = MagicMock()
+
+ with (
+ patch("litellm.proxy.proxy_server.prisma_client", prisma),
+ patch("litellm.proxy.proxy_server.user_api_key_cache", cache),
+ patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin"),
+ patch("litellm.proxy.proxy_server.premium_user", True),
+ ):
+ prisma.db.litellm_teamtable.find_unique = AsyncMock(return_value=existing)
+ prisma.jsonify_team_object = lambda db_data: db_data
+ prisma.db.litellm_teamtable.update = AsyncMock(return_value=updated)
+ prisma.db.litellm_budgettable.update = AsyncMock(return_value=update_budget_response)
+
+ await update_team(
+ data=UpdateTeamRequest(team_id="standalone-team-123", team_member_model_max_budget=member_caps),
+ http_request=MagicMock(spec=Request),
+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin"),
+ )
+
+ budget_update: Final = prisma.db.litellm_budgettable.update.call_args.kwargs
+ assert budget_update["where"]["budget_id"] == "member-budget-1"
+ assert budget_update["data"]["budget_id"] == "member-budget-1"
+ stored_member_model_caps: Final = json.loads(budget_update["data"]["model_max_budget"])
+ assert {
+ model: {
+ **budget,
+ "tpm_limit": budget.get("tpm_limit"),
+ "rpm_limit": budget.get("rpm_limit"),
+ }
+ for model, budget in stored_member_model_caps.items()
+ } == {
+ "gpt-4o": {
+ "max_budget": 5.0,
+ "budget_duration": "1d",
+ "tpm_limit": None,
+ "rpm_limit": None,
+ }
+ }
+ assert cache.async_delete_cache.await_args_list == [
+ call(key="team_member_default_budget:member-budget-1"),
+ call(key="team_member_default_budget:member-budget-1"),
+ ]
+
+
# ---------------------------------------------------------------------------
# Tests for _batch_resolve_access_group_resources
# ---------------------------------------------------------------------------
@@ -12519,11 +12690,13 @@ async def _drive_team_write(
**(existing_kwargs or {}),
)
auth = user or UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="u")
+ user_api_key_cache: Final = MagicMock()
+ user_api_key_cache.async_delete_cache = AsyncMock()
with (
_patch("litellm.proxy.proxy_server.prisma_client") as pc,
_patch("litellm.proxy.proxy_server.llm_router", None),
- _patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()),
+ _patch("litellm.proxy.proxy_server.user_api_key_cache", user_api_key_cache),
_patch("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock()),
_patch("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin"),
_patch(
@@ -16245,13 +16418,24 @@ def test_team_model_cap_authority_skips_omitted_field_malformed_rows_and_proxy_a
@pytest.mark.asyncio
-async def test_new_team_persists_model_max_budget(mock_db_client, mock_admin_auth):
+@pytest.mark.parametrize(
+ ("member_caps", "member_budget_duration"),
+ [
+ ({"gpt-4o": {"max_budget": 5.0, "budget_duration": "1d"}}, "30d"),
+ ({}, None),
+ ],
+)
+async def test_new_team_persists_model_max_budget(mock_db_client, mock_admin_auth, member_caps, member_budget_duration):
mock_db_client.jsonify_team_object = lambda db_data: db_data
mock_db_client.get_data = AsyncMock(return_value=None)
mock_db_client.update_data = AsyncMock(return_value=MagicMock())
mock_db_client.db = MagicMock()
mock_db_client.db.litellm_modeltable = MagicMock()
mock_db_client.db.litellm_modeltable.create = AsyncMock(return_value=MagicMock(id="model123"))
+ mock_db_client.db.litellm_budgettable = MagicMock()
+ mock_db_client.db.litellm_budgettable.create = AsyncMock(
+ side_effect=lambda *, data: MagicMock(budget_id=data["budget_id"])
+ )
team_create_result = MagicMock(team_id="team-model-caps")
team_create_result.model_dump.return_value = {"team_id": "team-model-caps"}
@@ -16269,11 +16453,18 @@ async def test_new_team_persists_model_max_budget(mock_db_client, mock_admin_aut
from litellm.proxy._types import NewTeamRequest
from litellm.proxy.management_endpoints.team_endpoints import new_team
- with patch("litellm.proxy.proxy_server.premium_user", True): # test-quality-ok: proxy_server module global is the endpoint's only injection point
+ member_budget_cache: Final = MagicMock()
+ member_budget_cache.async_delete_cache = AsyncMock()
+ with (
+ patch("litellm.proxy.proxy_server.premium_user", True),
+ patch("litellm.proxy.proxy_server.user_api_key_cache", member_budget_cache),
+ ):
await new_team(
data=NewTeamRequest(
team_alias="model-caps",
model_max_budget={"gpt-4o": {"max_budget": 10.0, "budget_duration": "1d"}},
+ team_member_budget_duration=member_budget_duration,
+ team_member_model_max_budget=member_caps,
),
http_request=MagicMock(spec=Request),
user_api_key_dict=mock_admin_auth,
@@ -16283,6 +16474,75 @@ async def test_new_team_persists_model_max_budget(mock_db_client, mock_admin_aut
assert team_data["model_max_budget"] == {
"gpt-4o": {"max_budget": 10.0, "budget_duration": "1d", "tpm_limit": None, "rpm_limit": None}
}
+ member_budget_row: Final = mock_db_client.db.litellm_budgettable.create.call_args.kwargs["data"]
+ member_budget_id: Final = member_budget_row["budget_id"]
+ assert team_data["metadata"]["team_member_budget_id"] == member_budget_id
+ assert member_budget_row.get("budget_duration") == member_budget_duration
+ stored_member_budget_model_caps: Final = json.loads(member_budget_row["model_max_budget"])
+ expected_member_model_caps: Final = (
+ {
+ "gpt-4o": {
+ "max_budget": 5.0,
+ "budget_duration": "1d",
+ "tpm_limit": None,
+ "rpm_limit": None,
+ }
+ }
+ if member_caps
+ else {}
+ )
+ assert {
+ model: {
+ **budget,
+ "tpm_limit": budget.get("tpm_limit"),
+ "rpm_limit": budget.get("rpm_limit"),
+ }
+ for model, budget in stored_member_budget_model_caps.items()
+ } == expected_member_model_caps
+ member_budget_cache.async_delete_cache.assert_awaited_once_with(
+ key=f"team_member_default_budget:{member_budget_id}"
+ )
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("endpoint_name", ["new", "update"])
+@pytest.mark.parametrize(
+ ("premium_user", "model_budget", "expected_status"),
+ [
+ (False, {"gpt-4o": {"max_budget": 10.0, "budget_duration": "1d"}}, 403),
+ (True, {"gpt-4o": {"max_budget": 10.0}}, 400),
+ ],
+)
+async def test_team_member_model_budget_validation(endpoint_name, premium_user, model_budget, expected_status):
+ from fastapi import Request
+
+ from litellm.proxy._types import NewTeamRequest, ProxyException, UpdateTeamRequest
+ from litellm.proxy.management_endpoints.team_endpoints import (
+ new_team,
+ )
+ from litellm.proxy.management_endpoints.team_endpoints import (
+ update_team as update_team_endpoint,
+ )
+
+ endpoint: Final = new_team if endpoint_name == "new" else update_team_endpoint
+ data: Final = (
+ NewTeamRequest(team_alias="member-model-validation", team_member_model_max_budget=model_budget)
+ if endpoint_name == "new"
+ else UpdateTeamRequest(team_id="member-model-validation", team_member_model_max_budget=model_budget)
+ )
+
+ with (
+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),
+ patch("litellm.proxy.proxy_server.premium_user", premium_user),
+ pytest.raises(ProxyException) as exc_info,
+ ):
+ await endpoint(
+ data=data,
+ http_request=MagicMock(spec=Request),
+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin"),
+ )
+
+ assert exc_info.value.code == str(expected_status)
@pytest.mark.asyncio
@@ -17098,6 +17358,87 @@ def test_member_budget_patch_maps_temp_budget_fields() -> None:
}
+def test_member_budget_patch_stores_model_max_budget_as_json_and_clears_on_empty() -> None:
+ from litellm.proxy.management_endpoints.common_utils import member_budget_patch
+
+ request: Final = TeamMemberUpdateRequest(
+ team_id="team-1",
+ user_id="user-1",
+ model_max_budget={"gpt-4o": {"budget_limit": 5, "time_period": "30d"}},
+ )
+ assert member_budget_patch(request) == {"model_max_budget": {"gpt-4o": {"max_budget": 5.0, "budget_duration": "30d"}}}
+
+ cleared: Final = TeamMemberUpdateRequest(team_id="team-1", user_id="user-1", model_max_budget={})
+ assert member_budget_patch(cleared) == {"model_max_budget": {}}
+
+
+@pytest.mark.asyncio
+async def test_upsert_budget_and_membership_clears_own_model_max_budget_to_empty_json() -> None:
+ from litellm.proxy.management_endpoints.common_utils import upsert_budget_and_membership
+
+ own_row: Final = SimpleNamespace(
+ model_dump=lambda: {
+ "budget_id": "member-b",
+ "max_budget": 50.0,
+ "model_max_budget": {"gpt-4o": {"max_budget": 2.5, "budget_duration": "7d"}},
+ }
+ )
+ tx: Final = MagicMock()
+ tx.litellm_budgettable.find_unique = AsyncMock(return_value=own_row)
+ tx.litellm_budgettable.update = AsyncMock()
+ tx.litellm_teammembership.update = AsyncMock()
+
+ await upsert_budget_and_membership(
+ tx,
+ team_id="team-1",
+ user_id="user-1",
+ existing_budget_id="member-b",
+ user_api_key_dict=UserAPIKeyAuth(user_id="admin"),
+ budget_patch={"model_max_budget": None},
+ team_default_budget_id="default-b",
+ )
+
+ assert tx.litellm_budgettable.update.await_args.kwargs["data"]["model_max_budget"] == "{}"
+ tx.litellm_teammembership.update.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+async def test_upsert_budget_and_membership_clone_keeps_shared_default_model_max_budget_as_json() -> None:
+ from litellm.proxy.management_endpoints.common_utils import upsert_budget_and_membership
+
+ default_model_budget: Final = {"gpt-4o": {"max_budget": 5.0, "budget_duration": "30d"}}
+ default_row: Final = SimpleNamespace(
+ model_dump=lambda: {
+ "budget_id": "default-b",
+ "max_budget": 10.0,
+ "model_max_budget": default_model_budget,
+ "budget_reset_at": None,
+ }
+ )
+ tx: Final = MagicMock()
+ tx.litellm_budgettable.find_unique = AsyncMock(return_value=default_row)
+ tx.litellm_budgettable.create = AsyncMock(return_value=SimpleNamespace(budget_id="member-b"))
+ tx.litellm_teammembership.upsert = AsyncMock()
+
+ await upsert_budget_and_membership(
+ tx,
+ team_id="team-1",
+ user_id="user-1",
+ existing_budget_id="default-b",
+ user_api_key_dict=UserAPIKeyAuth(user_id="admin"),
+ budget_patch={"tpm_limit": 7},
+ team_default_budget_id="default-b",
+ )
+
+ create_data: Final = tx.litellm_budgettable.create.await_args.kwargs["data"]
+ assert create_data["tpm_limit"] == 7
+ assert create_data["max_budget"] == 10.0
+ assert json.loads(create_data["model_max_budget"]) == {}
+ assert tx.litellm_teammembership.upsert.await_args.kwargs["data"]["update"] == {
+ "litellm_budget_table": {"connect": {"budget_id": "member-b"}}
+ }
+
+
def test_team_member_update_request_temp_budget_fields_must_be_set_together() -> None:
with pytest.raises(ValidationError, match="temp_budget_increase and temp_budget_expiry must be set together"):
TeamMemberUpdateRequest(team_id="team-1", user_id="user-1", temp_budget_increase=50.0)
@@ -17211,3 +17552,18 @@ def test_aggregated_date_range_error_accepts_canonical_dates_and_keeps_range_che
assert aggregated_date_range_error("2026-09-24", "2026-09-26") is None
assert aggregated_date_range_error("2026-09-26", "2026-09-24") == "end_date must be on or after start_date"
assert aggregated_date_range_error("2020-01-01", "2026-12-31") == "Date range must be at most 400 days"
+
+
+@pytest.mark.asyncio
+async def test_default_budget_cache_eviction_does_not_fail_after_redis_error() -> None:
+ from litellm.proxy.management_endpoints.team_endpoints import TeamMemberBudgetHandler
+
+ user_api_key_cache = MagicMock()
+ user_api_key_cache.async_delete_cache = AsyncMock(side_effect=RuntimeError("redis unavailable"))
+
+ await TeamMemberBudgetHandler._evict_default_budget_cache(
+ budget_id="budget_456",
+ user_api_key_cache=user_api_key_cache,
+ )
+
+ user_api_key_cache.async_delete_cache.assert_awaited_once_with(key="team_member_default_budget:budget_456")
diff --git a/tests/unit/proxy/management_helpers/test_management_helpers_utils.py b/tests/unit/proxy/management_helpers/test_management_helpers_utils.py
index b450a4dfd02..644f0656c7a 100644
--- a/tests/unit/proxy/management_helpers/test_management_helpers_utils.py
+++ b/tests/unit/proxy/management_helpers/test_management_helpers_utils.py
@@ -1,3 +1,4 @@
+import json
from collections.abc import Mapping, Sequence
from datetime import datetime, timezone
from types import SimpleNamespace
@@ -817,6 +818,10 @@ async def test_add_new_member_with_user_email_links_default_budget():
mock_prisma_client.db.litellm_budgettable.create.assert_not_called()
+def _as_stored(data: Mapping[str, object]) -> dict[str, object]:
+ return {k: json.loads(v) if k == "model_max_budget" and isinstance(v, str) else v for k, v in data.items()}
+
+
class _FakeBudgetTable:
def __init__(self) -> None:
self.rows: dict[str, dict[str, object]] = {}
@@ -829,14 +834,14 @@ class _FakeBudgetTable:
self, *, data: Mapping[str, object], include: Mapping[str, bool] | None = None
) -> LiteLLM_BudgetTable:
budget_id: Final = str(data.get("budget_id") or uuid.uuid4())
- self.rows[budget_id] = {**data, "budget_id": budget_id}
+ self.rows[budget_id] = {**_as_stored(data), "budget_id": budget_id}
return self._record(budget_id)
async def find_unique(self, *, where: Mapping[str, str]) -> LiteLLM_BudgetTable | None:
return self._record(where["budget_id"]) if where["budget_id"] in self.rows else None
async def update(self, *, where: Mapping[str, str], data: Mapping[str, object]) -> LiteLLM_BudgetTable:
- self.rows[where["budget_id"]] = {**self.rows[where["budget_id"]], **data}
+ self.rows[where["budget_id"]] = {**self.rows[where["budget_id"]], **_as_stored(data)}
return self._record(where["budget_id"])
diff --git a/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.py b/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.py
index fb8d98ef61e..bd66bc24837 100644
--- a/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.py
+++ b/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.py
@@ -7918,14 +7918,17 @@ def test_passthrough_carries_the_per_model_budgets():
key_budget = {"claude-opus-4-8": {"budget_limit": 1.0, "time_period": "18h"}}
user_budget = {"claude-opus-4-8": {"budget_limit": 2.0, "time_period": "1mo"}}
end_user_budget = {"claude-opus-4-8": {"budget_limit": 3.0, "time_period": "1d"}}
+ team_member_budget = {"claude-opus-4-8": {"budget_limit": 4.0, "time_period": "1d"}}
kwargs = _passthrough_kwargs_for_reservation(
UserAPIKeyAuth(
token="hash",
user_id="u-1",
+ team_id="team-1",
model_max_budget=key_budget,
user_model_max_budget=user_budget,
end_user_model_max_budget=end_user_budget,
+ team_member_model_max_budget=team_member_budget,
)
)
@@ -7933,6 +7936,7 @@ def test_passthrough_carries_the_per_model_budgets():
assert metadata["user_api_key_model_max_budget"] == key_budget
assert metadata["user_api_key_user_model_max_budget"] == user_budget
assert metadata["user_api_key_end_user_model_max_budget"] == end_user_budget
+ assert metadata["user_api_key_team_member_model_max_budget"] == team_member_budget
def test_passthrough_budget_metadata_cannot_be_forged_by_the_request_body():
@@ -7981,7 +7985,10 @@ async def test_user_defined_passthrough_is_neither_tracked_nor_enforced(metadata
budget: Final = {"managed-model": {"budget_limit": 0.1, "time_period": "1d"}}
limiter: Final = PROXY_VirtualKeyModelMaxBudgetLimiter(DualCache())
auth: Final = UserAPIKeyAuth(
- api_key="custom-key", token="custom-key", team_id="shared-team", team_model_max_budget=budget,
+ api_key="custom-key",
+ token="custom-key",
+ team_id="shared-team",
+ team_model_max_budget=budget,
)
endpoint: Final = create_pass_through_route(
endpoint="/custom-budget-test",
diff --git a/tests/unit/proxy/test_common_request_processing.py b/tests/unit/proxy/test_common_request_processing.py
index b040cc861bf..0f66674daf9 100644
--- a/tests/unit/proxy/test_common_request_processing.py
+++ b/tests/unit/proxy/test_common_request_processing.py
@@ -17,6 +17,7 @@ from fastapi.responses import JSONResponse, StreamingResponse
import litellm
from litellm._uuid import uuid
from litellm.anthropic_interface.exceptions import AnthropicErrorSseFrame, anthropic_error_sse_frame
+from litellm.caching.caching import DualCache
from litellm.litellm_core_utils.bug_report import (
DISABLE_ENV_VAR,
ISSUE_URL_BASE,
@@ -59,11 +60,18 @@ from litellm.proxy.common_request_processing import (
sse_error_payload,
)
from litellm.proxy.common_utils.callback_utils import add_guardrail_to_applied_guardrails_header
+from litellm.proxy.common_utils.proxy_rate_limit_error import ProxyRateLimitError
from litellm.proxy.common_utils.sse_keepalive import ANTHROPIC_PING_SSE_CHUNK
from litellm.proxy.dd_span_tagger import DDSpanTagger
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
-from litellm.proxy._types import ProxyErrorTypes, ProxyException
+from litellm.proxy._types import Litellm_EntityType, ProxyErrorTypes, ProxyException
from litellm.proxy._types import UserAPIKeyAuth as ProxyUserAPIKeyAuth
+from litellm.proxy.auth.fallback_budget import RouterFallbackBudgetCheck
+from litellm.proxy.hooks.model_max_budget_limiter import (
+ PROXY_VirtualKeyModelMaxBudgetLimiter,
+ model_budget_spend_cache_key,
+ team_member_budget_entity_id,
+)
from litellm.proxy.utils import ProxyLogging
from litellm.router import Router
from litellm.router_utils.add_retry_fallback_headers import prepare_response_for_header_attachment
@@ -7097,6 +7105,9 @@ class TestPreCallWithFallbacksOnLocalRateLimit:
fallbacks: list[dict[str, list[str]]],
model_guardrails: dict[str, list[str]] | None = None,
untagged_rate_limited_models: frozenset[str] = frozenset(),
+ fallback_budget_check: RouterFallbackBudgetCheck | None = None,
+ free_models: frozenset[str] = frozenset(),
+ extra_models: frozenset[str] = frozenset(),
) -> tuple[ProxyLogging, litellm.Router, ProxyConfig, list[str]]:
"""Real v3 limiter (the default ``parallel_request_limiter``) wired in through the
``proxy_logging_obj`` seam, so ``common_processing_pre_call_logic`` runs for real:
@@ -7145,11 +7156,17 @@ class TestPreCallWithFallbacksOnLocalRateLimit:
"api_key": "fake",
**({"guardrails": guardrails_by_group[group]} if group in guardrails_by_group else {}),
},
+ **(
+ {"model_info": {"input_cost_per_token": 0, "output_cost_per_token": 0}}
+ if group in free_models
+ else {}
+ ),
}
for chain in fallbacks
- for group in (*chain.keys(), *(m for models in chain.values() for m in models))
+ for group in (*chain.keys(), *(m for models in chain.values() for m in models), *sorted(extra_models))
],
fallbacks=fallbacks,
+ fallback_budget_check=fallback_budget_check,
)
return proxy_logging_obj, router, proxy_server.ProxyConfig(), limiter_models
@@ -7636,6 +7653,138 @@ class TestPreCallWithFallbacksOnLocalRateLimit:
assert data["metadata"]["guardrails"] == [structured_guardrail]
assert rig[3] == [primary_model, primary_model, fallback_model]
+ @staticmethod
+ async def _install_member_spend(monkeypatch: pytest.MonkeyPatch, model: str, spend: float) -> None:
+ from litellm.proxy import proxy_server
+
+ member_limiter: Final = PROXY_VirtualKeyModelMaxBudgetLimiter(dual_cache=DualCache())
+ await member_limiter.dual_cache.async_set_cache(
+ key=model_budget_spend_cache_key(
+ entity_type=Litellm_EntityType.TEAM_MEMBER,
+ entity_id=team_member_budget_entity_id(user_id="user-1", team_id="team-1"),
+ budget_model=model,
+ budget_duration="1d",
+ ),
+ value=spend,
+ )
+ monkeypatch.setattr(proxy_server, "model_max_budget_limiter", member_limiter)
+
+ def _member_key(self, primary_model: str, fallback_model: str) -> ProxyUserAPIKeyAuth:
+ return self._otel_key(model_rpm_limit={primary_model: 1}).model_copy(
+ update={
+ "user_id": "user-1",
+ "team_id": "team-1",
+ "team_member_model_max_budget": {fallback_model: {"max_budget": 5.0, "budget_duration": "1d"}},
+ }
+ )
+
+ @staticmethod
+ def _client_request(model: str) -> dict[str, object]:
+ return {"model": model, "messages": [{"role": "user", "content": "hi"}]}
+
+ @pytest.mark.asyncio
+ async def test_rate_limit_fallback_skips_backup_over_member_model_budget(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ primary_model: Final = "gpt-4.1"
+ fallback_model: Final = "gpt-4.1-mini"
+ await self._install_member_spend(monkeypatch, fallback_model, spend=5.0)
+ key: Final = self._member_key(primary_model, fallback_model)
+ rig: Final = self._v3_limiter_rig(monkeypatch, key, [{primary_model: [fallback_model]}])
+
+ _, (first_data, _) = await self._pre_call(self._client_request(primary_model), key, rig)
+ processor: Final = ProxyBaseLLMRequestProcessing(data=self._client_request(primary_model))
+ with pytest.raises(ProxyRateLimitError):
+ await self._run(processor, key, rig)
+
+ assert first_data["model"] == primary_model
+ assert rig[3] == [primary_model, primary_model]
+
+ @pytest.mark.asyncio
+ async def test_rate_limit_fallback_skips_backup_aliased_to_model_over_member_budget(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ primary_model: Final = "gpt-4.1"
+ fallback_model: Final = "gpt-4.1-mini"
+ resolved_model: Final = "expensive"
+ await self._install_member_spend(monkeypatch, resolved_model, spend=5.0)
+ key: Final = self._member_key(primary_model, fallback_model).model_copy(
+ update={
+ "router_settings": {"model_group_alias": {fallback_model: resolved_model}},
+ "team_member_model_max_budget": {resolved_model: {"max_budget": 5.0, "budget_duration": "1d"}},
+ }
+ )
+ rig: Final = self._v3_limiter_rig(
+ monkeypatch,
+ key,
+ [{primary_model: [fallback_model]}],
+ extra_models=frozenset({resolved_model}),
+ )
+
+ await self._pre_call(self._client_request(primary_model), key, rig)
+ processor: Final = ProxyBaseLLMRequestProcessing(data=self._client_request(primary_model))
+ with pytest.raises(ProxyRateLimitError):
+ await self._run(processor, key, rig)
+
+ assert processor.data["model"] == primary_model
+ assert rig[3] == [primary_model, primary_model]
+
+ @pytest.mark.asyncio
+ async def test_rate_limit_fallback_uses_backup_within_member_model_budget(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ primary_model: Final = "gpt-4.1"
+ fallback_model: Final = "gpt-4.1-mini"
+ await self._install_member_spend(monkeypatch, fallback_model, spend=4.0)
+ key: Final = self._member_key(primary_model, fallback_model)
+ rig: Final = self._v3_limiter_rig(monkeypatch, key, [{primary_model: [fallback_model]}])
+
+ await self._pre_call(self._client_request(primary_model), key, rig)
+ _, (data, logging_obj) = await self._pre_call(self._client_request(primary_model), key, rig)
+
+ assert data["model"] == fallback_model
+ assert logging_obj.model == fallback_model
+ assert rig[3] == [primary_model, primary_model, fallback_model]
+
+ @pytest.mark.asyncio
+ async def test_rate_limit_fallback_uses_free_backup_with_spent_member_model_budget(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ primary_model: Final = "gpt-4.1"
+ fallback_model: Final = "gpt-4.1-mini"
+ await self._install_member_spend(monkeypatch, fallback_model, spend=5.0)
+ key: Final = self._member_key(primary_model, fallback_model)
+ rig: Final = self._v3_limiter_rig(
+ monkeypatch, key, [{primary_model: [fallback_model]}], free_models=frozenset({fallback_model})
+ )
+
+ await self._pre_call(self._client_request(primary_model), key, rig)
+ _, (data, _) = await self._pre_call(self._client_request(primary_model), key, rig)
+
+ assert data["model"] == fallback_model
+ assert rig[3] == [primary_model, primary_model, fallback_model]
+
+ @pytest.mark.asyncio
+ async def test_rate_limit_fallback_ignores_key_budget_already_admitted_at_auth(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ primary_model: Final = "gpt-4.1"
+ fallback_model: Final = "gpt-4.1-mini"
+ key: Final = self._otel_key(model_rpm_limit={primary_model: 1}).model_copy(
+ update={"token": "hashed-key", "max_budget": 1.0, "spend": 2.0}
+ )
+ rig: Final = self._v3_limiter_rig(
+ monkeypatch,
+ key,
+ [{primary_model: [fallback_model]}],
+ fallback_budget_check=RouterFallbackBudgetCheck(is_enforced=lambda: True),
+ )
+
+ await self._pre_call(self._client_request(primary_model), key, rig)
+ _, (data, _) = await self._pre_call(self._client_request(primary_model), key, rig)
+
+ assert data["model"] == fallback_model
+ assert rig[3] == [primary_model, primary_model, fallback_model]
class _RecordingSuccessLogger(CustomLogger):
def __init__(self):
diff --git a/tests/unit/proxy/test_litellm_pre_call_utils.py b/tests/unit/proxy/test_litellm_pre_call_utils.py
index cf04b9ff91e..3a6aac9be05 100644
--- a/tests/unit/proxy/test_litellm_pre_call_utils.py
+++ b/tests/unit/proxy/test_litellm_pre_call_utils.py
@@ -2016,6 +2016,8 @@ async def test_add_litellm_data_to_request_user_spend_and_budget():
api_key="hashed-key",
metadata={},
team_metadata={},
+ team_id="team-1",
+ team_member_model_max_budget={"gpt-3.5-turbo": {"max_budget": 15.0, "budget_duration": "1d"}},
user_spend=150.0,
user_max_budget=500.0,
)
@@ -2032,6 +2034,9 @@ async def test_add_litellm_data_to_request_user_spend_and_budget():
metadata = updated_data.get("metadata", {})
assert metadata["user_api_key_user_spend"] == 150.0
assert metadata["user_api_key_user_max_budget"] == 500.0
+ assert metadata["user_api_key_team_member_model_max_budget"] == {
+ "gpt-3.5-turbo": {"max_budget": 15.0, "budget_duration": "1d"}
+ }
@pytest.mark.asyncio
diff --git a/tests/unit/router_utils/test_router_utils_common_utils.py b/tests/unit/router_utils/test_router_utils_common_utils.py
index e0829e42557..3694ecea4ed 100644
--- a/tests/unit/router_utils/test_router_utils_common_utils.py
+++ b/tests/unit/router_utils/test_router_utils_common_utils.py
@@ -14,6 +14,7 @@ from litellm.router_utils.common_utils import (
filter_web_search_deployments,
provider_for_generic_call,
resolve_model_group_alias,
+ resolve_served_model,
truncate_fallback_error_detail,
PROVIDER_SCOPED_CREDENTIAL_PARAMS,
warn_on_provider_credential_mismatch,
@@ -566,6 +567,25 @@ class TestResolveModelGroupAlias:
assert router.get_model_from_alias("group-b") is None
+@pytest.mark.parametrize(
+ "model, model_alias_map, key_aliases, model_group_alias, expected",
+ [
+ pytest.param("a", {"a": "b"}, {"b": "c"}, {"c": "d"}, "d", id="global-key-router-order"),
+ pytest.param("a", {}, ["a", "b"], {}, "a", id="non-mapping-key-aliases-ignored"),
+ pytest.param("a", {}, {}, {"a": {"model": "x"}}, "x", id="router-item-entry"),
+ pytest.param("a", {}, {}, {}, "a", id="no-alias"),
+ ],
+)
+def test_resolves_served_model_aliases_in_order(
+ model: str,
+ model_alias_map: object,
+ key_aliases: object,
+ model_group_alias: object,
+ expected: str,
+) -> None:
+ assert resolve_served_model(model, model_alias_map, key_aliases, model_group_alias) == expected
+
+
class TestTruncateFallbackErrorDetail:
def test_short_detail_is_returned_unchanged(self):
assert truncate_fallback_error_detail("boom") == "boom"
diff --git a/ui/litellm-dashboard/src/components/Teams.integration.test.tsx b/ui/litellm-dashboard/src/components/Teams.integration.test.tsx
new file mode 100644
index 00000000000..a6801e3c996
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/Teams.integration.test.tsx
@@ -0,0 +1,83 @@
+import { fireEvent, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { renderWithProviders, testQueryClient } from "../../tests/test-utils";
+import Teams from "./Teams";
+
+const sessionCookie = () => {
+ const encode = (value: object) =>
+ btoa(JSON.stringify(value)).replaceAll("=", "").replaceAll("+", "-").replaceAll("/", "_");
+ const claims = {
+ key: "sk-session-test",
+ user_id: "test-admin",
+ user_role: "proxy_admin",
+ premium_user: true,
+ exp: Date.now() / 1000 + 3600,
+ };
+ document.cookie = `token=${encode({ alg: "none" })}.${encode(claims)}.test; Path=/`;
+};
+
+const responseFor = (url: string): object | object[] => {
+ if (url.includes("/v2/team/list")) return { teams: [], total: 0, page: 1, page_size: 50, total_pages: 1 };
+ if (url.includes("/models")) return { data: [{ id: "gpt-4" }] };
+ if (url.includes("/v1/access_group")) return [];
+ if (url.includes("/v1/mcp/access_groups")) return { access_groups: [] };
+ if (url.includes("/guardrails/list")) return { guardrails: [] };
+ if (url.includes("/policies/list")) return { policies: [] };
+ if (url.includes("/organization/list")) return { organizations: [] };
+ if (url.includes("/team/new")) return { team_id: "new-team-1" };
+ if (url.includes("/default")) return { values: {} };
+ if (url.includes("/litellm-ui-config")) return { server_root_path: "", proxy_base_url: "" };
+ return {};
+};
+
+beforeEach(() => {
+ testQueryClient.clear();
+ sessionCookie();
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: RequestInfo | URL) => Response.json(responseFor(String(input)))),
+ );
+});
+
+afterEach(() => {
+ testQueryClient.clear();
+ vi.unstubAllGlobals();
+ document.cookie = "token=; Max-Age=0; Path=/";
+});
+
+describe("Teams creation integration", () => {
+ it("sends a configured default member per-model budget", async () => {
+ const user = userEvent.setup({ delay: null });
+ renderWithProviders();
+
+ await user.click(screen.getAllByRole("button", { name: /create team/i })[0]);
+ await screen.findByLabelText(/team name/i);
+ await user.click(screen.getByText("Additional Settings"));
+ await screen.findByText(/Team Member Key Duration/);
+
+ const addBudgetButtons = screen.getAllByRole("button", { name: /Add Model Budget/i });
+ await user.click(addBudgetButtons[1]);
+ const modelSelectors = screen.getAllByPlaceholderText("Select model");
+ await user.click(modelSelectors[0]);
+ await user.click(await screen.findByRole("option", { name: "gpt-4" }));
+ fireEvent.change(screen.getAllByPlaceholderText("Max spend ($)")[0], { target: { value: "4" } });
+ await user.click(screen.getByText("Additional Settings"));
+
+ fireEvent.change(screen.getByLabelText(/team name/i), { target: { value: "Budget Team" } });
+ await user.click(screen.getAllByRole("button", { name: /create team/i }).at(-1)!);
+ await waitFor(() => {
+ expect(vi.mocked(fetch)).toHaveBeenCalled();
+ });
+
+ const createRequest = vi.mocked(fetch).mock.calls.find(([input]) => String(input).includes("/team/new"));
+ expect(createRequest).toBeDefined();
+ const payload = JSON.parse(String(createRequest?.[1]?.body)) as Record;
+ expect(payload.team_member_model_max_budget).toStrictEqual({
+ "gpt-4": { budget_limit: 4, time_period: "30d" },
+ });
+ expect(JSON.parse(JSON.stringify(payload)).team_member_model_max_budget).toStrictEqual({
+ "gpt-4": { budget_limit: 4, time_period: "30d" },
+ });
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/Teams.tsx b/ui/litellm-dashboard/src/components/Teams.tsx
index 0b773fd0f04..9971010c3ef 100644
--- a/ui/litellm-dashboard/src/components/Teams.tsx
+++ b/ui/litellm-dashboard/src/components/Teams.tsx
@@ -51,6 +51,7 @@ import BudgetDurationDropdown, {
import { Organization, getDefaultTeamSettings, getGuardrailsList, getPoliciesList, teamDeleteCall } from "./networking";
import NumericalInput from "./shared/numerical_input";
import { ModelMaxBudget, ModelMaxBudgetField } from "./key_team_helpers/ModelMaxBudgetEditor";
+import { modelMaxBudgetUpdate } from "./key_team_helpers/modelMaxBudgetPayload";
import VectorStoreSelector from "./vector_store_management/VectorStoreSelector";
import SearchToolSelector from "./search_tools/SearchToolSelector";
import SkillSelector from "./skills/SkillSelector";
@@ -280,6 +281,7 @@ const Teams: React.FC = ({ accessToken, userID, userRole, isViewOnly
const [loggingSettings, setLoggingSettings] = useState([]);
const [modelAliases, setModelAliases] = useState<{ [key: string]: string }>({});
const [modelMaxBudget, setModelMaxBudget] = useState({});
+ const [teamMemberModelMaxBudget, setTeamMemberModelMaxBudget] = useState({});
const [routerSettings, setRouterSettings] = useState(null);
const [routerSettingsKey, setRouterSettingsKey] = useState(0);
@@ -358,6 +360,7 @@ const Teams: React.FC = ({ accessToken, userID, userRole, isViewOnly
setLoggingSettings([]);
setModelAliases({});
setModelMaxBudget({});
+ setTeamMemberModelMaxBudget({});
setRouterSettings(null);
setRouterSettingsKey((prev) => prev + 1);
};
@@ -551,9 +554,11 @@ const Teams: React.FC = ({ accessToken, userID, userRole, isViewOnly
}
const { require_trace_id: requireTraceId, ...teamCreateValues } = formValues;
+ const teamMemberModelBudgets = modelMaxBudgetUpdate(teamMemberModelMaxBudget, {});
await teamCreateCall(accessToken, {
...teamCreateValues,
...(requireTraceId === undefined ? {} : { require_trace_id: requireTraceId }),
+ ...(teamMemberModelBudgets !== undefined ? { team_member_model_max_budget: teamMemberModelBudgets } : {}),
models: normalizeTeamModelSelection(formValues.models),
});
toast.success("Team created");
@@ -912,6 +917,15 @@ const Teams: React.FC = ({ accessToken, userID, userRole, isViewOnly
/>
)}
+
(() => modelMaxBudgetToEntries(value));
+ const incoming = JSON.stringify(value ?? {});
+ const [syncedValue, setSyncedValue] = useState(incoming);
+ if (incoming !== syncedValue) {
+ setSyncedValue(incoming);
+ if (incoming !== JSON.stringify(entriesToModelMaxBudget(entries))) setEntries(modelMaxBudgetToEntries(value));
+ }
+
const emitChange = (updated: ModelBudgetEntry[]) => {
setEntries(updated);
onChange(entriesToModelMaxBudget(updated));
@@ -219,14 +226,15 @@ export function ModelMaxBudgetEditor({
interface ModelMaxBudgetFieldProps extends ModelMaxBudgetEditorProps {
hint: string;
+ label?: string;
}
/** The editor with its label, so every form that offers it presents it the same way. */
-export function ModelMaxBudgetField({ hint, ...editorProps }: ModelMaxBudgetFieldProps) {
+export function ModelMaxBudgetField({ hint, label = "Per-Model Budgets", ...editorProps }: ModelMaxBudgetFieldProps) {
return (
- Per-Model Budgets
+ {label}
diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx
index 54b2066c9c5..0fbf3d36355 100644
--- a/ui/litellm-dashboard/src/components/networking.tsx
+++ b/ui/litellm-dashboard/src/components/networking.tsx
@@ -94,6 +94,7 @@ import { Team } from "./key_team_helpers/key_list";
import { EmailEventSettingsResponse, EmailEventSettingsUpdateRequest } from "./email_events/types";
import type { ListPluginsResponse, SkillRegisterRequest } from "./claude_code_plugins/types";
import type { ModelBudgetUsage, ModelMaxBudget } from "./key_team_helpers/ModelMaxBudgetEditor";
+import type { StoredModelMaxBudget } from "./key_team_helpers/modelMaxBudgetPayload";
import type { ObjectPermission } from "./object_permission_types";
import type { components } from "@/lib/http/schema";
import { fetchClient } from "@/lib/http/api";
@@ -2831,6 +2832,7 @@ export interface Member {
allowed_models?: string[] | null;
temp_budget_increase?: number | null;
temp_budget_expiry?: string | null;
+ model_max_budget?: StoredModelMaxBudget | null;
}
export const teamMemberAddCall = async (accessToken: string, teamId: string, formValues: Member) => {
@@ -2971,6 +2973,9 @@ export const teamMemberUpdateCall = async (
if ("temp_budget_expiry" in formValues) {
requestBody.temp_budget_expiry = orNull(formValues.temp_budget_expiry);
}
+ if (formValues.model_max_budget !== undefined) {
+ requestBody.model_max_budget = formValues.model_max_budget;
+ }
const response = await fetch(url, {
method: "POST",
diff --git a/ui/litellm-dashboard/src/components/team/EditMembership.integration.test.tsx b/ui/litellm-dashboard/src/components/team/EditMembership.integration.test.tsx
index 45800a18ff8..2c98d17f961 100644
--- a/ui/litellm-dashboard/src/components/team/EditMembership.integration.test.tsx
+++ b/ui/litellm-dashboard/src/components/team/EditMembership.integration.test.tsx
@@ -1,4 +1,6 @@
+import { useState } from "react";
import { fireEvent, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders } from "../../../tests/test-utils";
import EditMembership from "./EditMembership";
@@ -104,6 +106,79 @@ describe("EditMembership submit payload", () => {
});
});
+ it("seeds the per-model budget editor from the member's stored budget and submits the edited cap", async () => {
+ const modelBudgetConfig = {
+ ...teamMemberConfig,
+ additionalFields: [
+ ...additionalFields,
+ {
+ name: "model_max_budget",
+ label: "Per-Model Budgets",
+ type: "model-max-budget" as const,
+ availableModels: ["gpt-4o"],
+ premiumUser: true,
+ },
+ ],
+ };
+ const member = {
+ user_id: "u1",
+ user_email: "a@b.com",
+ role: "user",
+ model_max_budget: { "gpt-4o": { max_budget: 5, budget_duration: "30d" } },
+ };
+ renderEdit(modelBudgetConfig, member);
+
+ const cap = await screen.findByPlaceholderText("Max spend ($)");
+ expect(cap).toHaveValue(5);
+ fireEvent.change(cap, { target: { value: "9" } });
+ save();
+
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledOnce());
+ expect(submitted().model_max_budget).toStrictEqual({ "gpt-4o": { budget_limit: 9, time_period: "30d" } });
+ });
+
+ it("saves a role-only edit for a member with stored model caps", async () => {
+ const modelBudgetConfig = {
+ ...teamMemberConfig,
+ additionalFields: [
+ ...additionalFields,
+ {
+ name: "model_max_budget",
+ label: "Per-Model Budgets",
+ type: "model-max-budget" as const,
+ availableModels: ["gpt-4o"],
+ premiumUser: true,
+ },
+ ],
+ };
+ const member = {
+ user_id: "u1",
+ user_email: "a@b.com",
+ role: "user",
+ model_max_budget: { "gpt-4o": { max_budget: 5, budget_duration: "30d" } },
+ };
+ renderEdit(modelBudgetConfig, member);
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole("combobox", { name: "Role(Current: User)" }));
+ await user.click(await screen.findByRole("option", { name: "Admin" }));
+ save();
+
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledOnce());
+ const expectedPayload = {
+ user_email: "a@b.com",
+ user_id: "u1",
+ role: "admin",
+ max_budget_in_team: null,
+ budget_duration: null,
+ tpm_limit: null,
+ rpm_limit: null,
+ allowed_models: [],
+ model_max_budget: { "gpt-4o": { budget_limit: 5, time_period: "30d" } },
+ };
+ expect(submitted()).toStrictEqual(expectedPayload);
+ });
+
it("omits a field the config hides even when the member record carries it", async () => {
renderEdit({ ...orgMemberConfig, showUserId: false }, { user_id: "u1", user_email: "a@b.com", role: "admin" });
@@ -342,3 +417,57 @@ describe("EditMembership submit payload", () => {
expect(screen.getByLabelText("Email")).toHaveValue("");
});
});
+
+it("discards an unfinished per-model budget row when an edit session is reopened", async () => {
+ const user = userEvent.setup({ delay: null });
+ const modelBudgetConfig = {
+ ...teamMemberConfig,
+ additionalFields: [
+ ...additionalFields,
+ {
+ name: "model_max_budget",
+ label: "Per-Model Budgets",
+ type: "model-max-budget" as const,
+ availableModels: ["gpt-4o"],
+ premiumUser: true,
+ },
+ ],
+ };
+ const member = { user_id: "u1", user_email: "a@b.com", role: "user", model_max_budget: {} };
+ const otherMember = { ...member, user_id: "u2", user_email: "c@d.com" };
+ const Harness = ({ initialData }: { initialData: typeof member }) => {
+ const [visible, setVisible] = useState(false);
+ return (
+ <>
+
+ setVisible(false)}
+ onSubmit={vi.fn()}
+ mode="edit"
+ config={modelBudgetConfig as never}
+ initialData={initialData as never}
+ />
+ >
+ );
+ };
+
+ const { rerender } = renderWithProviders();
+
+ await user.click(screen.getByRole("button", { name: "Open Edit Member" }));
+ await user.click(screen.getByRole("button", { name: /Add Model Budget/i }));
+ expect(screen.getByPlaceholderText("Select model")).toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: "Cancel" }));
+ await user.click(screen.getByRole("button", { name: "Open Edit Member" }));
+
+ expect(screen.queryByPlaceholderText("Select model")).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: /Add Model Budget/i }));
+ expect(screen.getByPlaceholderText("Select model")).toBeInTheDocument();
+
+ rerender();
+ expect(screen.queryByPlaceholderText("Select model")).not.toBeInTheDocument();
+});
diff --git a/ui/litellm-dashboard/src/components/team/EditMembership.tsx b/ui/litellm-dashboard/src/components/team/EditMembership.tsx
index 4aaeb42da98..4e1fa4cfbcf 100644
--- a/ui/litellm-dashboard/src/components/team/EditMembership.tsx
+++ b/ui/litellm-dashboard/src/components/team/EditMembership.tsx
@@ -12,11 +12,13 @@ import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { UiLoadingSpinner } from "@/components/ui/ui-loading-spinner";
import { UtcDateTimeInput } from "@/components/shared/form/UtcDateTimeInput";
+import { ModelMaxBudgetEditor } from "../key_team_helpers/ModelMaxBudgetEditor";
import { useZodForm } from "@/lib/forms/useZodForm";
import {
buildMemberFormData,
buildMemberFormValues,
emptyMemberFormValues,
+ isModelMaxBudget,
TEMP_BUDGET_PAIR_MESSAGE,
tempBudgetPairError,
type MemberAdditionalField,
@@ -51,7 +53,11 @@ const ROLE_REQUIRED_MESSAGE = "Please select a role!";
const isEmailish = (value: string): boolean =>
value === "" || z.email({ pattern: z.regexes.html5Email }).safeParse(value).success;
-const memberFieldSchema = z.union([z.string(), z.number(), z.null(), z.array(z.string())]).optional();
+const modelMaxBudgetSchema = z.record(z.string(), z.looseObject({ budget_limit: z.number(), time_period: z.string() }));
+
+const memberFieldSchema = z
+ .union([z.string(), z.number(), z.null(), z.array(z.string()), modelMaxBudgetSchema])
+ .optional();
const buildMemberSchema = (config: ModalConfig): z.ZodType => {
const shape = {
@@ -171,6 +177,16 @@ const MemberModal = ({
onChange={(next) => onChange(mode === "add" ? next ?? undefined : next)}
/>
);
+ case "model-max-budget":
+ return (
+
+ );
case "utc-datetime":
return (
{
expect(screen.queryByText("Reset member budgets?")).not.toBeInTheDocument();
expect(bulkUpdatePOST).not.toHaveBeenCalled();
});
+
+ it("omits the default member model budget when it has not changed", async () => {
+ const user = userEvent.setup({ delay: null });
+ const storedBudget = { "gpt-4": { budget_limit: 3, time_period: "30d" } };
+ const data = createMockTeamData({
+ models: ["gpt-4"],
+ team_member_budget_table: {
+ max_budget: 10,
+ budget_duration: null,
+ tpm_limit: null,
+ rpm_limit: null,
+ model_max_budget: storedBudget,
+ },
+ });
+ vi.mocked(networking.teamInfoCall).mockResolvedValue(data);
+ vi.mocked(networking.teamUpdateCall).mockResolvedValue({ data: savedTeam, team_id: "123" });
+
+ renderWithProviders();
+ await waitFor(() => expect(screen.queryAllByText("Test Team").length).toBeGreaterThan(0));
+ await user.click(screen.getByRole("tab", { name: "Settings" }));
+ await user.click(await screen.findByRole("button", { name: /edit settings/i }));
+ await user.click(screen.getByText("Team Member Settings"));
+ await screen.findByPlaceholderText("Max spend ($)");
+ await user.click(screen.getByRole("button", { name: /save changes/i }));
+
+ await waitFor(() => expect(networking.teamUpdateCall).toHaveBeenCalled());
+ expect(vi.mocked(networking.teamUpdateCall).mock.calls[0][1]).not.toHaveProperty("team_member_model_max_budget");
+ });
+
+ it("sends the default member model budget after an edit", async () => {
+ const user = userEvent.setup({ delay: null });
+ const storedBudget = { "gpt-4": { budget_limit: 3, time_period: "30d" } };
+ const data = createMockTeamData({
+ models: ["gpt-4"],
+ team_member_budget_table: {
+ max_budget: 10,
+ budget_duration: null,
+ tpm_limit: null,
+ rpm_limit: null,
+ model_max_budget: storedBudget,
+ },
+ });
+ vi.mocked(networking.teamInfoCall).mockResolvedValue(data);
+ vi.mocked(networking.teamUpdateCall).mockResolvedValue({ data: savedTeam, team_id: "123" });
+
+ renderWithProviders();
+ await waitFor(() => expect(screen.queryAllByText("Test Team").length).toBeGreaterThan(0));
+ await user.click(screen.getByRole("tab", { name: "Settings" }));
+ await user.click(await screen.findByRole("button", { name: /edit settings/i }));
+ await user.click(screen.getByText("Team Member Settings"));
+ fireEvent.change(await screen.findByPlaceholderText("Max spend ($)"), { target: { value: "7" } });
+ await user.click(screen.getByRole("button", { name: /save changes/i }));
+
+ await waitFor(() => expect(networking.teamUpdateCall).toHaveBeenCalled());
+ expect(vi.mocked(networking.teamUpdateCall).mock.calls[0][1].team_member_model_max_budget).toStrictEqual({
+ "gpt-4": { budget_limit: 7, time_period: "30d" },
+ });
+ });
+
+ it("offers access-group models in the default member budget picker", async () => {
+ const user = userEvent.setup({ delay: null });
+ vi.mocked(networking.teamInfoCall).mockResolvedValue(
+ createMockTeamData({
+ models: ["gpt-4o"],
+ access_group_models: ["claude-haiku-4-5"],
+ }) as TeamData,
+ );
+
+ renderWithProviders();
+ await waitFor(() => expect(screen.queryAllByText("Test Team").length).toBeGreaterThan(0));
+ await user.click(screen.getByRole("tab", { name: "Settings" }));
+ await user.click(await screen.findByRole("button", { name: /edit settings/i }));
+ await user.click(screen.getByText("Team Member Settings"));
+ await user.click(screen.getAllByRole("button", { name: /add model budget/i })[0]);
+ await user.click(screen.getByPlaceholderText("Select model"));
+
+ expect(await screen.findByRole("option", { name: "claude-haiku-4-5" })).toBeInTheDocument();
+ });
+
+ it("offers user models in the default member budget picker when the team model list is empty", async () => {
+ const user = userEvent.setup({ delay: null });
+ vi.mocked(networking.teamInfoCall).mockResolvedValue(createMockTeamData({ models: [] }) as TeamData);
+
+ renderWithProviders();
+ await waitFor(() => expect(screen.queryAllByText("Test Team").length).toBeGreaterThan(0));
+ await user.click(screen.getByRole("tab", { name: "Settings" }));
+ await user.click(await screen.findByRole("button", { name: /edit settings/i }));
+ await user.click(screen.getByText("Team Member Settings"));
+ await user.click(screen.getAllByRole("button", { name: /add model budget/i })[0]);
+ await user.click(screen.getByPlaceholderText("Select model"));
+
+ expect(await screen.findByRole("option", { name: "gpt-4o" })).toBeInTheDocument();
+ expect(screen.getByRole("option", { name: "claude-haiku-4-5" })).toBeInTheDocument();
+ });
});
diff --git a/ui/litellm-dashboard/src/components/team/TeamInfo.tsx b/ui/litellm-dashboard/src/components/team/TeamInfo.tsx
index a782112edb2..7663ef8c588 100644
--- a/ui/litellm-dashboard/src/components/team/TeamInfo.tsx
+++ b/ui/litellm-dashboard/src/components/team/TeamInfo.tsx
@@ -286,7 +286,7 @@ export interface TeamMembership {
max_parallel_requests: number | null;
tpm_limit: number | null;
rpm_limit: number | null;
- model_max_budget: Record | null;
+ model_max_budget: StoredModelMaxBudget | null;
budget_duration: string | null;
budget_reset_at: string | null;
allowed_models?: string[] | null;
@@ -339,6 +339,7 @@ export interface TeamData {
budget_duration: string | null;
tpm_limit: number | null;
rpm_limit: number | null;
+ model_max_budget?: StoredModelMaxBudget | null;
} | null;
};
keys: any[];
@@ -631,6 +632,7 @@ const TeamInfoView: React.FC = ({
const [isTeamSaving, setIsTeamSaving] = useState(false);
const [teamModelAliases, setTeamModelAliases] = useState>({});
const [teamModelMaxBudget, setTeamModelMaxBudget] = useState({});
+ const [teamMemberModelMaxBudget, setTeamMemberModelMaxBudget] = useState({});
const routerSettingsRef = React.useRef(null);
const [organization, setOrganization] = useState(null);
const { userRole, isViewOnly } = useAuthorized();
@@ -661,12 +663,20 @@ const TeamInfoView: React.FC = ({
] as const
).find(([failed]) => failed)?.[1] ?? null;
const availableRateLimitModels = useMemo(() => {
- const selected = watchedModels ?? teamData?.team_info?.models ?? [];
+ const selected = (isEditing ? watchedModels : undefined) ?? teamData?.team_info?.models ?? [];
if (selected.includes("all-proxy-models") || selected.includes("all-team-models")) {
return userModels;
}
return unfurlWildcardModelsInList(selected, userModels);
- }, [watchedModels, teamData, userModels]);
+ }, [isEditing, watchedModels, teamData, userModels]);
+ const availableModelBudgetModels = useMemo(() => {
+ const selected = (isEditing ? watchedModels : undefined) ?? teamData?.team_info?.models ?? [];
+ if (selected.length === 0 || selected.includes("all-proxy-models") || selected.includes("all-team-models")) {
+ return userModels;
+ }
+ const granted = [...selected, ...(teamData?.team_info?.access_group_models ?? [])];
+ return unfurlWildcardModelsInList(Array.from(new Set(granted)), userModels);
+ }, [isEditing, watchedModels, teamData, userModels]);
const teamEditAccess = useMemo(() => parseTeamEditAccess(teamData?.team_info?.caller_edit_access), [teamData]);
const canEditTeam = is_team_admin || is_proxy_admin || teamEditAccess.kind !== "none";
@@ -684,6 +694,9 @@ const TeamInfoView: React.FC = ({
const startEditing = () => {
form.reset(teamFormValues());
setTeamModelMaxBudget((teamData?.team_info?.model_max_budget ?? {}) as ModelMaxBudget);
+ setTeamMemberModelMaxBudget(
+ (teamData?.team_info?.team_member_budget_table?.model_max_budget ?? {}) as ModelMaxBudget,
+ );
setTeamMemberSettingsOpen(false);
setSearchToolSettingsOpen(false);
setIsEditing(true);
@@ -866,6 +879,7 @@ const TeamInfoView: React.FC = ({
allowed_models: values.allowed_models,
temp_budget_increase: values.temp_budget_increase,
temp_budget_expiry: values.temp_budget_expiry,
+ model_max_budget: modelMaxBudgetUpdate(values.model_max_budget ?? {}, selectedEditMember?.model_max_budget),
};
toast.dismiss(); // Remove all existing toasts
@@ -1223,6 +1237,14 @@ const TeamInfoView: React.FC = ({
updateData.model_max_budget = modelBudgets;
}
+ const teamMemberModelBudgets = modelMaxBudgetUpdate(
+ teamMemberModelMaxBudget,
+ info.team_member_budget_table?.model_max_budget,
+ );
+ if (teamMemberModelBudgets !== undefined) {
+ updateData.team_member_model_max_budget = teamMemberModelBudgets;
+ }
+
// Handle router_settings - read fresh values from DOM at save time.
const currentRouterSettings = routerSettingsRef.current?.getValue();
if (currentRouterSettings?.router_settings) {
@@ -1658,6 +1680,14 @@ const TeamInfoView: React.FC = ({
/>
)}
+
= ({
Max Budget: {info.team_member_budget_table?.max_budget ?? "No Limit"}
Budget Duration: {info.team_member_budget_table?.budget_duration || "No Limit"}
+ {modelMaxBudgetToEntries(
+ info.team_member_budget_table?.model_max_budget as ModelMaxBudget | null | undefined,
+ ).map(({ model, budgetLimit, timePeriod }) => (
+
+ Default Per-Model Budget ({model}):{" "}
+ {budgetLimit !== null ? `$${formatNumberWithCommas(budgetLimit, 4)}` : "No Limit"} per {timePeriod}
+
+ ))}
Key Duration: {info.metadata?.team_member_key_duration || "No Limit"}
TPM Limit: {info.team_member_budget_table?.tpm_limit ?? "No Limit"}
RPM Limit: {info.team_member_budget_table?.rpm_limit ?? "No Limit"}
@@ -2554,6 +2592,20 @@ const TeamInfoView: React.FC = ({
),
type: "utc-datetime" as const,
},
+ {
+ name: "model_max_budget",
+ label: (
+
+ Per-Model Budgets{" "}
+
+
+
+
+ ),
+ type: "model-max-budget" as const,
+ availableModels: availableModelBudgetModels,
+ premiumUser,
+ },
{
name: "tpm_limit",
label: (
diff --git a/ui/litellm-dashboard/src/components/team/TeamMemberTab.test.tsx b/ui/litellm-dashboard/src/components/team/TeamMemberTab.test.tsx
index 8953a06796f..b8f292222ed 100644
--- a/ui/litellm-dashboard/src/components/team/TeamMemberTab.test.tsx
+++ b/ui/litellm-dashboard/src/components/team/TeamMemberTab.test.tsx
@@ -432,10 +432,31 @@ describe("TeamMembersComponent", () => {
allowed_models: [],
temp_budget_increase: 0,
temp_budget_expiry: "2030-01-02T03:04:00Z",
+ model_max_budget: null,
};
expect(seedMemberBudgetFields({ user_id: "user1@test.com", role: "member" }, budget)).toStrictEqual(seeded);
});
+ it("seeds the team's default per-model budget when the member has no per-model override", () => {
+ const teamDefault = { "gpt-4o": { max_budget: 10, budget_duration: "30d" } };
+ const ownRowWithoutModelCaps = {
+ ...createMockTeamData().team_memberships[0].litellm_budget_table,
+ model_max_budget: {},
+ };
+ const memberOverride = { "gpt-4o": { max_budget: 2.5, budget_duration: "7d" } };
+ const ownRowWithModelCaps = { ...ownRowWithoutModelCaps, model_max_budget: memberOverride };
+
+ expect(
+ seedMemberBudgetFields({ user_id: "u", role: "user" }, ownRowWithoutModelCaps, teamDefault).model_max_budget,
+ ).toBe(teamDefault);
+ expect(seedMemberBudgetFields({ user_id: "u", role: "user" }, undefined, teamDefault).model_max_budget).toBe(
+ teamDefault,
+ );
+ expect(
+ seedMemberBudgetFields({ user_id: "u", role: "user" }, ownRowWithModelCaps, teamDefault).model_max_budget,
+ ).toBe(memberOverride);
+ });
+
it("seeds null temporary budget fields for a member without a budget row", () => {
expect(seedMemberBudgetFields({ user_id: "user2@test.com", role: "admin" }, undefined)).toMatchObject({
max_budget_in_team: null,
diff --git a/ui/litellm-dashboard/src/components/team/TeamMemberTab.tsx b/ui/litellm-dashboard/src/components/team/TeamMemberTab.tsx
index 6778b40e93c..f50c47dd12f 100644
--- a/ui/litellm-dashboard/src/components/team/TeamMemberTab.tsx
+++ b/ui/litellm-dashboard/src/components/team/TeamMemberTab.tsx
@@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { SimpleTooltip } from "@/components/ui/tooltip";
import MemberTable from "@/components/common_components/MemberTable";
+import type { StoredModelMaxBudget } from "@/components/key_team_helpers/modelMaxBudgetPayload";
import { Member } from "@/components/networking";
import { parseErrorMessage } from "@/components/shared/errorUtils";
import { DateCell, MoneyCell } from "@/components/shared/table_cells";
@@ -25,9 +26,13 @@ const BUDGET_SOURCE_LABELS: Record, stri
const formatBudget = (value: number | null): string =>
value === null ? "Unlimited" : `$${formatNumberWithCommas(value, 2)}`;
+const hasModelBudgets = (budget: StoredModelMaxBudget | null | undefined): budget is StoredModelMaxBudget =>
+ budget != null && Object.keys(budget).length > 0;
+
export const seedMemberBudgetFields = (
record: Member,
budget: TeamMembership["litellm_budget_table"] | undefined,
+ teamDefaultModelMaxBudget?: StoredModelMaxBudget | null,
): Member => ({
...record,
max_budget_in_team: budget?.max_budget ?? null,
@@ -37,6 +42,9 @@ export const seedMemberBudgetFields = (
allowed_models: budget?.allowed_models || [],
temp_budget_increase: budget?.temp_budget_increase ?? null,
temp_budget_expiry: budget?.temp_budget_expiry ?? null,
+ model_max_budget: hasModelBudgets(budget?.model_max_budget)
+ ? budget.model_max_budget
+ : teamDefaultModelMaxBudget ?? null,
});
interface TeamMemberTabProps {
@@ -305,7 +313,13 @@ export default function TeamMemberTab({
canEdit={canEditTeam}
onEdit={(record) => {
const membership = teamData.team_memberships.find((tm) => tm.user_id === record.user_id);
- setSelectedEditMember(seedMemberBudgetFields(record, membership?.litellm_budget_table));
+ setSelectedEditMember(
+ seedMemberBudgetFields(
+ record,
+ membership?.litellm_budget_table,
+ teamData.team_info.team_member_budget_table?.model_max_budget,
+ ),
+ );
setIsEditMemberModalVisible(true);
}}
onDelete={handleMemberDelete}
diff --git a/ui/litellm-dashboard/src/components/team/memberFormValues.ts b/ui/litellm-dashboard/src/components/team/memberFormValues.ts
index 77cf2dd3e43..df80e2dd9ac 100644
--- a/ui/litellm-dashboard/src/components/team/memberFormValues.ts
+++ b/ui/litellm-dashboard/src/components/team/memberFormValues.ts
@@ -1,8 +1,21 @@
-export type MemberFieldValue = string | number | null | undefined | string[];
+import {
+ entriesToModelMaxBudget,
+ modelMaxBudgetToEntries,
+ type ModelMaxBudget,
+} from "../key_team_helpers/ModelMaxBudgetEditor";
+
+export type MemberFieldValue = string | number | null | undefined | string[] | ModelMaxBudget;
export type MemberFormValues = Record;
-export type MemberFieldType = "input" | "select" | "numerical" | "multi-select" | "budget-duration" | "utc-datetime";
+export type MemberFieldType =
+ | "input"
+ | "select"
+ | "numerical"
+ | "multi-select"
+ | "budget-duration"
+ | "utc-datetime"
+ | "model-max-budget";
export interface MemberAdditionalField {
name: string;
@@ -12,6 +25,8 @@ export interface MemberAdditionalField {
step?: number;
min?: number;
placeholder?: string;
+ availableModels?: string[];
+ premiumUser?: boolean;
}
export interface MemberFieldsConfig {
@@ -33,6 +48,9 @@ export const TEMP_BUDGET_PAIR_MESSAGE = "Set both a temporary budget increase an
const isUnset = (value: MemberFieldValue): boolean => value === null || value === undefined || value === "";
+export const isModelMaxBudget = (value: MemberFieldValue): value is ModelMaxBudget =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
export const tempBudgetPairError = (values: MemberFormValues): "temp_budget_increase" | "temp_budget_expiry" | null => {
const increaseUnset = isUnset(values.temp_budget_increase);
const expiryUnset = isUnset(values.temp_budget_expiry);
@@ -66,6 +84,9 @@ export const buildMemberFormValues = (
allowed_models: initialData.allowed_models || [],
temp_budget_increase: initialData.temp_budget_increase ?? null,
temp_budget_expiry: initialData.temp_budget_expiry || null,
+ model_max_budget: isModelMaxBudget(initialData.model_max_budget)
+ ? entriesToModelMaxBudget(modelMaxBudgetToEntries(initialData.model_max_budget))
+ : {},
};
return pickFieldNames(config, seeded);
@@ -78,6 +99,8 @@ const emptyValueForType = (type: MemberFieldType | undefined): MemberFieldValue
switch (type) {
case "multi-select":
return [];
+ case "model-max-budget":
+ return {};
case "numerical":
case "budget-duration":
case "utc-datetime":
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index f36456628e5..731a92d8b98 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -16882,6 +16882,7 @@ export interface paths {
* - object_permission: Optional[LiteLLM_ObjectPermissionBase] - team-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "agents": ["agent_1", "agent_2"], "agent_access_groups": ["dev_group"]}. IF null or {} then no object permission.
* - team_member_budget: Optional[float] - The maximum budget allocated to an individual team member.
* - team_member_budget_duration: Optional[str] - The duration of the budget for the team member. Doc [here](https://docs.litellm.ai/docs/proxy/team_budgets)
+ * - team_member_model_max_budget: Optional[dict] - Per-model budgets shared by team members without an override.
* - team_member_rpm_limit: Optional[int] - The RPM (Requests Per Minute) limit for individual team members.
* - team_member_tpm_limit: Optional[int] - The TPM (Tokens Per Minute) limit for individual team members.
* - team_member_key_duration: Optional[str] - The duration for a team member's key. e.g. "1d", "1w", "1mo"
@@ -17111,6 +17112,7 @@ export interface paths {
* - object_permission: Optional[LiteLLM_ObjectPermissionBase] - team-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "agents": ["agent_1", "agent_2"], "agent_access_groups": ["dev_group"]}. IF null or {} then no object permission.
* - team_member_budget: Optional[float] - The maximum budget allocated to an individual team member.
* - team_member_budget_duration: Optional[str] - The duration of the budget for the team member. Doc [here](https://docs.litellm.ai/docs/proxy/team_budgets)
+ * - team_member_model_max_budget: Optional[dict] - Per-model budgets shared by team members without an override.
* - team_member_rpm_limit: Optional[int] - The RPM (Requests Per Minute) limit for individual team members.
* - team_member_tpm_limit: Optional[int] - The TPM (Tokens Per Minute) limit for individual team members.
* - team_member_key_duration: Optional[str] - The duration for a team member's key. e.g. "1d", "1w", "1mo"
@@ -38499,6 +38501,10 @@ export interface components {
team_member_budget_duration?: string | null;
/** Team Member Key Duration */
team_member_key_duration?: string | null;
+ /** Team Member Model Max Budget */
+ team_member_model_max_budget?: {
+ [key: string]: components["schemas"]["BudgetConfig"];
+ } | null;
/** Team Member Permissions */
team_member_permissions?: string[] | null;
/** Team Member Rpm Limit */
@@ -39584,6 +39590,10 @@ export interface components {
team_member_budget_duration?: string | null;
/** Team Member Key Duration */
team_member_key_duration?: string | null;
+ /** Team Member Model Max Budget */
+ team_member_model_max_budget?: {
+ [key: string]: components["schemas"]["BudgetConfig"];
+ } | null;
/** Team Member Rpm Limit */
team_member_rpm_limit?: number | null;
/** Team Member Tpm Limit */
@@ -45580,6 +45590,13 @@ export interface components {
budget_duration?: string | null;
/** Max Budget In Team */
max_budget_in_team?: number | null;
+ /**
+ * Model Max Budget
+ * @description Per-model spend caps for this team member, each with its own budget_duration. Overrides the team's default per-model member budget. Pass an empty dict to fall back to the team default.
+ */
+ model_max_budget?: {
+ [key: string]: components["schemas"]["BudgetConfig"];
+ } | null;
/** Role */
role?: ("admin" | "user") | null;
/**
@@ -45617,6 +45634,10 @@ export interface components {
budget_duration?: string | null;
/** Max Budget In Team */
max_budget_in_team?: number | null;
+ /** Model Max Budget */
+ model_max_budget?: {
+ [key: string]: components["schemas"]["BudgetConfig"];
+ } | null;
/** Rpm Limit */
rpm_limit?: number | null;
/** Team Id */
@@ -47559,6 +47580,10 @@ export interface components {
team_member_budget_duration?: string | null;
/** Team Member Key Duration */
team_member_key_duration?: string | null;
+ /** Team Member Model Max Budget */
+ team_member_model_max_budget?: {
+ [key: string]: components["schemas"]["BudgetConfig"];
+ } | null;
/** Team Member Rpm Limit */
team_member_rpm_limit?: number | null;
/** Team Member Tpm Limit */
From 12c36b054b2247b47eb9ccbc1aa7a3ae0cefe249 Mon Sep 17 00:00:00 2001
From: nate-berri
Date: Sat, 10 Oct 2026 13:33:58 -0700
Subject: [PATCH 07/40] refactor(constants): move AUTH_OBJECTS_TARGET into
litellm.constants (#45779)
* refactor(constants): move AUTH_OBJECTS_TARGET into litellm.constants
Part of LIT-9423
* fix(sdk): resolve litellm.proxy lazily on attribute access
The layer cleanup stopped import litellm from loading any proxy module, so litellm.proxy was no longer bound and litellm.proxy._types.X raised AttributeError. The module __getattr__ now imports litellm.proxy on first access, which keeps import litellm free of proxy._types and fixes the docs and code-quality checks on main
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
litellm/constants.py | 1 +
litellm/integrations/prometheus.py | 2 +-
litellm/proxy/common_utils/user_api_key_cache.py | 2 +-
3 files changed, 3 insertions(+), 2 deletions(-)
diff --git a/litellm/constants.py b/litellm/constants.py
index 8252e923ae5..a339fb76976 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -1969,6 +1969,7 @@ LITELLM_SETTINGS_SAFE_DB_OVERRIDES: Final = [
]
SPECIAL_LITELLM_AUTH_TOKEN: Final = ["ui-token"]
DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL = int(os.getenv("DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL", 60))
+AUTH_OBJECTS_TARGET: Final = "auth_objects"
DEFAULT_ACCESS_GROUP_CACHE_TTL: Final = int(os.getenv("DEFAULT_ACCESS_GROUP_CACHE_TTL", 600))
SPEND_LOG_KEY_METADATA_CACHE_TTL: Final = 600
SPEND_LOG_KEY_METADATA_MISS_CACHE_TTL: Final = 30
diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.py
index 8f4d1df2662..797c443e712 100644
--- a/litellm/integrations/prometheus.py
+++ b/litellm/integrations/prometheus.py
@@ -21,6 +21,7 @@ import litellm
from litellm._internal_context import with_service_target
from litellm._logging import print_verbose, verbose_logger
from litellm.constants import (
+ AUTH_OBJECTS_TARGET,
PROMETHEUS_OVERFLOW_SERIES_LABEL_VALUE,
PROXY_LLM_PROVIDER_FALLBACK,
PROXY_REJECTED_BEFORE_ROUTING_KEY,
@@ -53,7 +54,6 @@ from litellm.models.team import LiteLLM_TeamTable
from litellm.models.user import LiteLLM_UserTable
from litellm.models.verification_token import LiteLLM_DeletedVerificationToken
from litellm.proxy._types import UserAPIKeyAuth
-from litellm.proxy.common_utils.user_api_key_cache import AUTH_OBJECTS_TARGET
from litellm.repositories.base_repository import BaseRepository
from litellm.repositories.budget_repository import BudgetRepository
from litellm.repositories.organization_repository import OrganizationRepository
diff --git a/litellm/proxy/common_utils/user_api_key_cache.py b/litellm/proxy/common_utils/user_api_key_cache.py
index 8c830816207..e64fd755ef9 100644
--- a/litellm/proxy/common_utils/user_api_key_cache.py
+++ b/litellm/proxy/common_utils/user_api_key_cache.py
@@ -21,7 +21,7 @@ if TYPE_CHECKING:
T = TypeVar("T", bound=BaseModel)
-AUTH_OBJECTS_TARGET: Final = "auth_objects"
+from litellm.constants import AUTH_OBJECTS_TARGET as AUTH_OBJECTS_TARGET # noqa: E402, PLC0414 # public re-export
_HASHED_TOKEN_CACHE_KEY: Final = re.compile(r"[0-9a-f]{64}")
From 2374b0c398865e332f6b3b77f31a09ef707d4ed5 Mon Sep 17 00:00:00 2001
From: nate-berri
Date: Sat, 10 Oct 2026 13:34:39 -0700
Subject: [PATCH 08/40] refactor(types): annotate key request containers and
drop_blank_team_id (#45809)
* refactor(types): annotate key request containers and drop_blank_team_id
Part of LIT-9423
* fix(sdk): resolve litellm.proxy lazily on attribute access
The layer cleanup stopped import litellm from loading any proxy module, so litellm.proxy was no longer bound and litellm.proxy._types.X raised AttributeError. The module __getattr__ now imports litellm.proxy on first access, which keeps import litellm free of proxy._types and fixes the docs and code-quality checks on main
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
litellm/proxy/_types.py | 14 +++++++++-----
1 file changed, 9 insertions(+), 5 deletions(-)
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 7ac8b1f8538..9ee20c22cef 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -1243,8 +1243,8 @@ class KeyRequestBase(GenerateRequestBase):
enable_prompt_caching: bool | None = None
throttle_on_budget_exceeded: bool | None = None
enforced_params: list[str] | None = None
- allowed_routes: list | None = []
- allowed_passthrough_routes: list | None = None
+ allowed_routes: list[Any] | None = []
+ allowed_passthrough_routes: list[object] | None = None
denied_passthrough_routes: list[str] | None = None
allowed_vector_store_indexes: list[AllowedVectorStoreIndexItem] | None = None
rpm_limit_type: Literal["guaranteed_throughput", "best_effort_throughput", "dynamic"] | None = (
@@ -1333,13 +1333,17 @@ class GenerateKeyResponse(KeyRequestBase):
return values
+def _is_mapping(value: object) -> TypeIs[Mapping[object, object]]: # guard-ok: raw before-validator payload
+ return isinstance(value, Mapping)
+
+
class UpdateKeyRequest(KeyRequestBase):
# Note: the defaults of all Params here MUST BE NONE
# else they will get overwritten
duration: str | None = None
spend: float | None = None
soft_budget: float | None = None
- metadata: dict | None = None
+ metadata: dict[Any, Any] | None = None
temp_budget_increase: float | None = None
temp_budget_expiry: datetime | None = None
auto_rotate: bool | None = None
@@ -1354,7 +1358,7 @@ class UpdateKeyRequest(KeyRequestBase):
@model_validator(mode="before")
@classmethod
def drop_blank_team_id(cls, values: object) -> object:
- if isinstance(values, Mapping) and values.get("team_id") == "":
+ if _is_mapping(values) and values.get("team_id") == "":
return MappingProxyType({k: v for k, v in values.items() if k != "team_id"})
return values
@@ -1385,7 +1389,7 @@ class RegenerateKeyRequest(GenerateKeyRequest):
new_key: str | None = None
duration: str | None = None
spend: float | None = None
- metadata: dict | None = None
+ metadata: dict[Any, Any] | None = None
new_master_key: str | None = None
grace_period: str | None = None # Duration to keep old key valid (e.g. "24h", "2d"); None = immediate revoke
From 981710fab81c5551c09717b66da57ed41504885a Mon Sep 17 00:00:00 2001
From: nate-berri
Date: Sat, 10 Oct 2026 13:35:07 -0700
Subject: [PATCH 09/40] refactor(types): move GenerateRequestBase and
LiteLLM_ObjectPermissionBase into
litellm.types.proxy.management_endpoints.request_base (#45802)
* refactor(types): move LitellmUserRoles and KeyManagementRoutes into litellm.types.proxy.auth.user_roles
Part of LIT-9423
* refactor(types): annotate GenerateRequestBase containers and check_max_budget
Part of LIT-9423
* refactor(types): move GenerateRequestBase and LiteLLM_ObjectPermissionBase into litellm.types.proxy.management_endpoints.request_base
Part of LIT-9423
* fix(types): restore main's _types.py content alongside the request_base move
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix(sdk): resolve litellm.proxy lazily on attribute access
The layer cleanup stopped import litellm from loading any proxy module, so litellm.proxy was no longer bound and litellm.proxy._types.X raised AttributeError. The module __getattr__ now imports litellm.proxy on first access, which keeps import litellm free of proxy._types and fixes the docs and code-quality checks on main
* style(types): merge request_base re-exports into one import block
Part of LIT-9423
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
litellm/proxy/_types.py | 67 ++-----------------
.../management_endpoints/request_base.py | 67 +++++++++++++++++++
2 files changed, 73 insertions(+), 61 deletions(-)
create mode 100644 litellm/types/proxy/management_endpoints/request_base.py
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 9ee20c22cef..0715a4cae97 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -1159,71 +1159,16 @@ class ModelParams(LiteLLMPydanticObjectBase):
return values
-class LiteLLM_ObjectPermissionBase(LiteLLMPydanticObjectBase):
- mcp_servers: list[str] | None = None
- mcp_access_groups: list[str] | None = None
- mcp_tool_permissions: dict[str, list[str]] | None = None
- mcp_toolsets: list[str] | None = None
- blocked_tools: list[str] | None = None
- vector_stores: list[str] | None = None
- agents: list[str] | None = None
- agent_access_groups: list[str] | None = None
- models: list[str] | None = None
- search_tools: list[str] | None = None
- mcp_tool_search_enabled: bool | None = None
- skills: list[str] | None = None
-
-
from litellm.models.team import BudgetLimitEntry as BudgetLimitEntry # noqa: E402
from litellm.types.object_permission import ( # noqa: E402
ObjectPermissionDict as ObjectPermissionDict,
)
-
-
-class GenerateRequestBase(LiteLLMPydanticObjectBase):
- """
- Overlapping schema between key and user generate/update requests
- """
-
- key_alias: str | None = None
- duration: str | None = None
- models: list[Any] | None = []
- spend: float | None = 0
- max_budget: float | None = None
- user_id: str | None = None
- team_id: str | None = None
- agent_id: str | None = None
- max_parallel_requests: int | None = None
- metadata: dict[Any, Any] | None = {}
- tpm_limit: int | None = None
- rpm_limit: int | None = None
-
- budget_duration: str | None = None
- budget_limits: list[BudgetLimitEntry] | None = None # multiple concurrent budget windows
- allowed_cache_controls: list[object] | None = []
- config: dict[object, object] | None = {}
- permissions: dict[object, object] | None = {}
- model_max_budget: dict[object, object] | None = {} # {"gpt-4": 5.0, "gpt-3.5-turbo": 5.0}, defaults to {}
- budget_fallbacks: dict[str, list[str]] | None = None
-
- model_config = ConfigDict(protected_namespaces=())
- model_rpm_limit: dict[object, object] | None = None
- model_tpm_limit: dict[object, object] | None = None
- mcp_rpm_limit: dict[str, int] | None = None
- tag_rpm_limit: dict[str, int] | None = None
- guardrails: list[str] | None = None
- policies: list[str] | None = None
- prompts: list[str] | None = None
- blocked: bool | None = None
- aliases: dict[object, object] | None = {}
- object_permission: LiteLLM_ObjectPermissionBase | None = None
-
- @field_validator("max_budget", mode="before")
- @classmethod
- def check_max_budget(cls, v: object) -> object:
- if v == "":
- return None
- return v
+from litellm.types.proxy.management_endpoints.request_base import ( # noqa: E402 # re-export after the definitions above
+ GenerateRequestBase as GenerateRequestBase, # noqa: PLC0414 # public re-export
+)
+from litellm.types.proxy.management_endpoints.request_base import ( # noqa: E402 # re-export after the definitions above
+ LiteLLM_ObjectPermissionBase as LiteLLM_ObjectPermissionBase, # noqa: PLC0414 # public re-export
+)
class AllowedVectorStoreIndexItem(LiteLLMPydanticObjectBase):
diff --git a/litellm/types/proxy/management_endpoints/request_base.py b/litellm/types/proxy/management_endpoints/request_base.py
new file mode 100644
index 00000000000..6b4a76e0132
--- /dev/null
+++ b/litellm/types/proxy/management_endpoints/request_base.py
@@ -0,0 +1,67 @@
+from typing import Any # noqa: TID251 # metadata and models stay Any so existing callers keep type-checking
+
+from pydantic import ConfigDict, field_validator
+
+from litellm.models.team import BudgetLimitEntry
+from litellm.types.utils import LiteLLMPydanticObjectBase
+
+
+class LiteLLM_ObjectPermissionBase(LiteLLMPydanticObjectBase):
+ mcp_servers: list[str] | None = None
+ mcp_access_groups: list[str] | None = None
+ mcp_tool_permissions: dict[str, list[str]] | None = None
+ mcp_toolsets: list[str] | None = None
+ blocked_tools: list[str] | None = None
+ vector_stores: list[str] | None = None
+ agents: list[str] | None = None
+ agent_access_groups: list[str] | None = None
+ models: list[str] | None = None
+ search_tools: list[str] | None = None
+ mcp_tool_search_enabled: bool | None = None
+ skills: list[str] | None = None
+
+
+class GenerateRequestBase(LiteLLMPydanticObjectBase):
+ """
+ Overlapping schema between key and user generate/update requests
+ """
+
+ key_alias: str | None = None
+ duration: str | None = None
+ models: list[Any] | None = []
+ spend: float | None = 0
+ max_budget: float | None = None
+ user_id: str | None = None
+ team_id: str | None = None
+ agent_id: str | None = None
+ max_parallel_requests: int | None = None
+ metadata: dict[Any, Any] | None = {}
+ tpm_limit: int | None = None
+ rpm_limit: int | None = None
+
+ budget_duration: str | None = None
+ budget_limits: list[BudgetLimitEntry] | None = None # multiple concurrent budget windows
+ allowed_cache_controls: list[object] | None = []
+ config: dict[object, object] | None = {}
+ permissions: dict[object, object] | None = {}
+ model_max_budget: dict[object, object] | None = {} # {"gpt-4": 5.0, "gpt-3.5-turbo": 5.0}, defaults to {}
+ budget_fallbacks: dict[str, list[str]] | None = None
+
+ model_config = ConfigDict(protected_namespaces=())
+ model_rpm_limit: dict[object, object] | None = None
+ model_tpm_limit: dict[object, object] | None = None
+ mcp_rpm_limit: dict[str, int] | None = None
+ tag_rpm_limit: dict[str, int] | None = None
+ guardrails: list[str] | None = None
+ policies: list[str] | None = None
+ prompts: list[str] | None = None
+ blocked: bool | None = None
+ aliases: dict[object, object] | None = {}
+ object_permission: LiteLLM_ObjectPermissionBase | None = None
+
+ @field_validator("max_budget", mode="before")
+ @classmethod
+ def check_max_budget(cls, v: object) -> object:
+ if v == "":
+ return None
+ return v
From f58c86f1d711ca70f7202ee493f1bd8c0d5fe5ad Mon Sep 17 00:00:00 2001
From: yuneng-jiang
Date: Sat, 10 Oct 2026 13:35:11 -0700
Subject: [PATCH 10/40] perf(ci): use native timing splits with bounded
integration concurrency (#45837)
* perf(ci): use native timing splits with bounded integration concurrency
* fix(ci): make integration parallelism opt in
---
.circleci/config.yml | 123 +++++------
.circleci/scripts/run_integration.sh | 21 +-
tests/integration/README.md | 14 +-
tests/integration/_support/ordering.py | 83 --------
tests/integration/_support/sharding.py | 17 --
tests/integration/conftest.py | 54 ++---
.../database/test_harness_lifecycle.py | 194 +++++++++++++-----
tests/integration/run.py | 12 +-
.../unit/integration_support/test_ordering.py | 115 -----------
.../unit/integration_support/test_sharding.py | 58 +++---
10 files changed, 283 insertions(+), 408 deletions(-)
diff --git a/.circleci/config.yml b/.circleci/config.yml
index b22c2b4b7a9..bfca8310c0e 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -2747,33 +2747,6 @@ jobs:
- store_test_results:
path: test-results/provider-replay-harness
- integration_timing_snapshot:
- machine:
- image: ubuntu-2204:2024.04.1
- resource_class: medium
- working_directory: ~/project
- steps:
- - checkout
- - run:
- name: Prepare optional integration timing snapshots
- command: mkdir -p /tmp/integration-timings/{extensions,providers,mcp}
- - restore_cache:
- keys:
- - integration-timings-v1-extensions-{{ .Branch }}-{{ .Revision }}
- - integration-timings-v1-extensions-{{ .Branch }}-
- - restore_cache:
- keys:
- - integration-timings-v1-providers-{{ .Branch }}-{{ .Revision }}
- - integration-timings-v1-providers-{{ .Branch }}-
- - restore_cache:
- keys:
- - integration-timings-v1-mcp-{{ .Branch }}-{{ .Revision }}
- - integration-timings-v1-mcp-{{ .Branch }}-
- - persist_to_workspace:
- root: /tmp
- paths:
- - integration-timings
-
integration_contracts:
parameters:
suite:
@@ -2796,15 +2769,6 @@ jobs:
parallelism: << parameters.parallelism >>
steps:
- setup_litellm_test_deps
- - when:
- condition:
- or:
- - equal: [extensions, << parameters.suite >>]
- - equal: [providers, << parameters.suite >>]
- - equal: [mcp, << parameters.suite >>]
- steps:
- - attach_workspace:
- at: /tmp
- when:
condition:
equal: [browser, << parameters.suite >>]
@@ -2850,24 +2814,26 @@ jobs:
test -z "$(docker ps -aq --filter name=postgres-db --filter name=redis-cache)"
- when:
condition:
- or:
- - equal: [extensions, << parameters.suite >>]
- - equal: [providers, << parameters.suite >>]
- - equal: [mcp, << parameters.suite >>]
+ not:
+ equal: [1, << parameters.parallelism >>]
steps:
- run:
name: Prepare this shard's execution record
command: |
- mkdir -p "/tmp/integration-shards/<< parameters.suite >>/$CIRCLE_NODE_INDEX"
- cp test-results/integration-<< parameters.suite >>/execution.json "/tmp/integration-shards/<< parameters.suite >>/$CIRCLE_NODE_INDEX/execution.json"
+ results="test-results/integration-<< parameters.suite >>"
+ if [ "<< parameters.mode >>" = replica ]; then
+ results="$results-replica"
+ fi
+ mkdir -p "/tmp/integration-shards/<< parameters.suite >>-<< parameters.mode >>/$CIRCLE_NODE_INDEX"
+ cp "$results/execution.json" "/tmp/integration-shards/<< parameters.suite >>-<< parameters.mode >>/$CIRCLE_NODE_INDEX/execution.json"
if [ "<< parameters.suite >>" = mcp ]; then
- mkdir -p "/tmp/integration-shards/mcp/$CIRCLE_NODE_INDEX/coverage"
- cp test-results/integration-mcp/coverage/data "/tmp/integration-shards/mcp/$CIRCLE_NODE_INDEX/coverage/data.$CIRCLE_NODE_INDEX"
+ mkdir -p "/tmp/integration-shards/mcp-standard/$CIRCLE_NODE_INDEX/coverage"
+ cp test-results/integration-mcp/coverage/data "/tmp/integration-shards/mcp-standard/$CIRCLE_NODE_INDEX/coverage/data.$CIRCLE_NODE_INDEX"
fi
- persist_to_workspace:
root: /tmp/integration-shards
paths:
- - << parameters.suite >>
+ - << parameters.suite >>-<< parameters.mode >>
- store_test_results:
path: test-results
- store_artifacts:
@@ -2877,7 +2843,11 @@ jobs:
parameters:
suite:
type: enum
- enum: [extensions, providers, mcp]
+ enum: [management, accounting, database, extensions, providers, mcp]
+ mode:
+ type: enum
+ enum: [standard, replica]
+ default: standard
shards:
type: integer
machine:
@@ -2891,12 +2861,8 @@ jobs:
- run:
name: Verify every << parameters.suite >> case ran exactly once
command: |
- .venv/bin/python -m tests.integration._support.sharding /tmp/integration-shards/<< parameters.suite >> \
- --shards << parameters.shards >> --timings-output /tmp/integration-timings/<< parameters.suite >>/timings.json
- - save_cache:
- key: integration-timings-v1-<< parameters.suite >>-{{ .Branch }}-{{ .Revision }}
- paths:
- - /tmp/integration-timings/<< parameters.suite >>
+ .venv/bin/python -m tests.integration._support.sharding /tmp/integration-shards/<< parameters.suite >>-<< parameters.mode >> \
+ --shards << parameters.shards >>
- when:
condition:
equal: [mcp, << parameters.suite >>]
@@ -2906,7 +2872,7 @@ jobs:
command: |
mkdir -p test-results/integration-mcp/coverage
export COVERAGE_FILE="$PWD/test-results/integration-mcp/coverage/data"
- .venv/bin/python -m coverage combine --rcfile=tests/integration/mcp_coverage.toml /tmp/integration-shards/mcp/*/coverage
+ .venv/bin/python -m coverage combine --rcfile=tests/integration/mcp_coverage.toml /tmp/integration-shards/mcp-standard/*/coverage
.venv/bin/python -m coverage report --rcfile=tests/integration/mcp_coverage.toml > test-results/integration-mcp/coverage/coverage.txt
.venv/bin/python -m coverage html --rcfile=tests/integration/mcp_coverage.toml -d test-results/integration-mcp/coverage/html
- store_artifacts:
@@ -3205,48 +3171,59 @@ workflows:
- not:
equal: ["", << pipeline.parameters.routing_parity_base >>]
jobs:
- - integration_timing_snapshot:
- name: integration-timing-snapshot
- integration_contracts:
name: integration-<< matrix.suite >>
matrix:
parameters:
suite: [sdk, cost, browser]
+ parallelism: 1
- integration_contracts:
name: integration-security
suite: security
+ parallelism: 1
resource_class: xlarge
- integration_contracts:
name: integration-management
suite: management
- parallelism: 8
+ parallelism: 4
+ - integration_shard_coverage:
+ name: integration-management-coverage
+ suite: management
+ shards: 4
+ requires: [integration-management]
- integration_contracts:
name: integration-accounting
suite: accounting
- parallelism: 8
+ parallelism: 4
+ - integration_shard_coverage:
+ name: integration-accounting-coverage
+ suite: accounting
+ shards: 4
+ requires: [integration-accounting]
- integration_contracts:
name: integration-providers
suite: providers
- parallelism: 16
- requires:
- - integration-timing-snapshot
+ parallelism: 8
- integration_shard_coverage:
name: integration-providers-coverage
suite: providers
- shards: 16
+ shards: 8
requires:
- integration-providers
- integration_contracts:
name: integration-database
suite: database
parallelism: 2
+ - integration_shard_coverage:
+ name: integration-database-coverage
+ suite: database
+ shards: 2
+ requires: [integration-database]
- integration_contracts:
name: integration-mcp
suite: mcp
resource_class: xlarge
parallelism: 2
- requires:
- - integration-timing-snapshot
- integration_shard_coverage:
name: integration-mcp-coverage
suite: mcp
@@ -3256,25 +3233,35 @@ workflows:
- integration_contracts:
name: integration-extensions
suite: extensions
- parallelism: 32
- requires:
- - integration-timing-snapshot
+ parallelism: 8
- integration_shard_coverage:
name: integration-extensions-coverage
suite: extensions
- shards: 32
+ shards: 8
requires:
- integration-extensions
- integration_contracts:
name: integration-management-replica
suite: management
mode: replica
- parallelism: 8
+ parallelism: 4
+ - integration_shard_coverage:
+ name: integration-management-replica-coverage
+ suite: management
+ mode: replica
+ shards: 4
+ requires: [integration-management-replica]
- integration_contracts:
name: integration-database-replica
suite: database
mode: replica
parallelism: 2
+ - integration_shard_coverage:
+ name: integration-database-replica-coverage
+ suite: database
+ mode: replica
+ shards: 2
+ requires: [integration-database-replica]
- postgres_suite:
name: proxy-behavior
test_path: tests/proxy_behavior
diff --git a/.circleci/scripts/run_integration.sh b/.circleci/scripts/run_integration.sh
index 4bdef5eb23b..28d1fba68c7 100644
--- a/.circleci/scripts/run_integration.sh
+++ b/.circleci/scripts/run_integration.sh
@@ -216,18 +216,11 @@ if [ "$suite" = browser ]; then
exit 0
fi
-node_files=()
-case_shards=1
-case_shard_index=0
-if [ "$suite" = extensions ] || [ "$suite" = providers ] || [ "$suite" = mcp ]; then
- case_shards="${CIRCLE_NODE_TOTAL:-1}"
- case_shard_index="${CIRCLE_NODE_INDEX:-0}"
-elif [ "${CIRCLE_NODE_TOTAL:-1}" -gt 1 ]; then
- split="$(.venv/bin/python tests/integration/run.py "$suite" --list \
- | circleci tests split --split-by=timings --timings-type=filename)"
- read -r -a node_files <<< "$(printf '%s' "$split" | tr '\n' ' ')"
- test "${#node_files[@]}" -gt 0
- printf '%s\n' "${node_files[@]}" > "$results/node-files.txt"
+shard_arguments=()
+if [ "${CIRCLE_NODE_TOTAL:-1}" -gt 1 ]; then
+ .venv/bin/python tests/integration/run.py "$suite" --list \
+ | circleci tests split --split-by=timings --timings-type=filename > "$results/node-files.txt"
+ shard_arguments=(--shard-files "$results/node-files.txt")
fi
env -i PATH="$PATH" HOME="$HOME" PYTHONPATH="$PYTHONPATH" \
@@ -240,13 +233,13 @@ env -i PATH="$PATH" HOME="$HOME" PYTHONPATH="$PYTHONPATH" \
LITELLM_LICENSE="${LITELLM_LICENSE:-}" \
INTEGRATION_SEED="$INTEGRATION_SEED" \
INTEGRATION_ORDER_SEED="$INTEGRATION_ORDER_SEED" \
- INTEGRATION_CASE_SHARDS="$case_shards" INTEGRATION_CASE_SHARD_INDEX="$case_shard_index" \
+ INTEGRATION_CASE_SHARDS="${CIRCLE_NODE_TOTAL:-1}" INTEGRATION_CASE_SHARD_INDEX="${CIRCLE_NODE_INDEX:-0}" \
LITELLM_LOCAL_MODEL_COST_MAP=True AWS_EC2_METADATA_DISABLED=true DO_NOT_TRACK=1 \
INTEGRATION_PROXY_DATABASE_URL="$INTEGRATION_PROXY_DATABASE_URL" \
INTEGRATION_PROXY_READ_REPLICA_URL="$INTEGRATION_PROXY_READ_REPLICA_URL" \
INTEGRATION_ROUTING="$INTEGRATION_ROUTING" \
.venv/bin/python tests/integration/run.py "$suite" --results "$results" \
- --timings "/tmp/integration-timings/$suite/timings.json" "${node_files[@]}"
+ "${shard_arguments[@]}"
if [ "${INTEGRATION_COVERAGE:-0}" = 1 ]; then
for covered_pid in "$proxy_pid" "$peer_pid"; do
diff --git a/tests/integration/README.md b/tests/integration/README.md
index 8734e2e6237..3bbfc8e386e 100644
--- a/tests/integration/README.md
+++ b/tests/integration/README.md
@@ -10,7 +10,15 @@ Use `tests/integration/run.py management`, `accounting`, `database`, `providers`
Management also requires `INTEGRATION_PEER_URL`, `REDIS_HOST` and `REDIS_PORT`. CircleCI starts two directly addressed proxy processes sharing only that job's stores. The test-only CLI wrapper supplies enterprise route entitlement, following the existing behavior suite's convention. It does not qualify license validation; run it with one worker and no reload
-The generated lifecycle models use 20 examples, eight steps, generation and shrinking, with isolated resources per example. HTTP operation caps include generation and shrinking and exempt cleanup. Local qualification defaults to seed 4106601 and canonical order; CircleCI derives exploration and ordering seeds from the checked-out revision and workflow ID. The ordering seed shuffles files, scoped fixture configurations and cases within each configuration. Cases sharing a module or class fixture parameter stay together, so shuffling does not repeatedly rebuild the same configuration. Case partitions also group tests using the same unparametrized module or class fixtures. These groups split when they exceed a node's estimated time budget, limiting repeated setup without placing an oversized group on one node. A successful shard census saves every case's setup, call and teardown duration. The next CircleCI run restores that shared snapshot and balances measured cost. Missing or invalid timing data falls back to equal case weights. New cases receive the median known cost, and stale case identities cannot select or omit tests. Use `--timings ` to reproduce a measured partition Use `--seed` and `--order-seed` to reproduce a run. Actual installed Hypothesis version, settings, seeds and collected order are written beside the execution manifest
+The generated lifecycle models use 20 examples, eight steps, generation and shrinking, with isolated resources per example. HTTP operation caps include generation and shrinking and exempt cleanup. Local qualification defaults to seed 4106601 and canonical order; CircleCI derives exploration and ordering seeds from the checked-out revision and workflow ID. The ordering seed shuffles files, scoped fixture configurations and cases within each configuration. Cases sharing a module or class fixture parameter stay together, so shuffling does not repeatedly rebuild the same configuration
+
+CircleCI uses its built-in `circleci tests split --split-by=timings --timings-type=filename` to assign test files using the uploaded JUnit timings. Each file stays on one node, preserving its module and parametrized fixtures. Jobs default to one node. Parallelism should use the smallest node count that keeps the complete job, including setup and cleanup, within twenty minutes. A group that already finishes within that target on one node stays on one node. Management, accounting and management replica currently use four nodes. Providers and extensions use eight nodes; database and MCP use two, and fast suites use one. No job is configured above eight nodes. A single slow file can still determine a suite's runtime; split such a file along independent fixture boundaries rather than adding more nodes
+
+Every node collects the same candidate files before applying CircleCI's assigned file list. Its execution record retains the candidate inventory and the selected, passed and skipped cases. An empty assigned file list produces an empty shard, not a full-suite fallback. Every parallel group has a dependent census job that rejects an empty candidate inventory, missing shards, omitted cases and duplicate execution. Standard and replica runs keep separate workspace records
+
+Future change-based selection belongs before timing splitting. Pass the selected group files or node IDs to `run.py --list` to list their files, then give those filenames to CircleCI. Run the same candidate selection on every node with `--shard-files --shards --shard-index `. The census compares execution with the candidate inventory, while full-suite runs remain the default. CircleCI determines scheduling from timing history; timing data never selects or omits candidates. Use `--seed` and `--order-seed` to reproduce test generation and order. The installed Hypothesis version, settings, seeds and collected order are recorded beside the execution manifest
+
+A future selector must explicitly skip a group when no candidates apply; omitting positional candidates means the full group. Keep full runs on the default branch and scheduled workflows, and select the full affected groups when shared fixtures, CI configuration or an unknown dependency changes
Reuse the existing canned provider handlers through `_support/upstream.py`. It rejects internal request fields and exposes actual received requests for independent assertions. Register every created resource for cleanup immediately, keep expected values independent of production calculations, and assert readback plus the runtime effect of a change
@@ -34,7 +42,7 @@ Accounting cases compare persisted input and output cost components against lite
Provider contracts exercise actual TCP requests with synthetic credentials and local protocol peers. The S3 verifier uses independently implemented equations, a published known-answer vector, a fixed signing clock and deliberately invalid signed requests. Bedrock cases clear ambient AWS credential sources and check the literal model path, loaded role references, STS requests and bearer-only behavior
-CircleCI runs providers on 16 parallel nodes, partitioning cases while keeping scoped fixture configurations together. Each node owns its services. The dependent providers coverage job verifies all 16 execution records against the full case inventory and rejects missing, duplicate, failed or incomplete execution. Use `--shards 16 --shard-index ` to reproduce a node locally
+CircleCI runs providers on eight isolated nodes using its file timing splitter. Each node owns its services. The dependent providers coverage job verifies all eight execution records against the candidate case inventory and rejects missing, duplicate, failed or incomplete execution. The node's assigned filenames are saved in `node-files.txt` beside its execution record
Streaming checks send real HTTP transfer chunks, including one-byte partitions, fragmented tools, incomplete transfers and a cancellation barrier. They assert meaningful text, tool arguments, final usage and persisted cost. The Redis recovery case owns a separate database and Redis process, uses the supported one-second circuit-breaker recovery setting, waits for the real subscriber and verifies response data in Redis after restart. CircleCI reuses its existing Redis image for that extra process; it never pulls an image during tests
@@ -42,7 +50,7 @@ The `messages_endpoint/` directory holds `/v1/messages` endpoint contracts: nati
The sdk shard exercises the SDK's own HTTP clients against local protocol peers with no gateway in the path, so a case here fails only when the client library or its wire behavior changes. The HTTP/2 case runs a hypercorn TLS peer offering h2 and http/1.1 over ALPN, drives the sync and async httpx handlers at it with `LITELLM_HTTP2` off and on, and asserts the version both the client and the peer observed on the wire. Put a test here only when it needs no proxy or database. CircleCI starts a local Redis for this shard like the others, so SDK-side caching cases that need a real Redis server belong here too; a case that reaches the gateway belongs in one of the other shards
-The extensions shard uses the built-in generic callback and guardrail transports. It checks callback correlation and credential exclusion, guardrail rewriting and denial, retained OpenAI consumers and A2A wire versions. CircleCI runs it on 32 parallel large nodes. Each node starts its own database, Redis, upstream and proxy and runs its share of cases serially. The runner assigns cases deterministically by estimated duration, keeping scoped fixture configurations together. Each node records the full collection inventory and its selected, passed and skipped nodes. The dependent coverage job rejects missing shards, differing inventories, omitted or duplicate cases and incomplete execution. Use `--shards 32 --shard-index ` to reproduce a node locally. More parallel nodes increase setup overhead and concurrent machine use. Tests keep the isolation of a serial run; they still must not assume a particular set of sibling files. `run.py --list` prints a group's files and `run.py ...` runs a subset of them
+The extensions shard uses the built-in generic callback and guardrail transports. It checks callback correlation and credential exclusion, guardrail rewriting and denial, retained OpenAI consumers and A2A wire versions. CircleCI runs it on eight parallel large nodes using its file timing splitter. Each node starts its own database, Redis, upstream and proxy and runs its assigned files serially. The dependent coverage job verifies all eight execution records against the candidate case inventory. Tests must not assume a particular set of sibling files
The security shard uses four pytest workers on an xlarge machine, each with a private database and Redis. Route sweeps use a new HTTP client for every call and share only the TLS verification context, so authentication and response cookies cannot cross callers. The canary rig supplies owned OpenAI and Anthropic endpoints and synthetic credentials and rejects attempted external egress
diff --git a/tests/integration/_support/ordering.py b/tests/integration/_support/ordering.py
index 7dbc85396ff..fc10c372a93 100644
--- a/tests/integration/_support/ordering.py
+++ b/tests/integration/_support/ordering.py
@@ -2,39 +2,12 @@ from __future__ import annotations
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
-from functools import reduce
from itertools import chain, groupby
-from math import ceil, isfinite
-from statistics import median
from types import MappingProxyType
from typing import Final
import pytest
from _pytest.python import get_direct_param_fixture_func
-from pydantic import BaseModel, ConfigDict, Field, FiniteFloat, TypeAdapter, ValidationError
-
-EMPTY_DURATIONS: Final[Mapping[str, float]] = MappingProxyType({})
-
-
-class CaseTiming(BaseModel):
- model_config = ConfigDict(frozen=True, strict=True)
-
- nodeid: str = Field(min_length=1)
- seconds: FiniteFloat = Field(ge=0)
-
-
-TIMINGS: Final = TypeAdapter(tuple[CaseTiming, ...])
-
-
-def parse_timings(content: str) -> Mapping[str, float]:
- try:
- values: Final = TIMINGS.validate_json(content)
- except ValidationError:
- return EMPTY_DURATIONS
- durations: Final = {value.nodeid: max(value.seconds, 0.001) for value in values}
- if len(durations) != len(values) or not isfinite(sum(durations.values())):
- return EMPTY_DURATIONS
- return MappingProxyType(durations)
@dataclass(frozen=True, slots=True)
@@ -120,59 +93,3 @@ def _file_groups(cases: Iterable[CollectedCase]) -> tuple[tuple[str, str], ...]:
def fixture_groups(cases: tuple[CollectedCase, ...]) -> Mapping[str, str]:
files: Final = groupby(sorted(cases, key=_file), key=_file)
return MappingProxyType(dict(chain.from_iterable(_file_groups(members) for _, members in files)))
-
-
-def _allocate(
- shards: tuple[tuple[str, ...], ...], group: tuple[str, ...], durations: Mapping[str, float]
-) -> tuple[tuple[str, ...], ...]:
- index: Final = min(
- range(len(shards)),
- key=lambda candidate: (sum(durations[nodeid] for nodeid in shards[candidate]), len(shards[candidate])),
- )
- return tuple((*shard, *group) if candidate == index else shard for candidate, shard in enumerate(shards))
-
-
-def _add_case(
- groups: tuple[tuple[str, ...], ...], case: CollectedCase, maximum: float, durations: Mapping[str, float]
-) -> tuple[tuple[str, ...], ...]:
- if not groups:
- return ((case.nodeid,),)
- if sum(durations[nodeid] for nodeid in groups[-1]) + durations[case.nodeid] > maximum:
- return (*groups, (case.nodeid,))
- return (*groups[:-1], (*groups[-1], case.nodeid))
-
-
-def _partition_group(
- cases: Iterable[CollectedCase], maximum: float, durations: Mapping[str, float]
-) -> tuple[tuple[str, ...], ...]:
- members: Final = tuple(sorted(cases, key=lambda case: case.nodeid))
- nodeids: Final = tuple(case.nodeid for case in members)
- if members[0].parameters:
- return (nodeids,)
- return reduce(lambda groups, case: _add_case(groups, case, maximum, durations), members, ())
-
-
-def case_shards(
- cases: tuple[CollectedCase, ...], count: int, durations: Mapping[str, float] = EMPTY_DURATIONS
-) -> tuple[frozenset[str], ...]:
- if count < 1:
- raise ValueError("Integration shard count must be positive")
- groups: Final = fixture_groups(cases)
- known: Final = tuple(durations[case.nodeid] for case in cases if case.nodeid in durations)
- default: Final = max(float(median(known)), 0.001) if known else 1.0
- weights: Final = MappingProxyType({case.nodeid: max(durations.get(case.nodeid, default), 0.001) for case in cases})
-
- def key(case: CollectedCase) -> str:
- return groups[case.nodeid] or case.nodeid
-
- maximum: Final = sum(weights.values()) / count if known else float(max(1, ceil(len(cases) / count)))
- members: Final = tuple(
- chain.from_iterable(
- _partition_group(group, maximum, weights) for _, group in groupby(sorted(cases, key=key), key=key)
- )
- )
- ordered: Final = tuple(sorted(members, key=lambda group: (-sum(weights[nodeid] for nodeid in group), group[0])))
- allocation: Final = reduce(
- lambda shards, group: _allocate(shards, group, weights), ordered, tuple(() for _ in range(count))
- )
- return tuple(frozenset(shard) for shard in allocation)
diff --git a/tests/integration/_support/sharding.py b/tests/integration/_support/sharding.py
index 5267985ad17..661b9626e17 100644
--- a/tests/integration/_support/sharding.py
+++ b/tests/integration/_support/sharding.py
@@ -9,15 +9,12 @@ from typing import Final
from pydantic import BaseModel, ConfigDict, Field, ValidationError
-from tests.integration._support.ordering import TIMINGS, CaseTiming
-
class ShardingOptions(BaseModel):
model_config = ConfigDict(frozen=True)
directory: Path
shards: int = Field(gt=0)
- timings_output: Path | None = None
class ShardExecution(BaseModel):
@@ -31,16 +28,6 @@ class ShardExecution(BaseModel):
shard_index: int
complete: bool
exitstatus: int
- timings: tuple[CaseTiming, ...] = ()
-
-
-def merged_timings(executions: tuple[ShardExecution, ...]) -> tuple[CaseTiming, ...]:
- timings: Final = tuple(chain.from_iterable(execution.timings for execution in executions))
- measured: Final = Counter(timing.nodeid for timing in timings)
- selected: Final = Counter(chain.from_iterable(execution.collected for execution in executions))
- if measured != selected or any(amount != 1 for amount in measured.values()):
- return ()
- return tuple(sorted(timings, key=lambda timing: timing.nodeid))
def shard_errors(executions: tuple[ShardExecution, ...], count: int) -> tuple[str, ...]:
@@ -88,7 +75,6 @@ def main() -> int:
parser: Final = argparse.ArgumentParser()
parser.add_argument("directory", type=Path)
parser.add_argument("--shards", required=True, type=int)
- parser.add_argument("--timings-output", type=Path)
options: Final = ShardingOptions.model_validate(vars(parser.parse_args()))
paths: Final = tuple(sorted(options.directory.glob("*/execution.json")))
try:
@@ -100,9 +86,6 @@ def main() -> int:
if errors:
sys.stderr.write("\n".join(errors) + "\n")
return 1
- if options.timings_output is not None:
- options.timings_output.parent.mkdir(parents=True, exist_ok=True)
- options.timings_output.write_bytes(TIMINGS.dump_json(merged_timings(executions)))
sys.stdout.write(
f"Verified {len(executions[0].inventory)} integration cases across {options.shards} isolated shards\n"
)
diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py
index abb4a94c880..280a828e1d4 100644
--- a/tests/integration/conftest.py
+++ b/tests/integration/conftest.py
@@ -16,7 +16,7 @@ from redis import Redis
from tests.integration._support.client import Gateway, eventually, gateway_from_environment
from tests.integration._support.generation import LIFECYCLE_SETTINGS
from tests.integration._support.manifest import OWNED_DIRECTORIES
-from tests.integration._support.ordering import CaseTiming, case_shards, collected_case, fixture_groups, parse_timings
+from tests.integration._support.ordering import collected_case, fixture_groups
from tests.integration._support.provider import SharedProvider, shared_provider
from tests.integration._support.routing import RoutingPlugin
from tests.integration.run import GITHUB_FILES
@@ -25,7 +25,8 @@ COLLECTED: Final = pytest.StashKey[tuple[str, ...]]()
INVENTORY: Final = pytest.StashKey[tuple[str, ...]]()
REPORTS: Final = pytest.StashKey[list[pytest.TestReport]]()
WORKER_INVENTORY: Final = TypeAdapter(tuple[str, ...])
-TIMING_PATH: Final[TypeAdapter[Path | None]] = TypeAdapter(Path | None)
+SHARD_PATH: Final[TypeAdapter[Path | None]] = TypeAdapter(Path | None)
+SHARD_FILES: Final = pytest.StashKey[frozenset[str] | None]()
INTEGER_OPTION: Final = TypeAdapter(int)
@@ -48,13 +49,14 @@ def pytest_addoption(parser: pytest.Parser) -> None:
parser.addoption("--integration-order-seed", type=int, default=0)
parser.addoption("--integration-shard-count", type=int, default=1)
parser.addoption("--integration-shard-index", type=int, default=0)
- parser.addoption("--integration-timings", type=Path)
+ parser.addoption("--integration-shard-files", type=Path)
def pytest_configure(config: pytest.Config) -> None:
config.addinivalue_line("markers", "integration: owned real-service integration contracts")
config.addinivalue_line("markers", "covers(*ids): legacy contract IDs kept for existing tests, not enforced")
config.stash[REPORTS] = []
+ config.stash[SHARD_FILES] = _shard_files(SHARD_PATH.validate_python(config.getoption("integration_shard_files")))
config.pluginmanager.register(IntegrationReportPlugin(config))
if os.environ.get("INTEGRATION_ROUTING"):
config.pluginmanager.register(RoutingPlugin(config))
@@ -100,13 +102,16 @@ def _order_key(seed: int, nodeid: str, group: str = "") -> tuple[bytes, bytes, b
return _digest(seed, nodeid.split("::", 1)[0]), _digest(seed, group or nodeid), _digest(seed, nodeid)
-def _timing_content(path: Path | None) -> str:
+def _shard_files(path: Path | None) -> frozenset[str] | None:
if path is None:
- return "[]"
+ return None
try:
- return path.read_text()
- except (OSError, UnicodeError):
- return "[]"
+ files: Final = tuple(path.read_text().splitlines())
+ except (OSError, UnicodeError) as error:
+ raise pytest.UsageError(f"Cannot read integration shard selection: {error}") from error
+ if len(frozenset(files)) != len(files) or any(not file for file in files):
+ raise pytest.UsageError("Integration shard selection contains duplicate or blank files")
+ return frozenset(files)
@pytest.hookimpl(wrapper=True)
@@ -134,13 +139,15 @@ def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item
index: Final = INTEGER_OPTION.validate_python(config.getoption("integration_shard_index"))
if count < 1 or not 0 <= index < count:
raise pytest.UsageError("Integration shard index must be within the positive shard count")
- if count > 1:
- timing_path: Final = TIMING_PATH.validate_python(config.getoption("integration_timings"))
- shards: Final = case_shards(
- tuple(collected_case(item) for item in owned), count, parse_timings(_timing_content(timing_path))
- )
- selected: Final = tuple(item for item in items if item not in owned or item.nodeid in shards[index])
- deselected: Final = tuple(item for item in owned if item.nodeid not in shards[index])
+ files: Final = config.stash[SHARD_FILES]
+ if count > 1 and files is None:
+ raise pytest.UsageError("Parallel integration runs require CircleCI's shard file selection")
+ if files is not None:
+ available: Final = frozenset(item.nodeid.split("::", 1)[0] for item in owned)
+ if files - available:
+ raise pytest.UsageError(f"Integration shard selected uncollected files: {sorted(files - available)}")
+ selected: Final = tuple(item for item in items if item not in owned or item.nodeid.split("::", 1)[0] in files)
+ deselected: Final = tuple(item for item in owned if item.nodeid.split("::", 1)[0] not in files)
config.hook.pytest_deselected(items=deselected)
items[:] = selected
config.stash[COLLECTED] = tuple(item.nodeid for item in items if item in owned)
@@ -154,15 +161,13 @@ def pytest_sessionfinish(session: pytest.Session, exitstatus: int) -> None:
return
collected: Final = session.config.stash.get(COLLECTED, ())
reports: Final = tuple(report for report in session.config.stash[REPORTS] if report.nodeid in collected)
- timings: Final = tuple(
- CaseTiming(nodeid=nodeid, seconds=sum(report.duration for report in reports if report.nodeid == nodeid))
- for nodeid in collected
- )
+ inventory: Final = session.config.stash.get(INVENTORY, collected)
+ empty_shard: Final = session.config.stash[SHARD_FILES] == frozenset() and bool(inventory)
passed: Final = tuple(report.nodeid for report in reports if report.when == "call" and report.passed)
skipped: Final = tuple(report.nodeid for report in reports if report.skipped)
complete: Final = (
- exitstatus == 0
- and bool(collected)
+ (exitstatus == 0 or (empty_shard and exitstatus == pytest.ExitCode.NO_TESTS_COLLECTED))
+ and (bool(collected) or empty_shard)
and sorted(collected) == sorted(passed + skipped)
and not any(report.failed for report in reports)
)
@@ -172,14 +177,13 @@ def pytest_sessionfinish(session: pytest.Session, exitstatus: int) -> None:
json.dumps(
{
"collected": collected,
- "inventory": session.config.stash.get(INVENTORY, collected),
+ "inventory": inventory,
"shard_count": session.config.getoption("integration_shard_count"),
"shard_index": session.config.getoption("integration_shard_index"),
"passed": passed,
"skipped": skipped,
- "timings": tuple({"nodeid": timing.nodeid, "seconds": timing.seconds} for timing in timings),
"complete": complete,
- "exitstatus": exitstatus,
+ "exitstatus": 0 if complete else exitstatus,
"hypothesis_version": version("hypothesis"),
"hypothesis_seed": session.config.getoption("hypothesis_seed"),
"order_seed": session.config.getoption("integration_order_seed"),
@@ -196,6 +200,8 @@ def pytest_sessionfinish(session: pytest.Session, exitstatus: int) -> None:
)
if not complete and exitstatus == 0:
session.exitstatus = pytest.ExitCode.TESTS_FAILED
+ if complete and empty_shard:
+ session.exitstatus = pytest.ExitCode.OK
@pytest.fixture
diff --git a/tests/integration/database/test_harness_lifecycle.py b/tests/integration/database/test_harness_lifecycle.py
index 63e3cba7363..91688eef263 100644
--- a/tests/integration/database/test_harness_lifecycle.py
+++ b/tests/integration/database/test_harness_lifecycle.py
@@ -16,6 +16,7 @@ from contextlib import AbstractContextManager, ExitStack
from pathlib import Path
from queue import SimpleQueue
from threading import Event
+from tempfile import TemporaryDirectory
from types import FrameType
from typing import Final, Literal
@@ -38,6 +39,7 @@ from tests.integration._support.database_relay import (
held_statement_relay,
)
from tests.integration._support.runtime import configure_executor
+from tests.integration._support.sharding import ShardExecution, shard_errors
class ExitRecord(TypedDict):
@@ -282,75 +284,173 @@ def test_seeded_collection_reuses_scoped_fixtures_and_executes_every_case(tmp_pa
)
-def test_partitioned_collection_reuses_unparametrized_fixtures_and_executes_every_case(tmp_path: Path) -> None:
+@pytest.mark.parametrize("workers", (1, 2))
+@pytest.mark.parametrize("subset", (False, True))
+def test_native_file_selection_reuses_fixtures_and_qualifies_an_empty_shard(
+ tmp_path: Path, workers: int, subset: bool
+) -> None:
events: Final = tmp_path / "events.txt"
- probe: Final = tmp_path / "test_fixture_probe.py"
- probe.write_text(
- "import pytest\nfrom pathlib import Path\n"
- f"EVENTS = Path({str(events)!r})\n"
- "def record(value):\n"
- " with EVENTS.open('a') as output:\n"
- " output.write(value + '\\n')\n"
- "@pytest.fixture(scope='module')\n"
- "def shared():\n"
- " record('start shared')\n"
- " yield 'shared'\n"
- " record('stop shared')\n"
- "@pytest.mark.parametrize('number', range(4))\n"
- "def test_shared(shared, number):\n"
- " assert shared == 'shared'\n"
- " record('shared ' + str(number))\n"
- "@pytest.mark.parametrize('number', range(8))\n"
- "def test_plain(number):\n"
- " record('plain ' + str(number))\n"
+ root: Final = Path(__file__).resolve().parents[3]
+ with TemporaryDirectory(prefix="native-selection-", dir=Path(__file__).parent) as directory:
+ probe: Final = Path(directory) / "test_fixture_probe.py"
+ plain: Final = Path(directory) / "test_plain_probe.py"
+ probe.write_text(
+ "import pytest\nfrom pathlib import Path\n"
+ f"EVENTS = Path({str(events)!r})\n"
+ "def record(value):\n"
+ " with EVENTS.open('a') as output:\n"
+ " output.write(value + '\\n')\n"
+ "@pytest.fixture(scope='module')\n"
+ "def shared():\n"
+ " record('start shared')\n"
+ " yield 'shared'\n"
+ " record('stop shared')\n"
+ "@pytest.mark.parametrize('number', range(4))\n"
+ "@pytest.mark.xdist_group('shared')\n"
+ "def test_shared(shared, number):\n"
+ " assert shared == 'shared'\n"
+ " record('shared ' + str(number))\n"
+ )
+ plain.write_text(
+ "import pytest\nfrom pathlib import Path\n"
+ f"EVENTS = Path({str(events)!r})\n"
+ "@pytest.mark.parametrize('number', range(8))\n"
+ "def test_plain(number):\n"
+ " with EVENTS.open('a') as output:\n"
+ " output.write('plain ' + str(number) + '\\n')\n"
+ "def test_existing_skip():\n"
+ " pytest.skip('retained skip identity')\n"
+ )
+ selections: Final = (str(probe.relative_to(root)), str(plain.relative_to(root)), "")
+ candidates: Final = (
+ (f"{selections[0]}::test_shared[1]", f"{selections[1]}::test_existing_skip") if subset else selections[:2]
+ )
+ listed: Final = subprocess.run(
+ (sys.executable, "-P", "tests/integration/run.py", "database", "--list", *candidates),
+ cwd=root,
+ capture_output=True,
+ text=True,
+ timeout=15,
+ check=False,
+ )
+ assert listed.returncode == 0, listed.stdout + listed.stderr
+ assert tuple(listed.stdout.splitlines()) == tuple(sorted(selections[:2]))
+ outputs: Final = tuple(tmp_path / str(index) for index in range(3))
+ files: Final = tuple(tmp_path / f"selection-{index}.txt" for index in range(3))
+ for selection, path in zip(selections, files, strict=True):
+ path.write_text(selection + "\n" if selection else "")
+ results: Final = tuple(
+ subprocess.run(
+ (
+ sys.executable,
+ "-P",
+ "-m",
+ "pytest",
+ *candidates,
+ "--noconftest",
+ "-p",
+ "tests.integration.conftest",
+ "-o",
+ "addopts=",
+ "--integration-shard-count=3",
+ f"--integration-shard-index={index}",
+ f"--integration-shard-files={files[index]}",
+ "--integration-order-seed=1848224111",
+ "--hypothesis-seed=4106601",
+ "--timeout=15",
+ *(("-n", str(workers), "--dist=loadgroup") if workers > 1 else ()),
+ "-q",
+ ),
+ cwd=root,
+ env={
+ **{
+ name: value
+ for name, value in os.environ.items()
+ if name
+ not in (
+ "INTEGRATION_RESULTS_DIR",
+ "INTEGRATION_ROUTING",
+ "GITHUB_ACTIONS",
+ "PYTEST_XDIST_WORKER",
+ )
+ },
+ "INTEGRATION_RESULTS_DIR": str(outputs[index]),
+ "PYTHONPATH": os.pathsep.join((str(root), str(root / "tests"), str(root / "tests/e2e"))),
+ },
+ capture_output=True,
+ text=True,
+ timeout=30,
+ check=False,
+ )
+ for index in range(3)
+ )
+ assert all(result.returncode == 0 for result in results), tuple(
+ result.stdout + result.stderr for result in results
+ )
+ executions: Final = tuple(
+ ShardExecution.model_validate_json((output / "execution.json").read_text()) for output in outputs
+ )
+ assert shard_errors(executions, 3) == ()
+ assert len(executions[0].inventory) == (2 if subset else 13)
+ assert executions[2].collected == ()
+ assert executions[2].complete
+ assert len(executions[1].skipped) == 1
+ assert executions[1].skipped[0].endswith("::test_existing_skip")
+ observed: Final = tuple(events.read_text().splitlines())
+ assert observed.count("start shared") == observed.count("stop shared") == 1
+ assert sorted(event for event in observed if event.startswith("shared ")) == (
+ ["shared 1"] if subset else [f"shared {index}" for index in range(4)]
)
- (tmp_path / "partition_probe.py").write_text(
- "from integration._support.ordering import case_shards, collected_case\n"
- "def pytest_collection_modifyitems(config, items):\n"
- " shards = case_shards(tuple(collected_case(item) for item in items), 3)\n"
- " selected = shards[config.getoption('integration_shard_index')]\n"
- " items[:] = tuple(item for item in items if item.nodeid in selected)\n"
+ assert sorted(event for event in observed if event.startswith("plain ")) == (
+ [] if subset else [f"plain {index}" for index in range(8)]
)
- results: Final = tuple(
- subprocess.run(
+
+
+@pytest.mark.parametrize("assignment", ("absent", "missing", "foreign"))
+def test_invalid_native_selections_fail_before_any_case_runs(
+ tmp_path: Path, assignment: Literal["absent", "missing", "foreign"]
+) -> None:
+ root: Final = Path(__file__).resolve().parents[3]
+ events: Final = tmp_path / "executed.txt"
+ selection: Final = tmp_path / "node-files.txt"
+ if assignment == "foreign":
+ selection.write_text("tests/integration/database/test_unknown.py\n")
+ with TemporaryDirectory(prefix="invalid-selection-", dir=Path(__file__).parent) as directory:
+ probe: Final = Path(directory) / "test_probe.py"
+ probe.write_text(f"from pathlib import Path\ndef test_case():\n Path({str(events)!r}).write_text('ran')\n")
+ result: Final = subprocess.run(
(
sys.executable,
"-P",
"-m",
"pytest",
- str(probe),
+ str(probe.relative_to(root)),
+ "--noconftest",
"-p",
"tests.integration.conftest",
- "-p",
- "partition_probe",
- "--integration-shard-count=3",
- f"--integration-shard-index={index}",
- "--integration-order-seed=1848224111",
- "--timeout=15",
+ "-o",
+ "addopts=",
+ "--integration-shard-count=2",
+ "--integration-shard-index=0",
+ *((f"--integration-shard-files={selection}",) if assignment != "absent" else ()),
"-q",
),
+ cwd=root,
env={
**{
name: value
for name, value in os.environ.items()
- if name not in ("INTEGRATION_RESULTS_DIR", "INTEGRATION_ROUTING")
+ if name not in ("INTEGRATION_RESULTS_DIR", "INTEGRATION_ROUTING", "GITHUB_ACTIONS")
},
- "PYTHONPATH": os.pathsep.join((str(tmp_path), os.environ.get("PYTHONPATH", ""))),
+ "PYTHONPATH": os.pathsep.join((str(root), str(root / "tests"), str(root / "tests/e2e"))),
},
capture_output=True,
text=True,
- timeout=30,
+ timeout=15,
check=False,
)
- for index in range(3)
- )
- assert all(result.returncode == 0 for result in results), tuple(result.stdout + result.stderr for result in results)
- observed: Final = tuple(events.read_text().splitlines())
- assert observed.count("start shared") == observed.count("stop shared") == 1
- assert sorted(event for event in observed if event.startswith("shared ")) == [
- f"shared {index}" for index in range(4)
- ]
- assert sorted(event for event in observed if event.startswith("plain ")) == [f"plain {index}" for index in range(8)]
+ assert result.returncode == pytest.ExitCode.USAGE_ERROR, result.stdout + result.stderr
+ assert not events.exists()
@pytest.mark.parametrize("entrypoint", ("gateway", "refused"))
diff --git a/tests/integration/run.py b/tests/integration/run.py
index f89bd15adf9..98b727efce9 100644
--- a/tests/integration/run.py
+++ b/tests/integration/run.py
@@ -60,8 +60,8 @@ def main() -> int:
parser.add_argument("--workers", type=int, default=int(os.environ.get("INTEGRATION_WORKERS", "1")))
parser.add_argument("--shards", type=int, default=int(os.environ.get("INTEGRATION_CASE_SHARDS", "1")))
parser.add_argument("--shard-index", type=int, default=int(os.environ.get("INTEGRATION_CASE_SHARD_INDEX", "0")))
- parser.add_argument("--timings", type=Path)
- parser.add_argument("--list", action="store_true", help="print the group's test files and exit")
+ parser.add_argument("--shard-files", type=Path)
+ parser.add_argument("--list", action="store_true", help="print selected candidate files and exit")
parser.add_argument("files", nargs="*", help="run only these files, or pytest node ids inside them, of the group")
options: Final = parser.parse_intermixed_args()
root: Final = Path(__file__).resolve().parents[2]
@@ -71,14 +71,14 @@ def main() -> int:
for path in sorted((root / "tests/integration" / folder).rglob("test_*.py"))
if str(path.relative_to(root)) not in GITHUB_FILES
)
- if options.list:
- sys.stdout.write("\n".join(group_files) + "\n")
- return 0
selection: Final = select(tuple(options.files), group_files)
if selection.foreign:
parser.error(f"Not in the {options.group} group: {', '.join(selection.foreign)}")
if not selection.nodes:
parser.error(f"No integration test files selected for {options.group}")
+ if options.list:
+ sys.stdout.write("\n".join(sorted({file_of(node) for node in selection.nodes})) + "\n")
+ return 0
output: Final = options.results.resolve()
output.mkdir(parents=True, exist_ok=True)
environment: Final = {
@@ -109,7 +109,7 @@ def main() -> int:
f"--integration-order-seed={options.order_seed}",
f"--integration-shard-count={options.shards}",
f"--integration-shard-index={options.shard_index}",
- *(("--integration-timings", str(options.timings)) if options.timings is not None else ()),
+ *(("--integration-shard-files", str(options.shard_files)) if options.shard_files is not None else ()),
f"--junitxml={output / 'junit.xml'}",
"-o",
"junit_family=xunit1",
diff --git a/tests/unit/integration_support/test_ordering.py b/tests/unit/integration_support/test_ordering.py
index 98b08d0849c..775986c6e98 100644
--- a/tests/unit/integration_support/test_ordering.py
+++ b/tests/unit/integration_support/test_ordering.py
@@ -1,17 +1,12 @@
from __future__ import annotations
from itertools import groupby
-from types import MappingProxyType
from typing import Final
-import pytest
-
from tests.integration._support.ordering import (
CollectedCase,
ScopedParameter,
- case_shards,
fixture_groups,
- parse_timings,
)
from tests.integration.conftest import _order_key
@@ -68,113 +63,3 @@ def test_equal_unhashable_parameters_share_a_group_only_within_their_fixture_own
assert groups[first.nodeid] != groups[other_owner.nodeid]
assert groups[first.nodeid] != groups[other_file.nodeid]
assert groups[plain.nodeid] == ""
-
-
-def test_shards_balance_cases_without_splitting_a_scoped_configuration() -> None:
- cases: Final = tuple(
- CollectedCase(
- f"test_slots.py::test_route[{index}]",
- (ScopedParameter("module:slots", "rig", index // 4),),
- ("module:slots:extra",) if index % 2 else (),
- )
- for index in range(20)
- )
- plain: Final = tuple(CollectedCase(f"test_slots.py::test_plain[{index}]") for index in range(7))
- shards: Final = case_shards(cases + plain, 3)
- assert frozenset.union(*shards) == frozenset(case.nodeid for case in cases + plain)
- assert sum(len(shard) for shard in shards) == len(cases + plain)
- assert max(map(len, shards)) - min(map(len, shards)) <= 1
- for _, group in groupby(cases, key=lambda case: case.parameters[0].value):
- configuration: Final = frozenset(case.nodeid for case in group)
- assert sum(configuration <= shard for shard in shards) == 1
- assert shards == case_shards(tuple(reversed(cases + plain)), 3)
-
-
-def test_shards_reuse_unparametrized_fixtures_and_keep_different_results_separate() -> None:
- shared: Final = tuple(
- CollectedCase(f"test_sockets.py::test_override[{index}]", fixtures=("module:test_sockets.py:override",))
- for index in range(4)
- )
- other: Final = CollectedCase("test_sockets.py::test_default", fixtures=("module:test_sockets.py:default",))
- plain: Final = tuple(CollectedCase(f"test_other.py::test_plain[{index}]") for index in range(7))
- shards: Final = case_shards((*shared, other, *plain), 3)
- configuration: Final = frozenset(case.nodeid for case in shared)
- assert sum(configuration <= shard for shard in shards) == 1
- assert sorted(map(len, shards)) == [4, 4, 4]
- assert frozenset.union(*shards) == frozenset(case.nodeid for case in (*shared, other, *plain))
- groups: Final = fixture_groups((*shared, other))
- assert len({groups[case.nodeid] for case in shared}) == 1
- assert groups[other.nodeid] != groups[shared[0].nodeid]
- assert shards == case_shards(tuple(reversed((*shared, other, *plain))), 3)
-
-
-def test_an_oversized_unparametrized_fixture_is_split_into_bounded_groups() -> None:
- cases: Final = tuple(
- CollectedCase(f"test_sockets.py::test_route[{index:02}]", fixtures=("module:test_sockets.py:owned",))
- for index in range(20)
- )
- shards: Final = case_shards(cases, 4)
- assert tuple(map(len, shards)) == (5, 5, 5, 5)
- assert frozenset.union(*shards) == frozenset(case.nodeid for case in cases)
- assert sum(len(shard) for shard in shards) == len(cases)
-
-
-def test_measured_cost_splits_an_expensive_shared_fixture_without_losing_cases() -> None:
- expensive: Final = tuple(
- CollectedCase(f"test_tracing.py::test_route[{index}]", fixtures=("module:test_tracing.py:gateway",))
- for index in range(4)
- )
- cheap: Final = tuple(CollectedCase(f"test_other.py::test_route[{index}]") for index in range(8))
- cases: Final = (*expensive, *cheap)
- durations: Final = MappingProxyType({case.nodeid: 40.0 if case in expensive else 1.0 for case in cases})
- shards: Final = case_shards(cases, 4, durations)
- assert sorted(sum(durations[nodeid] for nodeid in shard) for shard in shards) == [42.0] * 4
- assert frozenset.union(*shards) == frozenset(case.nodeid for case in cases)
- assert sum(len(shard) for shard in shards) == len(cases)
- assert shards == case_shards(tuple(reversed(cases)), 4, durations)
-
-
-@pytest.mark.parametrize(
- "content",
- (
- "invalid",
- "{}",
- '[{"nodeid":"case","seconds":-1}]',
- '[{"nodeid":"case","seconds":"1"}]',
- '[{"nodeid":"case","seconds":NaN}]',
- '[{"nodeid":"case","seconds":Infinity}]',
- '[{"nodeid":"case","seconds":1},{"nodeid":"case","seconds":2}]',
- ),
-)
-def test_invalid_timing_cache_preserves_the_complete_cold_partition(content: str) -> None:
- cases: Final = tuple(CollectedCase(f"test_owned.py::test_route[{index}]") for index in range(9))
- durations: Final = parse_timings(content)
- assert not durations
- assert case_shards(cases, 3, durations) == case_shards(cases, 3)
-
-
-def test_timing_cache_keeps_zero_duration_skips_and_assigns_new_cases() -> None:
- durations: Final = parse_timings('[{"nodeid":"skip","seconds":0},{"nodeid":"old","seconds":12}]')
- cases: Final = (CollectedCase("skip"), CollectedCase("new"))
- shards: Final = case_shards(cases, 2, durations)
- assert durations["skip"] > 0
- assert frozenset.union(*shards) == frozenset({"skip", "new"})
- assert tuple(map(len, shards)) == (1, 1)
-
-
-def test_measured_cost_keeps_parametrized_fixture_configurations_atomic() -> None:
- shared: Final = tuple(
- CollectedCase(
- f"test_tracing.py::test_route[{index}]",
- (ScopedParameter("module:test_tracing.py", "configuration", "shared"),),
- )
- for index in range(3)
- )
- plain: Final = tuple(CollectedCase(f"test_other.py::test_route[{index}]") for index in range(5))
- cases: Final = (*shared, *plain)
- durations: Final = MappingProxyType({case.nodeid: 40.0 if case in shared else 1.0 for case in cases})
- shards: Final = case_shards(cases, 3, durations)
- configuration: Final = frozenset(case.nodeid for case in shared)
- assert sum(configuration <= shard for shard in shards) == 1
- assert frozenset.union(*shards) == frozenset(case.nodeid for case in cases)
- assert sum(len(shard) for shard in shards) == len(cases)
diff --git a/tests/unit/integration_support/test_sharding.py b/tests/unit/integration_support/test_sharding.py
index 3d3b53b6f51..2317279f2b2 100644
--- a/tests/unit/integration_support/test_sharding.py
+++ b/tests/unit/integration_support/test_sharding.py
@@ -2,14 +2,14 @@ from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
+from pathlib import Path
from types import MappingProxyType
from typing import Final
import pytest
-from tests.integration._support.ordering import CaseTiming
-from tests.integration._support.sharding import ShardExecution, merged_timings, shard_errors
-from tests.integration.conftest import COLLECTED, IntegrationReportPlugin
+from tests.integration._support.sharding import ShardExecution, shard_errors
+from tests.integration.conftest import COLLECTED, IntegrationReportPlugin, _shard_files
from tests.integration.conftest import INVENTORY as WORKER_INVENTORY
INVENTORY: Final = ("test_owned.py::test_first", "test_owned.py::test_skipped", "test_owned.py::test_last")
@@ -46,10 +46,34 @@ def test_shard_qualification_retains_passes_and_skip_identities() -> None:
assert shard_errors(executions, 2) == ()
+def test_a_selected_subset_can_leave_a_shard_empty_without_losing_the_inventory() -> None:
+ executions: Final = (_execution(0, INVENTORY), _execution(1, ()))
+ assert shard_errors(executions, 2) == ()
+ assert shard_errors((_execution(0, INVENTORY[:1]), _execution(1, ())), 2)
+
+
+def test_an_empty_assignment_is_distinct_from_no_assignment_or_a_missing_file(tmp_path: Path) -> None:
+ assignment: Final = tmp_path / "node-files.txt"
+ assert _shard_files(None) is None
+ with pytest.raises(pytest.UsageError, match="Cannot read"):
+ _shard_files(assignment)
+ assignment.write_text("")
+ assert _shard_files(assignment) == frozenset()
+
+
+@pytest.mark.parametrize("content", ("test_owned.py\ntest_owned.py\n", "test_owned.py\n\n", "\n"))
+def test_an_invalid_assignment_is_rejected_instead_of_running_extra_tests(tmp_path: Path, content: str) -> None:
+ assignment: Final = tmp_path / "node-files.txt"
+ assignment.write_text(content)
+ with pytest.raises(pytest.UsageError, match="duplicate or blank"):
+ _shard_files(assignment)
+
+
@pytest.mark.parametrize(
"executions",
(
(),
+ (_execution(0, (), inventory=()), _execution(1, (), inventory=())),
(_execution(0, INVENTORY),),
(_execution(0, INVENTORY[:2]), _execution(0, INVENTORY[2:])),
(_execution(0, INVENTORY[:1]), _execution(1, INVENTORY[2:])),
@@ -70,34 +94,6 @@ def test_shard_qualification_rejects_lost_duplicate_foreign_or_failed_cases(
assert shard_errors(executions, 2)
-def test_timing_snapshot_includes_every_executed_pass_and_skip_once() -> None:
- first: Final = CaseTiming(nodeid=INVENTORY[0], seconds=40.0)
- skipped: Final = CaseTiming(nodeid=INVENTORY[1], seconds=0.0)
- last: Final = CaseTiming(nodeid=INVENTORY[2], seconds=1.0)
- executions: Final = (
- _execution(0, INVENTORY[:2], skipped=INVENTORY[1:2]).model_copy(update={"timings": (first, skipped)}),
- _execution(1, INVENTORY[2:]).model_copy(update={"timings": (last,)}),
- )
- assert shard_errors(executions, 2) == ()
- assert merged_timings(executions) == tuple(sorted((first, skipped, last), key=lambda timing: timing.nodeid))
-
-
-@pytest.mark.parametrize(
- "timings",
- (
- (),
- (CaseTiming(nodeid=INVENTORY[0], seconds=1.0),),
- (CaseTiming(nodeid=INVENTORY[0], seconds=1.0),) * 2,
- (CaseTiming(nodeid="foreign", seconds=1.0), CaseTiming(nodeid=INVENTORY[1], seconds=0.0)),
- ),
-)
-def test_incomplete_duplicate_or_foreign_measurements_cannot_seed_the_timing_cache(
- timings: tuple[CaseTiming, ...],
-) -> None:
- execution: Final = _execution(0, INVENTORY[:2]).model_copy(update={"timings": timings})
- assert merged_timings((execution,)) == ()
-
-
@dataclass(frozen=True, slots=True)
class WorkerResult:
workeroutput: Mapping[str, object]
From 3981228d7038383fcc7e998e2561ef124f8c878c Mon Sep 17 00:00:00 2001
From: nate-berri
Date: Sat, 10 Oct 2026 13:35:49 -0700
Subject: [PATCH 11/40] refactor(anthropic): move raw SSE stream assembly
helpers out of proxy guardrails (#45749)
* refactor(anthropic): move passthrough SSE stream assembly into litellm/llms
Part of LIT-9423
* refactor(anthropic): move raw SSE stream assembly helpers out of proxy guardrails
Part of LIT-9423
* refactor(anthropic): give the anthropic_sse re-exports reasoned noqa codes
Part of LIT-9423
* fix(sdk): resolve litellm.proxy lazily on attribute access
The layer cleanup stopped import litellm from loading any proxy module, so litellm.proxy was no longer bound and litellm.proxy._types.X raised AttributeError. The module __getattr__ now imports litellm.proxy on first access, which keeps import litellm free of proxy._types and fixes the docs and code-quality checks on main
* test(anthropic): cover the raw SSE helpers in stream_assembly
Part of LIT-9423
---
litellm/integrations/otel/model/request_io.py | 2 +-
.../litellm_core_utils/served_output_texts.py | 5 +-
.../anthropic/pass_through/stream_assembly.py | 124 ++++++++++++++-
litellm/proxy/guardrails/anthropic_sse.py | 136 ++---------------
.../pass_through/test_stream_assembly.py | 144 ++++++++++++++++++
5 files changed, 284 insertions(+), 127 deletions(-)
create mode 100644 tests/unit/llms/anthropic/pass_through/test_stream_assembly.py
diff --git a/litellm/integrations/otel/model/request_io.py b/litellm/integrations/otel/model/request_io.py
index 4131f3de6da..287d28a0d17 100644
--- a/litellm/integrations/otel/model/request_io.py
+++ b/litellm/integrations/otel/model/request_io.py
@@ -6,7 +6,7 @@ from typing_extensions import ReadOnly, TypedDict
import litellm
from litellm.integrations.otel.mappers.utils import json_or_none
-from litellm.proxy.guardrails.anthropic_sse import assemble_anthropic_sse_stream, is_raw_sse_stream
+from litellm.llms.anthropic.pass_through.stream_assembly import assemble_anthropic_sse_stream, is_raw_sse_stream
from litellm.types.llms.base import LiteLLMBaseModel
from litellm.types.llms.openai import ResponseCompletedEvent, ResponsesAPIResponse
from litellm.types.utils import ModelResponse, ModelResponseStream
diff --git a/litellm/litellm_core_utils/served_output_texts.py b/litellm/litellm_core_utils/served_output_texts.py
index 2788720448b..ce9a568ea72 100644
--- a/litellm/litellm_core_utils/served_output_texts.py
+++ b/litellm/litellm_core_utils/served_output_texts.py
@@ -110,7 +110,10 @@ def served_output_texts(response: object) -> ServedTexts | None:
def served_stream_output_texts(chunks: Sequence[object]) -> ServedTexts | None:
if chunks and all(isinstance(chunk, ModelResponseStream) for chunk in chunks):
return _chat_stream_texts(tuple(chunk for chunk in chunks if isinstance(chunk, ModelResponseStream)))
- from litellm.proxy.guardrails.anthropic_sse import assemble_anthropic_sse_stream, is_anthropic_sse_stream
+ from litellm.llms.anthropic.pass_through.stream_assembly import (
+ assemble_anthropic_sse_stream,
+ is_anthropic_sse_stream,
+ )
if not is_anthropic_sse_stream(chunks):
return None
diff --git a/litellm/llms/anthropic/pass_through/stream_assembly.py b/litellm/llms/anthropic/pass_through/stream_assembly.py
index 76d1896ac32..89961bbe255 100644
--- a/litellm/llms/anthropic/pass_through/stream_assembly.py
+++ b/litellm/llms/anthropic/pass_through/stream_assembly.py
@@ -1,5 +1,6 @@
+import codecs
import json
-from collections.abc import Sequence
+from collections.abc import Mapping, Sequence
from typing import Final
import litellm
@@ -395,3 +396,124 @@ def build_usage_only_response_from_chunks(
],
usage=usage_obj,
)
+
+
+_ANTHROPIC_EVENT_TYPES: Final = frozenset(
+ {
+ "message_start",
+ "message_delta",
+ "message_stop",
+ "content_block_start",
+ "content_block_delta",
+ "content_block_stop",
+ "ping",
+ "error",
+ }
+)
+
+
+def is_raw_sse_stream(all_chunks: Sequence[object]) -> bool:
+ return any(isinstance(chunk, (str, bytes)) for chunk in all_chunks)
+
+
+def _joined_sse_stream(all_chunks: Sequence[object]) -> str | None:
+ raw: Final = b"".join(
+ chunk if isinstance(chunk, bytes) else chunk.encode("utf-8")
+ for chunk in all_chunks
+ if isinstance(chunk, (str, bytes))
+ )
+ try:
+ return codecs.getincrementaldecoder("utf-8")().decode(raw, final=False)
+ except UnicodeDecodeError:
+ return None
+
+
+def _parsed_sse_events(sse_stream: str) -> tuple[Mapping[str, object], ...]:
+ return tuple(
+ event_data
+ for event in split_sse_chunk_into_events(sse_stream)
+ if (event_data := extract_sse_data(event)) is not None
+ )
+
+
+def _anthropic_message_start(sse_stream: str) -> Mapping[str, object] | None:
+ return next(
+ (
+ message
+ for event_data in _parsed_sse_events(sse_stream)
+ if event_data.get("type") == "message_start" and isinstance(message := event_data.get("message"), dict)
+ ),
+ None,
+ )
+
+
+def is_anthropic_sse_stream(all_chunks: Sequence[object]) -> bool:
+ """Whether raw SSE frames are Anthropic Messages events.
+
+ ``is_raw_sse_stream`` only says the chunks are unparsed bytes, and ``/v1/messages`` is not the
+ only endpoint that streams those: the Google ``:streamGenerateContent`` route marks its own
+ stream raw too. Reading its frames as Anthropic ones would refuse the response in a wire format
+ its client cannot parse, so the surface is decided on the event types actually present.
+ """
+ sse_stream: Final = _joined_sse_stream(all_chunks)
+ if sse_stream is None:
+ return False
+ return any(event.get("type") in _ANTHROPIC_EVENT_TYPES for event in _parsed_sse_events(sse_stream))
+
+
+def assemble_anthropic_sse_stream(
+ all_chunks: Sequence[object], *, restore_identity: bool = False
+) -> ModelResponse | None:
+ """Assemble raw Anthropic SSE frames into a ModelResponse.
+
+ ``restore_identity`` stamps the upstream message id and model onto the result, which the
+ assembler does not carry through. It is off by default so callers that re-emit the assembled
+ response keep the wire shape they had before this helper was shared. The writes land on a
+ freshly built object that is unreachable from caller state until returned.
+ """
+ sse_stream: Final = _joined_sse_stream(all_chunks)
+ if sse_stream is None:
+ return None
+ message_start: Final = _anthropic_message_start(sse_stream)
+ if message_start is None:
+ return None
+ model: Final = message_start.get("model") if restore_identity else None
+ try:
+ assembled: Final = build_complete_streaming_response(
+ all_chunks=(sse_stream,),
+ litellm_logging_obj=None, # pyright: ignore[reportArgumentType] # only forwarded to stream_chunk_builder, which accepts None
+ model=model if isinstance(model, str) else "",
+ )
+ except Exception: # noqa: BLE001 # stream_chunk_builder re-raises every assembly failure as litellm.APIError
+ return None
+ if not isinstance(assembled, ModelResponse):
+ return None
+ if not restore_identity:
+ return assembled
+ message_id: Final = message_start.get("id")
+ if isinstance(message_id, str):
+ assembled.id = message_id
+ if isinstance(model, str) and model:
+ assembled.model = model
+ return assembled
+
+
+def is_sse_error_stream(all_chunks: Sequence[object]) -> bool:
+ """Whether the buffered stream carries nothing but error frames.
+
+ post_call guardrails run in a chain, so a hook can be handed the terminal error frames an
+ earlier guardrail emitted when it blocked. Those carry no message to assemble, and replacing
+ them would hide the refusal the client is owed. Covers both wire forms a guardrail emits: the
+ Anthropic ``error`` event and the chat-completions ``{"error": ...}`` payload.
+ """
+ if not all(isinstance(chunk, (str, bytes)) for chunk in all_chunks):
+ # A stream mixing typed chunks with an error frame still carries content to scan, and the
+ # frames-only join below would drop exactly the part that has to be scanned
+ return False
+ sse_stream: Final = _joined_sse_stream(all_chunks)
+ if sse_stream is None:
+ return False
+ events: Final = _parsed_sse_events(sse_stream)
+ return len(events) > 0 and all(
+ event.get("type") == "error" or isinstance(event.get("error"), Mapping) for event in events
+ )
diff --git a/litellm/proxy/guardrails/anthropic_sse.py b/litellm/proxy/guardrails/anthropic_sse.py
index 07a5d511117..c3a6f259f95 100644
--- a/litellm/proxy/guardrails/anthropic_sse.py
+++ b/litellm/proxy/guardrails/anthropic_sse.py
@@ -7,115 +7,19 @@ hook scan such a stream, and re-emit it when the guardrail rewrote the response.
from __future__ import annotations
-import codecs
import json
-from collections.abc import Mapping, Sequence
from typing import Final
-from litellm.types.utils import Choices, ModelResponse
-
-_ANTHROPIC_EVENT_TYPES: Final = frozenset(
- {
- "message_start",
- "message_delta",
- "message_stop",
- "content_block_start",
- "content_block_delta",
- "content_block_stop",
- "ping",
- "error",
- }
+from litellm.llms.anthropic.pass_through.stream_assembly import (
+ assemble_anthropic_sse_stream as assemble_anthropic_sse_stream, # noqa: PLC0414 # public re-export
)
-
-
-def is_raw_sse_stream(all_chunks: Sequence[object]) -> bool:
- return any(isinstance(chunk, (str, bytes)) for chunk in all_chunks)
-
-
-def _joined_sse_stream(all_chunks: Sequence[object]) -> str | None:
- raw: Final = b"".join(
- chunk if isinstance(chunk, bytes) else chunk.encode("utf-8")
- for chunk in all_chunks
- if isinstance(chunk, (str, bytes))
- )
- try:
- return codecs.getincrementaldecoder("utf-8")().decode(raw, final=False)
- except UnicodeDecodeError:
- return None
-
-
-def _parsed_sse_events(sse_stream: str) -> tuple[Mapping[str, object], ...]:
- from litellm.llms.anthropic.pass_through.stream_assembly import extract_sse_data, split_sse_chunk_into_events
-
- return tuple(
- event_data
- for event in split_sse_chunk_into_events(sse_stream)
- if (event_data := extract_sse_data(event)) is not None
- )
-
-
-def _anthropic_message_start(sse_stream: str) -> Mapping[str, object] | None:
- return next(
- (
- message
- for event_data in _parsed_sse_events(sse_stream)
- if event_data.get("type") == "message_start" and isinstance(message := event_data.get("message"), dict)
- ),
- None,
- )
-
-
-def is_anthropic_sse_stream(all_chunks: Sequence[object]) -> bool:
- """Whether raw SSE frames are Anthropic Messages events.
-
- ``is_raw_sse_stream`` only says the chunks are unparsed bytes, and ``/v1/messages`` is not the
- only endpoint that streams those: the Google ``:streamGenerateContent`` route marks its own
- stream raw too. Reading its frames as Anthropic ones would refuse the response in a wire format
- its client cannot parse, so the surface is decided on the event types actually present.
- """
- sse_stream: Final = _joined_sse_stream(all_chunks)
- if sse_stream is None:
- return False
- return any(event.get("type") in _ANTHROPIC_EVENT_TYPES for event in _parsed_sse_events(sse_stream))
-
-
-def assemble_anthropic_sse_stream(
- all_chunks: Sequence[object], *, restore_identity: bool = False
-) -> ModelResponse | None:
- """Assemble raw Anthropic SSE frames into a ModelResponse.
-
- ``restore_identity`` stamps the upstream message id and model onto the result, which the
- assembler does not carry through. It is off by default so callers that re-emit the assembled
- response keep the wire shape they had before this helper was shared. The writes land on a
- freshly built object that is unreachable from caller state until returned.
- """
- from litellm.llms.anthropic.pass_through.stream_assembly import build_complete_streaming_response
-
- sse_stream: Final = _joined_sse_stream(all_chunks)
- if sse_stream is None:
- return None
- message_start: Final = _anthropic_message_start(sse_stream)
- if message_start is None:
- return None
- model: Final = message_start.get("model") if restore_identity else None
- try:
- assembled: Final = build_complete_streaming_response(
- all_chunks=(sse_stream,),
- litellm_logging_obj=None, # pyright: ignore[reportArgumentType] # only forwarded to stream_chunk_builder, which accepts None
- model=model if isinstance(model, str) else "",
- )
- except Exception: # noqa: BLE001 # stream_chunk_builder re-raises every assembly failure as litellm.APIError
- return None
- if not isinstance(assembled, ModelResponse):
- return None
- if not restore_identity:
- return assembled
- message_id: Final = message_start.get("id")
- if isinstance(message_id, str):
- assembled.id = message_id
- if isinstance(model, str) and model:
- assembled.model = model
- return assembled
+from litellm.llms.anthropic.pass_through.stream_assembly import (
+ is_anthropic_sse_stream as is_anthropic_sse_stream, # noqa: PLC0414 # public re-export
+)
+from litellm.llms.anthropic.pass_through.stream_assembly import (
+ is_raw_sse_stream as is_raw_sse_stream, # noqa: PLC0414 # public re-export
+)
+from litellm.types.utils import Choices, ModelResponse
def model_response_text(response: ModelResponse) -> str:
@@ -141,25 +45,9 @@ def anthropic_sse_error_frames(message: str) -> tuple[bytes, ...]:
)
-def is_sse_error_stream(all_chunks: Sequence[object]) -> bool:
- """Whether the buffered stream carries nothing but error frames.
-
- post_call guardrails run in a chain, so a hook can be handed the terminal error frames an
- earlier guardrail emitted when it blocked. Those carry no message to assemble, and replacing
- them would hide the refusal the client is owed. Covers both wire forms a guardrail emits: the
- Anthropic ``error`` event and the chat-completions ``{"error": ...}`` payload.
- """
- if not all(isinstance(chunk, (str, bytes)) for chunk in all_chunks):
- # A stream mixing typed chunks with an error frame still carries content to scan, and the
- # frames-only join below would drop exactly the part that has to be scanned
- return False
- sse_stream: Final = _joined_sse_stream(all_chunks)
- if sse_stream is None:
- return False
- events: Final = _parsed_sse_events(sse_stream)
- return len(events) > 0 and all(
- event.get("type") == "error" or isinstance(event.get("error"), Mapping) for event in events
- )
+from litellm.llms.anthropic.pass_through.stream_assembly import ( # noqa: E402 # re-export after the definitions above
+ is_sse_error_stream as is_sse_error_stream, # noqa: PLC0414 # public re-export
+)
def anthropic_sse_chunks_from_response(assembled: ModelResponse) -> tuple[bytes, ...]:
diff --git a/tests/unit/llms/anthropic/pass_through/test_stream_assembly.py b/tests/unit/llms/anthropic/pass_through/test_stream_assembly.py
new file mode 100644
index 00000000000..33f95ccc9ff
--- /dev/null
+++ b/tests/unit/llms/anthropic/pass_through/test_stream_assembly.py
@@ -0,0 +1,144 @@
+import json
+from typing import Final
+
+import pytest
+
+from litellm.llms.anthropic.pass_through.stream_assembly import (
+ assemble_anthropic_sse_stream,
+ is_anthropic_sse_stream,
+ is_raw_sse_stream,
+ is_sse_error_stream,
+)
+from litellm.types.utils import Choices
+
+
+def _frame(event: str, data: dict[str, object]) -> bytes:
+ return f"event: {event}\ndata: {json.dumps(data)}\n\n".encode()
+
+
+MESSAGE_ID: Final = "msg_upstream_1"
+MODEL: Final = "claude-upstream"
+
+ANTHROPIC_STREAM: Final = (
+ _frame(
+ "message_start",
+ {
+ "type": "message_start",
+ "message": {
+ "id": MESSAGE_ID,
+ "type": "message",
+ "role": "assistant",
+ "model": MODEL,
+ "content": [],
+ "stop_reason": None,
+ "usage": {"input_tokens": 3, "output_tokens": 1},
+ },
+ },
+ ),
+ _frame(
+ "content_block_start",
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ ),
+ _frame(
+ "content_block_delta",
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hello"}},
+ ),
+ _frame(
+ "content_block_delta",
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": " there"}},
+ ),
+ _frame("content_block_stop", {"type": "content_block_stop", "index": 0}),
+ _frame(
+ "message_delta",
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 2}},
+ ),
+ _frame("message_stop", {"type": "message_stop"}),
+)
+
+GOOGLE_STREAM: Final = (b'data: {"candidates": [{"content": {"parts": [{"text": "Hello"}]}}]}\n\n',)
+ANTHROPIC_ERROR: Final = _frame("error", {"type": "error", "error": {"type": "overloaded_error", "message": "busy"}})
+CHAT_ERROR: Final = b'data: {"error": {"message": "blocked by guardrail"}}\n\n'
+INVALID_UTF8: Final = (b"\xff\xfe data",)
+
+
+@pytest.mark.parametrize(
+ ("chunks", "expected"),
+ [
+ ((b"data: {}\n\n",), True),
+ (("data: {}\n\n",), True),
+ ((object(), b"data: {}\n\n"), True),
+ ((object(),), False),
+ ((), False),
+ ],
+)
+def test_is_raw_sse_stream_is_true_only_when_a_chunk_is_str_or_bytes(chunks: tuple[object, ...], expected: bool):
+ assert is_raw_sse_stream(chunks) is expected
+
+
+@pytest.mark.parametrize(
+ ("chunks", "expected"),
+ [
+ (ANTHROPIC_STREAM, True),
+ ((ANTHROPIC_ERROR,), True),
+ (tuple(chunk.decode() for chunk in ANTHROPIC_STREAM), True),
+ (GOOGLE_STREAM, False),
+ (INVALID_UTF8, False),
+ ((), False),
+ ],
+)
+def test_is_anthropic_sse_stream_decides_on_the_event_types_present(chunks: tuple[object, ...], expected: bool):
+ assert is_anthropic_sse_stream(chunks) is expected
+
+
+def test_assemble_anthropic_sse_stream_joins_the_text_deltas():
+ assembled = assemble_anthropic_sse_stream(ANTHROPIC_STREAM)
+
+ assert assembled is not None
+ choice = assembled.choices[0]
+ assert isinstance(choice, Choices)
+ assert choice.message.content == "Hello there"
+
+
+def test_assemble_anthropic_sse_stream_restores_upstream_identity_only_when_asked():
+ plain = assemble_anthropic_sse_stream(ANTHROPIC_STREAM)
+ restored = assemble_anthropic_sse_stream(ANTHROPIC_STREAM, restore_identity=True)
+
+ assert plain is not None and restored is not None
+ assert plain.id != MESSAGE_ID
+ assert (restored.id, restored.model) == (MESSAGE_ID, MODEL)
+
+
+@pytest.mark.parametrize(
+ "chunks",
+ [GOOGLE_STREAM, INVALID_UTF8, (ANTHROPIC_ERROR,), ()],
+ ids=["no-message-start", "undecodable", "error-only", "empty"],
+)
+def test_assemble_anthropic_sse_stream_returns_none_without_a_message_to_build(chunks: tuple[object, ...]):
+ assert assemble_anthropic_sse_stream(chunks) is None
+
+
+@pytest.mark.parametrize(
+ ("chunks", "expected"),
+ [
+ ((ANTHROPIC_ERROR,), True),
+ ((CHAT_ERROR,), True),
+ ((ANTHROPIC_ERROR, CHAT_ERROR), True),
+ ((ANTHROPIC_ERROR, ANTHROPIC_STREAM[0]), False),
+ ((object(), ANTHROPIC_ERROR), False),
+ (ANTHROPIC_STREAM, False),
+ (INVALID_UTF8, False),
+ ((b"\n\n",), False),
+ ],
+ ids=[
+ "anthropic-error",
+ "chat-error",
+ "both-error-forms",
+ "error-then-message",
+ "typed-chunk-mixed-in",
+ "normal-stream",
+ "undecodable",
+ "no-events",
+ ],
+)
+def test_is_sse_error_stream_is_true_only_for_frames_that_are_all_errors(chunks: tuple[object, ...], expected: bool):
+ assert is_sse_error_stream(chunks) is expected
From dc95de52097e7824ed7d6c9fb1d290453d1e35e1 Mon Sep 17 00:00:00 2001
From: "devin-ai-integration[bot]"
<158243242+devin-ai-integration[bot]@users.noreply.github.com>
Date: Sat, 10 Oct 2026 13:52:32 -0700
Subject: [PATCH 12/40] feat(otel)!: let a team capture_message_content
override the global setting for its OTel v2 destination (#44264)
* feat(otel): let a team strip captured message content from its own OTel v2 destination
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* refactor(proxy): split the shared callback option conflict check and sync dashboard API types
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix(otel): address review feedback on team capture_message_content
Classify capture_message_content as NotSecret in the credential slot registry, inject test exporters through register_exporter_factory instead of patching _exporter_from_spec, type the test helpers, and stop reassigning processor in build_tracer_provider
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* test(otel): add integration cells for team capture_message_content
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* test(otel): cover weave_otel and newrelic team destinations in capture_message_content cells
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix(otel): stop rejecting client-sent capture_message_content at the request body boundary
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* feat(otel): let a team capture_message_content override the global setting in both directions
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix(otel): keep a team's capture_message_content on its own OTel v2 destination
The setting no longer rides the flattened team callback vars, so a sibling destination and a routed provider follow the global mode. Request bodies get the base 400 back, a failure-only entry rejects the setting, and entries for one backend must agree
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* test(otel): type the capture_message_content callback validation tests
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* test(otel): type the remaining capture_message_content test signatures
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* test(otel): mark the new capture_message_content test locals Final
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix(otel): default tenant capture to callback_settings.otel and keep CaptureMessageContent formatting bare
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix(otel): keep CaptureMessageContent a plain str like main
The str-to-Enum switch changed the public type: the config field's type,
repr and model_dump, a constructor that now raised on unknown values, and
unknown env values coerced to no_content. CaptureMessageContent is the plain
str subclass main ships again, the field is a str, and a
captures_span_content helper replaces the enum property. A test pins that a
published preset's capture mode stays the default for an unowned
destination, which is what main forwards.
* test(otel): drop the module-level CaptureMessageContent import the rewritten test no longer uses
* fix(lint): keep the merged branch within main's type budgets
Freeze the capture-mode settings model (LIT015) and read stored logging
entries through one typed sequence helper, so the conflicting-capture checks
add no unknown types.
* fix(otel): reject a destination capture_message_content while OTel v2 is off
The legacy OTel callbacks never read the per-destination setting, so a team
could register no_content and still export prompts and replies under the
global capture mode. Registration now refuses the var unless the proxy runs
with LITELLM_OTEL_V2=true, the same rule the Arize transport and New Relic
routing vars follow.
* test(otel): type the OTel v2 fixtures and the v2-off regression test
* fix(otel): accept only no_content and span_only on a team or key destination
OTel v2 writes captured content only to span attributes, so event_only
behaved like no_content and span_and_event like span_only on a
destination. The proxy-wide setting keeps all four values
* docs(otel): say an omitted capture setting follows the proxy's own callback for that backend
* test(otel): describe the general capture fallback in the unowned destination test
---------
Co-authored-by: mrinal
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: yucheng-berri
Co-authored-by: yucheng-berri <293926326+yucheng-berri@users.noreply.github.com>
---
litellm/integrations/otel/README.md | 4 +-
litellm/integrations/otel/langfuse_logger.py | 6 +
litellm/integrations/otel/logger.py | 17 +-
litellm/integrations/otel/model/config.py | 59 +-
.../integrations/otel/model/destination.py | 19 +-
.../integrations/otel/plumbing/providers.py | 187 ++++-
litellm/integrations/otel/plumbing/routing.py | 3 +-
.../integrations/otel/presets/destinations.py | 2 +
litellm/integrations/otel/presets/newrelic.py | 7 +-
.../initialize_dynamic_callback_params.py | 8 +
litellm/proxy/_types.py | 6 +-
.../callback_config_validation.py | 81 +-
litellm/proxy/litellm_pre_call_utils.py | 39 +-
.../team_callback_endpoints.py | 13 +
litellm/types/utils.py | 22 +
tests/integration/_support/otlp_sink.py | 5 +-
.../test_otel_team_capture_message_content.py | 720 ++++++++++++++++++
.../integrations/otel/test_langfuse_logger.py | 34 +-
.../otel/test_otel_v2_destinations.py | 582 +++++++++++++-
.../integrations/otel/test_otel_v2_logger.py | 59 +-
.../otel/test_otel_v2_sources_of_truth.py | 13 +
.../test_callback_config_validation.py | 115 +++
.../test_team_callback_endpoints.py | 60 ++
tests/unit/types/test_utils.py | 40 +
ui/litellm-dashboard/src/lib/http/schema.d.ts | 3 +
25 files changed, 2019 insertions(+), 85 deletions(-)
create mode 100644 tests/integration/observability/test_otel_team_capture_message_content.py
create mode 100644 tests/unit/types/test_utils.py
diff --git a/litellm/integrations/otel/README.md b/litellm/integrations/otel/README.md
index 38f96f954f1..4b963ca3415 100644
--- a/litellm/integrations/otel/README.md
+++ b/litellm/integrations/otel/README.md
@@ -295,7 +295,9 @@ nothing here imports outside it:
- [`config.py`](./model/config.py) — `OpenTelemetryV2Config`, a pydantic-settings
model that reads `OTEL_*` / `LITELLM_OTEL_*` env vars, plus the feature gate.
`capture_span_content` gates whether prompt/response bodies may be written as
- span attributes; it defaults **off** (`no_content`). The Baggage allowlists are
+ span attributes; it defaults **off** (`no_content`). A team or key can override
+ the global mode per OTel v2 destination with `capture_message_content`; omitted
+ values follow the proxy's own callback for that backend, else the global mode. The Baggage allowlists are
configurable, not hard-coded: set `LITELLM_OTEL_BAGGAGE_PROMOTED_KEYS` /
`LITELLM_OTEL_BAGGAGE_METADATA_KEYS` /
`LITELLM_OTEL_BAGGAGE_TEAM_METADATA_KEYS` (comma-separated) as env vars, or
diff --git a/litellm/integrations/otel/langfuse_logger.py b/litellm/integrations/otel/langfuse_logger.py
index d029b153c52..8f6a7d5eb51 100644
--- a/litellm/integrations/otel/langfuse_logger.py
+++ b/litellm/integrations/otel/langfuse_logger.py
@@ -51,6 +51,10 @@ class LangfuseContentOpenTelemetryV2(LangfuseOpenTelemetryV2):
response: "AsyncIterator[ModelResponseStream]",
request_data: Mapping[str, object],
) -> "AsyncGenerator[ModelResponseStream, None]":
+ if not self._capture_span_content():
+ async for chunk in response:
+ yield chunk
+ return
relayed: Final[list[ModelResponseStream]] = [] # mutable-ok: relayed as they arrive, assembled at end of stream
async for chunk in response:
relayed.append(chunk)
@@ -58,6 +62,8 @@ class LangfuseContentOpenTelemetryV2(LangfuseOpenTelemetryV2):
self._stamp_root_io(request_data, lambda: stream_output(tuple(relayed), request_data))
def _stamp_root_io(self, data: Mapping[str, object], render_output: Callable[[], str | None]) -> None:
+ if not self._capture_span_content():
+ return
root: Final = request_root_span()
if root is None or not root.is_recording():
return
diff --git a/litellm/integrations/otel/logger.py b/litellm/integrations/otel/logger.py
index 498ebe655da..d8dccc39c13 100644
--- a/litellm/integrations/otel/logger.py
+++ b/litellm/integrations/otel/logger.py
@@ -58,6 +58,7 @@ from litellm.integrations.otel.plumbing.context import (
is_recordable_span,
mcp_message_transport_span,
post_response_root,
+ request_destinations,
request_root_http_route,
request_root_span,
resolve_internal_call_span_context,
@@ -82,6 +83,7 @@ from litellm.integrations.otel.plumbing.providers import (
resolve_meter_provider,
)
from litellm.integrations.otel.plumbing.routing import TenantTracerCache
+from litellm.types.utils import captures_span_content
if TYPE_CHECKING:
from opentelemetry.metrics import MeterProvider
@@ -254,6 +256,11 @@ class OpenTelemetryV2(CustomLogger):
return None
return GenAIEventRecorder(get_event_logger(provider, LITELLM_TRACER_NAME), provider.resource)
+ def _capture_span_content(self) -> bool:
+ return self.config.capture_span_content or any(
+ captures_span_content(destination.capture_message_content) for destination in request_destinations()
+ )
+
# ====================================================================== #
# Proxy global registration
# ====================================================================== #
@@ -433,7 +440,7 @@ class OpenTelemetryV2(CustomLogger):
return False
payload: Final = cast("StandardLoggingPayload", raw_payload)
data: Final = MCPToolCallSpanData.from_standard_logging_payload(
- payload, capture_content=self.config.capture_span_content
+ payload, capture_content=self._capture_span_content()
)
# A stray LLM carrier from a ``pre_call`` that mis-fired for this id would
# otherwise linger until evicted; drop it so it's neither leaked nor closed
@@ -477,7 +484,7 @@ class OpenTelemetryV2(CustomLogger):
return False
payload: Final = cast("StandardLoggingPayload", raw_payload)
data: Final = MCPListToolsSpanData.from_standard_logging_payload(
- payload, capture_content=self.config.capture_span_content
+ payload, capture_content=self._capture_span_content()
)
if data.identity.call_id:
self._release_carrier(self._open_llm_calls.pop(data.identity.call_id, None))
@@ -569,7 +576,7 @@ class OpenTelemetryV2(CustomLogger):
return None
data: Final = LLMCallSpanData.from_standard_logging_payload(
payload,
- capture_content=self.config.capture_span_content,
+ capture_content=self._capture_span_content(),
time_to_first_chunk_seconds=call.time_to_first_chunk_seconds,
request_route=request_root_http_route(),
request_purpose=call.purpose,
@@ -1076,6 +1083,6 @@ def build_otel_v2_logger(
def _logger_class(config: OpenTelemetryV2Config) -> type[OpenTelemetryV2]:
if "langfuse" not in config.mapper_names:
return OpenTelemetryV2
- from litellm.integrations.otel.langfuse_logger import LangfuseContentOpenTelemetryV2, LangfuseOpenTelemetryV2
+ from litellm.integrations.otel.langfuse_logger import LangfuseContentOpenTelemetryV2
- return LangfuseContentOpenTelemetryV2 if config.capture_span_content else LangfuseOpenTelemetryV2
+ return LangfuseContentOpenTelemetryV2
diff --git a/litellm/integrations/otel/model/config.py b/litellm/integrations/otel/model/config.py
index 3cf49ea2f11..55ef28bf470 100644
--- a/litellm/integrations/otel/model/config.py
+++ b/litellm/integrations/otel/model/config.py
@@ -16,19 +16,17 @@ from litellm.integrations.otel.model.baggage import (
)
from litellm.integrations.otel.model.spans import POSTGRESQL, db_system
from litellm.types.llms.base import LiteLLMBaseModel
-from litellm.types.utils import OtelSpanScope
+from litellm.types.utils import (
+ CAPTURE_MESSAGE_CONTENT_VALUES,
+ CaptureMessageContent,
+ OtelSpanScope,
+ captures_span_content,
+)
#: Master feature-flag env var. The logger is inert until this is truthy.
OTEL_V2_ENV: Final = "LITELLM_OTEL_V2"
-class CaptureMessageContent(str):
- NO_CONTENT = "no_content"
- SPAN_ONLY = "span_only"
- EVENT_ONLY = "event_only"
- SPAN_AND_EVENT = "span_and_event"
-
-
class ExporterOwner(str, Enum):
"""The preset that contributed an exporter. Values match the callback names
in ``presets.PRESET_BY_CALLBACK`` so per-request dynamic-credential routing
@@ -297,9 +295,7 @@ class OpenTelemetryV2Config(BaseSettings):
here are lower_snake_case; normalizing at the boundary keeps both
spellings working and lets every downstream comparison stay exact.
"""
- if isinstance(value, str):
- return value.lower()
- return value
+ return _normalized_capture_message_content(value)
@field_validator("langfuse_span_scope", mode="before")
@classmethod
@@ -371,22 +367,39 @@ class OpenTelemetryV2Config(BaseSettings):
@property
def capture_span_content(self) -> bool:
- """Whether prompt/response content may be stamped as span attributes.
-
- Defaults off (``no_content``): an operator must opt in before message
- bodies leave the process, so a user request can never force its prompt
- or completion into the configured backend while capture is disabled.
- """
- return self.capture_message_content in (
- CaptureMessageContent.SPAN_ONLY,
- CaptureMessageContent.SPAN_AND_EVENT,
- )
+ """Whether the global setting permits prompt/response span attributes."""
+ return captures_span_content(self.capture_message_content)
@classmethod
def from_env(cls) -> "OpenTelemetryV2Config":
return cls()
+def _normalized_capture_message_content(value: object) -> object:
+ if isinstance(value, str):
+ return value.lower()
+ return value
+
+
+class _CaptureMessageContentSettings(BaseSettings):
+ model_config = SettingsConfigDict(extra="ignore", frozen=True)
+
+ capture_message_content: str = Field(
+ default=CaptureMessageContent.NO_CONTENT,
+ validation_alias=AliasChoices("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"),
+ )
+
+ @field_validator("capture_message_content", mode="before")
+ @classmethod
+ def _normalize_capture_message_content(cls, value: object) -> object:
+ return _normalized_capture_message_content(value)
+
+
+def capture_message_content_from_env() -> str:
+ """The global capture mode, read without building a settings model that rereads every other env var"""
+ return _CaptureMessageContentSettings().capture_message_content
+
+
_EXCLUDED_SERVICES_INPUT: Final[TypeAdapter[str | tuple[object, ...]]] = TypeAdapter(str | tuple[object, ...])
@@ -395,6 +408,10 @@ def excluded_db_systems_from(value: object) -> frozenset[str]:
return _normalize_excluded_services(excluded_service_names(value))
+def parse_capture_message_content(value: object) -> str | None:
+ return value if isinstance(value, str) and value in CAPTURE_MESSAGE_CONTENT_VALUES else None
+
+
def excluded_service_names(value: object) -> frozenset[str]:
"""Read a YAML list or comma-separated string of service names, logging and dropping unusable input
so a malformed value cannot stop the OTel logger from being built"""
diff --git a/litellm/integrations/otel/model/destination.py b/litellm/integrations/otel/model/destination.py
index 56b3123660c..b0c22dea292 100644
--- a/litellm/integrations/otel/model/destination.py
+++ b/litellm/integrations/otel/model/destination.py
@@ -11,7 +11,7 @@ from urllib.parse import quote
from pydantic import ConfigDict, Field
from litellm.types.llms.base import LiteLLMBaseModel
-from litellm.types.utils import OtelSpanScope
+from litellm.types.utils import OtelSpanScope, captures_span_content
class OtelDestination(LiteLLMBaseModel):
@@ -50,6 +50,17 @@ class OtelDestination(LiteLLMBaseModel):
default=None,
description="Same, for the requests with a failed span in their tree; ``None`` forwards every one.",
)
+ capture_message_content: str | None = Field(
+ default=None,
+ description=(
+ "An explicit mode overrides the global capture policy for this destination. "
+ "Omitted follows the global setting."
+ ),
+ )
+
+ def captures_content(self, default: str) -> bool:
+ setting: Final = self.capture_message_content
+ return captures_span_content(default if setting is None else setting)
def header_string(self) -> str:
"""Render headers as the ``k=v,k2=v2`` form an ``ExporterSpec`` expects.
@@ -64,9 +75,9 @@ class OtelDestination(LiteLLMBaseModel):
def cache_key(self) -> tuple[str, tuple[tuple[str, str], ...], tuple[tuple[str, str], ...], str | None]:
"""Identity for processor reuse, so one destination means one exporter.
- ``span_scope`` and the sampling rates are left out on purpose: they decide which
- spans reach the processor, not how the processor exports them, so a full and an
- ``llm_only`` view of the same account share one exporter.
+ ``span_scope``, the sampling rates and ``capture_message_content`` are left out on
+ purpose: they decide which spans reach the processor and what they carry, not how
+ the processor exports them, so two views of the same account share one exporter.
"""
return (
self.endpoint,
diff --git a/litellm/integrations/otel/plumbing/providers.py b/litellm/integrations/otel/plumbing/providers.py
index 37a8f1951d9..4e7d4f231ed 100644
--- a/litellm/integrations/otel/plumbing/providers.py
+++ b/litellm/integrations/otel/plumbing/providers.py
@@ -5,7 +5,7 @@ import random
import threading
import time
from collections import OrderedDict
-from collections.abc import Callable, Iterable, Mapping, Sequence
+from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from types import MappingProxyType
from typing import TYPE_CHECKING, Final, Literal
@@ -40,8 +40,19 @@ from opentelemetry.util.types import Attributes, AttributeValue
from litellm._logging import verbose_logger
from litellm._version import version as litellm_version
-from litellm.integrations.otel.mappers.langfuse import LANGFUSE_TRACE_NAME
-from litellm.integrations.otel.model.config import ExporterOwner, ExporterSpec, OpenTelemetryV2Config
+from litellm.integrations.otel.mappers.langfuse import (
+ LANGFUSE_OBSERVATION_INPUT,
+ LANGFUSE_OBSERVATION_OUTPUT,
+ LANGFUSE_TRACE_NAME,
+)
+from litellm.integrations.otel.model.config import (
+ CaptureMessageContent,
+ ExporterOwner,
+ ExporterSpec,
+ OpenTelemetryV2Config,
+ capture_message_content_from_env,
+ captures_span_content,
+)
from litellm.integrations.otel.model.semconv import (
DB,
MCP,
@@ -385,6 +396,26 @@ _CAPTURED_HEADER_PREFIXES: Final = ("http.request.header.", "http.response.heade
# ``?key=`` query parameter.
_URL_KEYS: Final = frozenset({"http.url", "http.target", "url.full"})
_URL_QUERY_KEY: Final = "url.query"
+# Prompt and response content, in every vocabulary the mappers write it in once the
+# global capture policy collects it: GenAI semconv (MCP tool-call arguments and results
+# included), Langfuse, OpenInference's blobs and per-index messages, Langtrace, Weave.
+_MESSAGE_CONTENT_KEYS: Final = frozenset(
+ {
+ GenAI.INPUT_MESSAGES,
+ GenAI.OUTPUT_MESSAGES,
+ GenAI.SYSTEM_INSTRUCTIONS,
+ GenAI.TOOL_CALL_ARGUMENTS,
+ GenAI.TOOL_CALL_RESULT,
+ LANGFUSE_OBSERVATION_INPUT,
+ LANGFUSE_OBSERVATION_OUTPUT,
+ "input.value",
+ "output.value",
+ "llm.prompts",
+ "llm.completions",
+ "weave.output",
+ }
+)
+_INDEXED_MESSAGE_PREFIXES: Final = ("llm.input_messages.", "llm.output_messages.")
class _SpanView(ReadableSpan):
@@ -415,6 +446,19 @@ class _SpanView(ReadableSpan):
)
+def _is_message_content(key: str) -> bool:
+ return key in _MESSAGE_CONTENT_KEYS or key.startswith(_INDEXED_MESSAGE_PREFIXES)
+
+
+def without_message_content(span: ReadableSpan) -> ReadableSpan:
+ """``span`` without its prompt and response content, everything else left as it was."""
+ attributes: Final = span.attributes or _NO_ATTRIBUTES
+ if not any(_is_message_content(key) for key in attributes):
+ return span
+ kept: Final = MappingProxyType({key: value for key, value in attributes.items() if not _is_message_content(key)})
+ return _SpanView(span, span.resource, kept, span.events, span.status, parent=span.parent)
+
+
def _is_database_span(attributes: Mapping[str, AttributeValue]) -> bool:
return any(key in attributes for key in _DB_SYSTEM_KEYS)
@@ -553,7 +597,11 @@ def _tenant_resource(resource: Resource, defaults: Mapping[str, str], extra: Map
return filled.merge(Resource(extra)) if extra else filled
-def _for_destination(span: ReadableSpan, destination: "OtelDestination") -> ReadableSpan:
+def _for_destination(
+ span: ReadableSpan,
+ destination: "OtelDestination",
+ default_capture: str,
+) -> ReadableSpan:
"""The view of ``span`` a tenant destination receives.
A span the tenant's own call produced keeps its error text. Every other span is
@@ -564,8 +612,10 @@ def _for_destination(span: ReadableSpan, destination: "OtelDestination") -> Read
exception it raised and names the operator's guardrail endpoint. Stack traces walk
the operator's install and come off every span, as do the headers the operator
captures on the server span, whose request side holds the caller's bearer token,
- and the query string of the request URL, which can hold the same key. The span
- itself stays, so the tenant still gets the whole trace tree.
+ and the query string of the request URL, which can hold the same key. A
+ destination whose effective setting disables span content loses the prompt and
+ response content too. The span itself stays, so the tenant still gets the whole
+ trace tree.
"""
extra: Final = destination.resource_attributes
defaults: Final = destination.resource_defaults
@@ -573,11 +623,12 @@ def _for_destination(span: ReadableSpan, destination: "OtelDestination") -> Read
database: Final = _is_database_span(attributes)
owned: Final = _is_tenant_owned_span(attributes)
unreachable: Final = _guardrail_unreachable(attributes)
+ redacted: Final = not destination.captures_content(default_capture)
kept: Final = MappingProxyType(
{
key: _without_query(key, value)
for key, value in attributes.items()
- if _tenant_visible(key, database, owned, unreachable)
+ if _tenant_visible(key, database, owned, unreachable) and not (redacted and _is_message_content(key))
}
)
recorded: Final = span.events
@@ -612,6 +663,8 @@ class TenantFanOutSpanProcessor(SpanProcessor):
shutdown_drain_seconds: float = _SHUTDOWN_DRAIN_SECONDS,
operator_sinks: 'Mapping[_SinkKey, "OtelSpanScope"]' = MappingProxyType({}),
excluded_db_systems: frozenset[str] = frozenset(),
+ default_capture: str = CaptureMessageContent.NO_CONTENT,
+ default_capture_by_backend: Mapping[str, str] = MappingProxyType({}),
pending_drains: int = _MAX_PENDING_DRAINS,
drain_pool: _DrainPool | None = None,
sampling_draw: Callable[[], float] | None = None,
@@ -619,6 +672,8 @@ class TenantFanOutSpanProcessor(SpanProcessor):
self._operator_sinks: Final = operator_sinks
self._draw: Final = sampling_draw if sampling_draw is not None else random.random
self._excluded_db_systems: Final = excluded_db_systems
+ self._default_capture: Final = default_capture
+ self._default_capture_by_backend: Final = default_capture_by_backend
self._drain_seconds: Final = shutdown_drain_seconds
self._lock: Final = threading.Condition()
self._closed = False # guarded by ``_lock``: an unlocked read races the teardown it gates
@@ -661,12 +716,22 @@ class TenantFanOutSpanProcessor(SpanProcessor):
for held_span, held_destination in self._settle(trace_id, failed):
self._forward(held_span, held_destination)
+ def _default_capture_for(self, destination: "OtelDestination") -> str:
+ backend: Final = destination.callback_name
+ return (
+ self._default_capture_by_backend.get(backend, self._default_capture) if backend else self._default_capture
+ )
+
def _forward(self, span: ReadableSpan, destination: "OtelDestination") -> None:
processor: Final = self._acquire(destination)
if processor is None:
return
try:
- processor.on_end(_scoped(_for_destination(span, destination), destination.span_scope))
+ processor.on_end(
+ _scoped(
+ _for_destination(span, destination, self._default_capture_for(destination)), destination.span_scope
+ )
+ )
except Exception as exc: # noqa: BLE001 # one destination's failure must not cost the others their span
verbose_logger.debug("OTel V2 fan-out: forwarding to %s failed: %s", destination.endpoint, exc)
finally:
@@ -963,14 +1028,15 @@ class _OverriddenBackendFilter(SpanProcessor):
Wrapping is the only place this works: ``SynchronousMultiSpanProcessor.on_end``
ignores return values, so a sibling processor can never veto the export.
- Under ``additive`` mode nothing is suppressed, so the wrapper passes every span
- straight through and the operator keeps its copy.
+ Under ``additive`` mode spans are not suppressed, though global content policy
+ still strips message content when disabled.
``scope`` narrows what the exporter receives independently of that: under
``llm_only`` the model-call spans go through as trace roots and the rest of the
tree is held back, unless a destination of the request names ``sink``, the account
this exporter writes to, with a wider scope: the fan-out then delivers the rest of
- the tree there and the model call keeps its place in it.
+ the tree there and the model call keeps its place in it. A destination naming
+ ``sink`` sets this exporter's content policy; otherwise it follows global capture.
"""
def __init__(
@@ -979,11 +1045,15 @@ class _OverriddenBackendFilter(SpanProcessor):
owner: str | None,
scope: "OtelSpanScope" = "full",
sink: _SinkKey | None = None,
+ global_captures: bool = True,
+ filter_content: bool = True,
) -> None:
self._inner: Final = inner
self._owner: Final = owner
self._scope: Final = scope
self._sink: Final = sink
+ self._global_captures: Final = global_captures
+ self._filter_content: Final = filter_content
def on_start(self, span: SDKSpan, parent_context: Context | None = None) -> None:
self._inner.on_start(span, parent_context)
@@ -991,7 +1061,28 @@ class _OverriddenBackendFilter(SpanProcessor):
def on_end(self, span: ReadableSpan) -> None:
if self._owner in suppressed_backends() or not _in_scope(span, self._scope):
return
- self._inner.on_end(_scoped(span, self._account_scope()))
+ scoped: Final = _scoped(span, self._account_scope())
+ self._inner.on_end(
+ without_message_content(scoped) if self._filter_content and not self._account_captures_content() else scoped
+ )
+
+ def _account_captures_content(self) -> bool:
+ """Whether a destination of this request that names ``sink`` captures content.
+
+ The fan-out skips a destination this exporter already writes to, so this copy is
+ the one that account gets and has to honor the destination's content mode.
+ """
+ explicit: Final = next(
+ (
+ destination.capture_message_content
+ for destination in request_destinations()
+ if self._sink is not None
+ and destination.capture_message_content is not None
+ and _sink_key(destination.endpoint, destination.headers) == self._sink
+ ),
+ None,
+ )
+ return captures_span_content(explicit) if explicit is not None else self._global_captures
def _account_scope(self) -> "OtelSpanScope":
if self._scope == "full" or self._sink is None:
@@ -1010,6 +1101,25 @@ class _OverriddenBackendFilter(SpanProcessor):
return self._inner.force_flush(timeout_millis)
+class _MessageContentFilter(SpanProcessor):
+ """Strip prompt and response content from every span before ``inner`` exports it."""
+
+ def __init__(self, inner: SpanProcessor) -> None:
+ self._inner: Final = inner
+
+ def on_start(self, span: SDKSpan, parent_context: Context | None = None) -> None:
+ self._inner.on_start(span, parent_context)
+
+ def on_end(self, span: ReadableSpan) -> None:
+ self._inner.on_end(without_message_content(span))
+
+ def shutdown(self) -> None:
+ self._inner.shutdown()
+
+ def force_flush(self, timeout_millis: int = 30000) -> bool:
+ return self._inner.force_flush(timeout_millis)
+
+
def build_span_exporter(config: OpenTelemetryV2Config) -> SpanExporter:
"""Build a single exporter from the top-level config fields.
@@ -1261,12 +1371,23 @@ def build_resource(config: OpenTelemetryV2Config) -> Resource:
return Resource.create(attributes)
+def _spec_processor(
+ spec: ExporterSpec, use_simple_processor: bool | None, strip_message_content: bool
+) -> SpanProcessor:
+ exporting: Final = _processor_for(
+ _exporter_from_spec(spec),
+ (spec.use_simple_processor if spec.use_simple_processor is not None else use_simple_processor),
+ )
+ return _MessageContentFilter(exporting) if strip_message_content else exporting
+
+
def build_tracer_provider(
config: OpenTelemetryV2Config,
exporter: SpanExporter | None = None,
baggage_processor: SpanProcessor | None = None,
use_simple_processor: bool | None = None,
tenant_overrides: bool = False,
+ strip_message_content: bool = False,
) -> TracerProvider:
"""Build the shared :class:`TracerProvider`.
@@ -1285,6 +1406,9 @@ def build_tracer_provider(
``config.langfuse_span_scope`` narrows the exporter owned by ``langfuse_otel``
alone; a collector or any other backend in the same config keeps the full tree.
+ ``strip_message_content`` removes prompt and response content before every
+ exporter, for a routed provider whose spans can carry content another
+ destination asked for.
"""
provider: Final = TracerProvider(resource=build_resource(config))
if baggage_processor is None:
@@ -1300,17 +1424,23 @@ def build_tracer_provider(
for spec in config.exporters:
if spec.requires_headers and not spec.headers:
continue
- exp = _exporter_from_spec(spec)
- processor = _processor_for(
- exp,
- (spec.use_simple_processor if spec.use_simple_processor is not None else use_simple_processor),
- )
+ processor = _spec_processor(spec, use_simple_processor, strip_message_content)
owner = spec.owner.value if tenant_overrides and spec.owner is not None else None
scope = _operator_scope(config, spec)
sink = _sink_key(spec.endpoint, parse_headers(spec.headers)) if _exports_to_the_wire(spec) else None
provider.add_span_processor(
- _OverriddenBackendFilter(processor, owner, scope, sink)
- if owner is not None or scope != "full"
+ _OverriddenBackendFilter(
+ processor,
+ owner,
+ scope,
+ sink,
+ config.capture_span_content,
+ tenant_overrides,
+ )
+ if owner is not None
+ or scope != "full"
+ or sink is not None
+ or (tenant_overrides and not config.capture_span_content)
else processor
)
return provider
@@ -1340,10 +1470,29 @@ def attach_tenant_fan_out(
TenantFanOutSpanProcessor(
operator_sinks=operator_sink_scopes(*configs),
excluded_db_systems=excluded_db_systems,
+ default_capture=_operator_capture_mode(configs),
+ default_capture_by_backend=MappingProxyType(dict(_owned_capture_modes(configs))),
)
)
+def _operator_capture_mode(configs: Sequence[OpenTelemetryV2Config]) -> str:
+ """The mode of the operator's generic ``otel`` callback, so ``callback_settings.otel`` counts as the global default"""
+ return next(
+ (config.capture_message_content for config in configs if any(spec.owner is None for spec in config.exporters)),
+ capture_message_content_from_env(),
+ )
+
+
+def _owned_capture_modes(
+ configs: Sequence[OpenTelemetryV2Config],
+) -> Iterator[tuple[str, str]]:
+ for config in configs:
+ for spec in config.exporters:
+ if spec.owner is not None:
+ yield spec.owner.value, config.capture_message_content
+
+
def deliverable_destinations(
destinations: Iterable["OtelDestination"],
provider: trace.TracerProvider | None = None,
diff --git a/litellm/integrations/otel/plumbing/routing.py b/litellm/integrations/otel/plumbing/routing.py
index d7b1cadfc92..eb90b9035c5 100644
--- a/litellm/integrations/otel/plumbing/routing.py
+++ b/litellm/integrations/otel/plumbing/routing.py
@@ -282,7 +282,8 @@ class TenantTracerCache:
self._providers.move_to_end(cache_key)
return cached
built: Final = build_tracer_provider(
- self._routed_config(credential_headers, project_headers, endpoint, service_name)
+ self._routed_config(credential_headers, project_headers, endpoint, service_name),
+ strip_message_content=not self._config.capture_span_content,
)
self._providers[cache_key] = built
return built
diff --git a/litellm/integrations/otel/presets/destinations.py b/litellm/integrations/otel/presets/destinations.py
index 91341a57634..c4273fbb337 100644
--- a/litellm/integrations/otel/presets/destinations.py
+++ b/litellm/integrations/otel/presets/destinations.py
@@ -187,6 +187,7 @@ def destination_for(
callback_name: str,
params: StandardCallbackDynamicParams,
service_name: str | None = None,
+ capture_message_content: str | None = None,
) -> OtelDestination | None:
"""The destination ``params`` names for ``callback_name``, or ``None``.
@@ -217,6 +218,7 @@ def destination_for(
callback_name=callback_name,
protocol=protocol,
span_scope=_span_scope(callback_name, params),
+ capture_message_content=capture_message_content,
success_sampling_rate=success_sampling_rate,
error_sampling_rate=error_sampling_rate,
)
diff --git a/litellm/integrations/otel/presets/newrelic.py b/litellm/integrations/otel/presets/newrelic.py
index 771b3f643c8..9d8d04d8f0d 100644
--- a/litellm/integrations/otel/presets/newrelic.py
+++ b/litellm/integrations/otel/presets/newrelic.py
@@ -9,6 +9,7 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
from litellm._logging import verbose_logger
from litellm.integrations.otel.model.config import (
+ CaptureMessageContent,
ExporterOwner,
ExporterSpec,
OpenTelemetryV2Config,
@@ -66,7 +67,11 @@ def newrelic_preset(
# New Relic ingests the OTLP GenAI semantic conventions natively.
"mapper_names": ensure_mappers(base.mapper_names, "genai"),
**(
- {"capture_message_content": ("span_only" if settings.record_content else "no_content")}
+ {
+ "capture_message_content": (
+ CaptureMessageContent.SPAN_ONLY if settings.record_content else CaptureMessageContent.NO_CONTENT
+ )
+ }
if settings.record_content is not None
else {}
),
diff --git a/litellm/litellm_core_utils/initialize_dynamic_callback_params.py b/litellm/litellm_core_utils/initialize_dynamic_callback_params.py
index d2ba17e169a..2efeead6bb2 100644
--- a/litellm/litellm_core_utils/initialize_dynamic_callback_params.py
+++ b/litellm/litellm_core_utils/initialize_dynamic_callback_params.py
@@ -6,6 +6,7 @@ from typing import Any, Final
from litellm.types.utils import (
ARIZE_OTLP_PROTOCOLS,
+ CAPTURE_MESSAGE_CONTENT_VALUES,
OTEL_SPAN_SCOPES,
TRUSTED_CALLBACK_VARS_FIELD,
StandardCallbackDynamicParams,
@@ -91,6 +92,13 @@ def validate_arize_otlp_protocol_value(value: str) -> None:
raise ValueError(f"Invalid arize_otlp_protocol {value!r}: must be one of {sorted(ARIZE_OTLP_PROTOCOLS)}")
+def validate_capture_message_content_value(value: str) -> None:
+ if value not in CAPTURE_MESSAGE_CONTENT_VALUES:
+ raise ValueError(
+ f"Invalid capture_message_content {value!r}: must be one of {sorted(CAPTURE_MESSAGE_CONTENT_VALUES)}"
+ )
+
+
# Hardcoded list of supported callback params to avoid runtime inspection issues with TypedDict
_supported_callback_params: Final[tuple[str, ...]] = (
"langfuse_public_key",
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 0715a4cae97..39892bcc29c 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -33,6 +33,7 @@ from litellm._uuid import uuid
from litellm.constants import DEFAULT_STAGGER_WINDOW_SECONDS, MCP_STDIO_ALLOWED_COMMANDS
from litellm.litellm_core_utils.initialize_dynamic_callback_params import (
validate_arize_otlp_protocol_value,
+ validate_capture_message_content_value,
validate_langfuse_environment_value,
validate_langfuse_span_scope_value,
validate_no_callback_env_reference,
@@ -79,6 +80,7 @@ from litellm.types.router import AllowedModelRegion, RouterErrors, UpdateRouterC
from litellm.types.router_weights import validate_router_settings_dict
from litellm.types.secret_managers.main import KeyManagementSystem
from litellm.types.utils import (
+ CAPTURE_MESSAGE_CONTENT_VAR,
AzureSpillover,
CallTypes,
CostBreakdown,
@@ -2202,7 +2204,7 @@ class AddTeamCallback(LiteLLMPydanticObjectBase):
@classmethod
def validate_callback_vars(cls, values):
callback_vars: Final = values.get("callback_vars", {})
- valid_keys: Final = set(StandardCallbackDynamicParams.__annotations__.keys())
+ valid_keys: Final = {*StandardCallbackDynamicParams.__annotations__, CAPTURE_MESSAGE_CONTENT_VAR}
for key, value in callback_vars.items():
if key not in valid_keys:
raise ValueError(f"Invalid callback variable: {key}. Must be one of {valid_keys}")
@@ -2214,6 +2216,8 @@ class AddTeamCallback(LiteLLMPydanticObjectBase):
validate_langfuse_span_scope_value(callback_vars[key])
if key == "arize_otlp_protocol":
validate_arize_otlp_protocol_value(callback_vars[key])
+ if key == CAPTURE_MESSAGE_CONTENT_VAR:
+ validate_capture_message_content_value(callback_vars[key])
return values
diff --git a/litellm/proxy/common_utils/callback_config_validation.py b/litellm/proxy/common_utils/callback_config_validation.py
index 5b9fb2e3977..4956da853c6 100644
--- a/litellm/proxy/common_utils/callback_config_validation.py
+++ b/litellm/proxy/common_utils/callback_config_validation.py
@@ -10,6 +10,8 @@ from collections.abc import Mapping, Sequence
from types import MappingProxyType
from typing import Final
+from litellm.types.utils import CAPTURE_MESSAGE_CONTENT_VAR
+
_NEWRELIC_CALLBACK: Final = "newrelic"
_NEWRELIC_VAR_PREFIX: Final = "newrelic_"
_LANGFUSE_OTEL_CALLBACK: Final = "langfuse_otel"
@@ -36,6 +38,9 @@ def callback_config_error(
)
if langfuse_error is not None:
return langfuse_error
+ capture_error: Final = _capture_message_content_error(callback_name, callback_vars, callback_type)
+ if capture_error is not None:
+ return capture_error
if callback_name != _NEWRELIC_CALLBACK:
return None
return _newrelic_config_error(callback_vars)
@@ -80,6 +85,32 @@ def _langfuse_span_scope_error(callback_name: str | None, callback_vars: Mapping
return None
+def _capture_message_content_error(
+ callback_name: str | None, callback_vars: Mapping[str, str], callback_type: str | None
+) -> str | None:
+ value: Final = callback_vars.get(CAPTURE_MESSAGE_CONTENT_VAR)
+ if value is None:
+ return None
+ from litellm.integrations.otel.model.config import is_otel_v2_enabled
+ from litellm.integrations.otel.presets.destinations import destination_capable_backends
+ from litellm.litellm_core_utils.initialize_dynamic_callback_params import (
+ validate_capture_message_content_value,
+ )
+
+ supported: Final = sorted(destination_capable_backends())
+ if callback_name not in supported:
+ return f"{CAPTURE_MESSAGE_CONTENT_VAR} applies to the OTel v2 callbacks {supported} only, not {callback_name!r}"
+ if not is_otel_v2_enabled():
+ return f"Per-destination {CAPTURE_MESSAGE_CONTENT_VAR} requires the proxy to run with LITELLM_OTEL_V2=true."
+ try:
+ validate_capture_message_content_value(value)
+ except ValueError as e:
+ return str(e)
+ if callback_type == "failure":
+ return f"{CAPTURE_MESSAGE_CONTENT_VAR} needs callback_type 'success' or 'success_and_failure'"
+ return None
+
+
# Which credential family a dynamic variable belongs to. The families are the
# integrations that share one account: every langfuse_* variable configures the
# same Langfuse project whether it rides the classic callback or the OTel one,
@@ -190,20 +221,41 @@ def conflicting_span_scope_error(
)
+def conflicting_capture_error(
+ callback_name: str,
+ callback_vars: Mapping[str, str] | None,
+ stored_entries: Sequence[tuple[str | None, Mapping[str, str]]],
+) -> str | None:
+ incoming: Final = None if callback_vars is None else callback_vars.get(CAPTURE_MESSAGE_CONTENT_VAR)
+ if incoming is None:
+ return None
+ return next(
+ (
+ f"{CAPTURE_MESSAGE_CONTENT_VAR} is already set to {stored!r} by another {callback_name} entry. "
+ f"Every {callback_name} entry shares one value: remove that entry or send the same value."
+ for name, entry_vars in stored_entries
+ if name == callback_name and (stored := entry_vars.get(CAPTURE_MESSAGE_CONTENT_VAR)) not in (None, incoming)
+ ),
+ None,
+ )
+
+
def logging_metadata_config_error(metadata: Mapping[str, object] | None) -> str | None:
"""Validate every ``logging`` entry of a team/key metadata payload."""
if not metadata:
return None
- entries: Final = metadata.get("logging")
- if not isinstance(entries, Sequence) or isinstance(entries, (str, bytes)):
+ entries: Final = _object_sequence(metadata.get("logging"))
+ if entries is None:
return None
entry_vars: Final = tuple(_entry_callback_vars(entry) for entry in entries)
+ named_vars: Final = tuple(zip((_entry_callback_name(entry) for entry in entries), entry_vars))
return next(
(
error
for error in (
*(_logging_entry_error(entry) for entry in entries),
*(conflicting_span_scope_error(entry_vars[i], entry_vars[:i]) for i in range(len(entry_vars))),
+ *(_conflicting_entry_capture_error(named_vars[i], named_vars[:i]) for i in range(len(named_vars))),
)
if error is not None
),
@@ -211,6 +263,31 @@ def logging_metadata_config_error(metadata: Mapping[str, object] | None) -> str
)
+def stored_capture_entries(logging_entries: object) -> tuple[tuple[str | None, Mapping[str, str]], ...]:
+ """The callback name and vars of every stored ``logging`` entry, for ``conflicting_capture_error``."""
+ entries: Final = _object_sequence(logging_entries) or ()
+ return tuple((_entry_callback_name(entry), _entry_callback_vars(entry)) for entry in entries)
+
+
+def _object_sequence(value: object) -> Sequence[object] | None:
+ return value if isinstance(value, Sequence) and not isinstance(value, (str, bytes)) else None
+
+
+def _entry_callback_name(entry: object) -> str | None:
+ match entry:
+ case {"callback_name": str() as callback_name}:
+ return callback_name
+ case _:
+ return None
+
+
+def _conflicting_entry_capture_error(
+ entry: tuple[str | None, Mapping[str, str]], earlier: Sequence[tuple[str | None, Mapping[str, str]]]
+) -> str | None:
+ callback_name, callback_vars = entry
+ return None if callback_name is None else conflicting_capture_error(callback_name, callback_vars, earlier)
+
+
def _entry_callback_vars(entry: object) -> Mapping[str, str]:
callback_vars: Final = entry.get("callback_vars") if isinstance(entry, Mapping) else None
if not isinstance(callback_vars, Mapping):
diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.py
index 0d693b85ce8..fdc2e6d94b8 100644
--- a/litellm/proxy/litellm_pre_call_utils.py
+++ b/litellm/proxy/litellm_pre_call_utils.py
@@ -227,6 +227,7 @@ from litellm.types.litellm_params import AGENTIC_LOOP_KWARG_NAMES
from litellm.types.llms.anthropic import ANTHROPIC_API_HEADERS
from litellm.types.services import ServiceTypes
from litellm.types.utils import (
+ CAPTURE_MESSAGE_CONTENT_VAR,
CustomPricingLiteLLMParams,
LlmProviders,
ProviderSpecificHeader,
@@ -975,6 +976,8 @@ def convert_key_logging_metadata_to_callback(
team_callback_settings_obj.callbacks.append(data.callback_name)
for var, value in data.callback_vars.items():
+ if var == CAPTURE_MESSAGE_CONTENT_VAR:
+ continue
# New Relic routing reads these from the trusted-vars overlay with no
# callback-name check, so scope them to the newrelic entry: a team that
# put newrelic_* under a different callback never asked for New Relic and
@@ -1162,7 +1165,6 @@ def resolve_tenant_otel_destinations(
span still routes to the tenant's credentials the way it did then.
"""
from litellm.integrations.otel.model.config import is_otel_v2_enabled
- from litellm.integrations.otel.presets.destinations import destination_for
if not is_otel_v2_enabled():
return ()
@@ -1186,23 +1188,28 @@ def resolve_tenant_otel_destinations(
for name in dict.fromkeys(
callback.callback_name for callback in callbacks if callback.callback_type != "failure"
)
- if (
- destination := destination_for(
- name,
- _tenant_otel_params(
- MappingProxyType(
- {
- var: value
- for callback in callbacks
- if callback.callback_name == name
- for var, value in callback.callback_vars.items()
- }
- )
- ),
- _tenant_service_name(user_api_key_dict),
+ if (destination := _tenant_destination(name, callbacks, _tenant_service_name(user_api_key_dict))) is not None
+ )
+
+
+def _tenant_destination(
+ name: str, callbacks: Sequence[AddTeamCallback], service_name: str | None
+) -> "OtelDestination | None":
+ from litellm.integrations.otel.model.config import parse_capture_message_content
+ from litellm.integrations.otel.presets.destinations import destination_for
+
+ callback_vars: Final = MappingProxyType(
+ dict(
+ itertools.chain.from_iterable(
+ callback.callback_vars.items() for callback in callbacks if callback.callback_name == name
)
)
- is not None
+ )
+ return destination_for(
+ name,
+ _tenant_otel_params(callback_vars),
+ service_name,
+ parse_capture_message_content(callback_vars.get(CAPTURE_MESSAGE_CONTENT_VAR)),
)
diff --git a/litellm/proxy/management_endpoints/team_callback_endpoints.py b/litellm/proxy/management_endpoints/team_callback_endpoints.py
index 91fd447fb8d..3908ab3c927 100644
--- a/litellm/proxy/management_endpoints/team_callback_endpoints.py
+++ b/litellm/proxy/management_endpoints/team_callback_endpoints.py
@@ -31,8 +31,10 @@ from litellm.proxy._types import (
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
from litellm.proxy.common_utils.callback_config_validation import (
callback_config_error,
+ conflicting_capture_error,
conflicting_span_scope_error,
cross_entry_family_error,
+ stored_capture_entries,
)
from litellm.proxy.common_utils.callback_utils import ( # noqa: F401 # legacy module exports
_CALLBACK_VAR_ENCRYPTED_PREFIX, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package export
@@ -288,6 +290,9 @@ async def add_team_callbacks(
- langfuse_host: The host for the Langfuse callback
- langfuse_environment: The tracing environment for the Langfuse callback (lowercase; falls back to LANGFUSE_TRACING_ENVIRONMENT)
- langfuse_span_scope: For langfuse_otel, "full" (default) sends the whole request trace, "llm_only" sends only the model-call spans
+ - capture_message_content: For OTel v2 callbacks, "no_content" or "span_only".
+ An explicit value overrides the global setting for this destination; omitted follows the proxy's own callback for that backend, else the global setting.
+ "span_only" puts prompt and response content on the destination's spans, "no_content" leaves it out
- gcs_bucket_name: The name of the GCS bucket
- gcs_path_service_account: The path to the GCS service account
- langsmith_api_key: The API key for the Langsmith callback
@@ -351,11 +356,19 @@ async def add_team_callbacks(
# Decrypted, because the checks compare the incoming values against
# the stored ones and the credentials are encrypted at rest.
decrypted_logging: Final = decrypt_callback_vars(team_metadata).get("logging")
+ stored_capture: Final = stored_capture_entries(decrypted_logging)
stored_entries: Final = decrypted_logging if isinstance(decrypted_logging, list) else ()
stored_entry_vars: Final = [entry.get("callback_vars") or {} for entry in stored_entries]
scope_error: Final = conflicting_span_scope_error(data.callback_vars, stored_entry_vars)
if scope_error is not None:
raise _callback_config_error(scope_error)
+ capture_error: Final = conflicting_capture_error(
+ data.callback_name,
+ data.callback_vars,
+ stored_capture,
+ )
+ if capture_error is not None:
+ raise _callback_config_error(capture_error)
# One entry has to own a credential family end to end. The entries are
# flattened into one dict before a request reads them, so an entry
# naming only a destination would pair with a key written on another
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 4a962e5b3bd..d6751610e7a 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -3726,6 +3726,28 @@ ArizeOtlpProtocol = Literal["grpc", "http/protobuf"]
ARIZE_OTLP_PROTOCOLS: Final[frozenset[str]] = frozenset(get_args(ArizeOtlpProtocol))
+CAPTURE_MESSAGE_CONTENT_VAR: Final = "capture_message_content"
+
+
+class CaptureMessageContent(str):
+ NO_CONTENT = "no_content"
+ SPAN_ONLY = "span_only"
+ EVENT_ONLY = "event_only"
+ SPAN_AND_EVENT = "span_and_event"
+
+
+# The values a team or key destination may set. OTel v2 writes content only to span attributes,
+# so the event modes stay global-only settings
+CAPTURE_MESSAGE_CONTENT_VALUES: Final[frozenset[str]] = frozenset(
+ {CaptureMessageContent.NO_CONTENT, CaptureMessageContent.SPAN_ONLY}
+)
+
+
+def captures_span_content(mode: str | None) -> bool:
+ """Whether a capture mode puts prompt and response content on spans"""
+ return mode in (CaptureMessageContent.SPAN_ONLY, CaptureMessageContent.SPAN_AND_EVENT)
+
+
class StandardCallbackDynamicParams(TypedDict, total=False):
# Langfuse dynamic params
langfuse_public_key: str | None
diff --git a/tests/integration/_support/otlp_sink.py b/tests/integration/_support/otlp_sink.py
index eeabe9d886f..a4d2ea30959 100644
--- a/tests/integration/_support/otlp_sink.py
+++ b/tests/integration/_support/otlp_sink.py
@@ -186,6 +186,7 @@ class _Handler(BaseHTTPRequestHandler):
"count": len(recorded),
"host": self.headers.get("host", ""),
"headers": dict(self.headers),
+ "span_ids": [span["span_id"] for span in recorded],
}
)
self._send_json({"recorded": len(recorded)}, status=self.state.status)
@@ -466,9 +467,7 @@ def _await_sink(url: str) -> None:
def owned_grpc_sink(directory: Path) -> Iterator[GrpcSink]:
http_port: Final = _free_port()
grpc_port: Final = _free_port()
- with _spawn_sink(
- directory, "otlp-grpc-sink.log", ["--port", str(http_port), "--grpc-port", str(grpc_port)]
- ):
+ with _spawn_sink(directory, "otlp-grpc-sink.log", ["--port", str(http_port), "--grpc-port", str(grpc_port)]):
control_url: Final = f"http://127.0.0.1:{http_port}"
_await_sink(control_url)
yield GrpcSink(url=f"http://127.0.0.1:{grpc_port}", control_url=control_url)
diff --git a/tests/integration/observability/test_otel_team_capture_message_content.py b/tests/integration/observability/test_otel_team_capture_message_content.py
new file mode 100644
index 00000000000..84da9a40486
--- /dev/null
+++ b/tests/integration/observability/test_otel_team_capture_message_content.py
@@ -0,0 +1,720 @@
+import json
+import re
+import uuid
+from collections.abc import Generator, Iterator, Mapping
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import contextmanager
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Final, Literal
+from urllib.parse import urlparse
+
+import httpx
+import pytest
+import yaml
+from integration._support.client import Gateway, Scenario, eventually, gateway_from_environment, object_value
+from integration._support.otlp_sink import (
+ ConnectSink,
+ Span,
+ SpanSinks,
+ configure_sink,
+ owned_connect_sink,
+ recorded_requests,
+ recorded_spans,
+)
+from integration._support.process import OwnedProxy, owned_proxy_process
+from integration._support.wire import Reply, Request, Wire, wire_server
+from pydantic import JsonValue, TypeAdapter
+
+MARKER: Final = re.compile(rb"cmc-(?:tool-|fail-)?[0-9a-f]{32}")
+JSON: Final[TypeAdapter[JsonValue]] = TypeAdapter(JsonValue)
+SERVER: Final = 2
+CALL_ID: Final = "litellm.call_id"
+OPERATION: Final = "gen_ai.operation.name"
+INPUT_TOKENS: Final = "gen_ai.usage.input_tokens"
+Endpoint = Literal["chat", "responses", "messages"]
+Capture = Literal["no_content", "span_only"]
+
+
+def _marker(kind: str = "") -> str:
+ return f"cmc-{kind}{uuid.uuid4().hex}"
+
+
+def _usage() -> dict[str, JsonValue]:
+ return {"prompt_tokens": 7, "completion_tokens": 2, "total_tokens": 9}
+
+
+def _chat_reply(marker: str, stream: bool) -> Reply:
+ identity: Final = f"chatcmpl-{uuid.uuid4().hex}"
+ if marker.startswith("cmc-tool-"):
+ call: Final[dict[str, JsonValue]] = {
+ "id": "call_1",
+ "type": "function",
+ "function": {"name": "lookup", "arguments": json.dumps({"query": marker})},
+ }
+ message: Final[dict[str, JsonValue]] = {"role": "assistant", "content": None, "tool_calls": [call]}
+ return Reply(
+ body=json.dumps(
+ {
+ "id": identity,
+ "object": "chat.completion",
+ "created": 1,
+ "model": "gpt-4o-mini",
+ "choices": [{"index": 0, "message": message, "finish_reason": "tool_calls"}],
+ "usage": _usage(),
+ }
+ ).encode()
+ )
+ if not stream:
+ return Reply(
+ body=json.dumps(
+ {
+ "id": identity,
+ "object": "chat.completion",
+ "created": 1,
+ "model": "gpt-4o-mini",
+ "choices": [
+ {"index": 0, "message": {"role": "assistant", "content": marker}, "finish_reason": "stop"}
+ ],
+ "usage": _usage(),
+ }
+ ).encode()
+ )
+ chunk: Final = {"id": identity, "object": "chat.completion.chunk", "created": 1, "model": "gpt-4o-mini"}
+ deltas: Final[tuple[dict[str, JsonValue], ...]] = (
+ {**chunk, "choices": [{"index": 0, "delta": {"role": "assistant", "content": marker}}]},
+ {**chunk, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
+ {**chunk, "choices": [], "usage": _usage()},
+ )
+ return Reply(
+ content_type="text/event-stream",
+ chunks=(*(b"data: " + json.dumps(delta).encode() + b"\n\n" for delta in deltas), b"data: [DONE]\n\n"),
+ )
+
+
+def _responses_reply(marker: str, stream: bool) -> Reply:
+ identity: Final = uuid.uuid4().hex
+ response: Final[dict[str, JsonValue]] = {
+ "id": f"resp_{identity}",
+ "object": "response",
+ "created_at": 1,
+ "status": "completed",
+ "model": "gpt-4o-mini",
+ "output": [
+ {
+ "id": f"msg_{identity}",
+ "type": "message",
+ "role": "assistant",
+ "status": "completed",
+ "content": [{"type": "output_text", "text": marker, "annotations": []}],
+ }
+ ],
+ "usage": {"input_tokens": 7, "output_tokens": 2, "total_tokens": 9},
+ }
+ if not stream:
+ return Reply(body=json.dumps(response).encode())
+ events: Final[tuple[dict[str, JsonValue], ...]] = (
+ {
+ "type": "response.created",
+ "sequence_number": 0,
+ "response": {**response, "status": "in_progress", "output": []},
+ },
+ {
+ "type": "response.output_text.delta",
+ "sequence_number": 1,
+ "item_id": f"msg_{identity}",
+ "output_index": 0,
+ "content_index": 0,
+ "delta": marker,
+ },
+ {"type": "response.completed", "sequence_number": 2, "response": response},
+ )
+ return Reply(
+ content_type="text/event-stream",
+ chunks=tuple(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n".encode() for event in events),
+ )
+
+
+def _upstream(request: Request) -> Reply:
+ found: Final = MARKER.search(request.body)
+ if found is None:
+ return Reply(status=404, body=b'{"error":"no marker"}')
+ marker: Final = found.group(0).decode()
+ if marker.startswith("cmc-fail-"):
+ return Reply(status=500, body=b'{"error":{"message":"scripted upstream failure","type":"server_error"}}')
+ stream: Final = object_value(JSON.validate_json(request.body)).get("stream") is True
+ if request.target.endswith("/responses"):
+ return _responses_reply(marker, stream)
+ return _chat_reply(marker, stream)
+
+
+def _body(model: str, endpoint: Endpoint, marker: str, stream: bool) -> tuple[str, dict[str, JsonValue]]:
+ if endpoint == "responses":
+ return "/v1/responses", {"model": model, "input": marker, "stream": stream}
+ messages: Final[list[JsonValue]] = [{"role": "user", "content": marker}]
+ if endpoint == "messages":
+ return "/v1/messages", {"model": model, "max_tokens": 16, "messages": messages, "stream": stream}
+ return "/v1/chat/completions", {"model": model, "messages": messages, "stream": stream}
+
+
+@dataclass(frozen=True, slots=True)
+class Sent:
+ marker: str
+ trace_id: str
+ call_id: str
+ status: int
+ text: str
+
+
+@dataclass(frozen=True, slots=True)
+class Cursors:
+ operator: int
+ tenant: int
+ arize: int
+ newrelic: int
+
+
+@dataclass(frozen=True, slots=True)
+class Rig:
+ proxy: Gateway
+ owned: OwnedProxy
+ scenario: Scenario
+ model: str
+ upstream: Wire
+ sinks: SpanSinks
+ newrelic: ConnectSink
+
+ def cursors(self) -> Cursors:
+ self.upstream.drain()
+ return Cursors(
+ recorded_spans(self.sinks.operator)[0],
+ recorded_spans(self.sinks.tenant)[0],
+ recorded_spans(self.sinks.arize)[0],
+ recorded_spans(self.newrelic.control_url)[0],
+ )
+
+ def upstream_hits(self, marker: str) -> int:
+ return sum(1 for request in self.upstream.drain() if marker.encode() in request.body)
+
+ def langfuse(self, name: str, host: str | None = None) -> dict[str, str]:
+ return {
+ "langfuse_public_key": f"pk-lf-{name}",
+ "langfuse_secret_key": f"sk-lf-{name}",
+ "langfuse_host": host or self.sinks.tenant,
+ }
+
+ def attach(self, team: str, callback: str, variables: Mapping[str, str], kind: str | None = None) -> httpx.Response:
+ body: Final[dict[str, JsonValue]] = {"callback_name": callback, "callback_vars": dict(variables)}
+ return self.proxy.request(
+ "POST", f"/team/{team}/callback", body if kind is None else {**body, "callback_type": kind}
+ )
+
+ def team_key(
+ self,
+ capture: Capture | None,
+ name: str,
+ *,
+ callback: str = "langfuse_otel",
+ variables: Mapping[str, str] | None = None,
+ kind: str | None = None,
+ ) -> tuple[str, str]:
+ team: Final = self.scenario.team()
+ base: Final = dict(variables) if variables is not None else self.langfuse(name)
+ attached: Final = self.attach(
+ team, callback, base if capture is None else {**base, "capture_message_content": capture}, kind
+ )
+ assert attached.status_code == 200, attached.text
+ return team, self.scenario.key(team_id=team)
+
+ def send(
+ self,
+ key: str,
+ endpoint: Endpoint = "chat",
+ stream: bool = False,
+ *,
+ marker: str | None = None,
+ extra: Mapping[str, JsonValue] | None = None,
+ ) -> Sent:
+ tagged: Final = marker or _marker()
+ path, body = _body(self.model, endpoint, tagged, stream)
+ trace_id: Final = uuid.uuid4().hex
+ call_id: Final = str(uuid.uuid4())
+ headers: Final = {
+ "Authorization": f"Bearer {key}",
+ "traceparent": f"00-{trace_id}-{uuid.uuid4().hex[:16]}-01",
+ "x-litellm-call-id": call_id,
+ }
+ with self.proxy.client.stream("POST", path, json={**body, **(extra or {})}, headers=headers) as response:
+ text: Final = response.read().decode()
+ return Sent(tagged, trace_id, call_id, response.status_code, text)
+
+
+def _served(sent: Sent) -> Sent:
+ assert sent.status == 200, sent.text
+ assert sent.marker in sent.text, sent.text
+ return sent
+
+
+Credential = tuple[str, str]
+
+
+def _sent_with(url: str, credential: Credential) -> frozenset[str]:
+ """Span ids ``url`` received in export requests whose ``credential`` header matched."""
+ header, value = credential
+ return frozenset(
+ span_id
+ for request in recorded_requests(url)
+ if {name.lower(): seen for name, seen in object_value(request.get("headers") or {}).items()}.get(header)
+ == value
+ for span_id in request.get("span_ids") or ()
+ if isinstance(span_id, str)
+ )
+
+
+def _of_request(url: str, since: int, sent: Sent, credential: Credential | None = None) -> tuple[Span, ...]:
+ """Spans of ``sent``'s trace at ``url``, narrowed to one account's export requests when ``credential`` is set."""
+ spans: Final = recorded_spans(url, since)[1]
+ traces: Final = {sent.trace_id} | {
+ span["trace_id"] for span in spans if span["attributes"].get(CALL_ID) == sent.call_id
+ }
+ owned: Final = None if credential is None else _sent_with(url, credential)
+ return tuple(span for span in spans if span["trace_id"] in traces and (owned is None or span["span_id"] in owned))
+
+
+def _carries(span: Span, marker: str) -> bool:
+ return marker in json.dumps(span["attributes"])
+
+
+def _model_spans(spans: tuple[Span, ...]) -> tuple[Span, ...]:
+ return tuple(span for span in spans if OPERATION in span["attributes"])
+
+
+def _names(spans: tuple[Span, ...]) -> list[str]:
+ return sorted(span["name"] for span in spans)
+
+
+def _with_content(url: str, since: int, sent: Sent) -> tuple[Span, ...]:
+ """The copy of ``sent`` at ``url`` once its model span arrived and some span carries the marker."""
+ return eventually(
+ lambda: _of_request(url, since, sent),
+ lambda spans: bool(_model_spans(spans)) and any(_carries(span, sent.marker) for span in spans),
+ seconds=40,
+ )
+
+
+def _arrived(
+ url: str, since: int, sent: Sent, expected: frozenset[str], credential: Credential | None = None
+) -> tuple[Span, ...]:
+ """The copy of ``sent`` at ``url`` once every span name in ``expected`` and a usage-bearing model span landed."""
+ spans: Final = eventually(
+ lambda: _of_request(url, since, sent, credential),
+ lambda found: (
+ expected <= {span["name"] for span in found}
+ and any(INPUT_TOKENS in span["attributes"] for span in _model_spans(found))
+ ),
+ seconds=40,
+ )
+ assert all(
+ span["attributes"].get(INPUT_TOKENS) == 7 for span in _model_spans(spans) if INPUT_TOKENS in span["attributes"]
+ )
+ return spans
+
+
+def _assert_redacted_twin(
+ rig: Rig, sent: Sent, cursors: Cursors, sink: str, since: int, credential: Credential | None = None
+) -> tuple[Span, ...]:
+ operator: Final = _with_content(rig.sinks.operator, cursors.operator, sent)
+ carried: Final = frozenset(span["name"] for span in operator if _carries(span, sent.marker))
+ tenant: Final = _arrived(sink, since, sent, carried, credential)
+ leaked: Final = [span["name"] for span in tenant if _carries(span, sent.marker)]
+ assert leaked == [], f"{leaked} carried content; tenant saw {_names(tenant)}"
+ model: Final = _model_spans(tenant)[0]["attributes"]
+ assert "gen_ai.input.messages" not in model and "gen_ai.output.messages" not in model, sorted(model)
+ assert model.get("gen_ai.request.model"), sorted(model)
+ return tenant
+
+
+def _assert_content_twin(rig: Rig, sent: Sent, cursors: Cursors) -> None:
+ operator: Final = _with_content(rig.sinks.operator, cursors.operator, sent)
+ carried: Final = frozenset(span["name"] for span in operator if _carries(span, sent.marker))
+ tenant: Final = _arrived(rig.sinks.tenant, cursors.tenant, sent, carried)
+ kept: Final = frozenset(span["name"] for span in tenant if _carries(span, sent.marker))
+ assert carried <= kept, f"content lost on {sorted(carried - kept)}"
+
+
+@pytest.mark.parametrize(
+ ("endpoint", "stream"),
+ [("chat", False), ("chat", True), ("responses", False), ("messages", True)],
+ ids=["chat-unary", "chat-stream", "responses-unary", "messages-stream"],
+)
+def test_no_content_team_keeps_its_trace_and_metadata_without_content(
+ rig: Rig, endpoint: Endpoint, stream: bool
+) -> None:
+ _, key = rig.team_key("no_content", "a")
+ cursors: Final = rig.cursors()
+ sent: Final = _served(rig.send(key, endpoint, stream))
+ assert rig.upstream_hits(sent.marker) == 1
+ _assert_redacted_twin(rig, sent, cursors, rig.sinks.tenant, cursors.tenant)
+
+
+@pytest.mark.parametrize("capture", ["span_only", None], ids=["span_only", "omitted"])
+def test_span_only_and_omitted_teams_keep_the_globally_captured_content(rig: Rig, capture: Capture | None) -> None:
+ _, key = rig.team_key(capture, "b")
+ cursors: Final = rig.cursors()
+ sent: Final = _served(rig.send(key))
+ _assert_content_twin(rig, sent, cursors)
+
+
+def test_tool_call_arguments_never_reach_a_no_content_team(rig: Rig) -> None:
+ _, key = rig.team_key("no_content", "a")
+ cursors: Final = rig.cursors()
+ tool: Final[dict[str, JsonValue]] = {
+ "type": "function",
+ "function": {"name": "lookup", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}}},
+ }
+ sent: Final = rig.send(key, marker=_marker("tool-"), extra={"tools": [tool]})
+ assert sent.status == 200 and sent.marker in sent.text, sent.text
+ operator: Final = _with_content(rig.sinks.operator, cursors.operator, sent)
+ assert any(sent.marker in str(span["attributes"].get("gen_ai.output.messages", "")) for span in operator), (
+ "operator copy lacks the tool-call arguments"
+ )
+ tenant: Final = _assert_redacted_twin(rig, sent, cursors, rig.sinks.tenant, cursors.tenant)
+ assert "lookup" in json.dumps([span["attributes"] for span in tenant]), "tool definitions are metadata and stay"
+
+
+def test_cache_hit_twin_of_a_no_content_team_is_redacted(rig: Rig) -> None:
+ _, key = rig.team_key("no_content", "a")
+ marker: Final = _marker()
+ _served(rig.send(key, marker=marker))
+ assert rig.upstream_hits(marker) == 1
+ cursors: Final = rig.cursors()
+ hit: Final = eventually(
+ lambda: _served(rig.send(key, marker=marker)), lambda _: rig.upstream_hits(marker) == 0, seconds=20
+ )
+ operator: Final = eventually(
+ lambda: _of_request(rig.sinks.operator, cursors.operator, hit),
+ lambda spans: any(span["kind"] == SERVER for span in spans),
+ seconds=40,
+ )
+ expected: Final = frozenset(span["name"] for span in operator if span["kind"] == SERVER)
+ tenant: Final = eventually(
+ lambda: _of_request(rig.sinks.tenant, cursors.tenant, hit),
+ lambda spans: expected <= {span["name"] for span in spans},
+ seconds=40,
+ )
+ assert [span["name"] for span in tenant if _carries(span, marker)] == [], _names(tenant)
+
+
+def test_a_failure_only_entry_rejects_the_setting(rig: Rig) -> None:
+ team: Final = rig.scenario.team()
+ response: Final = rig.attach(
+ team, "langfuse_otel", {**rig.langfuse("fail"), "capture_message_content": "no_content"}, "failure"
+ )
+ assert response.status_code == 400, response.text
+ assert "success_and_failure" in response.text, response.text
+
+
+def test_key_level_logging_with_no_content_is_redacted(rig: Rig) -> None:
+ logging: Final[list[JsonValue]] = [
+ {
+ "callback_name": "langfuse_otel",
+ "callback_type": "success",
+ "callback_vars": {**rig.langfuse("key"), "capture_message_content": "no_content"},
+ }
+ ]
+ key: Final = rig.scenario.key(metadata={"logging": logging})
+ cursors: Final = rig.cursors()
+ sent: Final = _served(rig.send(key))
+ _assert_redacted_twin(rig, sent, cursors, rig.sinks.tenant, cursors.tenant)
+
+
+def test_same_account_destination_redacts_the_shared_copy_only_for_that_team(rig: Rig) -> None:
+ _, restricted = rig.team_key("no_content", "operator", variables=rig.langfuse("operator", host=rig.sinks.operator))
+ _, other = rig.team_key("span_only", "b")
+ cursors: Final = rig.cursors()
+ shared: Final = _served(rig.send(restricted))
+ assert rig.upstream_hits(shared.marker) == 1
+ copy: Final = eventually(
+ lambda: _of_request(rig.sinks.operator, cursors.operator, shared),
+ lambda spans: any(INPUT_TOKENS in span["attributes"] for span in _model_spans(spans)),
+ seconds=40,
+ )
+ assert [span["name"] for span in copy if _carries(span, shared.marker)] == [], _names(copy)
+ assert len([span for span in copy if span["kind"] == SERVER and span["name"].startswith("POST ")]) == 1, _names(
+ copy
+ )
+ _assert_content_twin(rig, _served(rig.send(other)), cursors)
+
+
+def test_arize_destination_drops_openinference_content(rig: Rig) -> None:
+ _, key = rig.team_key(
+ "no_content", "arize", callback="arize", variables={"arize_space_key": "space-a", "arize_api_key": "arize-a"}
+ )
+ cursors: Final = rig.cursors()
+ sent: Final = _served(rig.send(key))
+ operator: Final = _with_content(rig.sinks.operator, cursors.operator, sent)
+ assert any(sent.marker in str(span["attributes"].get("input.value", "")) for span in operator), (
+ "operator copy has no OpenInference content to strip"
+ )
+ tenant: Final = _assert_redacted_twin(
+ rig, sent, cursors, rig.sinks.arize, cursors.arize, ("arize-space-id", "space-a")
+ )
+ model: Final = _model_spans(tenant)[0]["attributes"]
+ assert not any(name.startswith(("llm.input_messages.", "llm.output_messages.")) for name in model), sorted(model)
+ assert "input.value" not in model and "output.value" not in model, sorted(model)
+ assert model.get("llm.model_name"), sorted(model)
+
+
+def test_weave_destination_drops_its_content(rig: Rig) -> None:
+ _, key = rig.team_key(
+ "no_content",
+ "weave",
+ callback="weave_otel",
+ variables={"wandb_api_key": "wandb-a", "weave_project_id": "team/a"},
+ )
+ cursors: Final = rig.cursors()
+ sent: Final = _served(rig.send(key))
+ operator: Final = eventually(
+ lambda: _of_request(rig.sinks.arize, cursors.arize, sent, ("project_id", "operator/weave")),
+ lambda spans: any(sent.marker in str(span["attributes"].get("weave.output", "")) for span in spans),
+ seconds=40,
+ )
+ assert operator, "operator weave copy has no weave.output to strip"
+ tenant: Final = _assert_redacted_twin(rig, sent, cursors, rig.sinks.arize, cursors.arize, ("project_id", "team/a"))
+ assert not any("weave.output" in span["attributes"] for span in tenant), _names(tenant)
+
+
+def test_newrelic_destination_drops_genai_content(rig: Rig) -> None:
+ _, key = rig.team_key("no_content", "newrelic", callback="newrelic", variables={"newrelic_api_key": "nr-team-a"})
+ cursors: Final = rig.cursors()
+ sent: Final = _served(rig.send(key))
+ tenant: Final = _assert_redacted_twin(
+ rig, sent, cursors, rig.newrelic.control_url, cursors.newrelic, ("api-key", "nr-team-a")
+ )
+ hosts: Final = {
+ object_value(request.get("headers") or {}).get("Host")
+ for request in recorded_requests(rig.newrelic.control_url)
+ if object_value(request.get("headers") or {}).get("api-key") == "nr-team-a"
+ }
+ assert hosts == {"otlp.nr-data.net"}, hosts
+ assert tenant
+
+
+def test_span_only_team_lifts_global_no_content_only_for_its_destination(dark_rig: Rig) -> None:
+ """The sibling Arize entry gets a fan-out destination and the SigNoz entry rides the routed tracer."""
+ team, key = dark_rig.team_key("span_only", "b")
+ siblings: Final = (
+ dark_rig.attach(team, "arize", {"arize_space_key": "space-sibling", "arize_api_key": "arize-sibling"}),
+ dark_rig.attach(
+ team,
+ "signoz",
+ {"signoz_ingestion_endpoint": dark_rig.sinks.arize + "/v1/traces", "signoz_ingestion_key": "signoz-team"},
+ ),
+ )
+ assert [response.status_code for response in siblings] == [200, 200], [response.text for response in siblings]
+ cursors: Final = dark_rig.cursors()
+ sent: Final = _served(dark_rig.send(key))
+ assert dark_rig.upstream_hits(sent.marker) == 1
+ operator: Final = _arrived(dark_rig.sinks.operator, cursors.operator, sent, frozenset())
+ tenant: Final = _with_content(dark_rig.sinks.tenant, cursors.tenant, sent)
+ sibling: Final = _arrived(
+ dark_rig.sinks.arize,
+ cursors.arize,
+ sent,
+ frozenset(),
+ ("arize-space-id", "space-sibling"),
+ )
+ signoz: Final = _arrived(
+ dark_rig.sinks.arize,
+ cursors.arize,
+ sent,
+ frozenset(),
+ ("signoz-ingestion-key", "signoz-team"),
+ )
+ assert any(_carries(span, sent.marker) for span in tenant), _names(tenant)
+ assert not any(_carries(span, sent.marker) for span in operator), _names(operator)
+ assert not any(_carries(span, sent.marker) for span in sibling), _names(sibling)
+ assert not any(_carries(span, sent.marker) for span in signoz), _names(signoz)
+
+
+def test_an_unsupported_value_fails_registration(rig: Rig) -> None:
+ team: Final = rig.scenario.team()
+ response: Final = rig.attach(team, "langfuse_otel", {**rig.langfuse("a"), "capture_message_content": "bogus"})
+ assert response.status_code == 422, response.text
+ assert "Invalid capture_message_content 'bogus'" in response.text, response.text
+
+
+def test_classic_langfuse_rejects_the_setting(rig: Rig) -> None:
+ team: Final = rig.scenario.team()
+ response: Final = rig.attach(team, "langfuse", {**rig.langfuse("a"), "capture_message_content": "no_content"})
+ assert response.status_code == 400, response.text
+ assert "capture_message_content" in response.text, response.text
+
+
+def test_a_second_entry_for_the_same_backend_cannot_disagree(rig: Rig) -> None:
+ team, _ = rig.team_key("no_content", "a")
+ response: Final = rig.attach(team, "langfuse_otel", {"capture_message_content": "span_only"}, "success_and_failure")
+ assert response.status_code == 400, response.text
+ assert "already set to 'no_content' by another langfuse_otel entry" in response.text, response.text
+
+
+def test_replacing_the_registration_switches_the_team_to_content(rig: Rig) -> None:
+ team, key = rig.team_key("no_content", "a")
+ cursors: Final = rig.cursors()
+ _assert_redacted_twin(rig, _served(rig.send(key)), cursors, rig.sinks.tenant, cursors.tenant)
+ removed: Final = rig.proxy.request("DELETE", f"/team/{team}/callback/langfuse_otel")
+ assert removed.status_code == 200, removed.text
+ replaced: Final = rig.attach(team, "langfuse_otel", {**rig.langfuse("a"), "capture_message_content": "span_only"})
+ assert replaced.status_code == 200, replaced.text
+
+ def attempt() -> bool:
+ since: Final = rig.cursors()
+ sent: Final = _served(rig.send(key))
+ operator: Final = _with_content(rig.sinks.operator, since.operator, sent)
+ carried: Final = frozenset(span["name"] for span in operator if _carries(span, sent.marker))
+ tenant: Final = _arrived(rig.sinks.tenant, since.tenant, sent, carried)
+ return any(_carries(span, sent.marker) for span in tenant)
+
+ assert eventually(attempt, bool, seconds=60)
+
+
+def test_request_metadata_cannot_lift_the_team_restriction(rig: Rig) -> None:
+ _, key = rig.team_key("no_content", "a")
+ cursors: Final = rig.cursors()
+ sent: Final = _served(rig.send(key, extra={"metadata": {"capture_message_content": "span_only"}}))
+ assert rig.upstream_hits(sent.marker) == 1
+ _assert_redacted_twin(rig, sent, cursors, rig.sinks.tenant, cursors.tenant)
+
+
+def test_stalled_tenant_during_a_mixed_burst_keeps_serving_and_each_teams_policy(rig: Rig) -> None:
+ _, restricted = rig.team_key("no_content", "a")
+ _, open_key = rig.team_key("span_only", "b")
+ shapes: Final[tuple[tuple[Endpoint, bool], ...]] = (
+ ("chat", False),
+ ("chat", True),
+ ("responses", False),
+ ("messages", True),
+ )
+ plan: Final = [(restricted if index % 2 else open_key, *shapes[index % len(shapes)]) for index in range(30)]
+ cursors: Final = rig.cursors()
+ configure_sink(rig.sinks.tenant, paused=True)
+ try:
+ with ThreadPoolExecutor(max_workers=10) as pool:
+ sent: Final = list(pool.map(lambda job: rig.send(job[0], job[1], job[2]), plan))
+ finally:
+ configure_sink(rig.sinks.tenant, paused=False)
+ assert [result.status for result in sent] == [200] * 30, [result.text for result in sent if result.status != 200]
+ for (key, _, _), result in zip(plan, sent, strict=True):
+ roots = [
+ span
+ for span in _with_content(rig.sinks.operator, cursors.operator, result)
+ if span["kind"] == SERVER and span["name"].startswith("POST ")
+ ]
+ assert len(roots) == 1, roots
+ if key == restricted:
+ _assert_redacted_twin(rig, result, cursors, rig.sinks.tenant, cursors.tenant)
+ else:
+ _assert_content_twin(rig, result, cursors)
+
+
+def _write_config(directory: Path, sinks: SpanSinks, name: str, callbacks: tuple[str, ...]) -> Path:
+ config: Final = yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text())
+ config["litellm_settings"] = {
+ **config.get("litellm_settings", {}),
+ "callbacks": list(callbacks),
+ "otel_tenant_destination_mode": "additive",
+ "provider_url_destination_allowed_hosts": [
+ urlparse(sinks.tenant).netloc,
+ urlparse(sinks.operator).netloc,
+ urlparse(sinks.arize).netloc,
+ ],
+ }
+ config["general_settings"] = {**config.get("general_settings", {}), "user_api_key_cache_ttl": 2}
+ path: Final = directory / f"{name}.yaml"
+ path.write_text(yaml.safe_dump(config))
+ return path
+
+
+@contextmanager
+def _started(
+ provider: Wire,
+ sinks: SpanSinks,
+ newrelic: ConnectSink,
+ directory: Path,
+ capture: str | None,
+ callbacks: tuple[str, ...] = ("langfuse_otel",),
+) -> Generator[Rig]:
+ environment: Final = {
+ "LITELLM_OTEL_V2": "1",
+ "OTEL_BSP_SCHEDULE_DELAY": "300",
+ "MAPPER_NAMES": "genai,openinference",
+ "LANGFUSE_HOST": sinks.operator,
+ "LANGFUSE_PUBLIC_KEY": "pk-lf-operator",
+ "LANGFUSE_SECRET_KEY": "sk-lf-operator",
+ "ARIZE_SPACE_KEY": "space-operator",
+ "ARIZE_API_KEY": "arize-operator",
+ "ARIZE_HTTP_ENDPOINT": sinks.arize + "/v1/traces",
+ "WANDB_API_KEY": "wandb-operator",
+ "WANDB_PROJECT_ID": "operator/weave",
+ "WANDB_HOST": sinks.arize,
+ "SIGNOZ_INGESTION_ENDPOINT": sinks.arize + "/v1/traces",
+ "SIGNOZ_INGESTION_KEY": "signoz-operator",
+ "HTTPS_PROXY": newrelic.proxy_url,
+ "NO_PROXY": "127.0.0.1,localhost",
+ "REQUESTS_CA_BUNDLE": newrelic.ca_pem,
+ **({} if capture is None else {"OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT": capture}),
+ }
+ with (
+ gateway_from_environment() as gateway,
+ owned_proxy_process(
+ gateway,
+ directory,
+ environment,
+ config=_write_config(directory, sinks, "capture", callbacks),
+ remove_environment=(
+ "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT",
+ "LITELLM_OTEL_TENANT_DESTINATION_MODE",
+ ),
+ workers=2,
+ ) as owned,
+ owned.gateway.scenario() as scenario,
+ ):
+ yield Rig(
+ owned.gateway, owned, scenario, scenario.model(api_base=provider.url + "/v1"), provider, sinks, newrelic
+ )
+
+
+@pytest.fixture(scope="module")
+def provider() -> Iterator[Wire]:
+ with wire_server(_upstream) as wire:
+ yield wire
+
+
+@pytest.fixture(scope="module")
+def newrelic_sink(tmp_path_factory: pytest.TempPathFactory) -> Iterator[ConnectSink]:
+ with owned_connect_sink(tmp_path_factory.mktemp("newrelic-sink")) as sink:
+ yield sink
+
+
+@pytest.fixture(scope="module")
+def rig(
+ provider: Wire, audit_sinks: SpanSinks, newrelic_sink: ConnectSink, tmp_path_factory: pytest.TempPathFactory
+) -> Iterator[Rig]:
+ directory: Final = tmp_path_factory.mktemp("capture-span-only")
+ with _started(provider, audit_sinks, newrelic_sink, directory, "span_only") as started:
+ yield started
+
+
+@pytest.fixture(scope="module")
+def dark_rig(
+ provider: Wire, audit_sinks: SpanSinks, newrelic_sink: ConnectSink, tmp_path_factory: pytest.TempPathFactory
+) -> Iterator[Rig]:
+ with _started(
+ provider,
+ audit_sinks,
+ newrelic_sink,
+ tmp_path_factory.mktemp("capture-no-content"),
+ None,
+ ("langfuse_otel", "signoz"),
+ ) as started:
+ yield started
diff --git a/tests/unit/integrations/otel/test_langfuse_logger.py b/tests/unit/integrations/otel/test_langfuse_logger.py
index aca9dcc8a5e..ff2060d91c2 100644
--- a/tests/unit/integrations/otel/test_langfuse_logger.py
+++ b/tests/unit/integrations/otel/test_langfuse_logger.py
@@ -16,6 +16,7 @@ import litellm # noqa: E402
from litellm.caching.dual_cache import DualCache # noqa: E402
from litellm.integrations.otel.logger import OpenTelemetryV2, build_otel_v2_logger # noqa: E402
from litellm.integrations.otel.model.config import OpenTelemetryV2Config, is_otel_v2_enabled # noqa: E402
+from litellm.integrations.otel.model.destination import OtelDestination # noqa: E402
from litellm.integrations.otel.model.spans import LITELLM_PROXY_REQUEST_SPAN_NAME, SpanRole # noqa: E402
from litellm.integrations.otel.plumbing import context as otel_context # noqa: E402
from litellm.integrations.otel.plumbing import providers # noqa: E402
@@ -155,6 +156,25 @@ def test_chat_request_stamps_root_observation_input_and_output():
assert [(turn["role"], turn["content"]) for turn in output] == [("assistant", "pong")]
+def test_content_on_destination_stamps_langfuse_root_io_when_global_capture_is_off() -> None:
+ logger, exporter = _logger(capture="no_content")
+ destination: Final = OtelDestination(
+ endpoint="https://team.example.com/api/public/otel",
+ callback_name="langfuse_otel",
+ capture_message_content="span_only",
+ )
+ token: Final = otel_context.set_request_destinations((destination,))
+ try:
+ response: Final = ModelResponse(choices=[Choices(message=Message(role="assistant", content="pong"))])
+ _run_request(logger, CHAT_DATA, "acompletion", response)
+ finally:
+ otel_context.reset_request_destinations(token)
+
+ attrs: Final = _root_attrs(exporter)
+ assert json.loads(attrs[INPUT_ATTR]) == [{"role": "user", "content": "ping"}]
+ assert json.loads(attrs[OUTPUT_ATTR]) == [{"role": "assistant", "content": "pong"}]
+
+
def test_responses_request_folds_instructions_into_input_and_stamps_output_items():
logger, exporter = _logger()
data = {"model": "gpt-5.4-mini", "instructions": "be terse", "input": "ping"}
@@ -461,7 +481,9 @@ def test_a_request_without_trace_controls_stamps_none_of_them():
logger, exporter = _logger()
root_attrs, generation_attrs = _run_named_request(
- logger, exporter, {"metadata": {"user_api_key_team_id": "t1", "tags": []}, "proxy_server_request": {"headers": {}}}
+ logger,
+ exporter,
+ {"metadata": {"user_api_key_team_id": "t1", "tags": []}, "proxy_server_request": {"headers": {}}},
)
assert set(TRACE_CONTROL_ATTRS).isdisjoint(root_attrs)
@@ -472,7 +494,7 @@ def test_a_request_without_trace_controls_stamps_none_of_them():
("capture", "mappers"),
[("no_content", ("genai", "langfuse")), ("span_only", ("genai",))],
)
-def test_factory_keeps_the_base_logger_unless_langfuse_content_capture_is_on(capture, mappers):
+def test_langfuse_root_io_requires_global_or_destination_capture(capture: str, mappers: tuple[str, ...]) -> None:
logger, exporter = _logger(capture=capture, mappers=mappers)
_run_request(logger, CHAT_DATA, "acompletion", ModelResponse())
@@ -484,13 +506,13 @@ def test_factory_keeps_the_base_logger_unless_langfuse_content_capture_is_on(cap
("capture", "mappers", "relays_streams"),
[
("span_only", ("genai", "langfuse"), True),
- ("no_content", ("genai", "langfuse"), False),
+ ("no_content", ("genai", "langfuse"), True),
("span_only", ("genai",), False),
],
)
-def test_only_langfuse_content_capture_takes_proxy_streams_off_the_fast_path(
- monkeypatch, capture, mappers, relays_streams
-):
+def test_langfuse_mapper_relays_streams_for_per_request_content_capture(
+ monkeypatch: pytest.MonkeyPatch, capture: str, mappers: tuple[str, ...], relays_streams: bool
+) -> None:
logger, _ = _logger(capture=capture, mappers=mappers)
monkeypatch.setattr(litellm, "callbacks", [logger])
diff --git a/tests/unit/integrations/otel/test_otel_v2_destinations.py b/tests/unit/integrations/otel/test_otel_v2_destinations.py
index 2d7e0745039..5c9cab88784 100644
--- a/tests/unit/integrations/otel/test_otel_v2_destinations.py
+++ b/tests/unit/integrations/otel/test_otel_v2_destinations.py
@@ -5,6 +5,7 @@ import contextvars
import time
from base64 import b64encode
from collections.abc import Mapping
+from dataclasses import replace
from datetime import datetime, timezone
from functools import reduce
from types import MappingProxyType
@@ -13,13 +14,14 @@ from typing import Final
import pytest
from opentelemetry import trace as trace_api
from opentelemetry.sdk.resources import Resource
-from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import Status, StatusCode
import litellm
from litellm.integrations.custom_logger import CustomLogger
+from litellm.integrations.otel import GenAIOperation
from litellm.integrations.otel import logger as otel_logger
from litellm.integrations.otel.logger import (
OpenTelemetryV2,
@@ -27,13 +29,24 @@ from litellm.integrations.otel.logger import (
fan_out_provider,
publish_global_otel_v2_provider,
)
+from litellm.integrations.otel.mappers import resolve_mappers
from litellm.integrations.otel.model.config import (
+ CaptureMessageContent,
ExporterOwner,
ExporterSpec,
OpenTelemetryV2Config,
is_otel_v2_enabled,
)
from litellm.integrations.otel.model.destination import OtelDestination
+from litellm.integrations.otel.model.payloads import (
+ LLMCallSpanData,
+ LLMRequestParams,
+ LLMUsage,
+ MCPToolCallSpanData,
+ RequestIdentity,
+ ServerInfo,
+ ToolDefinition,
+)
from litellm.integrations.otel.plumbing import providers as otel_providers
from litellm.integrations.otel.plumbing.context import (
destination_backends,
@@ -44,9 +57,11 @@ from litellm.integrations.otel.plumbing.providers import (
TenantFanOutSpanProcessor,
_OverriddenBackendFilter,
_sink_key,
+ attach_tenant_fan_out,
build_tracer_provider,
deliverable_destinations,
operator_sink_scopes,
+ register_exporter_factory,
)
from litellm.integrations.otel.plumbing.routing import TenantTracerCache, get_tracer
from litellm.integrations.otel.presets.arize import arize_preset
@@ -55,7 +70,7 @@ from litellm.integrations.otel.presets.destinations import (
destination_for,
)
from litellm.integrations.otel.presets.langfuse import langfuse_preset
-from litellm.proxy._types import AddTeamCallback, UserAPIKeyAuth
+from litellm.proxy._types import AddTeamCallback, TeamCallbackMetadata, UserAPIKeyAuth
from litellm.proxy.litellm_pre_call_utils import (
convert_key_logging_metadata_to_callback,
resolve_tenant_otel_destinations,
@@ -4228,6 +4243,569 @@ class TestTenantHostSsrfGuard:
assert sum("provider_url_destination_allowed_hosts" in record.message for record in caplog.records) == 1
+_ALL_MAPPERS: Final = ("genai", "legacy", "openinference", "langfuse", "weave", "langtrace")
+_SECRET: Final = "SECRET-MARKER"
+_MODEL_CALL_WITH_CONTENT: Final = LLMCallSpanData(
+ operation=GenAIOperation.CHAT,
+ provider="openai",
+ request_model="gpt-4o",
+ response_model="gpt-4o-2024",
+ response_id="resp_1",
+ request_params=LLMRequestParams(temperature=0.5, max_tokens=128),
+ usage=LLMUsage(input_tokens=12, output_tokens=8, total_tokens=20),
+ finish_reasons=("tool_calls",),
+ error=None,
+ response_cost=0.001,
+ server=ServerInfo("api.openai.com", 443),
+ identity=RequestIdentity(call_id="c1", team_id="t1"),
+ tools=(ToolDefinition(name="lookup", description="Find a city", parameters_json='{"type":"object"}'),),
+ messages_in=(
+ {"role": "system", "content": f"system {_SECRET}"},
+ {"role": "user", "content": f"prompt {_SECRET}"},
+ ),
+ choices_out=(
+ {
+ "finish_reason": "tool_calls",
+ "message": {
+ "role": "assistant",
+ "content": f"answer {_SECRET}",
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {"name": "lookup", "arguments": f'{{"city": "{_SECRET}"}}'},
+ }
+ ],
+ },
+ },
+ ),
+)
+_MODEL_CALL_WITHOUT_CONTENT: Final = replace(_MODEL_CALL_WITH_CONTENT, messages_in=(), choices_out=())
+_TOOL_CALL_WITH_CONTENT: Final = MCPToolCallSpanData(
+ operation=GenAIOperation.EXECUTE_TOOL,
+ method="tools/call",
+ tool_name="lookup",
+ server_name="maps",
+ server_address="maps.local",
+ server_port=443,
+ session_id="s1",
+ arguments_json=f'{{"city": "{_SECRET}"}}',
+ result_json=f'{{"weather": "{_SECRET}"}}',
+ error=None,
+ response_cost=None,
+ identity=RequestIdentity(call_id="c2", team_id="t1"),
+)
+_TOOL_CALL_WITHOUT_CONTENT: Final = replace(_TOOL_CALL_WITH_CONTENT, arguments_json=None, result_json=None)
+
+NO_CONTENT_DEST = OtelDestination(
+ endpoint="http://team-a.local/api/public/otel",
+ headers=MappingProxyType({"Authorization": "Basic YQ=="}),
+ callback_name="langfuse_otel",
+ capture_message_content="no_content",
+)
+INHERITING_DEST = OtelDestination(
+ endpoint="http://team-b.local/v1",
+ headers=MappingProxyType({"api_key": "k", "arize-space-id": "s"}),
+ callback_name="arize",
+)
+
+
+def mapped(data: LLMCallSpanData | MCPToolCallSpanData) -> Mapping[str, object]:
+ """What the configured mappers write on the span, the way the logger stamps it."""
+ return MappingProxyType(reduce(lambda acc, mapper: {**acc, **mapper.map(data)}, resolve_mappers(_ALL_MAPPERS), {}))
+
+
+def recorded(attributes: Mapping[str, object]) -> dict[str, object]:
+ """``attributes`` the way the SDK records them, sequences frozen into tuples."""
+ return {key: tuple(value) if isinstance(value, list) else value for key, value in attributes.items()}
+
+
+def model_call_tree(provider: TracerProvider, attributes: Mapping[str, object]) -> None:
+ tracer: Final = get_tracer(provider, "litellm")
+ with tracer.start_as_current_span("POST /v1/chat/completions"):
+ with tracer.start_as_current_span("chat gpt-4o") as llm:
+ llm.set_attributes(attributes)
+ llm.add_event("gen_ai.content.first_chunk", {"gen_ai.response.model": "gpt-4o-2024"})
+
+
+def by_name(exporter: InMemorySpanExporter) -> dict[str, ReadableSpan]:
+ return {span.name: span for span in exporter.get_finished_spans()}
+
+
+def carries_content(span: ReadableSpan) -> bool:
+ return any(_SECRET in str(value) for value in span.attributes.values())
+
+
+class TestCaptureMessageContent:
+ """A destination's explicit capture mode overrides the global default."""
+
+ @staticmethod
+ def _fan_out(
+ operator: InMemorySpanExporter,
+ exporters: Mapping[str, InMemorySpanExporter],
+ default_capture: CaptureMessageContent = CaptureMessageContent.SPAN_ONLY,
+ ) -> TracerProvider:
+ provider: Final = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(operator))
+ provider.add_span_processor(
+ TenantFanOutSpanProcessor(
+ processor_factory=lambda d: SimpleSpanProcessor(exporters[d.endpoint]),
+ default_capture=default_capture,
+ )
+ )
+ return provider
+
+ @staticmethod
+ def _run(
+ provider: TracerProvider, destinations: tuple[OtelDestination, ...], attributes: Mapping[str, object]
+ ) -> None:
+ def run() -> None:
+ set_request_destinations(destinations)
+ model_call_tree(provider, attributes)
+
+ in_fresh_context(run)
+
+ @pytest.mark.parametrize(
+ ("setting", "content_exported"),
+ [
+ (None, True),
+ ("no_content", False),
+ ("span_only", True),
+ ("event_only", False),
+ ("span_and_event", True),
+ ],
+ )
+ def test_a_destination_setting_controls_its_copy_and_omission_uses_the_global_default(
+ self, setting: str | None, content_exported: bool
+ ) -> None:
+ attributes: Final = mapped(_MODEL_CALL_WITH_CONTENT)
+ destination: Final = OtelDestination(
+ endpoint="http://team.local/api/public/otel",
+ headers=MappingProxyType({"Authorization": "Basic dA=="}),
+ callback_name="langfuse_otel",
+ capture_message_content=setting,
+ )
+ operator, tenant = InMemorySpanExporter(), InMemorySpanExporter()
+
+ self._run(self._fan_out(operator, {destination.endpoint: tenant}), (destination,), attributes)
+
+ exported: Final = by_name(tenant)["chat gpt-4o"]
+ assert carries_content(exported) is content_exported
+ assert carries_content(by_name(operator)["chat gpt-4o"])
+ assert exported.attributes["gen_ai.request.model"] == "gpt-4o"
+ assert exported.attributes["gen_ai.usage.input_tokens"] == 12
+ assert exported.attributes["gen_ai.usage.output_tokens"] == 8
+
+ def test_a_span_only_team_lifts_global_no_content_only_for_its_destination(self) -> None:
+ operator_exporter, team_exporter, sibling_exporter = (
+ InMemorySpanExporter(),
+ InMemorySpanExporter(),
+ InMemorySpanExporter(),
+ )
+ kind: Final = "lit8244_global_no_content_capture"
+ register_exporter_factory(kind, lambda _spec: operator_exporter)
+ config: Final = OpenTelemetryV2Config(
+ capture_message_content=CaptureMessageContent.NO_CONTENT,
+ exporters=[ExporterSpec(kind=kind)],
+ )
+ provider: Final = build_tracer_provider(config, use_simple_processor=True, tenant_overrides=True)
+ team: Final = OtelDestination(
+ endpoint="http://team.local/api/public/otel",
+ headers=MappingProxyType({"Authorization": "Basic dA=="}),
+ callback_name="langfuse_otel",
+ capture_message_content="span_only",
+ )
+ sibling: Final = INHERITING_DEST
+ provider.add_span_processor(
+ TenantFanOutSpanProcessor(
+ processor_factory=lambda destination: SimpleSpanProcessor(
+ team_exporter if destination.endpoint == team.endpoint else sibling_exporter
+ ),
+ default_capture=config.capture_message_content,
+ )
+ )
+
+ self._run(
+ provider,
+ (team, sibling),
+ mapped(_MODEL_CALL_WITH_CONTENT),
+ )
+
+ assert carries_content(by_name(team_exporter)["chat gpt-4o"])
+ assert not any(carries_content(span) for span in operator_exporter.get_finished_spans())
+ assert not any(carries_content(span) for span in sibling_exporter.get_finished_spans())
+
+ @pytest.mark.parametrize(
+ ("with_content", "without_content"),
+ [
+ (_MODEL_CALL_WITH_CONTENT, _MODEL_CALL_WITHOUT_CONTENT),
+ (_TOOL_CALL_WITH_CONTENT, _TOOL_CALL_WITHOUT_CONTENT),
+ ],
+ ids=["model_call", "mcp_tool_call"],
+ )
+ def test_no_content_removes_exactly_what_global_capture_adds_in_every_mapper_vocabulary(
+ self,
+ with_content: LLMCallSpanData | MCPToolCallSpanData,
+ without_content: LLMCallSpanData | MCPToolCallSpanData,
+ ) -> None:
+ captured, uncaptured = mapped(with_content), mapped(without_content)
+ assert frozenset(captured) - frozenset(uncaptured), "the fixture must exercise captured content"
+ operator, tenant = InMemorySpanExporter(), InMemorySpanExporter()
+
+ self._run(self._fan_out(operator, {NO_CONTENT_DEST.endpoint: tenant}), (NO_CONTENT_DEST,), captured)
+
+ exported: Final = by_name(tenant)["chat gpt-4o"]
+ assert dict(exported.attributes) == recorded(uncaptured), "only content goes, every other attribute stays"
+ assert not carries_content(exported)
+
+ def test_restricting_one_destination_leaves_the_original_span_and_the_other_destination_alone(self) -> None:
+ attributes: Final = mapped(_MODEL_CALL_WITH_CONTENT)
+ operator, restricted, inheriting = InMemorySpanExporter(), InMemorySpanExporter(), InMemorySpanExporter()
+ exporters: Final = {NO_CONTENT_DEST.endpoint: restricted, INHERITING_DEST.endpoint: inheriting}
+
+ self._run(self._fan_out(operator, exporters), (NO_CONTENT_DEST, INHERITING_DEST), attributes)
+
+ original: Final = by_name(operator)
+ kept: Final = by_name(inheriting)
+ stripped: Final = by_name(restricted)
+ assert dict(original["chat gpt-4o"].attributes) == recorded(attributes)
+ assert dict(kept["chat gpt-4o"].attributes) == recorded(attributes)
+ assert not carries_content(stripped["chat gpt-4o"])
+ for copy in (kept, stripped):
+ for name, span in copy.items():
+ assert span.context == original[name].context, "same trace id and span id"
+ assert span.parent == original[name].parent, "same place in the tree"
+ assert [e.name for e in copy["chat gpt-4o"].events] == [e.name for e in original["chat gpt-4o"].events]
+
+ def test_an_omitted_setting_and_span_only_export_the_same_span(self) -> None:
+ attributes: Final = mapped(_MODEL_CALL_WITH_CONTENT)
+ span_only: Final = INHERITING_DEST.model_copy(
+ update={"capture_message_content": CaptureMessageContent.SPAN_ONLY}
+ )
+ omitted_exporter, span_only_exporter = InMemorySpanExporter(), InMemorySpanExporter()
+
+ for destination, exporter in ((INHERITING_DEST, omitted_exporter), (span_only, span_only_exporter)):
+ self._run(
+ self._fan_out(InMemorySpanExporter(), {destination.endpoint: exporter}), (destination,), attributes
+ )
+
+ assert {n: dict(s.attributes) for n, s in by_name(omitted_exporter).items()} == {
+ n: dict(s.attributes) for n, s in by_name(span_only_exporter).items()
+ }
+
+ @pytest.mark.parametrize(
+ ("globally_captured", "setting", "content_exported"),
+ [
+ (True, "no_content", False),
+ (True, None, True),
+ (False, "span_only", True),
+ (False, None, False),
+ ],
+ )
+ def test_the_operators_exporter_on_the_same_account_honors_the_teams_setting_once(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ globally_captured: bool,
+ setting: str | None,
+ content_exported: bool,
+ ) -> None:
+ """The fan-out skips a destination the operator already writes to, so the operator's
+ copy is the one that account receives and must not bypass the team's restriction."""
+ monkeypatch.setattr(litellm, "otel_tenant_destination_mode", "additive", raising=False)
+ shared: Final = InMemorySpanExporter()
+ provider: Final = TracerProvider()
+ provider.add_span_processor(
+ _OverriddenBackendFilter(
+ SimpleSpanProcessor(shared),
+ "langfuse_otel",
+ "full",
+ TestRoutingMode.OPERATOR_SINK,
+ global_captures=globally_captured,
+ )
+ )
+ provider.add_span_processor(
+ TenantFanOutSpanProcessor(
+ processor_factory=lambda _d: SimpleSpanProcessor(shared),
+ operator_sinks=MappingProxyType({TestRoutingMode.OPERATOR_SINK: "full"}),
+ )
+ )
+ destination: Final = OtelDestination(
+ endpoint=TestRoutingMode.SAME_ACCOUNT_ENDPOINT,
+ headers=MappingProxyType({"Authorization": "Basic op"}),
+ callback_name="langfuse_otel",
+ capture_message_content=setting,
+ )
+
+ self._run(provider, (destination,), mapped(_MODEL_CALL_WITH_CONTENT))
+
+ model_calls: Final = [s for s in shared.get_finished_spans() if s.name == "chat gpt-4o"]
+ assert len(model_calls) == 1, "the same account received the span twice"
+ assert carries_content(model_calls[0]) is content_exported
+
+ @pytest.mark.parametrize("mode", ["override", "additive"])
+ def test_an_operator_collector_on_the_teams_account_does_not_bypass_no_content(
+ self, monkeypatch: pytest.MonkeyPatch, mode: str
+ ) -> None:
+ monkeypatch.setattr(litellm, "otel_tenant_destination_mode", mode, raising=False)
+ shared: Final = InMemorySpanExporter()
+ kind: Final = f"lit8244_collector_{mode}"
+ register_exporter_factory(kind, lambda _spec: shared)
+ config: Final = OpenTelemetryV2Config(
+ exporters=[
+ ExporterSpec(
+ kind=kind,
+ endpoint=TestRoutingMode.OPERATOR_SINK[0],
+ headers="authorization=Basic op",
+ )
+ ]
+ )
+ provider: Final = build_tracer_provider(config, use_simple_processor=True, tenant_overrides=True)
+ provider.add_span_processor(
+ TenantFanOutSpanProcessor(
+ processor_factory=lambda _d: SimpleSpanProcessor(shared),
+ operator_sinks=operator_sink_scopes(config),
+ )
+ )
+ destination: Final = OtelDestination(
+ endpoint=TestRoutingMode.SAME_ACCOUNT_ENDPOINT,
+ headers=MappingProxyType({"Authorization": "Basic op"}),
+ callback_name="langfuse_otel",
+ capture_message_content="no_content",
+ )
+
+ self._run(provider, (destination,), mapped(_MODEL_CALL_WITH_CONTENT))
+
+ model_calls: Final = [s for s in shared.get_finished_spans() if s.name == "chat gpt-4o"]
+ assert model_calls, "the account must receive the model call before its content can be judged absent"
+ assert not any(carries_content(span) for span in model_calls)
+
+ @pytest.mark.parametrize(
+ ("global_capture", "content_exported"),
+ [(CaptureMessageContent.NO_CONTENT, False), (CaptureMessageContent.SPAN_ONLY, True)],
+ )
+ def test_a_routed_provider_exports_content_only_when_the_global_setting_captures(
+ self, global_capture: str, content_exported: bool
+ ) -> None:
+ """A sibling destination's span_only makes the logger collect content, and a request
+ routed to this callback's team credentials must not carry it under a global no_content."""
+ exporters: dict[ExporterOwner | None, InMemorySpanExporter] = {}
+ kind: Final = f"lit8244_routed_{global_capture}"
+ register_exporter_factory(kind, lambda spec: exporters.setdefault(spec.owner, InMemorySpanExporter()))
+ config: Final = OpenTelemetryV2Config(
+ capture_message_content=global_capture,
+ exporters=[
+ ExporterSpec(
+ kind=kind,
+ endpoint="http://op.local",
+ owner=ExporterOwner.LANGFUSE_OTEL,
+ use_simple_processor=True,
+ ),
+ ExporterSpec(kind=kind),
+ ],
+ )
+ cache: Final = TenantTracerCache(config, "langfuse_otel", "litellm")
+
+ route: Final = cache.route_for(
+ get_tracer(TracerProvider(), "litellm"),
+ {"langfuse_public_key": "pk-team", "langfuse_secret_key": "sk-team"},
+ )
+ with route.tracer.start_as_current_span("chat gpt-4o") as llm:
+ llm.set_attributes(mapped(_MODEL_CALL_WITH_CONTENT))
+ cache.release(route.provider)
+
+ assert route.detached is True
+ for exporter in (exporters[ExporterOwner.LANGFUSE_OTEL], exporters[None]):
+ copy = by_name(exporter)["chat gpt-4o"]
+ assert carries_content(copy) is content_exported
+ assert copy.attributes["gen_ai.usage.input_tokens"] == 12
+
+ @pytest.mark.parametrize("first", ["newrelic", "langfuse_otel"])
+ def test_an_omitted_setting_follows_its_own_callbacks_mode_whatever_the_callback_order(
+ self, monkeypatch: pytest.MonkeyPatch, first: str
+ ) -> None:
+ monkeypatch.delenv("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", raising=False)
+ tenant: Final = InMemorySpanExporter()
+ monkeypatch.setitem(otel_providers._EXPORTER_FACTORIES, "otlp_http", lambda _spec: tenant)
+ langfuse: Final = OpenTelemetryV2Config(
+ capture_message_content=CaptureMessageContent.SPAN_ONLY,
+ exporters=[ExporterSpec(kind="in_memory", owner=ExporterOwner.LANGFUSE_OTEL)],
+ )
+ newrelic: Final = OpenTelemetryV2Config(
+ capture_message_content=CaptureMessageContent.NO_CONTENT,
+ exporters=[ExporterSpec(kind="in_memory", owner=ExporterOwner.NEWRELIC)],
+ )
+ provider: Final = TracerProvider()
+ attach_tenant_fan_out(provider, *((newrelic, langfuse) if first == "newrelic" else (langfuse, newrelic)))
+ destination: Final = OtelDestination(
+ endpoint="http://team.local/api/public/otel",
+ headers=MappingProxyType({"Authorization": "Basic dA=="}),
+ callback_name="langfuse_otel",
+ )
+
+ self._run(provider, (destination,), mapped(_MODEL_CALL_WITH_CONTENT))
+ provider.force_flush()
+
+ assert carries_content(by_name(tenant)["chat gpt-4o"])
+
+ def test_an_omitted_setting_follows_the_capture_mode_set_in_callback_settings_otel(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.delenv("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", raising=False)
+ tenant: Final = InMemorySpanExporter()
+ monkeypatch.setitem(otel_providers._EXPORTER_FACTORIES, "otlp_http", lambda _spec: tenant)
+ operator: Final = OpenTelemetryV2Config(**{"capture_message_content": "span_only", "exporter": "in_memory"})
+ provider: Final = TracerProvider()
+ attach_tenant_fan_out(provider, operator)
+ destination: Final = OtelDestination(
+ endpoint="http://team.local/api/public/otel",
+ headers=MappingProxyType({"Authorization": "Basic dA=="}),
+ callback_name="langfuse_otel",
+ )
+
+ self._run(provider, (destination,), mapped(_MODEL_CALL_WITH_CONTENT))
+ provider.force_flush()
+
+ assert carries_content(by_name(tenant)["chat gpt-4o"]), "the YAML value is the global default, not only the env"
+
+ def test_a_published_presets_capture_mode_is_the_default_for_an_unowned_destination(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """A destination for a backend the proxy does not export to itself falls back to the published logger's mode,
+ here New Relic with record_content on, so it keeps the content."""
+ monkeypatch.delenv("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", raising=False)
+ tenant: Final = InMemorySpanExporter()
+ monkeypatch.setitem(otel_providers._EXPORTER_FACTORIES, "otlp_http", lambda _spec: tenant)
+ newrelic: Final = OpenTelemetryV2Config(
+ capture_message_content=CaptureMessageContent.SPAN_ONLY,
+ exporters=[
+ ExporterSpec(kind="console"),
+ ExporterSpec(kind="in_memory", owner=ExporterOwner.NEWRELIC),
+ ],
+ )
+ provider: Final = TracerProvider()
+ attach_tenant_fan_out(provider, newrelic)
+ destination: Final = OtelDestination(
+ endpoint="http://team.local/api/public/otel",
+ headers=MappingProxyType({"Authorization": "Basic dA=="}),
+ callback_name="langfuse_otel",
+ )
+
+ self._run(provider, (destination,), mapped(_MODEL_CALL_WITH_CONTENT))
+ provider.force_flush()
+
+ assert carries_content(by_name(tenant)["chat gpt-4o"])
+
+ @pytest.mark.usefixtures("allow_test_hosts")
+ @pytest.mark.parametrize("setting", ["no_content", "span_only", None])
+ def test_the_setting_rides_the_teams_destination_and_omission_stays_omitted(
+ self, monkeypatch: pytest.MonkeyPatch, setting: str | None
+ ) -> None:
+ monkeypatch.setenv("LITELLM_OTEL_V2", "true")
+ is_otel_v2_enabled.cache_clear()
+ callback_vars: Final = {
+ "langfuse_public_key": "pk-team",
+ "langfuse_secret_key": "sk-team",
+ "langfuse_host": "http://team.local",
+ }
+ if setting is not None:
+ callback_vars["capture_message_content"] = setting
+ auth: Final = UserAPIKeyAuth(
+ team_metadata={
+ "logging": [
+ {"callback_name": "langfuse_otel", "callback_type": "success", "callback_vars": callback_vars},
+ {
+ "callback_name": "arize",
+ "callback_type": "success",
+ "callback_vars": {"arize_api_key": "k", "arize_space_id": "s"},
+ },
+ ]
+ }
+ )
+
+ destinations: Final = {d.callback_name: d for d in resolve_tenant_otel_destinations(auth)}
+
+ assert destinations["langfuse_otel"].capture_message_content == setting
+ assert destinations["arize"].capture_message_content is None, "the setting stays on its own callback"
+
+ @pytest.mark.usefixtures("allow_test_hosts")
+ @pytest.mark.parametrize("setting", ["event_only", "span_and_event"])
+ def test_a_stored_event_mode_is_skipped_like_any_invalid_entry(
+ self, monkeypatch: pytest.MonkeyPatch, setting: str
+ ) -> None:
+ monkeypatch.setenv("LITELLM_OTEL_V2", "true")
+ is_otel_v2_enabled.cache_clear()
+ auth: Final = UserAPIKeyAuth(
+ team_metadata={
+ "logging": [
+ {
+ "callback_name": "langfuse_otel",
+ "callback_type": "success",
+ "callback_vars": {
+ "langfuse_public_key": "pk-team",
+ "langfuse_secret_key": "sk-team",
+ "langfuse_host": "http://team.local",
+ "capture_message_content": setting,
+ },
+ },
+ {
+ "callback_name": "arize",
+ "callback_type": "success",
+ "callback_vars": {"arize_api_key": "k", "arize_space_id": "s"},
+ },
+ ]
+ }
+ )
+
+ destinations: Final = [d.callback_name for d in resolve_tenant_otel_destinations(auth)]
+
+ assert destinations == ["arize"]
+
+ @pytest.mark.parametrize("value", ["full", "NO_CONTENT", "", "true", "event_only", "span_and_event"])
+ def test_an_unsupported_value_fails_registration(self, value: str) -> None:
+ with pytest.raises(
+ ValueError,
+ match=r"Invalid capture_message_content .*\['no_content', 'span_only'\]",
+ ):
+ AddTeamCallback(
+ callback_name="langfuse_otel",
+ callback_type="success",
+ callback_vars={
+ "langfuse_public_key": "pk",
+ "langfuse_secret_key": "sk",
+ "capture_message_content": value,
+ },
+ )
+
+ @pytest.mark.parametrize("value", ["no_content", "span_only"])
+ def test_a_supported_value_is_stored_as_given(self, value: str) -> None:
+ saved: Final = AddTeamCallback(
+ callback_name="langfuse_otel",
+ callback_type="success",
+ callback_vars={"langfuse_public_key": "pk", "langfuse_secret_key": "sk", "capture_message_content": value},
+ )
+
+ assert saved.callback_vars["capture_message_content"] == value
+
+ def test_a_team_wide_callback_vars_map_cannot_carry_the_setting(self) -> None:
+ """The flattened map is shared by every callback, so a value there would apply to all of them."""
+ with pytest.raises(ValueError, match="Invalid callback variable: capture_message_content"):
+ TeamCallbackMetadata(
+ success_callback=["langfuse_otel", "signoz"], callback_vars={"capture_message_content": "span_only"}
+ )
+
+ def test_flattening_the_entries_leaves_the_setting_on_its_own_entry(self) -> None:
+ flattened: Final = convert_key_logging_metadata_to_callback(
+ AddTeamCallback(
+ callback_name="langfuse_otel",
+ callback_type="success",
+ callback_vars={"langfuse_public_key": "pk", "capture_message_content": "span_only"},
+ ),
+ None,
+ )
+
+ assert flattened.callback_vars == {"langfuse_public_key": "pk"}
+
+
class TestArizeProjectRouting:
"""Arize rejects an export that names no project (400: set x-project-name,
arize.project.name, openinference.project.name, or model_id), so an Arize
diff --git a/tests/unit/integrations/otel/test_otel_v2_logger.py b/tests/unit/integrations/otel/test_otel_v2_logger.py
index 3b1dd592d08..6a9a963948e 100644
--- a/tests/unit/integrations/otel/test_otel_v2_logger.py
+++ b/tests/unit/integrations/otel/test_otel_v2_logger.py
@@ -9,11 +9,13 @@ hooks, proxy SERVER span lifecycle (start + setters), parent-context resolution
import ast
import asyncio
import contextlib
+import contextvars
import os
import re
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
+from types import MappingProxyType
from typing import Final
from unittest.mock import patch
@@ -43,7 +45,8 @@ from litellm.integrations.otel import ( # noqa: E402
OpenTelemetryV2Config,
)
from litellm.integrations.otel.logger import OpenTelemetryV2 # noqa: E402
-from litellm.integrations.otel.model.config import ExporterSpec # noqa: E402
+from litellm.integrations.otel.model.config import CaptureMessageContent, ExporterSpec # noqa: E402
+from litellm.integrations.otel.model.destination import OtelDestination # noqa: E402
from litellm.integrations.otel.model.spans import ( # noqa: E402
LITELLM_PROXY_REQUEST_SPAN_NAME,
SpanRole,
@@ -55,6 +58,7 @@ from litellm.integrations.otel.plumbing.context import ( # noqa: E402
reset_mcp_message_transport_span,
set_mcp_message_trace_carrier,
set_mcp_message_transport_span,
+ set_request_destinations,
set_request_root_span,
)
from litellm.types.utils import AUTOROUTER_CLASSIFIER_CALL_ORIGIN # noqa: E402
@@ -617,8 +621,6 @@ def _mcp_payload(**overrides):
def _logger_capturing():
- from litellm.integrations.otel.model.config import CaptureMessageContent
-
cfg = OpenTelemetryV2Config(
exporter="in_memory",
legacy_compat=False,
@@ -684,6 +686,57 @@ def test_mcp_tool_call_captures_io_when_enabled():
assert "21" in span.attributes["gen_ai.tool.call.result"]
+@pytest.mark.parametrize(
+ ("capture_mode", "captures_content"),
+ [
+ (None, False),
+ (CaptureMessageContent.NO_CONTENT, False),
+ (CaptureMessageContent.SPAN_ONLY, True),
+ (CaptureMessageContent.EVENT_ONLY, False),
+ (CaptureMessageContent.SPAN_AND_EVENT, True),
+ ],
+)
+def test_only_a_request_destination_can_turn_on_llm_payload_content(
+ capture_mode: CaptureMessageContent | None, captures_content: bool
+) -> None:
+ config: Final = OpenTelemetryV2Config(
+ exporter="in_memory",
+ capture_message_content=CaptureMessageContent.NO_CONTENT,
+ )
+ exporter: Final = InMemorySpanExporter()
+ logger: Final = OpenTelemetryV2(
+ config=config, tracer_provider=providers.build_tracer_provider(config, exporter=exporter)
+ )
+ payload: Final = _payload(
+ messages=[{"role": "user", "content": "prompt marker"}],
+ response={
+ "id": "resp_1",
+ "model": "gpt-4o-2024",
+ "choices": [{"finish_reason": "stop", "message": {"role": "assistant", "content": "answer marker"}}],
+ },
+ )
+ kwargs: Final = {
+ **_kwargs(payload),
+ "standard_callback_dynamic_params": {"capture_message_content": "span_only"},
+ }
+ destination: Final = OtelDestination(
+ endpoint="http://team.local/api/public/otel",
+ headers=MappingProxyType({"Authorization": "Basic dA=="}),
+ callback_name="langfuse_otel",
+ capture_message_content=capture_mode,
+ )
+
+ def emit() -> None:
+ set_request_destinations((destination,))
+ _emit_llm(logger, kwargs)
+
+ contextvars.copy_context().run(emit)
+
+ (span,) = exporter.get_finished_spans()
+ assert ("gen_ai.input.messages" in span.attributes) is captures_content
+ assert ("gen_ai.output.messages" in span.attributes) is captures_content
+
+
def test_mcp_tool_call_failure_marks_error():
logger, exporter = _logger()
payload = _mcp_payload(
diff --git a/tests/unit/integrations/otel/test_otel_v2_sources_of_truth.py b/tests/unit/integrations/otel/test_otel_v2_sources_of_truth.py
index ea0416cecbd..318859cb3ed 100644
--- a/tests/unit/integrations/otel/test_otel_v2_sources_of_truth.py
+++ b/tests/unit/integrations/otel/test_otel_v2_sources_of_truth.py
@@ -1692,6 +1692,19 @@ def test_capture_message_content_normalizer_only_touches_strings():
OpenTelemetryV2Config(capture_message_content=123)
+def test_unknown_capture_message_content_env_is_kept_as_a_plain_string_that_captures_nothing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT", "Invalid-Mode")
+
+ config: Final = OpenTelemetryV2Config()
+
+ assert type(config.capture_message_content) is str
+ assert config.capture_message_content == "invalid-mode"
+ assert config.capture_span_content is False
+ assert config.model_dump()["capture_message_content"] == "invalid-mode"
+
+
def test_v2_flag_is_off_by_default(monkeypatch):
monkeypatch.delenv("LITELLM_OTEL_V2", raising=False)
is_otel_v2_enabled.cache_clear()
diff --git a/tests/unit/proxy/common_utils/test_callback_config_validation.py b/tests/unit/proxy/common_utils/test_callback_config_validation.py
index d10a96e2aef..a6544e56c57 100644
--- a/tests/unit/proxy/common_utils/test_callback_config_validation.py
+++ b/tests/unit/proxy/common_utils/test_callback_config_validation.py
@@ -1,7 +1,11 @@
+from collections.abc import Iterator
+from typing import Final
+
import pytest
from litellm.proxy.common_utils.callback_config_validation import (
callback_config_error,
+ conflicting_capture_error,
conflicting_span_scope_error,
cross_entry_family_error,
logging_metadata_config_error,
@@ -259,3 +263,114 @@ def test_arize_sampling_rates_are_not_family_credentials():
stored = [{"arize_api_key": "k1", "arize_success_sampling_rate": "0.5"}]
assert cross_entry_family_error({"arize_success_sampling_rate": "0.1"}, stored) is None
assert cross_entry_family_error({"arize_error_sampling_rate": "0.5"}, stored) is None
+
+
+@pytest.fixture
+def otel_v2_on(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
+ from litellm.integrations.otel.model.config import is_otel_v2_enabled
+
+ monkeypatch.setenv("LITELLM_OTEL_V2", "true")
+ is_otel_v2_enabled.cache_clear()
+ yield
+ is_otel_v2_enabled.cache_clear()
+
+
+@pytest.mark.usefixtures("otel_v2_on")
+@pytest.mark.parametrize("callback_name", ["langfuse_otel", "arize", "weave_otel", "newrelic"])
+@pytest.mark.parametrize("value", ["no_content", "span_only"])
+def test_capture_message_content_is_accepted_on_every_otel_v2_destination(callback_name: str, value: str) -> None:
+ assert callback_config_error(callback_name, {"capture_message_content": value}) is None
+
+
+def test_capture_message_content_is_rejected_while_otel_v2_is_off(monkeypatch: pytest.MonkeyPatch) -> None:
+ from litellm.integrations.otel.model.config import is_otel_v2_enabled
+
+ monkeypatch.delenv("LITELLM_OTEL_V2", raising=False)
+ is_otel_v2_enabled.cache_clear()
+ try:
+ error: Final = callback_config_error("langfuse_otel", {"capture_message_content": "no_content"})
+ finally:
+ is_otel_v2_enabled.cache_clear()
+ assert error is not None and "capture_message_content" in error and "LITELLM_OTEL_V2" in error
+
+
+@pytest.mark.parametrize("callback_name", ["langfuse", "datadog", "otel", "arize_phoenix", None])
+def test_capture_message_content_is_rejected_where_it_would_never_take_effect(callback_name: str | None) -> None:
+ error: Final = callback_config_error(callback_name, {"capture_message_content": "no_content"})
+ assert error is not None and "capture_message_content" in error and "langfuse_otel" in error
+
+
+@pytest.mark.usefixtures("otel_v2_on")
+@pytest.mark.parametrize("value", ["full", "event_only", "span_and_event"])
+def test_an_unsupported_capture_message_content_is_rejected_on_key_logging_metadata(value: str) -> None:
+ error: Final = logging_metadata_config_error(
+ {
+ "logging": [
+ {
+ "callback_name": "langfuse_otel",
+ "callback_type": "success",
+ "callback_vars": {"capture_message_content": value},
+ }
+ ]
+ }
+ )
+ assert error is not None and "Invalid capture_message_content" in error
+
+
+@pytest.mark.usefixtures("otel_v2_on")
+def test_each_entry_keeps_its_own_capture_message_content() -> None:
+ error: Final = logging_metadata_config_error(
+ {
+ "logging": [
+ {
+ "callback_name": "langfuse_otel",
+ "callback_type": "success",
+ "callback_vars": {"capture_message_content": "span_only"},
+ },
+ {
+ "callback_name": "arize",
+ "callback_type": "success",
+ "callback_vars": {"capture_message_content": "no_content"},
+ },
+ ]
+ }
+ )
+ assert error is None
+
+
+@pytest.mark.usefixtures("otel_v2_on")
+def test_a_failure_only_entry_rejects_capture_message_content() -> None:
+ error: Final = callback_config_error("langfuse_otel", {"capture_message_content": "no_content"}, "failure")
+ assert error is not None and "capture_message_content" in error and "success_and_failure" in error
+
+
+@pytest.mark.parametrize(
+ ("stored", "rejected"),
+ [
+ ([("langfuse_otel", {"capture_message_content": "no_content"})], True),
+ ([("langfuse_otel", {"capture_message_content": "span_only"})], False),
+ ([("langfuse_otel", {"langfuse_public_key": "pk"})], False),
+ ([("newrelic", {"capture_message_content": "no_content"})], False),
+ ],
+)
+def test_entries_for_one_backend_share_one_capture_message_content(
+ stored: list[tuple[str, dict[str, str]]], rejected: bool
+) -> None:
+ """The backend's entries merge into one destination, so a second value would silently win or lose."""
+ error: Final = conflicting_capture_error("langfuse_otel", {"capture_message_content": "span_only"}, stored)
+ assert (error is not None) is rejected
+
+
+@pytest.mark.usefixtures("otel_v2_on")
+def test_key_logging_entries_for_one_backend_may_not_disagree_on_capture_message_content() -> None:
+ def entry(callback_type: str, capture: str) -> dict[str, str | dict[str, str]]:
+ return {
+ "callback_name": "langfuse_otel",
+ "callback_type": callback_type,
+ "callback_vars": {"capture_message_content": capture},
+ }
+
+ error: Final = logging_metadata_config_error(
+ {"logging": [entry("success", "no_content"), entry("success_and_failure", "span_only")]}
+ )
+ assert error is not None and "already set to 'no_content' by another langfuse_otel entry" in error
diff --git a/tests/unit/proxy/management_endpoints/test_team_callback_endpoints.py b/tests/unit/proxy/management_endpoints/test_team_callback_endpoints.py
index f576bac4742..ad5b6903ece 100644
--- a/tests/unit/proxy/management_endpoints/test_team_callback_endpoints.py
+++ b/tests/unit/proxy/management_endpoints/test_team_callback_endpoints.py
@@ -7,6 +7,7 @@ redacted audit rows for callback mutations.
"""
import json
+from collections.abc import Iterator
from typing import Final
from unittest.mock import AsyncMock, MagicMock, Mock, patch
@@ -1712,3 +1713,62 @@ def test_add_team_callback_accepts_arize_sampling_rate_vars():
)
assert data.callback_vars["arize_success_sampling_rate"] == "0.5"
assert data.callback_vars["arize_error_sampling_rate"] == "1.0"
+
+
+@pytest.mark.asyncio
+async def test_add_team_callbacks_rejects_capture_message_content_on_a_non_otel_v2_callback(patched_prisma):
+ data: Final = AddTeamCallback(
+ callback_name="langfuse",
+ callback_type="success",
+ callback_vars={
+ "langfuse_public_key": "pk",
+ "langfuse_secret_key": "sk",
+ "capture_message_content": "no_content",
+ },
+ )
+ with pytest.raises(HTTPException) as exc:
+ await add_team_callbacks(
+ data=data,
+ http_request=Mock(spec=Request),
+ team_id="team-victim",
+ user_api_key_dict=_admin_auth(),
+ )
+ assert exc.value.status_code == 400
+ assert "capture_message_content" in str(exc.value.detail)
+ patched_prisma.db.litellm_teamtable.update.assert_not_called()
+
+
+@pytest.fixture
+def otel_v2_on(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
+ from litellm.integrations.otel.model.config import is_otel_v2_enabled
+
+ monkeypatch.setenv("LITELLM_OTEL_V2", "true")
+ is_otel_v2_enabled.cache_clear()
+ yield
+ is_otel_v2_enabled.cache_clear()
+
+
+@pytest.mark.usefixtures("otel_v2_on")
+@pytest.mark.asyncio
+@pytest.mark.parametrize("capture", ["no_content", "span_only"])
+async def test_add_team_callbacks_stores_capture_message_content_in_the_existing_callback_metadata(
+ patched_prisma, capture: str
+) -> None:
+ data: Final = AddTeamCallback(
+ callback_name="langfuse_otel",
+ callback_type="success",
+ callback_vars={
+ "langfuse_public_key": "pk",
+ "langfuse_secret_key": "sk",
+ "capture_message_content": capture,
+ },
+ )
+ await add_team_callbacks(
+ data=data,
+ http_request=Mock(spec=Request),
+ team_id="team-victim",
+ user_api_key_dict=_admin_auth(),
+ )
+ patched_prisma.db.litellm_teamtable.update.assert_awaited_once()
+ stored: Final = json.loads(patched_prisma.db.litellm_teamtable.update.await_args.kwargs["data"]["metadata"])
+ assert [entry["callback_vars"].get("capture_message_content") for entry in stored["logging"]] == [capture]
diff --git a/tests/unit/types/test_utils.py b/tests/unit/types/test_utils.py
new file mode 100644
index 00000000000..09063d894e7
--- /dev/null
+++ b/tests/unit/types/test_utils.py
@@ -0,0 +1,40 @@
+import pytest
+
+from litellm.types.utils import CAPTURE_MESSAGE_CONTENT_VALUES, CaptureMessageContent, captures_span_content
+
+
+@pytest.mark.parametrize(
+ "mode",
+ [
+ CaptureMessageContent.NO_CONTENT,
+ CaptureMessageContent.SPAN_ONLY,
+ CaptureMessageContent.EVENT_ONLY,
+ CaptureMessageContent.SPAN_AND_EVENT,
+ ],
+)
+def test_capture_message_content_members_are_plain_strings(mode: str) -> None:
+ assert type(mode) is str
+ assert (str(mode), f"{mode}", repr(mode)) == (mode, mode, repr(str(mode)))
+
+
+def test_a_destination_may_only_set_the_span_capture_modes() -> None:
+ assert CAPTURE_MESSAGE_CONTENT_VALUES == {"no_content", "span_only"}
+
+
+def test_capture_message_content_constructor_accepts_any_string() -> None:
+ assert CaptureMessageContent("custom") == "custom"
+
+
+@pytest.mark.parametrize(
+ ("mode", "captures"),
+ [
+ ("no_content", False),
+ ("span_only", True),
+ ("event_only", False),
+ ("span_and_event", True),
+ ("bogus", False),
+ (None, False),
+ ],
+)
+def test_captures_span_content(mode: str | None, captures: bool) -> None:
+ assert captures_span_content(mode) is captures
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index 731a92d8b98..47df4593a65 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -17246,6 +17246,9 @@ export interface paths {
* - langfuse_host: The host for the Langfuse callback
* - langfuse_environment: The tracing environment for the Langfuse callback (lowercase; falls back to LANGFUSE_TRACING_ENVIRONMENT)
* - langfuse_span_scope: For langfuse_otel, "full" (default) sends the whole request trace, "llm_only" sends only the model-call spans
+ * - capture_message_content: For OTel v2 callbacks, "no_content" or "span_only".
+ * An explicit value overrides the global setting for this destination; omitted follows the proxy's own callback for that backend, else the global setting.
+ * "span_only" puts prompt and response content on the destination's spans, "no_content" leaves it out
* - gcs_bucket_name: The name of the GCS bucket
* - gcs_path_service_account: The path to the GCS service account
* - langsmith_api_key: The API key for the Langsmith callback
From c9d706adb5d387807d9d03fd9d90c49ef8a66847 Mon Sep 17 00:00:00 2001
From: nate-berri
Date: Sat, 10 Oct 2026 13:58:07 -0700
Subject: [PATCH 13/40] refactor(types): move key request models into
litellm.types.proxy.management_endpoints.key_requests (#45810)
* refactor(types): move LitellmUserRoles and KeyManagementRoutes into litellm.types.proxy.auth.user_roles
Part of LIT-9423
* refactor(types): annotate GenerateRequestBase containers and check_max_budget
Part of LIT-9423
* refactor(types): move GenerateRequestBase and LiteLLM_ObjectPermissionBase into litellm.types.proxy.management_endpoints.request_base
Part of LIT-9423
* refactor(types): annotate key request containers and drop_blank_team_id
Part of LIT-9423
* refactor(types): move key request models into litellm.types.proxy.management_endpoints.key_requests
Part of LIT-9423
* fix(types): keep MappingProxyType exported from litellm.proxy._types for star importers
Part of LIT-9423
* fix(sdk): resolve litellm.proxy lazily on attribute access
The layer cleanup stopped import litellm from loading any proxy module, so litellm.proxy was no longer bound and litellm.proxy._types.X raised AttributeError. The module __getattr__ now imports litellm.proxy on first access, which keeps import litellm free of proxy._types and fixes the docs and code-quality checks on main
---
litellm/proxy/_types.py | 144 +++---------------
.../key_management_endpoints.py | 8 +-
.../management_endpoints/key_requests.py | 138 +++++++++++++++++
3 files changed, 161 insertions(+), 129 deletions(-)
create mode 100644 litellm/types/proxy/management_endpoints/key_requests.py
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 39892bcc29c..4cbf4f15d6d 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -3,7 +3,7 @@ import json
import os
from collections.abc import Callable, Mapping, Sequence
from datetime import datetime
-from types import MappingProxyType
+from types import MappingProxyType as MappingProxyType # noqa: PLC0414 # public re-export
from typing import TYPE_CHECKING, Annotated, Any, Final, Literal, NamedTuple, TypeAlias
import httpx
@@ -1165,6 +1165,18 @@ from litellm.models.team import BudgetLimitEntry as BudgetLimitEntry # noqa: E4
from litellm.types.object_permission import ( # noqa: E402
ObjectPermissionDict as ObjectPermissionDict,
)
+from litellm.types.proxy.management_endpoints.key_requests import ( # noqa: E402 # re-export after the definitions above
+ AllowedVectorStoreIndexItem as AllowedVectorStoreIndexItem, # noqa: PLC0414 # public re-export
+)
+from litellm.types.proxy.management_endpoints.key_requests import ( # noqa: E402 # re-export after the definitions above
+ GenerateKeyRequest as GenerateKeyRequest, # noqa: PLC0414 # public re-export
+)
+from litellm.types.proxy.management_endpoints.key_requests import ( # noqa: E402 # re-export after the definitions above
+ KeyRequestBase as KeyRequestBase, # noqa: PLC0414 # public re-export
+)
+from litellm.types.proxy.management_endpoints.key_requests import ( # noqa: E402 # re-export after the definitions above
+ LiteLLMKeyType as LiteLLMKeyType, # noqa: PLC0414 # public re-export
+)
from litellm.types.proxy.management_endpoints.request_base import ( # noqa: E402 # re-export after the definitions above
GenerateRequestBase as GenerateRequestBase, # noqa: PLC0414 # public re-export
)
@@ -1173,71 +1185,6 @@ from litellm.types.proxy.management_endpoints.request_base import ( # noqa: E40
)
-class AllowedVectorStoreIndexItem(LiteLLMPydanticObjectBase):
- index_name: str
- index_permissions: list[Literal["read", "write"]]
-
-
-class KeyRequestBase(GenerateRequestBase):
- key: str | None = None
- tpd_limit: int | None = None
- default_estimated_output_tokens: PositiveInt | None = None
- default_estimated_output_tokens_per_model: Mapping[str, PositiveInt] | None = None
- budget_id: str | None = None
- end_user_budget_id: str | None = None
- tags: list[str] | None = None
- disable_global_guardrails: bool | None = None
- enable_prompt_caching: bool | None = None
- throttle_on_budget_exceeded: bool | None = None
- enforced_params: list[str] | None = None
- allowed_routes: list[Any] | None = []
- allowed_passthrough_routes: list[object] | None = None
- denied_passthrough_routes: list[str] | None = None
- allowed_vector_store_indexes: list[AllowedVectorStoreIndexItem] | None = None
- rpm_limit_type: Literal["guaranteed_throughput", "best_effort_throughput", "dynamic"] | None = (
- None # raise an error if 'guaranteed_throughput' is set and we're overallocating rpm
- )
- tpm_limit_type: Literal["guaranteed_throughput", "best_effort_throughput", "dynamic"] | None = (
- None # raise an error if 'guaranteed_throughput' is set and we're overallocating tpm
- )
- router_settings: UpdateRouterConfig | None = None
- access_group_ids: list[str] | None = None
-
-
-class LiteLLMKeyType(str, enum.Enum):
- """
- Enum for key types that determine what routes a key can access
- """
-
- LLM_API = "llm_api" # Can call LLM API routes (chat/completions, embeddings, etc.)
- MANAGEMENT = "management" # Can call management routes (user/team/key management)
- READ_ONLY = "read_only" # Can only call info/read routes
- DEFAULT = "default" # Uses default allowed routes
-
-
-class GenerateKeyRequest(KeyRequestBase):
- soft_budget: float | None = None
- send_invite_email: bool | None = None
- key_type: LiteLLMKeyType | None = Field(
- default=LiteLLMKeyType.DEFAULT,
- description="Type of key that determines default allowed routes.",
- )
- auto_rotate: bool | None = Field(default=False, description="Whether this key should be automatically rotated")
- rotation_interval: str | None = Field(
- default=None,
- description="How often to rotate this key (e.g., '30d', '90d'). Required if auto_rotate=True",
- )
- organization_id: str | None = None
- project_id: str | None = None
-
- @field_validator("team_id", "organization_id", "project_id", mode="before")
- @classmethod
- def treat_cleared_id_as_unset(cls, v: object) -> object:
- if v == "":
- return None
- return v
-
-
class GenerateKeyResponse(KeyRequestBase):
key: str
key_name: str | None = None
@@ -1280,65 +1227,12 @@ class GenerateKeyResponse(KeyRequestBase):
return values
-def _is_mapping(value: object) -> TypeIs[Mapping[object, object]]: # guard-ok: raw before-validator payload
- return isinstance(value, Mapping)
-
-
-class UpdateKeyRequest(KeyRequestBase):
- # Note: the defaults of all Params here MUST BE NONE
- # else they will get overwritten
- duration: str | None = None
- spend: float | None = None
- soft_budget: float | None = None
- metadata: dict[Any, Any] | None = None
- temp_budget_increase: float | None = None
- temp_budget_expiry: datetime | None = None
- auto_rotate: bool | None = None
- rotation_interval: str | None = None
- organization_id: str | None = None
-
- project_id: str | None = Field(
- default=None,
- description="Omit to retain the project, or send null to detach. Assigning a different project is not supported.",
- )
-
- @model_validator(mode="before")
- @classmethod
- def drop_blank_team_id(cls, values: object) -> object:
- if _is_mapping(values) and values.get("team_id") == "":
- return MappingProxyType({k: v for k, v in values.items() if k != "team_id"})
- return values
-
- @field_validator("organization_id", mode="before")
- @classmethod
- def treat_cleared_organization_id_as_unset(cls, v: object) -> object:
- if v == "":
- return None
- return v
-
- @model_validator(mode="after")
- def validate_temp_budget(self) -> "UpdateKeyRequest":
- if self.temp_budget_increase is not None or self.temp_budget_expiry is not None:
- if self.temp_budget_increase is None or self.temp_budget_expiry is None:
- raise ValueError("temp_budget_increase and temp_budget_expiry must be set together")
- return self
-
- @model_validator(mode="after")
- def validate_key_identifier(self) -> "UpdateKeyRequest":
- if self.key is None and self.key_alias is None:
- raise ValueError("either key or key_alias must be provided")
- return self
-
-
-class RegenerateKeyRequest(GenerateKeyRequest):
- # This needs to be different from UpdateKeyRequest, because "key" is optional for this
- key: str | None = None
- new_key: str | None = None
- duration: str | None = None
- spend: float | None = None
- metadata: dict[Any, Any] | None = None
- new_master_key: str | None = None
- grace_period: str | None = None # Duration to keep old key valid (e.g. "24h", "2d"); None = immediate revoke
+from litellm.types.proxy.management_endpoints.key_requests import ( # noqa: E402 # re-export after the definitions above
+ RegenerateKeyRequest as RegenerateKeyRequest, # noqa: PLC0414 # public re-export
+)
+from litellm.types.proxy.management_endpoints.key_requests import ( # noqa: E402 # re-export after the definitions above
+ UpdateKeyRequest as UpdateKeyRequest, # noqa: PLC0414 # public re-export
+)
class ResetSpendRequest(LiteLLMPydanticObjectBase):
diff --git a/litellm/types/proxy/management_endpoints/key_management_endpoints.py b/litellm/types/proxy/management_endpoints/key_management_endpoints.py
index 05b63100ea4..f4348391710 100644
--- a/litellm/types/proxy/management_endpoints/key_management_endpoints.py
+++ b/litellm/types/proxy/management_endpoints/key_management_endpoints.py
@@ -5,14 +5,14 @@ from pydantic import ConfigDict, model_validator
from typing_extensions import ReadOnly, TypedDict
from litellm.models.verification_token import LiteLLM_VerificationToken
-from litellm.proxy._types import (
+from litellm.types.llms.base import LiteLLMBaseModel, LiteLLMPydanticObjectBase
+from litellm.types.proxy.management_endpoints.internal_user_endpoints import InsensitiveContains
+from litellm.types.proxy.management_endpoints.key_requests import (
GenerateKeyRequest,
- LiteLLM_ObjectPermissionBase,
RegenerateKeyRequest,
UpdateKeyRequest,
)
-from litellm.types.llms.base import LiteLLMBaseModel, LiteLLMPydanticObjectBase
-from litellm.types.proxy.management_endpoints.internal_user_endpoints import InsensitiveContains
+from litellm.types.proxy.management_endpoints.request_base import LiteLLM_ObjectPermissionBase
class KeyTokenWhere(TypedDict):
diff --git a/litellm/types/proxy/management_endpoints/key_requests.py b/litellm/types/proxy/management_endpoints/key_requests.py
new file mode 100644
index 00000000000..baa02b68d98
--- /dev/null
+++ b/litellm/types/proxy/management_endpoints/key_requests.py
@@ -0,0 +1,138 @@
+import enum
+from collections.abc import Mapping
+from datetime import datetime
+from types import MappingProxyType
+from typing import Any, Literal # noqa: TID251 # allowed_routes and metadata stay Any for existing callers
+
+from pydantic import Field, PositiveInt, field_validator, model_validator
+from typing_extensions import TypeIs # noqa: TID251 # narrows the raw payload a before-validator receives
+
+from litellm.types.proxy.management_endpoints.request_base import GenerateRequestBase
+from litellm.types.router import UpdateRouterConfig
+from litellm.types.utils import LiteLLMPydanticObjectBase
+
+
+class AllowedVectorStoreIndexItem(LiteLLMPydanticObjectBase):
+ index_name: str
+ index_permissions: list[Literal["read", "write"]]
+
+
+class KeyRequestBase(GenerateRequestBase):
+ key: str | None = None
+ tpd_limit: int | None = None
+ default_estimated_output_tokens: PositiveInt | None = None
+ default_estimated_output_tokens_per_model: Mapping[str, PositiveInt] | None = None
+ budget_id: str | None = None
+ end_user_budget_id: str | None = None
+ tags: list[str] | None = None
+ disable_global_guardrails: bool | None = None
+ enable_prompt_caching: bool | None = None
+ throttle_on_budget_exceeded: bool | None = None
+ enforced_params: list[str] | None = None
+ allowed_routes: list[Any] | None = []
+ allowed_passthrough_routes: list[object] | None = None
+ denied_passthrough_routes: list[str] | None = None
+ allowed_vector_store_indexes: list[AllowedVectorStoreIndexItem] | None = None
+ rpm_limit_type: Literal["guaranteed_throughput", "best_effort_throughput", "dynamic"] | None = (
+ None # raise an error if 'guaranteed_throughput' is set and we're overallocating rpm
+ )
+ tpm_limit_type: Literal["guaranteed_throughput", "best_effort_throughput", "dynamic"] | None = (
+ None # raise an error if 'guaranteed_throughput' is set and we're overallocating tpm
+ )
+ router_settings: UpdateRouterConfig | None = None
+ access_group_ids: list[str] | None = None
+
+
+class LiteLLMKeyType(str, enum.Enum):
+ """
+ Enum for key types that determine what routes a key can access
+ """
+
+ LLM_API = "llm_api" # Can call LLM API routes (chat/completions, embeddings, etc.)
+ MANAGEMENT = "management" # Can call management routes (user/team/key management)
+ READ_ONLY = "read_only" # Can only call info/read routes
+ DEFAULT = "default" # Uses default allowed routes
+
+
+class GenerateKeyRequest(KeyRequestBase):
+ soft_budget: float | None = None
+ send_invite_email: bool | None = None
+ key_type: LiteLLMKeyType | None = Field(
+ default=LiteLLMKeyType.DEFAULT,
+ description="Type of key that determines default allowed routes.",
+ )
+ auto_rotate: bool | None = Field(default=False, description="Whether this key should be automatically rotated")
+ rotation_interval: str | None = Field(
+ default=None,
+ description="How often to rotate this key (e.g., '30d', '90d'). Required if auto_rotate=True",
+ )
+ organization_id: str | None = None
+ project_id: str | None = None
+
+ @field_validator("team_id", "organization_id", "project_id", mode="before")
+ @classmethod
+ def treat_cleared_id_as_unset(cls, v: object) -> object:
+ if v == "":
+ return None
+ return v
+
+
+def _is_mapping(value: object) -> TypeIs[Mapping[object, object]]: # guard-ok: raw before-validator payload
+ return isinstance(value, Mapping)
+
+
+class UpdateKeyRequest(KeyRequestBase):
+ # Note: the defaults of all Params here MUST BE NONE
+ # else they will get overwritten
+ duration: str | None = None
+ spend: float | None = None
+ soft_budget: float | None = None
+ metadata: dict[Any, Any] | None = None
+ temp_budget_increase: float | None = None
+ temp_budget_expiry: datetime | None = None
+ auto_rotate: bool | None = None
+ rotation_interval: str | None = None
+ organization_id: str | None = None
+
+ project_id: str | None = Field(
+ default=None,
+ description="Omit to retain the project, or send null to detach. Assigning a different project is not supported.",
+ )
+
+ @model_validator(mode="before")
+ @classmethod
+ def drop_blank_team_id(cls, values: object) -> object:
+ if _is_mapping(values) and values.get("team_id") == "":
+ return MappingProxyType({k: v for k, v in values.items() if k != "team_id"})
+ return values
+
+ @field_validator("organization_id", mode="before")
+ @classmethod
+ def treat_cleared_organization_id_as_unset(cls, v: object) -> object:
+ if v == "":
+ return None
+ return v
+
+ @model_validator(mode="after")
+ def validate_temp_budget(self) -> "UpdateKeyRequest":
+ if self.temp_budget_increase is not None or self.temp_budget_expiry is not None:
+ if self.temp_budget_increase is None or self.temp_budget_expiry is None:
+ raise ValueError("temp_budget_increase and temp_budget_expiry must be set together")
+ return self
+
+ @model_validator(mode="after")
+ def validate_key_identifier(self) -> "UpdateKeyRequest":
+ if self.key is None and self.key_alias is None:
+ raise ValueError("either key or key_alias must be provided")
+ return self
+
+
+class RegenerateKeyRequest(GenerateKeyRequest):
+ # This needs to be different from UpdateKeyRequest, because "key" is optional for this
+ key: str | None = None
+ new_key: str | None = None
+ duration: str | None = None
+ spend: float | None = None
+ metadata: dict[Any, Any] | None = None
+ new_master_key: str | None = None
+ grace_period: str | None = None # Duration to keep old key valid (e.g. "24h", "2d"); None = immediate revoke
From 513e7a89ac17e5301ceb57fa30e078454cacee7f Mon Sep 17 00:00:00 2001
From: nate-berri
Date: Sat, 10 Oct 2026 13:58:11 -0700
Subject: [PATCH 14/40] refactor(types): move user request models into
litellm.types.proxy.management_endpoints.user_requests (#45813)
* refactor(types): move LitellmUserRoles and KeyManagementRoutes into litellm.types.proxy.auth.user_roles
Part of LIT-9423
* refactor(types): annotate GenerateRequestBase containers and check_max_budget
Part of LIT-9423
* refactor(types): move GenerateRequestBase and LiteLLM_ObjectPermissionBase into litellm.types.proxy.management_endpoints.request_base
Part of LIT-9423
* refactor(types): annotate user request metadata and check_user_info validators
Part of LIT-9423
* refactor(types): move user request models into litellm.types.proxy.management_endpoints.user_requests
Part of LIT-9423
* fix(types): restore main's _types.py content alongside the request_base move
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix(sdk): resolve litellm.proxy lazily on attribute access
The layer cleanup stopped import litellm from loading any proxy module, so litellm.proxy was no longer bound and litellm.proxy._types.X raised AttributeError. The module __getattr__ now imports litellm.proxy on first access, which keeps import litellm free of proxy._types and fixes the docs and code-quality checks on main
* fix(sdk): resolve litellm.proxy lazily on attribute access
The layer cleanup stopped import litellm from loading any proxy module, so litellm.proxy was no longer bound and litellm.proxy._types.X raised AttributeError. The module __getattr__ now imports litellm.proxy on first access, which keeps import litellm free of proxy._types and fixes the docs and code-quality checks on main
* style(types): merge request_base re-exports into one import block
Part of LIT-9423
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
litellm/proxy/_types.py | 84 ++++---------------
.../internal_user_endpoints.py | 6 +-
.../management_endpoints/user_requests.py | 82 ++++++++++++++++++
3 files changed, 100 insertions(+), 72 deletions(-)
create mode 100644 litellm/types/proxy/management_endpoints/user_requests.py
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 4cbf4f15d6d..f43ce4dc211 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -1684,41 +1684,12 @@ class ListSkillsRequest(LiteLLMPydanticObjectBase):
offset: int | None = 0
-class NewUserRequestTeam(LiteLLMPydanticObjectBase):
- team_id: str
- max_budget_in_team: float | None = None
- user_role: Literal["user", "admin"] = "user"
-
-
-class NewUserRequest(GenerateRequestBase):
- max_budget: float | None = None
- user_email: str | None = None
- user_alias: str | None = None
- user_role: (
- Literal[
- LitellmUserRoles.PROXY_ADMIN,
- LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,
- LitellmUserRoles.INTERNAL_USER,
- LitellmUserRoles.INTERNAL_USER_VIEW_ONLY,
- ]
- | None
- ) = None
- teams: list[str] | list[NewUserRequestTeam] | None = None
- auto_create_key: bool = True # flag used for returning a key as part of the /user/new response
- send_invite_email: bool | None = None
- sso_user_id: str | None = None
- organizations: list[str] | None = None
- password: str | None = None
-
- @field_validator("password")
- @classmethod
- def password_not_supported(cls, value: str | None) -> str | None:
- if value is not None:
- raise ValueError(
- "password cannot be set via /user/new. Users set their own password through an "
- "invitation link (POST /invitation/new)."
- )
- return value
+from litellm.types.proxy.management_endpoints.user_requests import ( # noqa: E402 # re-export after the definitions above
+ NewUserRequest as NewUserRequest, # noqa: PLC0414 # public re-export
+)
+from litellm.types.proxy.management_endpoints.user_requests import ( # noqa: E402 # re-export after the definitions above
+ NewUserRequestTeam as NewUserRequestTeam, # noqa: PLC0414 # public re-export
+)
class NewUserResponse(GenerateKeyResponse):
@@ -1740,36 +1711,12 @@ class NewUserResponse(GenerateKeyResponse):
updated_at: datetime | None = None
-class UpdateUserRequestNoUserIDorEmail(GenerateRequestBase): # shared with BulkUpdateUserRequest
- # repr=False keeps the plaintext out of management-endpoint alerts, which str() the request model
- password: str | None = Field(default=None, repr=False)
- spend: float | None = None
- metadata: dict[object, object] | None = None
- user_alias: str | None = None
- user_role: (
- Literal[
- LitellmUserRoles.PROXY_ADMIN,
- LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,
- LitellmUserRoles.INTERNAL_USER,
- LitellmUserRoles.INTERNAL_USER_VIEW_ONLY,
- ]
- | None
- ) = None
- max_budget: float | None = None
-
-
-class UpdateUserRequest(UpdateUserRequestNoUserIDorEmail):
- # Note: the defaults of all Params here MUST BE NONE
- # else they will get overwritten
- user_id: str | None = None
- user_email: str | None = None
-
- @model_validator(mode="before")
- @classmethod
- def check_user_info(cls, values: Mapping[str, object]) -> Mapping[str, object]:
- if values.get("user_id") is None and values.get("user_email") is None:
- raise ValueError("Either user id or user email must be provided")
- return values
+from litellm.types.proxy.management_endpoints.user_requests import ( # noqa: E402 # re-export after the definitions above
+ UpdateUserRequest as UpdateUserRequest, # noqa: PLC0414 # public re-export
+)
+from litellm.types.proxy.management_endpoints.user_requests import ( # noqa: E402 # re-export after the definitions above
+ UpdateUserRequestNoUserIDorEmail as UpdateUserRequestNoUserIDorEmail, # noqa: PLC0414 # public re-export
+)
class ChangePasswordRequest(LiteLLMPydanticObjectBase):
@@ -3632,10 +3579,6 @@ class LiteLLM_UserTableFiltered(LiteLLMBaseModel): # done to avoid exposing sen
user_email: str | None = None
-class LiteLLM_UserTableWithKeyCount(LiteLLM_UserTable):
- key_count: int = 0
-
-
from litellm.models.access_group import ( # noqa: E402
LiteLLM_AccessGroupTable as LiteLLM_AccessGroupTable,
)
@@ -3649,6 +3592,9 @@ from litellm.models.spend_logs import ( # noqa: E402
LiteLLM_SpendLogs as LiteLLM_SpendLogs,
)
from litellm.models.tag import LiteLLM_TagTable as LiteLLM_TagTable # noqa: E402
+from litellm.types.proxy.management_endpoints.user_requests import ( # noqa: E402 # re-export after the definitions above
+ LiteLLM_UserTableWithKeyCount as LiteLLM_UserTableWithKeyCount, # noqa: PLC0414 # public re-export
+)
AUDIT_ACTIONS = Literal["created", "updated", "deleted", "blocked", "unblocked", "rotated", "kill_switch_fired"]
diff --git a/litellm/types/proxy/management_endpoints/internal_user_endpoints.py b/litellm/types/proxy/management_endpoints/internal_user_endpoints.py
index 1fd3e7dca53..febd4485d10 100644
--- a/litellm/types/proxy/management_endpoints/internal_user_endpoints.py
+++ b/litellm/types/proxy/management_endpoints/internal_user_endpoints.py
@@ -4,14 +4,14 @@ from typing import Any, Final, Literal
from pydantic import ConfigDict, Field, field_validator
from typing_extensions import ReadOnly, TypedDict
-from litellm.proxy._types import (
+from litellm.types.llms.base import LiteLLMBaseModel
+from litellm.types.proxy.management_endpoints.management_v1 import ResourceResponse
+from litellm.types.proxy.management_endpoints.user_requests import (
LiteLLM_UserTableWithKeyCount,
NewUserRequest,
UpdateUserRequest,
UpdateUserRequestNoUserIDorEmail,
)
-from litellm.types.llms.base import LiteLLMBaseModel
-from litellm.types.proxy.management_endpoints.management_v1 import ResourceResponse
MAX_BULK_DELETE_USERS: Final = 500
diff --git a/litellm/types/proxy/management_endpoints/user_requests.py b/litellm/types/proxy/management_endpoints/user_requests.py
new file mode 100644
index 00000000000..49dda5995bc
--- /dev/null
+++ b/litellm/types/proxy/management_endpoints/user_requests.py
@@ -0,0 +1,82 @@
+from collections.abc import Mapping
+from typing import Literal
+
+from pydantic import Field, field_validator, model_validator
+
+from litellm.models.user import LiteLLM_UserTable
+from litellm.types.proxy.auth.user_roles import LitellmUserRoles
+from litellm.types.proxy.management_endpoints.request_base import GenerateRequestBase
+from litellm.types.utils import LiteLLMPydanticObjectBase
+
+
+class NewUserRequestTeam(LiteLLMPydanticObjectBase):
+ team_id: str
+ max_budget_in_team: float | None = None
+ user_role: Literal["user", "admin"] = "user"
+
+
+class NewUserRequest(GenerateRequestBase):
+ max_budget: float | None = None
+ user_email: str | None = None
+ user_alias: str | None = None
+ user_role: (
+ Literal[
+ LitellmUserRoles.PROXY_ADMIN,
+ LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,
+ LitellmUserRoles.INTERNAL_USER,
+ LitellmUserRoles.INTERNAL_USER_VIEW_ONLY,
+ ]
+ | None
+ ) = None
+ teams: list[str] | list[NewUserRequestTeam] | None = None
+ auto_create_key: bool = True # flag used for returning a key as part of the /user/new response
+ send_invite_email: bool | None = None
+ sso_user_id: str | None = None
+ organizations: list[str] | None = None
+ password: str | None = None
+
+ @field_validator("password")
+ @classmethod
+ def password_not_supported(cls, value: str | None) -> str | None:
+ if value is not None:
+ raise ValueError(
+ "password cannot be set via /user/new. Users set their own password through an "
+ "invitation link (POST /invitation/new)."
+ )
+ return value
+
+
+class UpdateUserRequestNoUserIDorEmail(GenerateRequestBase): # shared with BulkUpdateUserRequest
+ # repr=False keeps the plaintext out of management-endpoint alerts, which str() the request model
+ password: str | None = Field(default=None, repr=False)
+ spend: float | None = None
+ metadata: dict[object, object] | None = None
+ user_alias: str | None = None
+ user_role: (
+ Literal[
+ LitellmUserRoles.PROXY_ADMIN,
+ LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,
+ LitellmUserRoles.INTERNAL_USER,
+ LitellmUserRoles.INTERNAL_USER_VIEW_ONLY,
+ ]
+ | None
+ ) = None
+ max_budget: float | None = None
+
+
+class UpdateUserRequest(UpdateUserRequestNoUserIDorEmail):
+ # Note: the defaults of all Params here MUST BE NONE
+ # else they will get overwritten
+ user_id: str | None = None
+ user_email: str | None = None
+
+ @model_validator(mode="before")
+ @classmethod
+ def check_user_info(cls, values: Mapping[str, object]) -> Mapping[str, object]:
+ if values.get("user_id") is None and values.get("user_email") is None:
+ raise ValueError("Either user id or user email must be provided")
+ return values
+
+
+class LiteLLM_UserTableWithKeyCount(LiteLLM_UserTable):
+ key_count: int = 0
From 2011004d0adf28c45d0bc2194b3cdba67f666327 Mon Sep 17 00:00:00 2001
From: nate-berri
Date: Sat, 10 Oct 2026 13:58:46 -0700
Subject: [PATCH 15/40] refactor(types): move MemberDeleteRequest into
litellm.types.proxy.management_endpoints.team_endpoints (#45814)
* refactor(types): move LitellmUserRoles and KeyManagementRoutes into litellm.types.proxy.auth.user_roles
Part of LIT-9423
* refactor(types): annotate GenerateRequestBase containers and check_max_budget
Part of LIT-9423
* refactor(types): move GenerateRequestBase and LiteLLM_ObjectPermissionBase into litellm.types.proxy.management_endpoints.request_base
Part of LIT-9423
* refactor(types): annotate user request metadata and check_user_info validators
Part of LIT-9423
* refactor(types): move user request models into litellm.types.proxy.management_endpoints.user_requests
Part of LIT-9423
* refactor(types): move MemberDeleteRequest into litellm.types.proxy.management_endpoints.team_endpoints
Part of LIT-9423
* fix(types): restore main's _types.py content alongside the request_base move
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix(sdk): resolve litellm.proxy lazily on attribute access
The layer cleanup stopped import litellm from loading any proxy module, so litellm.proxy was no longer bound and litellm.proxy._types.X raised AttributeError. The module __getattr__ now imports litellm.proxy on first access, which keeps import litellm free of proxy._types and fixes the docs and code-quality checks on main
* fix(sdk): resolve litellm.proxy lazily on attribute access
The layer cleanup stopped import litellm from loading any proxy module, so litellm.proxy was no longer bound and litellm.proxy._types.X raised AttributeError. The module __getattr__ now imports litellm.proxy on first access, which keeps import litellm free of proxy._types and fixes the docs and code-quality checks on main
* fix(sdk): resolve litellm.proxy lazily on attribute access
The layer cleanup stopped import litellm from loading any proxy module, so litellm.proxy was no longer bound and litellm.proxy._types.X raised AttributeError. The module __getattr__ now imports litellm.proxy on first access, which keeps import litellm free of proxy._types and fixes the docs and code-quality checks on main
* style(types): merge request_base re-exports into one import block
Part of LIT-9423
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---
litellm/proxy/_types.py | 13 +++----------
.../management_endpoints/team_endpoints.py | 19 +++++++++++++++----
2 files changed, 18 insertions(+), 14 deletions(-)
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index f43ce4dc211..4abb93454c7 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -4370,16 +4370,9 @@ class OrganizationAddMemberResponse(LiteLLMPydanticObjectBase):
updated_organization_memberships: list[LiteLLM_OrganizationMembershipTable]
-class MemberDeleteRequest(LiteLLMPydanticObjectBase):
- user_id: str | None = None
- user_email: str | None = None
-
- @model_validator(mode="before")
- @classmethod
- def check_user_info(cls, values: Mapping[str, object]) -> Mapping[str, object]:
- if values.get("user_id") is None and values.get("user_email") is None:
- raise ValueError("Either user id or user email must be provided")
- return values
+from litellm.types.proxy.management_endpoints.team_endpoints import ( # noqa: E402 # re-export after the definitions above
+ MemberDeleteRequest as MemberDeleteRequest, # noqa: PLC0414 # public re-export
+)
class MemberUpdateResponse(LiteLLMPydanticObjectBase):
diff --git a/litellm/types/proxy/management_endpoints/team_endpoints.py b/litellm/types/proxy/management_endpoints/team_endpoints.py
index 796bcae37bc..065205dcad8 100644
--- a/litellm/types/proxy/management_endpoints/team_endpoints.py
+++ b/litellm/types/proxy/management_endpoints/team_endpoints.py
@@ -1,16 +1,15 @@
+from collections.abc import Mapping
from typing import Any, Final, Literal
from pydantic import ConfigDict, Field, field_validator, model_validator
from litellm.models.team import LiteLLM_DeletedTeamTable, LiteLLM_TeamTable, Member
from litellm.models.team_membership import LiteLLM_TeamMembership
-from litellm.proxy._types import (
- KeyManagementRoutes,
- MemberDeleteRequest,
-)
from litellm.proxy.common_utils.timezone_utils import budget_duration_error
from litellm.types.llms.base import LiteLLMBaseModel
+from litellm.types.proxy.auth.user_roles import KeyManagementRoutes
from litellm.types.proxy.management_endpoints.management_v1 import ResourceResponse
+from litellm.types.utils import LiteLLMPydanticObjectBase
TeamIdSearchMatch = Literal["exact", "prefix"]
@@ -19,6 +18,18 @@ MAX_BULK_TEAM_MEMBER_DELETES: Final = 500
MAX_BULK_TEAM_MEMBER_BUDGET_UPDATES: Final = 500
+class MemberDeleteRequest(LiteLLMPydanticObjectBase):
+ user_id: str | None = None
+ user_email: str | None = None
+
+ @model_validator(mode="before")
+ @classmethod
+ def check_user_info(cls, values: Mapping[str, object]) -> Mapping[str, object]:
+ if values.get("user_id") is None and values.get("user_email") is None:
+ raise ValueError("Either user id or user email must be provided")
+ return values
+
+
class GetTeamMemberPermissionsRequest(LiteLLMBaseModel):
"""Request to get the team member permissions for a team"""
From 38bdda9ca7c2f7b31d8d133a3d09f4c8a8d694b3 Mon Sep 17 00:00:00 2001
From: Soham Chatterjee <96soham96@gmail.com>
Date: Sat, 10 Oct 2026 23:01:17 +0200
Subject: [PATCH 16/40] feat(scaledown): add native text provider support
(#44168)
* Add ScaleDown model pricing
Registers the five ScaleDown models in the pricing map. ScaleDown bills on
input tokens only, so output_cost_per_token is zero for every entry. The
classify and decisions models bill at $0.04 per million input tokens, and
extract, summarize, and compress bill at $0.05 per million.
Co-Authored-By: Claude Opus 5
* Price all ScaleDown models at $0.04 per million and drop unverified context limits
Every ScaleDown model now bills $0.04 per million input tokens. The
32000-token max_input_tokens/max_output_tokens values were not confirmed
against the service, so they are removed rather than registered.
Co-Authored-By: Claude Sonnet 5.5
* Price all ScaleDown models at $0.05 per million input tokens
This is the standard rate in ScaleDown's billing and matches the usage dashboard.
The Decisions usage.cost field is not used for pricing.
Co-Authored-By: Claude Sonnet 5.5
* Add regression tests for the ScaleDown pricing entries
Co-Authored-By: Claude Sonnet 5.5
* Cite the source of the ScaleDown rate in the pricing tests and type them
Co-Authored-By: Claude Sonnet 5.5
* Add ScaleDown as a chat provider
ScaleDown serves five models over two wire protocols. extract, summarize, and
compress speak OpenAI chat on /v1/chat/completions, while classify and
decisions implement the Jev Decisions API on /v1/scaledown, taking a state
object plus a questions map and returning one typed answer per question.
The provider authenticates with x-api-key rather than a bearer token, and the
decisions models need a non-chat request body, so it routes through the HTTP
handler instead of the OpenAI passthrough. Malformed decisions requests are
rejected locally with a message naming the problem, so callers do not have to
decode an opaque 422 from upstream. Decisions bills one model call per
question, so the cost upstream reports is passed through rather than
re-estimated from token counts.
Co-Authored-By: Claude Opus 5
* Route ScaleDown domain models to the native API and stop trusting usage.cost
The /v1/chat/completions and /v1/models routes return 403 on api.scaledown.xyz,
so extract, summarize and compress now call the native /extract,
/summarization/abstractive and /compress/raw/ endpoints. The default api_base is
the bare host; a trailing /v1 is stripped and re-added only for decisions.
The Decisions usage.cost field was about 600x the dashboard amount, so it is no
longer passed through; cost is computed from input tokens at the registered rate.
Native responses are returned unchanged as JSON, including the _value/_span_anchor
wrappers on nested extraction. They carry no output token count, so
completion_tokens is reported as 0 and documented as unmeasured.
Co-Authored-By: Claude Sonnet 5.5
* Move ScaleDown translation into llms/ and address review findings
- Dispatch moves to llms/scaledown/chat/handler.py; main.py keeps a thin call
and get_llm_provider_logic.py no longer has a ScaleDown branch, since the
config resolves key and base URL itself.
- questions passed via extra_body are merged and validated after the shared
merge (sign_request), so the documented extra_body path works.
- extra_body can no longer change the upstream model, and decisions state may
carry a document but not text, so guardrails always see the text.
- A custom api_base requires its own api_key; the environment key is only sent
to the default host or SCALEDOWN_API_BASE.
- Image content parts become the decisions document; max_completion_tokens maps
to max_tokens; stream is served as one chunk for every model.
Co-Authored-By: Claude Sonnet 5.5
* Refuse prompt-bearing extra_body keys and empty-key fallback to the env credential
extra_body is merged after guardrails inspect the messages, so each model now
accepts only option keys there (extract threshold/top_n, compress
compression_rate, decisions questions/state); text, instructions, prompt,
context and model are rejected. An empty api_key no longer lets the
SCALEDOWN_API_KEY from the environment go to a custom api_base.
Co-Authored-By: Claude Sonnet 5.5
* Read compress token usage from the real response shape
/compress/raw/ nests the per-prompt counts under results and reports the total
as a top-level input_tokens; the provider read a top-level original_prompt_tokens
that is not there, so compress reported zero tokens and zero cost.
Co-Authored-By: Claude Sonnet 5.5
* Accept the router's max_retries and word the extra_body error clearly
The proxy adds max_retries to every call, which map_openai_params rejected, so
every proxied ScaleDown request failed with a 400. It is now accepted and not
forwarded.
Co-Authored-By: Claude Sonnet 5.5
* Return extracted fields from extract, follow schema refs, and meet the type-discipline gate
- extract content is now the extracted fields (span anchors dropped, wrappers
unwrapped), so it validates against the caller's response_format; the raw
payload stays on _hidden_params['scaledown_response'].
- Local $ref/$defs in the response_format schema are resolved.
- The adapter is rewritten with Final locals, read-only annotations, one raising
helper and a typed handler; check_type_discipline reports no violations.
Co-Authored-By: Claude Sonnet 5.5
* Fix stream_options, schema-guided extract cleaning, document input and multi-image handling
- stream_options is accepted and not sent upstream, so include_usage streams work.
- Extract output is cleaned against the requested entities, so a field named
_value or *_span_anchor is no longer dropped.
- Extract and summarize send an image or PDF as the native document fields.
- More than one image is rejected instead of silently using the first.
- The cost test derives its rate from the cost map.
Co-Authored-By: Claude Sonnet 5.5
* Cut recursive schema refs at the cycle and cap the expanded entity count
A small response_format schema with a self-referencing $def expanded to 4^16
leaves before any request was sent. Refs that point back into themselves are now
cut off at that point, and the total expanded entities are capped at 1000 so
repeated acyclic refs are rejected with a clear error.
Co-Authored-By: Claude Sonnet 5.5
* Bound ref chains and schema nesting so long schemas fail cleanly
Resolving a chain of thousands of distinct $refs recursed until RecursionError.
Ref resolution is now an iterative walk capped at 32 hops, and nested properties
are capped at 32 levels; both raise a clear 400 instead.
Co-Authored-By: Claude Sonnet 5.5
* fix(scaledown): support native classify and preserve extraction results
* test(scaledown): include provider regressions in CI shard
* fix(scaledown): pass registry typing and bounded recursion checks
* docs(scaledown): capture provider setup before and after
* fix(scaledown): preserve nullable schemas and reject malformed requests
* fix(scaledown): isolate provider dispatch from existing providers
* fix(scaledown): preserve the shared dispatch return contract
* fix(scaledown): preserve failure logging and reject lossy schemas
* fix(scaledown): keep timeout typing annotation on its expression
* fix(scaledown): resolve escaped extraction schema references
* fix(scaledown): annotate the bounded reference walk
* chore(scaledown): remove unused loop suppression
---------
Co-authored-by: Claude Opus 5
Co-authored-by: moe-berri
---
.github/assets/scaledown/provider-after.jpg | Bin 0 -> 110207 bytes
.github/assets/scaledown/provider-before.jpg | Bin 0 -> 111487 bytes
.github/workflows/test-unit.yml | 1 +
README.md | 1 +
litellm/__init__.py | 10 +-
litellm/_lazy_imports_registry.py | 5 +
litellm/constants.py | 1 +
litellm/llms/scaledown/__init__.py | 3 +
litellm/llms/scaledown/chat/__init__.py | 3 +
litellm/llms/scaledown/chat/transformation.py | 648 +++++++++
litellm/main.py | 35 +
...odel_prices_and_context_window_backup.json | 46 +
.../provider_endpoints_support_backup.json | 18 +
.../provider_create_fields.json | 18 +
litellm/types/utils.py | 1 +
litellm/utils.py | 1 +
model_prices_and_context_window.json | 46 +
provider_endpoints_support.json | 18 +
.../code_coverage_tests/recursive_detector.py | 1 +
tests/unit/llms/scaledown/__init__.py | 0
tests/unit/llms/scaledown/chat/__init__.py | 0
.../test_scaledown_chat_transformation.py | 1213 +++++++++++++++++
tests/unit/test_scaledown_model_prices.py | 46 +
23 files changed, 2114 insertions(+), 1 deletion(-)
create mode 100644 .github/assets/scaledown/provider-after.jpg
create mode 100644 .github/assets/scaledown/provider-before.jpg
create mode 100644 litellm/llms/scaledown/__init__.py
create mode 100644 litellm/llms/scaledown/chat/__init__.py
create mode 100644 litellm/llms/scaledown/chat/transformation.py
create mode 100644 tests/unit/llms/scaledown/__init__.py
create mode 100644 tests/unit/llms/scaledown/chat/__init__.py
create mode 100644 tests/unit/llms/scaledown/chat/test_scaledown_chat_transformation.py
create mode 100644 tests/unit/test_scaledown_model_prices.py
diff --git a/.github/assets/scaledown/provider-after.jpg b/.github/assets/scaledown/provider-after.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..bcf1c59c96fb5d5360d4667c35508e4a75d8f8d7
GIT binary patch
literal 110207
zcmeFZ30PCvmOmP_91(F~P(V<@iLqo|yQo
zTfem>pC#j)*~vgNlQ;Q9vm*|u}rwr{@KwtL5p?K}7E
z-m^z~x3sj(-UIt&_U_*+Exk`+-~NMg^78U~WEBr7$Q?Q$ColI~BT`#|I^S&DwQbuj
zIT>jgx&Px!@*cE*=a$}WpsiBJL0k4qZQU;=X$GkQa&D9Q;|2QDCA9^Rar=&)yLL+h
z1qk~U`Voc^QaS3A`&SALMc(Z|s+
zxcl(&uH6cXhYl;9IC<*y8BIeYW0P~|O|N`sWo=_?_x;UVU}qOsH+Qdl-afv5F#o`y
z;E>R;@Q5crMaRTGeHNFJ`g2-(#xI#!uk#BEi;7F$lvY*a2{pvpcXf?T%`L5MAKN?n
z2L`D_!=FcJEcV2g$*JkDGqc>~mDRO%9)Dx=H@&0)J^y_Dn__>b*M2~+E#G{z^_v~P
z=_R!#6u7tU|7P2#v%(9+k^Ow)?q^d}kS-Mu#$oIEx$V{MVPf)tv2tw%~guODML
z_9d9*3u+v0(#VoHZkGh~LHCse^l@z-b9V}}Dsxi;0%dF*j`W9iB^91)Ifd4mj*?y%
z@prLxdq|odH_s?b+N*7
z|C46ci9_r&9eW`I)|J2da;m5&HE{`|@>jCium|#k5c7}s_ELVq26qkXK7aW-<$01j
z$o-6g{l%T(FCT!B6$^MiicWfpyE`-GaJ*FP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