From 9514e5599753e5f9b8a233038386784c09fff99b Mon Sep 17 00:00:00 2001 From: Sameer Kankute Date: Tue, 16 Jun 2026 22:50:00 +0530 Subject: [PATCH 1/7] chore(codecov): add Batches, Videos, and Realtime components (#30517) * chore(codecov): add Batches, Videos, and Realtime components Define per-feature Codecov components so PR comments track coverage for batch API, video generation, and realtime streaming paths. Co-authored-by: Cursor * chore(codecov): use wildcard path for Batches proxy component Align batches_endpoints glob with Videos, Realtime, and Proxy_Authentication. Co-authored-by: Cursor --------- Co-authored-by: Cursor --- codecov.yaml | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/codecov.yaml b/codecov.yaml index 58681b884d0c..3baea13e2d36 100644 --- a/codecov.yaml +++ b/codecov.yaml @@ -35,6 +35,22 @@ component_management: - component_id: "Enterprise" paths: - "enterprise/**" + - component_id: "Batches" + paths: + - "*/proxy/batches_endpoints/**" + - "litellm/batches/**" + - "*/llms/*/batches/**" + - component_id: "Videos" + paths: + - "litellm/videos/**" + - "*/proxy/video_endpoints/**" + - "*/llms/*/videos/**" + - component_id: "Realtime" + paths: + - "litellm/realtime_api/**" + - "*/proxy/realtime_endpoints/**" + - "*/llms/*/realtime/**" + - "litellm/litellm_core_utils/realtime_streaming.py" comment: layout: "header, diff, flags, components" # show component info in the PR comment From bed6ce820cf998c1c1f94766487a2c7ec9f51abe Mon Sep 17 00:00:00 2001 From: Sameer Kankute Date: Tue, 16 Jun 2026 22:50:59 +0530 Subject: [PATCH 2/7] test(batches): move orphan tests into tests/test_litellm for CI coverage (#30510) Four batch-related tests lived under tests/litellm/ and were never picked up by GitHub Actions. Relocate them and fix gemini multimodal e2e to use the batchEmbedContents path expected for gemini/ provider. Co-authored-by: Cursor --- .../vertex_ai/test_gemini_batch_embeddings.py | 47 +++++++++++-------- .../test_batch_x_litellm_model_encoding.py | 4 +- .../test_model_based_routing_files_batches.py | 0 ...t_batch_completion_models_all_responses.py | 0 4 files changed, 28 insertions(+), 23 deletions(-) rename tests/{litellm => test_litellm}/llms/vertex_ai/test_gemini_batch_embeddings.py (95%) rename tests/{litellm => test_litellm}/proxy/test_batch_x_litellm_model_encoding.py (99%) rename tests/{litellm => test_litellm}/proxy/test_model_based_routing_files_batches.py (100%) rename tests/{litellm => test_litellm}/test_batch_completion_models_all_responses.py (100%) diff --git a/tests/litellm/llms/vertex_ai/test_gemini_batch_embeddings.py b/tests/test_litellm/llms/vertex_ai/test_gemini_batch_embeddings.py similarity index 95% rename from tests/litellm/llms/vertex_ai/test_gemini_batch_embeddings.py rename to tests/test_litellm/llms/vertex_ai/test_gemini_batch_embeddings.py index 54ea41a64504..98abf5459df7 100644 --- a/tests/litellm/llms/vertex_ai/test_gemini_batch_embeddings.py +++ b/tests/test_litellm/llms/vertex_ai/test_gemini_batch_embeddings.py @@ -8,12 +8,8 @@ """ import json -import os -import sys from unittest.mock import MagicMock, patch -sys.path.insert(0, os.path.abspath("../../../..")) - import pytest import litellm @@ -311,13 +307,16 @@ def mock_auth_token(*args, **kwargs): ): mock_get_token.return_value = ( {"x-goog-api-key": "test-key"}, - "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2-preview:embedContent", + "https://generativelanguage.googleapis.com/v1beta/models/gemini-embedding-2-preview:batchEmbedContents", ) mock_response = MagicMock() mock_response.status_code = 200 mock_response.json.return_value = { - "embedding": {"values": [0.1, 0.2, 0.3, 0.4, 0.5]} + "embeddings": [ + {"values": [0.1, 0.2, 0.3, 0.4, 0.5]}, + {"values": [0.6, 0.7, 0.8, 0.9, 1.0]}, + ] } mock_post.return_value = mock_response @@ -338,17 +337,21 @@ def mock_auth_token(*args, **kwargs): request_body = json.loads(kwargs.get("data", "{}")) - assert "content" in request_body - assert "parts" in request_body["content"] - parts = request_body["content"]["parts"] + assert "requests" in request_body + assert len(request_body["requests"]) == 2 - assert len(parts) == 2 - assert parts[0]["text"] == "The food was delicious" - assert "inline_data" in parts[1] - assert parts[1]["inline_data"]["mime_type"] == "image/png" + text_parts = request_body["requests"][0]["content"]["parts"] + image_parts = request_body["requests"][1]["content"]["parts"] - assert len(response.data) == 1 + assert len(text_parts) == 1 + assert text_parts[0]["text"] == "The food was delicious" + assert len(image_parts) == 1 + assert "inline_data" in image_parts[0] + assert image_parts[0]["inline_data"]["mime_type"] == "image/png" + + assert len(response.data) == 2 assert response.data[0].embedding == [0.1, 0.2, 0.3, 0.4, 0.5] + assert response.data[1].embedding == [0.6, 0.7, 0.8, 0.9, 1.0] def test_gemini_multimodal_embedding_with_audio(): @@ -581,17 +584,21 @@ def mock_auth_token(*args, **kwargs): def test_filter_embed_params_drops_unsupported(): """Unsupported params like max_tokens should be filtered out.""" - result = _filter_embed_params({"dimensions": 768, "max_tokens": 256, "temperature": 0.5}) + result = _filter_embed_params( + {"dimensions": 768, "max_tokens": 256, "temperature": 0.5} + ) assert result == {"outputDimensionality": 768} def test_filter_embed_params_keeps_supported(): """All supported Gemini embedding params should pass through.""" - result = _filter_embed_params({ - "dimensions": 768, - "task_type": "RETRIEVAL_DOCUMENT", - "title": "My doc", - }) + result = _filter_embed_params( + { + "dimensions": 768, + "task_type": "RETRIEVAL_DOCUMENT", + "title": "My doc", + } + ) assert result == { "outputDimensionality": 768, "taskType": "RETRIEVAL_DOCUMENT", diff --git a/tests/litellm/proxy/test_batch_x_litellm_model_encoding.py b/tests/test_litellm/proxy/test_batch_x_litellm_model_encoding.py similarity index 99% rename from tests/litellm/proxy/test_batch_x_litellm_model_encoding.py rename to tests/test_litellm/proxy/test_batch_x_litellm_model_encoding.py index 49e0498f1409..101dc48603ad 100644 --- a/tests/litellm/proxy/test_batch_x_litellm_model_encoding.py +++ b/tests/test_litellm/proxy/test_batch_x_litellm_model_encoding.py @@ -422,9 +422,7 @@ async def test_cancel_batch_with_unified_id_routes_with_decoded_model_and_batch_ model_id = "deployment-123" raw_batch_id = "batch_openai_123" - unified_batch_id = _make_unified_batch_id( - model_id=model_id, batch_id=raw_batch_id - ) + unified_batch_id = _make_unified_batch_id(model_id=model_id, batch_id=raw_batch_id) mock_response = _make_batch_response(batch_id=raw_batch_id, status="cancelled") mock_response._hidden_params = {} mock_router = MagicMock() diff --git a/tests/litellm/proxy/test_model_based_routing_files_batches.py b/tests/test_litellm/proxy/test_model_based_routing_files_batches.py similarity index 100% rename from tests/litellm/proxy/test_model_based_routing_files_batches.py rename to tests/test_litellm/proxy/test_model_based_routing_files_batches.py diff --git a/tests/litellm/test_batch_completion_models_all_responses.py b/tests/test_litellm/test_batch_completion_models_all_responses.py similarity index 100% rename from tests/litellm/test_batch_completion_models_all_responses.py rename to tests/test_litellm/test_batch_completion_models_all_responses.py From 4faeabc2541912bfec38c2d755cbad0ae3394671 Mon Sep 17 00:00:00 2001 From: Yassin Kortam Date: Tue, 16 Jun 2026 11:17:03 -0700 Subject: [PATCH 3/7] fix(guardrails): run pre_call hook once for model-level guardrails (#30543) * fix(guardrails): run pre_call hook once for model-level guardrails A CustomGuardrail attached to a deployment via litellm_params.guardrails gets its async_pre_call_hook invoked twice per request: once by the proxy pre-call loop and again by async_pre_call_deployment_hook after the router spreads the model-level guardrails into the top-level request kwargs. Record in request metadata that the proxy pre-call loop already ran a given guardrail, and have the deployment hook skip it when the marker is present. Direct-SDK usage never runs the proxy loop, so the deployment hook stays the sole invocation there and still fires exactly once. The marker key is stripped from untrusted caller metadata so a request body cannot suppress a model-only guardrail by pre-seeding it. * fix(guardrails): mark pre_call dedup on the post-hook request data Record the exactly-once marker after async_pre_call_hook runs, on the data object that flows downstream, rather than before it. A guardrail whose hook returns a brand-new request dict (instead of mutating or spreading the one it received) would otherwise discard the marker, letting the deployment hook re-run the guardrail a second time. --- litellm/constants.py | 4 + litellm/integrations/custom_guardrail.py | 54 +++++++ litellm/proxy/common_utils/callback_utils.py | 2 + litellm/proxy/litellm_pre_call_utils.py | 2 + .../proxy/policy_engine/pipeline_executor.py | 4 + litellm/proxy/utils.py | 2 + .../integrations/test_custom_guardrail.py | 106 ++++++++++++ .../proxy/test_model_level_guardrails.py | 152 +++++++++++++++++- 8 files changed, 325 insertions(+), 1 deletion(-) diff --git a/litellm/constants.py b/litellm/constants.py index 663afb87fb5f..b44c204432ce 100644 --- a/litellm/constants.py +++ b/litellm/constants.py @@ -190,6 +190,10 @@ # Override with LITELLM_MAX_CALLBACKS env var for large deployments (e.g., many teams with guardrails) MAX_CALLBACKS = get_env_int("LITELLM_MAX_CALLBACKS", 100) +# Metadata key recording which pre_call guardrails the proxy loop already ran, +# so the deployment-level hook does not re-run them for the same request +PRE_CALL_EXECUTED_GUARDRAILS_KEY = "_pre_call_executed_guardrails" + # Generic fallback for unknown models DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET = int( os.getenv("DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET", 128) diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.py index fc5f0429b63c..059658991fb1 100644 --- a/litellm/integrations/custom_guardrail.py +++ b/litellm/integrations/custom_guardrail.py @@ -1,3 +1,4 @@ +import secrets from datetime import datetime from typing import ( TYPE_CHECKING, @@ -43,6 +44,7 @@ dc = DualCache() +from litellm.constants import PRE_CALL_EXECUTED_GUARDRAILS_KEY from litellm.exceptions import ( BlockedPiiEntityError, GuardrailRaisedException, @@ -50,6 +52,12 @@ SensitiveDataRouteException, ) +# Per-process secret tagging each recorded marker. The deployment hook only +# honors markers carrying this token, so a caller cannot forge the metadata +# field to suppress a guardrail on the direct-SDK path that never reaches the +# proxy's metadata sanitizer. +_PRE_CALL_EXECUTED_TOKEN = secrets.token_hex(16) + def get_session_id_from_request_data(request_data: Dict[str, Any]) -> Optional[str]: """Extract session_id from request data (litellm_session_id or metadata).""" @@ -458,6 +466,49 @@ def _guardrail_is_in_requested_guardrails( return False + def _pre_call_marker(self) -> Optional[str]: + name = self.guardrail_name + if not name: + return None + return f"{_PRE_CALL_EXECUTED_TOKEN}:{name}" + + def mark_pre_call_hook_ran(self, data: Dict[str, Any]) -> None: + """ + Record that this guardrail's ``async_pre_call_hook`` already ran for this + request, so the deployment-level hook does not run it a second time. + + The proxy runs pre-call guardrails in ``ProxyLogging.pre_call_hook``. The + router later spreads a deployment's model-level ``guardrails`` into the + top-level request kwargs, which would otherwise re-trigger the same hook + from ``async_pre_call_deployment_hook``. + """ + marker = self._pre_call_marker() + if marker is None: + return + for meta_key in ("metadata", "litellm_metadata"): + meta = data.get(meta_key) + if isinstance(meta, dict): + executed = meta.get(PRE_CALL_EXECUTED_GUARDRAILS_KEY) + if isinstance(executed, list): + if marker not in executed: + executed.append(marker) + else: + meta[PRE_CALL_EXECUTED_GUARDRAILS_KEY] = [marker] + return + data["metadata"] = {PRE_CALL_EXECUTED_GUARDRAILS_KEY: [marker]} + + def _pre_call_hook_already_ran(self, data: Dict[str, Any]) -> bool: + marker = self._pre_call_marker() + if marker is None: + return False + for meta_key in ("metadata", "litellm_metadata"): + meta = data.get(meta_key) + if isinstance(meta, dict): + executed = meta.get(PRE_CALL_EXECUTED_GUARDRAILS_KEY) + if isinstance(executed, list) and marker in executed: + return True + return False + async def async_pre_call_deployment_hook( self, kwargs: Dict[str, Any], call_type: Optional[CallTypes] ) -> Optional[dict]: @@ -468,6 +519,9 @@ async def async_pre_call_deployment_hook( if litellm_guardrails is None or not isinstance(litellm_guardrails, list): return kwargs + if self._pre_call_hook_already_ran(kwargs): + return kwargs + if ( self.should_run_guardrail( data=kwargs, event_type=GuardrailEventHooks.pre_call diff --git a/litellm/proxy/common_utils/callback_utils.py b/litellm/proxy/common_utils/callback_utils.py index c630294c1ec0..ab1eeaf1646c 100644 --- a/litellm/proxy/common_utils/callback_utils.py +++ b/litellm/proxy/common_utils/callback_utils.py @@ -4,6 +4,7 @@ import litellm from litellm import get_secret from litellm._logging import verbose_proxy_logger +from litellm.constants import PRE_CALL_EXECUTED_GUARDRAILS_KEY from litellm.integrations.custom_logger import CustomLogger from litellm.litellm_core_utils.sensitive_data_masker import SensitiveDataMasker from litellm.proxy._types import CommonProxyErrors, LiteLLMPromptInjectionParams @@ -497,6 +498,7 @@ def get_metadata_variable_name_from_kwargs( "guardrail_config", "_guardrail_pipelines", "_pipeline_managed_guardrails", + PRE_CALL_EXECUTED_GUARDRAILS_KEY, "disable_global_guardrails", "disable_global_guardrail", "opted_out_global_guardrails", diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.py index fca395f889cd..0587ce1cc290 100644 --- a/litellm/proxy/litellm_pre_call_utils.py +++ b/litellm/proxy/litellm_pre_call_utils.py @@ -13,6 +13,7 @@ import litellm from litellm._logging import verbose_logger, verbose_proxy_logger from litellm._service_logger import ServiceLogging +from litellm.constants import PRE_CALL_EXECUTED_GUARDRAILS_KEY from litellm.litellm_core_utils.credential_accessor import CredentialAccessor from litellm.litellm_core_utils.safe_json_loads import safe_json_loads from litellm.litellm_core_utils.url_utils import is_url_destination_allowed_by_host @@ -161,6 +162,7 @@ def parse_cache_control(cache_control): "secret_fields", "_guardrail_pipelines", "_pipeline_managed_guardrails", + PRE_CALL_EXECUTED_GUARDRAILS_KEY, ) _UNTRUSTED_REQUEST_HEADER_CONTROL_FIELDS = frozenset( diff --git a/litellm/proxy/policy_engine/pipeline_executor.py b/litellm/proxy/policy_engine/pipeline_executor.py index 3c5a1d67be4a..e46e3e1dc9ff 100644 --- a/litellm/proxy/policy_engine/pipeline_executor.py +++ b/litellm/proxy/policy_engine/pipeline_executor.py @@ -171,6 +171,10 @@ async def _run_step( data=data, call_type=call_type, # type: ignore ) + if isinstance(callback, CustomGuardrail): + callback.mark_pre_call_hook_ran(data) + if isinstance(response, dict): + callback.mark_pre_call_hook_ran(response) elif mode == "post_call": response = await target.async_post_call_success_hook( user_api_key_dict=user_api_key_dict, diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py index e81bf85604dd..4638922ec6ad 100644 --- a/litellm/proxy/utils.py +++ b/litellm/proxy/utils.py @@ -1171,6 +1171,8 @@ async def _process_guardrail_callback( response=response, data=data, call_type=call_type ) + callback.mark_pre_call_hook_ran(data) + except SensitiveDataRouteException: status = "intervened" raise diff --git a/tests/test_litellm/integrations/test_custom_guardrail.py b/tests/test_litellm/integrations/test_custom_guardrail.py index f0bc7b8ebedb..57fb0fe6714f 100644 --- a/tests/test_litellm/integrations/test_custom_guardrail.py +++ b/tests/test_litellm/integrations/test_custom_guardrail.py @@ -84,6 +84,112 @@ async def test_async_pre_call_deployment_hook_with_guardrails_and_message_update assert result["messages"] == mock_result["messages"] assert result["messages"] != original_messages + @pytest.mark.asyncio + async def test_deployment_hook_skips_when_pre_call_already_ran(self): + """The deployment hook must not re-run async_pre_call_hook once the proxy + pre-call loop has already run it for this request.""" + + class CountingGuardrail(CustomGuardrail): + def __init__(self): + super().__init__(guardrail_name="g1", default_on=True) + self.pre_call_count = 0 + + async def async_pre_call_hook( + self, user_api_key_dict, cache, data, call_type + ): + self.pre_call_count += 1 + return data + + guardrail = CountingGuardrail() + kwargs = { + "messages": [{"role": "user", "content": "hi"}], + "model": "gpt-3.5-turbo", + "guardrails": ["g1"], + "metadata": {}, + } + + guardrail.mark_pre_call_hook_ran(kwargs) + await guardrail.async_pre_call_deployment_hook( + kwargs=kwargs, call_type=CallTypes.completion + ) + + assert guardrail.pre_call_count == 0 + + @pytest.mark.asyncio + async def test_deployment_hook_runs_when_not_marked(self): + """Without the proxy marker (direct-SDK usage) the deployment hook is the + only execution path and must still run the guardrail exactly once.""" + + class CountingGuardrail(CustomGuardrail): + def __init__(self): + super().__init__(guardrail_name="g1", default_on=True) + self.pre_call_count = 0 + + async def async_pre_call_hook( + self, user_api_key_dict, cache, data, call_type + ): + self.pre_call_count += 1 + return data + + guardrail = CountingGuardrail() + kwargs = { + "messages": [{"role": "user", "content": "hi"}], + "model": "gpt-3.5-turbo", + "guardrails": ["g1"], + "metadata": {}, + } + + await guardrail.async_pre_call_deployment_hook( + kwargs=kwargs, call_type=CallTypes.completion + ) + + assert guardrail.pre_call_count == 1 + + def test_mark_pre_call_hook_ran_uses_litellm_metadata(self): + """The marker is recorded in litellm_metadata when that is the metadata + bucket in use, and is then visible to the skip check.""" + from litellm.constants import PRE_CALL_EXECUTED_GUARDRAILS_KEY + + guardrail = CustomGuardrail(guardrail_name="g1") + kwargs = {"litellm_metadata": {}} + + guardrail.mark_pre_call_hook_ran(kwargs) + + assert kwargs["litellm_metadata"][PRE_CALL_EXECUTED_GUARDRAILS_KEY] + assert guardrail._pre_call_hook_already_ran(kwargs) is True + + @pytest.mark.asyncio + async def test_deployment_hook_ignores_forged_caller_marker(self): + """A direct-SDK caller controls request metadata but cannot know the + per-process token, so a hand-crafted marker must not suppress a + requested guardrail in async_pre_call_deployment_hook.""" + from litellm.constants import PRE_CALL_EXECUTED_GUARDRAILS_KEY + + class CountingGuardrail(CustomGuardrail): + def __init__(self): + super().__init__(guardrail_name="g1", default_on=True) + self.pre_call_count = 0 + + async def async_pre_call_hook( + self, user_api_key_dict, cache, data, call_type + ): + self.pre_call_count += 1 + return data + + guardrail = CountingGuardrail() + kwargs = { + "messages": [{"role": "user", "content": "hi"}], + "model": "gpt-3.5-turbo", + "guardrails": ["g1"], + "metadata": {PRE_CALL_EXECUTED_GUARDRAILS_KEY: ["g1"]}, + } + + await guardrail.async_pre_call_deployment_hook( + kwargs=kwargs, call_type=CallTypes.completion + ) + + assert guardrail.pre_call_count == 1 + class TestCustomGuardrailShouldRunGuardrail: diff --git a/tests/test_litellm/proxy/test_model_level_guardrails.py b/tests/test_litellm/proxy/test_model_level_guardrails.py index 3d74edd772b0..9a79fa7f496b 100644 --- a/tests/test_litellm/proxy/test_model_level_guardrails.py +++ b/tests/test_litellm/proxy/test_model_level_guardrails.py @@ -19,7 +19,6 @@ _merge_guardrails_with_existing, ) - # --------------------------------------------------------------------------- # Unit tests for _check_and_merge_model_level_guardrails # --------------------------------------------------------------------------- @@ -159,6 +158,157 @@ def test_returns_new_data_dict(self): assert "existing" in result["metadata"]["guardrails"] +# --------------------------------------------------------------------------- +# Regression test: pre_call hook must run exactly once with model-level guardrails +# --------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_pre_call_hook_runs_once_with_model_level_guardrails(): + """ + A guardrail attached at the model level (litellm_params.guardrails) is + spread into the top-level request kwargs by the router. The proxy pre-call + loop (async_pre_call_hook) and the deployment-level hook + (async_pre_call_deployment_hook) must together invoke async_pre_call_hook + exactly once, not twice. + """ + from litellm.caching.caching import DualCache + from litellm.integrations.custom_guardrail import CustomGuardrail + from litellm.proxy._types import CallTypes, UserAPIKeyAuth + from litellm.proxy.utils import ProxyLogging + from litellm.types.guardrails import GuardrailEventHooks + + class CountingGuardrail(CustomGuardrail): + def __init__(self): + super().__init__( + guardrail_name="counting-guardrail", + event_hook=GuardrailEventHooks.pre_call, + default_on=True, + ) + self.pre_call_count = 0 + + async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type): + self.pre_call_count += 1 + return data + + guardrail = CountingGuardrail() + + with patch("litellm.callbacks", [guardrail]): + ProxyLogging._callback_capabilities_cache.clear() + proxy_logging = ProxyLogging(user_api_key_cache=DualCache()) + user_api_key_dict = UserAPIKeyAuth(api_key="test-key") + + data = { + "model": "gpt-4", + "messages": [{"role": "user", "content": "hello"}], + "metadata": {}, + } + + # Path A: proxy pre-call loop runs the guardrail and records that it ran + data = await proxy_logging.pre_call_hook( + user_api_key_dict=user_api_key_dict, + data=data, + call_type="acompletion", + ) + + # Path B: the router spreads the deployment's model-level guardrails into + # the top-level kwargs, then litellm.acompletion fires the deployment hook + data["guardrails"] = ["counting-guardrail"] + await guardrail.async_pre_call_deployment_hook(data, CallTypes.acompletion) + + assert guardrail.pre_call_count == 1 + + +@pytest.mark.asyncio +async def test_pre_call_hook_runs_once_when_hook_returns_fresh_dict(): + """ + async_pre_call_hook may return a brand-new request dict instead of mutating + or spreading the one it received. The exactly-once marker must live on the + data that flows downstream, so the deployment hook still skips the guardrail + even when the proxy loop swapped in a fresh dict that never carried it. + """ + from litellm.caching.caching import DualCache + from litellm.integrations.custom_guardrail import CustomGuardrail + from litellm.proxy._types import CallTypes, UserAPIKeyAuth + from litellm.proxy.utils import ProxyLogging + from litellm.types.guardrails import GuardrailEventHooks + + class FreshDictGuardrail(CustomGuardrail): + def __init__(self): + super().__init__( + guardrail_name="counting-guardrail", + event_hook=GuardrailEventHooks.pre_call, + default_on=True, + ) + self.pre_call_count = 0 + + async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type): + self.pre_call_count += 1 + return {"model": data["model"], "messages": data["messages"]} + + guardrail = FreshDictGuardrail() + + with patch("litellm.callbacks", [guardrail]): + ProxyLogging._callback_capabilities_cache.clear() + proxy_logging = ProxyLogging(user_api_key_cache=DualCache()) + user_api_key_dict = UserAPIKeyAuth(api_key="test-key") + + data = { + "model": "gpt-4", + "messages": [{"role": "user", "content": "hello"}], + "metadata": {}, + } + + data = await proxy_logging.pre_call_hook( + user_api_key_dict=user_api_key_dict, + data=data, + call_type="acompletion", + ) + + data["guardrails"] = ["counting-guardrail"] + await guardrail.async_pre_call_deployment_hook(data, CallTypes.acompletion) + + assert guardrail.pre_call_count == 1 + + +@pytest.mark.asyncio +async def test_deployment_hook_runs_pre_call_without_proxy_loop(): + """ + Direct-SDK usage (litellm.acompletion(..., guardrails=[...]) without the + proxy) never runs the proxy pre-call loop, so the deployment hook is the + only place the guardrail executes and it must still run exactly once. + """ + from litellm.integrations.custom_guardrail import CustomGuardrail + from litellm.proxy._types import CallTypes + from litellm.types.guardrails import GuardrailEventHooks + + class CountingGuardrail(CustomGuardrail): + def __init__(self): + super().__init__( + guardrail_name="counting-guardrail", + event_hook=GuardrailEventHooks.pre_call, + default_on=True, + ) + self.pre_call_count = 0 + + async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type): + self.pre_call_count += 1 + return data + + guardrail = CountingGuardrail() + + data = { + "model": "gpt-4", + "messages": [{"role": "user", "content": "hello"}], + "guardrails": ["counting-guardrail"], + "metadata": {}, + } + + await guardrail.async_pre_call_deployment_hook(data, CallTypes.acompletion) + + assert guardrail.pre_call_count == 1 + + # --------------------------------------------------------------------------- # Integration test: post_call_success_hook with model-level guardrails # --------------------------------------------------------------------------- From 9fa74ad8b4a3cf206c847d92d20c1bd20daa2b69 Mon Sep 17 00:00:00 2001 From: Yassin Kortam Date: Tue, 16 Jun 2026 11:17:49 -0700 Subject: [PATCH 4/7] fix(guardrails): stop re-initializing DB guardrails on every poll (#30542) * fix(guardrails): stop re-initializing DB guardrails on every poll InMemoryGuardrailHandler._has_guardrail_params_changed compared the in-memory LitellmParams against the raw dict loaded from the DB. The in-memory side carries every field default and coerces enums via model_dump(), while the DB side only holds the keys originally stored, so the two shapes never compared equal and the guardrail was rebuilt on every poll cycle. Each rebuild created a fresh instance, but delete_in_memory_guardrail only removed the old callback from litellm.callbacks. Request handling promotes guardrail callbacks into the success/failure/async lists, so the previous instance stayed referenced there and instances accumulated. Normalize both sides through LitellmParams(...).model_dump() before diffing, and purge the callback from every callback list on delete. * refactor(guardrails): narrow params-normalization fallback to ValidationError The comparison normalizer caught a bare Exception and silently fell back to the raw dict, which hid the cause and quietly degraded the affected guardrail back to re-initializing on every poll. Catch only the ValidationError that LitellmParams construction can raise, log a warning so the offending row is diagnosable, and let any other error surface instead of being swallowed. * refactor(callbacks): add remove_callback_from_all_lists helper to manager Move the knowledge of which callback lists a callback can be promoted into out of the guardrail registry and into LoggingCallbackManager, where the rest of the callback-list bookkeeping already lives. delete_in_memory_guardrail now delegates to the new helper instead of iterating the lists itself. --- .../logging_callback_manager.py | 16 ++ .../proxy/guardrails/guardrail_registry.py | 64 +++++-- .../test_logging_callback_manager.py | 23 +++ .../guardrails/test_guardrail_registry.py | 169 ++++++++++++++++++ 4 files changed, 253 insertions(+), 19 deletions(-) diff --git a/litellm/litellm_core_utils/logging_callback_manager.py b/litellm/litellm_core_utils/logging_callback_manager.py index 6c749118dec4..b7adda3a9a43 100644 --- a/litellm/litellm_core_utils/logging_callback_manager.py +++ b/litellm/litellm_core_utils/logging_callback_manager.py @@ -394,6 +394,22 @@ def _get_all_callbacks(self) -> List[Union[CustomLogger, Callable, str]]: + litellm._async_failure_callback ) + def remove_callback_from_all_lists(self, obj, require_self=False) -> None: + """ + Remove a callback object from every callback list it may have been + promoted into, so a re-initialized callback leaves no stale instance behind. + """ + for callback_list in ( + litellm.callbacks, + litellm.success_callback, + litellm.failure_callback, + litellm._async_success_callback, + litellm._async_failure_callback, + ): + self.remove_callback_from_list_by_object( + callback_list, obj, require_self=require_self + ) + def get_active_additional_logging_utils_from_custom_logger( self, ) -> Set[AdditionalLoggingUtils]: diff --git a/litellm/proxy/guardrails/guardrail_registry.py b/litellm/proxy/guardrails/guardrail_registry.py index a80bb8178902..b99ea8f14a06 100644 --- a/litellm/proxy/guardrails/guardrail_registry.py +++ b/litellm/proxy/guardrails/guardrail_registry.py @@ -5,6 +5,8 @@ from datetime import datetime, timezone from typing import Any, Dict, List, Literal, Optional, Set, Type, cast +from pydantic import ValidationError + import litellm from litellm import Router from litellm._logging import verbose_proxy_logger @@ -601,21 +603,25 @@ def update_in_memory_guardrail( def delete_in_memory_guardrail(self, guardrail_id: str) -> None: """ Delete a guardrail in memory and remove from litellm callbacks. + + The callback is purged from every callback list, not just + litellm.callbacks: request handling promotes guardrail callbacks into the + success/failure/async lists, so removing it from only litellm.callbacks + leaves the old instance stranded in those lists on every re-initialization. """ # Remove from in-memory storage self.IN_MEMORY_GUARDRAILS.pop(guardrail_id, None) self._sources.pop(guardrail_id, None) - # Remove the callback from litellm.callbacks custom_guardrail_callback = self.guardrail_id_to_custom_guardrail.pop( guardrail_id, None ) - if custom_guardrail_callback: - litellm.logging_callback_manager.remove_callback_from_list_by_object( - callback_list=litellm.callbacks, - obj=custom_guardrail_callback, - require_self=False, - ) + if custom_guardrail_callback is None: + return + + litellm.logging_callback_manager.remove_callback_from_all_lists( + custom_guardrail_callback + ) def list_in_memory_guardrails(self) -> List[Guardrail]: """ @@ -657,6 +663,34 @@ def reconcile_db_guardrails(self, db_guardrail_ids: Set[str]) -> List[str]: self.delete_in_memory_guardrail(guardrail_id) return stale_ids + @staticmethod + def _normalize_litellm_params_for_comparison( + params: Optional[Any], + ) -> Optional[Dict[str, Any]]: + """ + Render litellm_params to a canonical dict so an in-memory LitellmParams and + the raw dict loaded from the DB compare equal when they describe the same + config. The in-memory side is a LitellmParams whose model_dump() carries + every field default and coerces enums, while the DB side is the raw stored + dict holding only the keys originally provided. Comparing those two shapes + directly never matches, so each DB poll would re-initialize the guardrail + forever; normalizing both through LitellmParams keeps the diff meaningful. + """ + if params is None: + return None + if isinstance(params, LitellmParams): + return params.model_dump() + if isinstance(params, dict): + try: + return LitellmParams(**params).model_dump() + except ValidationError as e: + verbose_proxy_logger.warning( + f"Could not normalize guardrail litellm_params for comparison; " + f"treating the guardrail as changed. Error: {e}" + ) + return params + return params + def _has_guardrail_params_changed( self, guardrail_id: str, new_guardrail: Guardrail ) -> bool: @@ -673,19 +707,11 @@ def _has_guardrail_params_changed( return True # Compare litellm_params - existing_params = existing.get("litellm_params") - new_params = new_guardrail.get("litellm_params") - - # Convert to dicts for comparison - existing_dict = ( - existing_params.model_dump() - if isinstance(existing_params, LitellmParams) - else existing_params + existing_dict = self._normalize_litellm_params_for_comparison( + existing.get("litellm_params") ) - new_dict = ( - new_params.model_dump() - if isinstance(new_params, LitellmParams) - else new_params + new_dict = self._normalize_litellm_params_for_comparison( + new_guardrail.get("litellm_params") ) # Compare and identify specific differences diff --git a/tests/litellm_utils_tests/test_logging_callback_manager.py b/tests/litellm_utils_tests/test_logging_callback_manager.py index d9540f8f850b..d9bfca425e48 100644 --- a/tests/litellm_utils_tests/test_logging_callback_manager.py +++ b/tests/litellm_utils_tests/test_logging_callback_manager.py @@ -192,6 +192,29 @@ def callback(self): assert len(litellm._async_failure_callback) == 0 +def test_remove_callback_from_all_lists(): + manager = LoggingCallbackManager() + manager._reset_all_callbacks() + + class TestLogger(CustomLogger): + pass + + obj = TestLogger() + manager.add_litellm_callback(obj) + manager.add_litellm_success_callback(obj) + manager.add_litellm_failure_callback(obj) + manager.add_litellm_async_success_callback(obj) + manager.add_litellm_async_failure_callback(obj) + + manager.remove_callback_from_all_lists(obj) + + assert obj not in litellm.callbacks + assert obj not in litellm.success_callback + assert obj not in litellm.failure_callback + assert obj not in litellm._async_success_callback + assert obj not in litellm._async_failure_callback + + def test_reset_callbacks(callback_manager): # Add various callbacks callback_manager.add_litellm_callback("test") diff --git a/tests/test_litellm/proxy/guardrails/test_guardrail_registry.py b/tests/test_litellm/proxy/guardrails/test_guardrail_registry.py index 9f7173383b0e..0ef9ad857f91 100644 --- a/tests/test_litellm/proxy/guardrails/test_guardrail_registry.py +++ b/tests/test_litellm/proxy/guardrails/test_guardrail_registry.py @@ -180,3 +180,172 @@ def test_sync_guardrail_from_db_marks_source_db_when_unchanged(): handler.sync_guardrail_from_db(g) assert handler.get_source("collide") == "db" + + +def _db_litellm_params() -> dict: + """ + Shape produced by GuardrailRegistry.get_all_guardrails_from_db: litellm_params + is a raw dict (not a LitellmParams), holding only the keys originally stored, + a non-schema extra key, and plain-string enum values. + """ + return { + "guardrail": "litellm_content_filter", + "mode": "pre_call", + "default_on": True, + "version": 2, + "blocked_words": [{"keyword": "secret", "action": "BLOCK"}], + } + + +def test_unchanged_db_params_do_not_register_as_changed(): + """ + A DB poll returns litellm_params as a raw dict while the in-memory copy is a + LitellmParams whose model_dump() fills every field default and coerces enums. + The two shapes must compare equal when the config is identical; otherwise + every poll cycle re-initializes the guardrail indefinitely. + """ + handler = InMemoryGuardrailHandler() + raw = _db_litellm_params() + gid = "11111111-1111-1111-1111-111111111111" + handler.IN_MEMORY_GUARDRAILS[gid] = Guardrail( + guardrail_id=gid, + guardrail_name="cf", + litellm_params=LitellmParams(**raw), + ) + + new = Guardrail(guardrail_id=gid, guardrail_name="cf", litellm_params=dict(raw)) + assert handler._has_guardrail_params_changed(gid, new) is False + + +def test_changed_db_params_register_as_changed(): + """Normalizing both sides must still surface a genuine config change.""" + handler = InMemoryGuardrailHandler() + raw = _db_litellm_params() + gid = "22222222-2222-2222-2222-222222222222" + handler.IN_MEMORY_GUARDRAILS[gid] = Guardrail( + guardrail_id=gid, + guardrail_name="cf", + litellm_params=LitellmParams(**raw), + ) + + changed = {**raw, "blocked_words": [{"keyword": "different", "action": "BLOCK"}]} + new = Guardrail(guardrail_id=gid, guardrail_name="cf", litellm_params=changed) + assert handler._has_guardrail_params_changed(gid, new) is True + + +def test_unnormalizable_db_params_register_as_changed_without_raising(): + """ + A DB row whose litellm_params fail LitellmParams validation must not crash the + poll loop. The comparison falls back to treating the guardrail as changed so it + re-initializes (and surfaces the bad row in logs) rather than propagating the + validation error up through the polling cycle. + """ + handler = InMemoryGuardrailHandler() + raw = _db_litellm_params() + gid = "55555555-5555-5555-5555-555555555555" + handler.IN_MEMORY_GUARDRAILS[gid] = Guardrail( + guardrail_id=gid, + guardrail_name="cf", + litellm_params=LitellmParams(**raw), + ) + + malformed = {**raw, "default_on": "not-a-bool-xyz"} + new = Guardrail(guardrail_id=gid, guardrail_name="cf", litellm_params=malformed) + assert handler._has_guardrail_params_changed(gid, new) is True + + +def _all_callback_lists(): + import litellm + + return [ + litellm.callbacks, + litellm.success_callback, + litellm.failure_callback, + litellm._async_success_callback, + litellm._async_failure_callback, + ] + + +def test_delete_in_memory_guardrail_removes_callback_from_all_lists(): + """ + Request handling promotes guardrail callbacks from litellm.callbacks into the + success/failure/async lists. delete_in_memory_guardrail must purge the callback + from every list, otherwise a re-initialized guardrail leaves its old instance + stranded in those lists and instances accumulate. + """ + handler = InMemoryGuardrailHandler() + callback = CustomGuardrail( + guardrail_name="cf-delete", + default_on=True, + event_hook=GuardrailEventHooks.pre_call, + ) + gid = "33333333-3333-3333-3333-333333333333" + handler.IN_MEMORY_GUARDRAILS[gid] = _make_guardrail(gid, "cf-delete") + handler._sources[gid] = "db" + handler.guardrail_id_to_custom_guardrail[gid] = callback + + lists = _all_callback_lists() + snapshots = [list(cb_list) for cb_list in lists] + try: + for cb_list in lists: + cb_list.append(callback) + + handler.delete_in_memory_guardrail(gid) + + for cb_list in lists: + assert callback not in cb_list + finally: + for cb_list, snapshot in zip(lists, snapshots): + cb_list[:] = snapshot + + +def test_repeated_db_sync_does_not_accumulate_runner_instances(): + """ + End-to-end regression for the OOM: across repeated DB polls (with the config + genuinely changing each cycle to force re-initialization), exactly one live + guardrail instance must exist across all callback lists. On the unfixed code + the stale instance lingers in the success/failure lists and the distinct count + climbs above one. + """ + import litellm + + handler = InMemoryGuardrailHandler() + gid = "44444444-4444-4444-4444-444444444444" + name = "cf-accum" + + def db_guardrail(word: str) -> Guardrail: + params = { + **_db_litellm_params(), + "blocked_words": [{"keyword": word, "action": "BLOCK"}], + } + return Guardrail(guardrail_id=gid, guardrail_name=name, litellm_params=params) + + def promote_into_request_lists() -> None: + manager = litellm.logging_callback_manager + for callback in list(litellm.callbacks): + manager.add_litellm_success_callback(callback) + manager.add_litellm_failure_callback(callback) + manager.add_litellm_async_success_callback(callback) + manager.add_litellm_async_failure_callback(callback) + + def distinct_runner_instances() -> int: + seen = set() + for callback in litellm.logging_callback_manager._get_all_callbacks(): + if ( + isinstance(callback, CustomGuardrail) + and getattr(callback, "guardrail_name", None) == name + ): + seen.add(id(callback)) + return len(seen) + + lists = _all_callback_lists() + snapshots = [list(cb_list) for cb_list in lists] + try: + for cycle in range(5): + handler.sync_guardrail_from_db(db_guardrail(f"word-{cycle}")) + promote_into_request_lists() + + assert distinct_runner_instances() == 1 + finally: + for cb_list, snapshot in zip(lists, snapshots): + cb_list[:] = snapshot From 816fca939f30b9aee5eeb470541b04fedbd97d9f Mon Sep 17 00:00:00 2001 From: Sameer Kankute Date: Wed, 17 Jun 2026 00:36:41 +0530 Subject: [PATCH 5/7] chore(oss): litellm oss staging 150626 (#30463) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(pricing): add GitHub Copilot MAI Code Flash pricing (#30415) * fix(pricing): add GitHub Copilot MAI Code Flash pricing Add GitHub Copilot pricing entries for MAI-Code-1-Flash and the internal Copilot CLI model name so cost calculation can price input, cached input, and output tokens. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * test(pricing): cover GitHub Copilot MAI Code Flash pricing Add regression coverage for both GitHub Copilot MAI-Code-1-Flash model names, including cached input pricing, chat endpoint metadata, and cost_per_token arithmetic. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(router/proxy): propagate completed_response through FallbackResponsesStreamWrapper for streaming /v1/responses container ownership (#30210) (#30213) * fix(router/proxy): propagate completed_response through FallbackResponsesStreamWrapper for streaming /v1/responses container ownership (#30210) #28990 added ownership recording for streaming /v1/responses via _wrap_responses_stream_for_container_ownership, which reads `getattr(stream_response, 'completed_response', None)` to extract the ResponsesAPIResponse. The unit test bypassed the Router, so it never exercised the production wrapping path. Through the Router (every proxy deployment), the stream is wrapped by FallbackResponsesStreamWrapper (router.py:2527). Its __init__ set `self.completed_response = None` and __anext__ only forwarded chunks — the inner source iterator's terminal event never bubbled up to the attribute the ownership hook reads, so the hook silently recorded nothing and every follow-up /v1/containers//files call returned 403 for non-admin keys. This commit: - router.py: pre-resolves the responses-API terminal event tuple (response.completed / .incomplete / .failed) once per _aresponses_streaming_iterator call, and has the wrapper's __anext__ sniff each forwarded chunk's .type. First terminal event hit gets stored on the wrapper's completed_response. Iterator-agnostic — works for source_iterator AND any future wrapper. - common_request_processing.py: when _extract_completed_responses_response returns None we now warn instead of silently skipping. Reporter on #30210 lost a day to this exact silent skip; the warning surfaces future regressions of the same shape directly in operator logs. Fixes #30210 * fix(router): type-ignore wrapper getattr-defaults; broaden ownership-skip warning CI lint (mypy) flagged the three pre-existing getattr(..., None) assignments in FallbackResponsesStreamWrapper.__init__: router.py:2564 self.response = getattr(source_iterator, 'response', None) router.py:2565 self.model = getattr(source_iterator, 'model', None) router.py:2566 self.logging_obj = getattr(..., None) Those lines also exist on litellm_internal_staging and pass mypy there. Adding the typed terminal-event tuple above the class made the function body more narrowable, which surfaced the pre-existing mismatch — base class declares non-Optional types but the bridge path (LiteLLMCompletionStreamingIterator) legitimately omits these. Keep the None fallback and silence with type: ignore[assignment]. Greptile 4/5 note: the ownership-skip warning hard-named code_interpreter which misleads operators when a non-code_interpreter stream aborts. Generalize to 'any tool container (e.g. code_interpreter)'. * fix(register_model): drop synthesized zero costs to preserve sparse entries (#30198) (#30201) * fix(register_model): drop synthesized zero costs to preserve sparse entries (#30198) get_model_info synthesizes input_cost_per_token / output_cost_per_token = 0 when they are absent from the raw entry (the price-unknown and free cases share the same representation). register_model then merges that result back into litellm.model_cost, which flips a sparse entry from 'no cost keys' (priced via model name) to 'cost keys = 0' (free). That defeats _is_cost_explicitly_configured (#24949) on re-registration: _is_model_cost_zero returns True, common_checks skips every tag / key / team / user / org budget check for the group, and over-budget traffic keeps returning 200. Spend keeps recording because cost calc still resolves by model name, so the symptom is silent and only triggers on the second register_model pass (router rebuild, /model/update, config sync). Mirror the existing litellm_provider-None guard one block above and pop the cost fields from the synthesized result when they are absent from the raw entry and not in the caller's value. Caller-provided zeros (genuinely free models, BYOK overrides) are preserved. Fixes #30198 * fix(register_model): switch _raw_entry to is-None checks + drop dead test assertion Greptile #30201 review notes: - the `or`-chain in the raw-entry lookup treated an empty dict (a key with no fields) as falsy and fell through to the second arm — replace with explicit `is None` checks so a present-but-empty entry is still taken at face value. - the first assertion in `test_router_double_init_keeps_db_model_entry_sparse` used `in (None, 0)` which passes under the bug condition (cost = 0 matches the tuple); the strong follow-up assertion already covers every shape, so drop the dead branch. * fix(bedrock mantle): use unique function-call id for responses->chat tool calls (#30426) * fix(bedrock mantle): use unique function-call id for responses->chat tool calls ... * fix(bedrock mantle): scope unique tool-call id fallback to degenerate call_id The previous revision preferred the Responses item id for every tool call, which broke providers (and existing tests) where call_id is a unique, canonical correlation key. Restrict the fallback to the degenerate index-based call_id that Bedrock Mantle returns (call_0, call_1, ... resetting per response) and keep call_id otherwise. Revert the change to the OUTPUT_ITEM_DONE streaming handler, whose tool_call_chunk is never emitted (dead code, per review). Extend the regression tests to assert a normal call_id is preserved. * fix(router): preserve azure_ad_token through CredentialLiteLLMParams for /v1/files + batches (#30235) (#30241) * fix(router): preserve azure_ad_token through CredentialLiteLLMParams for /v1/files + batches (#30235) Router.get_deployment_credentials_with_provider re-validates a deployment's litellm_params through CredentialLiteLLMParams before handing them to file/batch/passthrough callers: return CredentialLiteLLMParams( **deployment.litellm_params.model_dump(exclude_none=True) ).model_dump(exclude_none=True) Any field NOT declared on CredentialLiteLLMParams gets silently dropped on the way through. azure_ad_token was undeclared, so Azure deployments using OAuth/M2M (azure_ad_token instead of a static api_key) silently lost their token at the files endpoint and the proxy returned: Missing credentials. Please pass one of api_key, azure_ad_token, azure_ad_token_provider, ... Declare azure_ad_token on CredentialLiteLLMParams alongside api_key / api_base / api_version so it rides through the round-trip. Static-key deployments stay unaffected (Optional, default None, dropped by exclude_none=True). Provider-callable (azure_ad_token_provider) is a separate concern and out of scope here. Fixes #30235 * fix(ui-types): regenerate schema.d.ts for new azure_ad_token field CI's 'Verify schema.d.ts matches the proxy OpenAPI spec' check auto-detected the new field and emitted the exact diff to apply. Two schemas had `aws_secret_access_key` from CredentialLiteLLMParams, both get the new azure_ad_token marker next to it. * fix(proxy): org_admin with own user_id now sees all org teams on /v2/team/list (#30247) When the UI sends the callers own user_id (as it does for non-Admin global roles), _enforce_list_team_v2_access now nulls it out for org admins so _build_team_list_where_conditions scopes by organization_id only -- matching the legacy /team/list behavior and the documented intent. Fixes #30215 Co-authored-by: Claude Opus 4.6 * test(vertex_ai): multi-region regression coverage for cachedContents host (#29571) (#29707) litellm_internal_staging already routes the cachedContents URL through get_vertex_base_url, fixing the multi-region 404 reported in #29571 — but carries no test coverage for the actual regression scenario (eu/us must resolve to the REP host aiplatform.{geo}.rep.googleapis.com). Add TestContextCachingMultiRegionUrls: parametrized eu/us REP-host assertions (including absence of the old broken {geo}-aiplatform host), plus regional (us-central1) and global no-regression checks. * fix(proxy): close upstream LLM stream when client disconnects mid-stream (#30245) * fix(proxy): close upstream LLM stream when client disconnects mid-stream When a streaming client disconnects, Starlette abandons the response body iterator without calling aclose(), so the proxy's connection to the upstream backend stays open until garbage collection, which may never come. The backend (e.g. vLLM) keeps generating into a dead pipe: small responses drain invisibly into TCP buffers while large ones block the backend on a full send buffer indefinitely (observed via lsof as an ESTABLISHED proxy->backend connection minutes after the client left) create_response now returns a StreamingResponse subclass that closes both its body iterator and the wrapped upstream-facing generator in a shielded finally. The upstream generator is closed directly rather than through a cascade because aclose() on a never-started generator skips its body, which would make the cascade a no-op when the client disconnects before the first chunk is sent. async_streaming_data_generator also gains the same shielded finally-aclose that async_data_generator in proxy_server.py already had, covering the Anthropic and Google SSE paths With this, killing a streaming client causes the backend to observe the abort within about a second and free its slot, while completed streams are unaffected. No flag is needed, unlike the non-streaming opt-in cancel in #30223: this only releases resources after the client is already gone and does not change any response a client can observe Fixes #30244 * fix(proxy): close upstream even when body iterator aclose raises BaseException Addresses the Greptile finding on #30245: the cleanup loop caught only Exception while the generator-level cleanup catches BaseException, so a CancelledError or GeneratorExit escaping body_iterator.aclose() would skip closing the upstream generator. Both sites now use the same scope and a regression test pins that the upstream is closed even when the body iterator explodes with a BaseException * fix(llms): expose aclose on BaseModelResponseIterator so stream close reaches the provider connection The response-level close added for #30244 only worked for SDK-based providers (e.g. openai), whose streams expose aclose all the way down. Providers served by base_llm_http_handler (hosted_vllm and most modern transformation-based providers) wrap a bare response.aiter_lines() generator in BaseModelResponseIterator, which had no aclose or close at all, and nothing retained the httpx response object; so CustomStreamWrapper.aclose() silently did nothing and the upstream connection stayed open. Verified with a vLLM-style mock: with hosted_vllm/ the backend streamed all 100 chunks to completion after the client disconnected, while openai/ aborted at chunk 6 BaseModelResponseIterator now carries an optional http_response and an aclose() that closes it; make_async_call_stream_helper attaches the response after building the iterator. With this, hosted_vllm aborts the backend within ~1.6s of the client dropping, and completed streams are unaffected --------- Co-authored-by: kursad * feat(anthropic): surface compaction usage iterations data (#27065) * feat(anthropic): surface compaction usage iterations data * style: apply black formatting to fix lint checks * fix(usage): correct calculate usage with cached tokens when use ChatCompletionUsageBlock (#30422) * fix(usage): correct calculate usage with cached tokens when use ChatCompletionUsageBlock * fix(usage): optimize test imports * feat: add fastCRW search provider (#30434) * feat(provider): add LibertAI as a JSON-configured OpenAI-compatible provider (#30203) * feat(provider): add LibertAI as a JSON-configured OpenAI-compatible provider * libertai: update served endpoints backup + add mode/matrix tests Addresses review feedback: - Add libertai to litellm/provider_endpoints_support_backup.json, the file actually served by GET /public/supported_endpoints (the root provider_endpoints_support.json already had it). - Add tests asserting bge-m3 normalizes to mode='embedding' and that the served matrix lists libertai. embeddings stays false: the JSON-configured provider path only wires chat routing (OpenAILike embedding handler is reached only for literal openai_like/llamafile/lm_studio), matching the llamagate precedent; bge-m3 remains in the cost map for metadata. --------- Co-authored-by: Moshe Malawach * feat(provider): add ModelScope as an OpenAI-compatible provider (#28460) * add ModelScope API support * add modelscope api support * update modelscope model list * add image-genetation support * update test and multimodal * fix: address PR review feedback for modelscope provider * update README * fix(customer_endpoints): restrict /customer/daily/activity to admin-only (#28849) * fix(customer_endpoints): restrict /customer/daily/activity to admin-only * fix(customer_endpoints): check role before prisma_client guard * fix(custom_guardrail): key disable_global_guardrails takes precedence over team guardrail list (#28563) * fix(fallbacks): preserve fallback model in SDK fallback responses (#28260) * fix(fallbacks): preserve fallback model in response when using SDK-level fallbacks * fix(fallbacks): gate x-litellm-* passthrough to trusted callers only The previous patch unconditionally let `x-litellm-*` keys bypass the `llm_provider-` prefix in `process_response_headers`. That function is also called on raw upstream-provider response headers (e.g. from `llm_http_handler.py`), so a malicious provider could return `x-litellm-attempted-fallbacks` and spoof a LiteLLM-internal marker, bypassing the proxy model-override guard. Add a `preserve_litellm_internal_headers` flag (default False). Only `response_metadata.py`, which re-processes the already-built `_hidden_params["additional_headers"]` dict (LiteLLM-owned), passes True. Raw provider header callsites keep the default False, so upstream `x-litellm-*` still gets the `llm_provider-` prefix. Adds a regression test for the spoofing case and renames the existing preserve test to make the trusted-path semantics explicit. * fix(fallbacks): ignore preserve_litellm_internal_headers for raw httpx.Headers inputs * style(core_helpers): apply black formatting * fix(lint): remove banned typing.List/Dict/Any imports and suppress PLR0913 on interface overrides Co-Authored-By: Claude Sonnet 4.6 * fix(lint): apply black formatting to modelscope chat transformation Co-Authored-By: Claude Sonnet 4.6 * fix(lint): replace noqa with proper fixes — use **kwargs and Awaitable instead of Any/List Co-Authored-By: Claude Sonnet 4.6 * fix(lint): remove unused AllMessageValues import Co-Authored-By: Claude Sonnet 4.6 * revert: restore base_model_iterator.py to original PR state Co-Authored-By: Claude Sonnet 4.6 * fix(lint): restore full method signatures for MyPy compatibility; bump PLR0913 budget for new provider files Co-Authored-By: Claude Sonnet 4.6 * fix(lint): use @override to suppress PLR0913 on inherited signatures instead of bumping budget The overrides keep their full base-class signatures for MyPy compatibility, but those signatures carry more than five parameters, which tripped PLR0913 on each subclass redeclaration. Since the arity is dictated by the base class and cannot be reduced, decorate the overrides with typing_extensions.override; ruff treats that as the intended signal that the parameter count is not under the author's control and skips PLR0913. This restores the PLR0913 baseline to 1813. * fix(lint): add @override to modelscope image generation overrides Apply the same typing_extensions.override treatment to the image generation config so its inherited-signature overrides do not count against PLR0913. --------- Co-authored-by: Joel Tony Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: hcl Co-authored-by: ztko <96878659+koztkozt@users.noreply.github.com> Co-authored-by: Nahrin Co-authored-by: Claude Opus 4.6 Co-authored-by: Humphrey Co-authored-by: kursadlacin Co-authored-by: kursad Co-authored-by: Dushyant Acharya Co-authored-by: Yuriy Co-authored-by: Recep S <22618852+us@users.noreply.github.com> Co-authored-by: Moshe Malawach Co-authored-by: Moshe Malawach Co-authored-by: Rongkun Yan <2493404415@qq.com> Co-authored-by: Varshith Co-authored-by: Mateo Wang <277851410+mateo-berri@users.noreply.github.com> --- README.md | 1 + litellm/__init__.py | 8 + litellm/_lazy_imports_registry.py | 5 + .../transformation.py | 8 +- litellm/constants.py | 48 ++ litellm/integrations/custom_guardrail.py | 3 + litellm/litellm_core_utils/core_helpers.py | 27 +- litellm/litellm_core_utils/fallback_utils.py | 10 +- .../get_llm_provider_logic.py | 10 + .../llm_response_utils/response_metadata.py | 3 +- .../streaming_chunk_builder_utils.py | 2 + litellm/llms/anthropic/chat/transformation.py | 44 +- litellm/llms/base_llm/base_model_iterator.py | 17 +- litellm/llms/custom_httpx/llm_http_handler.py | 7 +- litellm/llms/fastcrw/__init__.py | 7 + litellm/llms/fastcrw/search/__init__.py | 7 + litellm/llms/fastcrw/search/transformation.py | 182 +++++++ .../llms/modelscope/chat/transformation.py | 93 ++++ .../modelscope/image_generation/__init__.py | 31 ++ .../image_generation/transformation.py | 248 ++++++++++ litellm/llms/openai_like/providers.json | 8 + ...odel_prices_and_context_window_backup.json | 200 ++++++++ .../provider_endpoints_support_backup.json | 17 + litellm/proxy/common_request_processing.py | 82 +++- .../customer_endpoints.py | 13 + .../management_endpoints/team_endpoints.py | 8 + .../transformation.py | 20 +- litellm/router.py | 43 +- litellm/types/router.py | 7 + litellm/types/utils.py | 3 + litellm/utils.py | 29 ++ model_prices_and_context_window.json | 200 ++++++++ provider_endpoints_support.json | 52 ++ .../enforce_llms_folder_style.py | 1 + tests/test_anthropic_compaction_usage.py | 96 ++++ ...responses_transformation_transformation.py | 34 ++ .../integrations/test_custom_guardrail.py | 48 ++ .../litellm_core_utils/test_fallback_utils.py | 128 ++++- .../test_streaming_chunk_builder_utils.py | 39 +- .../llms/base_llm/test_base_model_iterator.py | 35 ++ .../fastcrw/search/test_transformation.py | 182 +++++++ .../test_modelscope_chat_transformation.py | 394 +++++++++++++++ ...est_modelscope_image_gen_transformation.py | 456 ++++++++++++++++++ .../openai_like/test_libertai_provider.py | 131 +++++ .../test_vertex_ai_context_caching.py | 54 +++ .../test_customer_endpoints.py | 98 ++++ .../test_team_endpoints.py | 100 ++++ .../test_spend_management_endpoints.py | 1 + .../proxy/test_common_request_processing.py | 181 +++++++ .../test_litellm_completion_responses.py | 25 + ...st_azure_ad_token_credential_resolution.py | 145 ++++++ tests/test_litellm/test_cost_calculator.py | 39 +- ...st_register_model_zero_cost_persistence.py | 187 +++++++ ...responses_streaming_container_ownership.py | 261 ++++++++++ ui/litellm-dashboard/src/lib/http/schema.d.ts | 4 + 55 files changed, 4053 insertions(+), 29 deletions(-) create mode 100644 litellm/llms/fastcrw/__init__.py create mode 100644 litellm/llms/fastcrw/search/__init__.py create mode 100644 litellm/llms/fastcrw/search/transformation.py create mode 100644 litellm/llms/modelscope/chat/transformation.py create mode 100644 litellm/llms/modelscope/image_generation/__init__.py create mode 100644 litellm/llms/modelscope/image_generation/transformation.py create mode 100644 tests/test_anthropic_compaction_usage.py create mode 100644 tests/test_litellm/llms/fastcrw/search/test_transformation.py create mode 100644 tests/test_litellm/llms/modelscope/chat/test_modelscope_chat_transformation.py create mode 100644 tests/test_litellm/llms/modelscope/image_generation/test_modelscope_image_gen_transformation.py create mode 100644 tests/test_litellm/llms/openai_like/test_libertai_provider.py create mode 100644 tests/test_litellm/test_azure_ad_token_credential_resolution.py create mode 100644 tests/test_litellm/test_register_model_zero_cost_persistence.py create mode 100644 tests/test_litellm/test_responses_streaming_container_ownership.py diff --git a/README.md b/README.md index d600f3952c6d..d7dc665dcec6 100644 --- a/README.md +++ b/README.md @@ -327,6 +327,7 @@ curl -X POST 'http://0.0.0.0:4000/v1/chat/completions' \ | [Maritalk (`maritalk`)](https://docs.litellm.ai/docs/providers/maritalk) | ✅ | ✅ | ✅ | | | | | | | | | [Meta - Llama API (`meta_llama`)](https://docs.litellm.ai/docs/providers/meta_llama) | ✅ | ✅ | ✅ | | | | | | | | | [Mistral AI API (`mistral`)](https://docs.litellm.ai/docs/providers/mistral) | ✅ | ✅ | ✅ | ✅ | | | | | | | +| [ModelScope (`modelscope`)](https://docs.litellm.ai/docs/providers/modelscope) | ✅ | ✅ | ✅ | | ✅ | | | | | | | [Moonshot (`moonshot`)](https://docs.litellm.ai/docs/providers/moonshot) | ✅ | ✅ | ✅ | | | | | | | | | [Morph (`morph`)](https://docs.litellm.ai/docs/providers/morph) | ✅ | ✅ | ✅ | | | | | | | | | [Nebius AI Studio (`nebius`)](https://docs.litellm.ai/docs/providers/nebius) | ✅ | ✅ | ✅ | ✅ | | | | | | | diff --git a/litellm/__init__.py b/litellm/__init__.py index d5fbb41c4623..0d6a788e368f 100644 --- a/litellm/__init__.py +++ b/litellm/__init__.py @@ -73,6 +73,7 @@ def _dev_env_hot_reload_enabled() -> bool: replicate_models, clarifai_models, huggingface_models, + modelscope_models, empower_models, together_ai_models, baseten_models, @@ -900,6 +901,8 @@ def add_known_models(model_cost_map: Optional[Dict] = None): heroku_models.add(key) elif value.get("litellm_provider") == "dashscope": dashscope_models.add(key) + elif value.get("litellm_provider") == "modelscope": + modelscope_models.add(key) elif value.get("litellm_provider") == "moonshot": moonshot_models.add(key) elif value.get("litellm_provider") == "publicai": @@ -1019,6 +1022,7 @@ def add_known_models(model_cost_map: Optional[Dict] = None): | zai_models | fal_ai_models | deepseek_models + | modelscope_models | azure_ai_models | voyage_models | infinity_models @@ -1152,6 +1156,7 @@ def add_known_models(model_cost_map: Optional[Dict] = None): "elevenlabs": elevenlabs_models, "heroku": heroku_models, "dashscope": dashscope_models, + "modelscope": modelscope_models, "moonshot": moonshot_models, "publicai": publicai_models, "v0": v0_models, @@ -1975,6 +1980,9 @@ def set_global_gitlab_config(config: Dict[str, Any]) -> None: from .llms.dashscope.rerank.transformation import ( DashScopeRerankConfig as DashScopeRerankConfig, ) + from .llms.modelscope.chat.transformation import ( + ModelScopeChatConfig as ModelScopeChatConfig, + ) from .llms.moonshot.chat.transformation import ( MoonshotChatConfig as MoonshotChatConfig, ) diff --git a/litellm/_lazy_imports_registry.py b/litellm/_lazy_imports_registry.py index 6073b6b28336..e653b40fd04f 100644 --- a/litellm/_lazy_imports_registry.py +++ b/litellm/_lazy_imports_registry.py @@ -306,6 +306,7 @@ "GigaChatConfig", "GigaChatEmbeddingConfig", "DashScopeChatConfig", + "ModelScopeChatConfig", "MoonshotChatConfig", "DockerModelRunnerChatConfig", "V0ChatConfig", @@ -1161,6 +1162,10 @@ ".llms.dashscope.chat.transformation", "DashScopeChatConfig", ), + "ModelScopeChatConfig": ( + ".llms.modelscope.chat.transformation", + "ModelScopeChatConfig", + ), "MoonshotChatConfig": (".llms.moonshot.chat.transformation", "MoonshotChatConfig"), "DockerModelRunnerChatConfig": ( ".llms.docker_model_runner.chat.transformation", diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py index 6d8b5cf8a57d..78826f822bc0 100644 --- a/litellm/completion_extras/litellm_responses_transformation/transformation.py +++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py @@ -1293,9 +1293,15 @@ def translate_responses_chunk_to_openai_stream( # noqa: PLR0915 provider_specific_fields ) + from litellm.responses.litellm_completion_transformation.transformation import ( + LiteLLMCompletionResponsesConfig, + ) + tool_call_index = parsed_chunk.get("output_index", 0) tool_call_chunk = ChatCompletionToolCallChunk( - id=output_item.get("call_id"), + id=LiteLLMCompletionResponsesConfig._tool_call_id_from_responses_item( + output_item.get("id"), output_item.get("call_id") + ), index=tool_call_index, type="function", function=function_chunk, diff --git a/litellm/constants.py b/litellm/constants.py index b44c204432ce..b51d15b6d251 100644 --- a/litellm/constants.py +++ b/litellm/constants.py @@ -622,6 +622,7 @@ "nscale", "nebius", "dashscope", + "modelscope", "moonshot", "publicai", "v0", @@ -780,6 +781,7 @@ "inference.api.nscale.com/v1", "api.studio.nebius.ai/v1", "https://dashscope-intl.aliyuncs.com/compatible-mode/v1", + "https://api-inference.modelscope.cn/v1", "https://api.moonshot.ai/v1", "https://api.publicai.co/v1", "https://api.synthetic.new/openai/v1", @@ -797,6 +799,7 @@ "https://ai-gateway.vercel.sh/v1", "https://api.inference.wandb.ai/v1", "https://api.clarifai.com/v2/ext/openai/v1", + "https://api.libertai.io/v1", ] @@ -840,10 +843,12 @@ "poe", # Poe - JSON-configured provider "chutes", # Chutes - JSON-configured provider "parasail", # Parasail - JSON-configured provider + "libertai", # LibertAI - JSON-configured provider "featherless_ai", "nscale", "nebius", "dashscope", + "modelscope", "moonshot", "v0", "helicone", @@ -869,6 +874,7 @@ "featherless_ai", "nebius", "dashscope", + "modelscope", "moonshot", "publicai", "synthetic", @@ -1129,6 +1135,48 @@ ] ) +modelscope_models: set = set( + [ + # Qwen series models + "Qwen/Qwen3-0.6B", + "Qwen/Qwen3-1.7B", + "Qwen/Qwen3-4B", + "Qwen/Qwen3-8B", + "Qwen/Qwen3-14B", + "Qwen/Qwen3-30B-A3B", + "Qwen/Qwen3-32B", + "Qwen/Qwen3-235B-A22B", + "Qwen/Qwen3-235B-A22B-Instruct-2507", + "Qwen/Qwen3-235B-A22B-Thinking-2507", + "Qwen/Qwen3-30B-A3B-Thinking-2507", + "Qwen/Qwen3-Coder-30B-A3B-Instruct", + "Qwen/Qwen3-Coder-480B-A35B-Instruct", + "Qwen/Qwen3-Next-80B-A3B-Instruct", + "Qwen/Qwen3-Next-80B-A3B-Thinking", + "Qwen/Qwen3-VL-235B-A22B-Instruct", + "Qwen/Qwen3-VL-8B-Instruct", + "Qwen/Qwen3-VL-8B-Thinking", + "Qwen/Qwen3.5-122B-A10B", + "Qwen/Qwen3.5-27B", + "Qwen/Qwen3.5-35B-A3B", + "Qwen/Qwen3.5-397B-A17B", + "Qwen/QwQ-32B", + "Qwen/QwQ-32B-Preview", + "Qwen/QVQ-72B-Preview", + "Qwen/Qwen-Image-Edit", + # DeepSeek series models + "deepseek-ai/DeepSeek-R1-0528", + "deepseek-ai/DeepSeek-R1-Distill-Llama-70B", + "deepseek-ai/DeepSeek-R1-Distill-Llama-8B", + "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B", + "deepseek-ai/DeepSeek-R1-Distill-Qwen-14B", + "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B", + "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", + "deepseek-ai/DeepSeek-V3.2", + "deepseek-ai/DeepSeek-V4-Flash", + ] +) + BEDROCK_INVOKE_PROVIDERS_LITERAL = Literal[ "cohere", "anthropic", diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.py index 059658991fb1..38245a2e5baa 100644 --- a/litellm/integrations/custom_guardrail.py +++ b/litellm/integrations/custom_guardrail.py @@ -621,6 +621,9 @@ def should_run_guardrail( ): return False + if self.default_on is True and disable_global_guardrail is True: + return False + if self.default_on is True and disable_global_guardrail is not True: if self._event_hook_is_event_type(event_type): if isinstance(self.event_hook, Mode): diff --git a/litellm/litellm_core_utils/core_helpers.py b/litellm/litellm_core_utils/core_helpers.py index e984df821403..98b792efa59e 100644 --- a/litellm/litellm_core_utils/core_helpers.py +++ b/litellm/litellm_core_utils/core_helpers.py @@ -242,9 +242,28 @@ def _get_parent_otel_span_from_kwargs( return None -def process_response_headers(response_headers: Union[httpx.Headers, dict]) -> dict: +def process_response_headers( + response_headers: Union[httpx.Headers, dict], + preserve_litellm_internal_headers: bool = False, +) -> dict: + """ + `preserve_litellm_internal_headers` must only be True when the input is a + LiteLLM-owned dict (e.g. `_hidden_params["additional_headers"]` that has + already been through one round of processing). For raw upstream provider + headers — whether passed as `httpx.Headers` or a plain dict — it must + remain False, otherwise a malicious provider returning `x-litellm-*` could + spoof LiteLLM-internal markers (e.g. `x-litellm-attempted-fallbacks`). + + When the input is an `httpx.Headers` object the flag is always treated as + False regardless of what the caller requested, because `httpx.Headers` is + always a raw provider response and can never be LiteLLM-owned. + """ from litellm.types.utils import OPENAI_RESPONSE_HEADERS + # Raw httpx.Headers objects come directly from provider HTTP responses and + # must never be treated as LiteLLM-owned, regardless of caller intent. + _preserve = preserve_litellm_internal_headers and isinstance(response_headers, dict) + openai_headers = {} processed_headers = {} additional_headers = {} @@ -256,6 +275,12 @@ def process_response_headers(response_headers: Union[httpx.Headers, dict]) -> di "llm_provider-" ): # return raw provider headers (incl. openai-compatible ones) processed_headers[k] = v + elif _preserve and k.startswith("x-litellm-"): + # LiteLLM's own internal headers (e.g. x-litellm-attempted-fallbacks, + # x-litellm-model-group) are not LLM provider headers and must not be + # prefixed. Downstream consumers (proxy override, callers checking + # whether a fallback happened) look up the bare key. + processed_headers[k] = v else: additional_headers["{}-{}".format("llm_provider", k)] = v diff --git a/litellm/litellm_core_utils/fallback_utils.py b/litellm/litellm_core_utils/fallback_utils.py index daacca85c8af..1606b53e1f98 100644 --- a/litellm/litellm_core_utils/fallback_utils.py +++ b/litellm/litellm_core_utils/fallback_utils.py @@ -7,6 +7,9 @@ safe_deep_copy, filter_internal_params, ) +from litellm.router_utils.add_retry_fallback_headers import ( + add_fallback_headers_to_response, +) from .asyncify import run_async_function @@ -42,7 +45,7 @@ async def async_completion_with_fallbacks(**kwargs): # Try each fallback model most_recent_exception_str: Optional[str] = None - for fallback in fallbacks: + for attempted_fallbacks, fallback in enumerate(fallbacks): try: completion_kwargs = safe_deep_copy(base_kwargs) # Handle dictionary fallback configurations @@ -63,7 +66,10 @@ async def async_completion_with_fallbacks(**kwargs): ) if response is not None: - return response + return add_fallback_headers_to_response( + response=response, + attempted_fallbacks=attempted_fallbacks, + ) except Exception as e: verbose_logger.exception( diff --git a/litellm/litellm_core_utils/get_llm_provider_logic.py b/litellm/litellm_core_utils/get_llm_provider_logic.py index 5dc3f5c68681..80ee406b7e7f 100644 --- a/litellm/litellm_core_utils/get_llm_provider_logic.py +++ b/litellm/litellm_core_utils/get_llm_provider_logic.py @@ -334,6 +334,9 @@ def get_llm_provider( # noqa: PLR0915 elif endpoint == "dashscope-intl.aliyuncs.com/compatible-mode/v1": custom_llm_provider = "dashscope" dynamic_api_key = get_secret_str("DASHSCOPE_API_KEY") + elif endpoint == "https://api-inference.modelscope.cn/v1": + custom_llm_provider = "modelscope" + dynamic_api_key = get_secret_str("MODELSCOPE_API_KEY") elif endpoint == "api.moonshot.ai/v1": custom_llm_provider = "moonshot" dynamic_api_key = get_secret_str("MOONSHOT_API_KEY") @@ -927,6 +930,13 @@ def _get_openai_compatible_provider_info( # noqa: PLR0915 ) = litellm.DashScopeChatConfig()._get_openai_compatible_provider_info( api_base, api_key ) + elif custom_llm_provider == "modelscope": + ( + api_base, + dynamic_api_key, + ) = litellm.ModelScopeChatConfig()._get_openai_compatible_provider_info( + api_base, api_key + ) elif custom_llm_provider == "moonshot": ( api_base, diff --git a/litellm/litellm_core_utils/llm_response_utils/response_metadata.py b/litellm/litellm_core_utils/llm_response_utils/response_metadata.py index 06933a6fbcb0..ba870eb9459b 100644 --- a/litellm/litellm_core_utils/llm_response_utils/response_metadata.py +++ b/litellm/litellm_core_utils/llm_response_utils/response_metadata.py @@ -49,7 +49,8 @@ def set_hidden_params( result=self.result, litellm_model_name=model, router_model_id=model_id ), "additional_headers": process_response_headers( - self._get_value_from_hidden_params("additional_headers") or {} + self._get_value_from_hidden_params("additional_headers") or {}, + preserve_litellm_internal_headers=True, ), "litellm_model_name": model, } diff --git a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py index b495b183ec06..d51b937d4341 100644 --- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py +++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py @@ -604,6 +604,8 @@ def _calculate_usage_per_chunk( usage_chunk = chunk._hidden_params.get("usage", None) if usage_chunk is not None: + if isinstance(usage_chunk, dict): + usage_chunk = Usage(**usage_chunk) usage_chunk_dict = self._usage_chunk_calculation_helper(usage_chunk) if ( usage_chunk_dict["prompt_tokens"] is not None diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.py index 9ecd0df0cb81..e8c1e659e9f2 100644 --- a/litellm/llms/anthropic/chat/transformation.py +++ b/litellm/llms/anthropic/chat/transformation.py @@ -2214,18 +2214,33 @@ def calculate_usage( if "inference_geo" in _usage and _usage["inference_geo"] is not None: inference_geo = _usage["inference_geo"] - if ( - "cache_creation_input_tokens" in _usage - and _usage["cache_creation_input_tokens"] is not None - ): - cache_creation_input_tokens = _usage["cache_creation_input_tokens"] - prompt_tokens += cache_creation_input_tokens - if ( - "cache_read_input_tokens" in _usage - and _usage["cache_read_input_tokens"] is not None - ): - cache_read_input_tokens = _usage["cache_read_input_tokens"] - prompt_tokens += cache_read_input_tokens + iterations: Optional[List[Any]] = _usage.get("iterations") + if iterations: + prompt_tokens = sum(it.get("input_tokens", 0) or 0 for it in iterations) + completion_tokens = sum( + it.get("output_tokens", 0) or 0 for it in iterations + ) + cache_creation_input_tokens = sum( + it.get("cache_creation_input_tokens", 0) or 0 for it in iterations + ) + cache_read_input_tokens = sum( + it.get("cache_read_input_tokens", 0) or 0 for it in iterations + ) + prompt_tokens += cache_creation_input_tokens + cache_read_input_tokens + + if not iterations: + if ( + "cache_creation_input_tokens" in _usage + and _usage["cache_creation_input_tokens"] is not None + ): + cache_creation_input_tokens = _usage["cache_creation_input_tokens"] + prompt_tokens += cache_creation_input_tokens + if ( + "cache_read_input_tokens" in _usage + and _usage["cache_read_input_tokens"] is not None + ): + cache_read_input_tokens = _usage["cache_read_input_tokens"] + prompt_tokens += cache_read_input_tokens if "server_tool_use" in _usage and _usage["server_tool_use"] is not None: if ( "web_search_requests" in _usage["server_tool_use"] @@ -2264,7 +2279,9 @@ def calculate_usage( ), ) - raw_input_tokens = usage_object.get("input_tokens", 0) or 0 + raw_input_tokens = ( + prompt_tokens - cache_read_input_tokens - cache_creation_input_tokens + ) prompt_tokens_details = PromptTokensDetailsWrapper( cached_tokens=cache_read_input_tokens, cache_creation_tokens=cache_creation_input_tokens, @@ -2296,6 +2313,7 @@ def calculate_usage( cache_creation_input_tokens=cache_creation_input_tokens, cache_read_input_tokens=cache_read_input_tokens, completion_tokens_details=completion_token_details, + iterations=iterations, server_tool_use=( ServerToolUse( web_search_requests=web_search_requests, diff --git a/litellm/llms/base_llm/base_model_iterator.py b/litellm/llms/base_llm/base_model_iterator.py index bf1bfd06537a..422ae947997f 100644 --- a/litellm/llms/base_llm/base_model_iterator.py +++ b/litellm/llms/base_llm/base_model_iterator.py @@ -1,8 +1,11 @@ import json from abc import abstractmethod -from typing import List, Optional, Union, cast +from typing import TYPE_CHECKING, List, Optional, Union, cast import litellm + +if TYPE_CHECKING: + import httpx from litellm.types.utils import ( Choices, Delta, @@ -69,6 +72,18 @@ def __init__( self.streaming_response = streaming_response self.response_iterator = self.streaming_response self.json_mode = json_mode + self.http_response: Optional["httpx.Response"] = None + + async def aclose(self) -> None: + """Close the upstream HTTP response so the provider connection is + released (and a backend like vLLM aborts generation) when the stream + is abandoned before its natural end. + + ``streaming_response`` is usually a bare ``aiter_lines()`` generator + that holds no reference to the response, so the handler that owns the + response attaches it here after construction.""" + if self.http_response is not None: + await self.http_response.aclose() def chunk_parser( self, chunk: dict diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py index c3f487997c33..5575385fb28a 100644 --- a/litellm/llms/custom_httpx/llm_http_handler.py +++ b/litellm/llms/custom_httpx/llm_http_handler.py @@ -33,7 +33,10 @@ from litellm.llms.base_llm.audio_transcription.transformation import ( BaseAudioTranscriptionConfig, ) -from litellm.llms.base_llm.base_model_iterator import MockResponseIterator +from litellm.llms.base_llm.base_model_iterator import ( + BaseModelResponseIterator, + MockResponseIterator, +) from litellm.llms.base_llm.batches.transformation import BaseBatchesConfig from litellm.llms.base_llm.chat.transformation import BaseConfig from litellm.llms.base_llm.containers.transformation import BaseContainerConfig @@ -814,6 +817,8 @@ async def make_async_call_stream_helper( completion_stream = provider_config.get_model_response_iterator( streaming_response=response.aiter_lines(), sync_stream=False ) + if isinstance(completion_stream, BaseModelResponseIterator): + completion_stream.http_response = response # LOGGING logging_obj.post_call( input=messages, diff --git a/litellm/llms/fastcrw/__init__.py b/litellm/llms/fastcrw/__init__.py new file mode 100644 index 000000000000..d65ed8d3fa19 --- /dev/null +++ b/litellm/llms/fastcrw/__init__.py @@ -0,0 +1,7 @@ +""" +fastCRW API integration module. +""" + +from litellm.llms.fastcrw.search.transformation import FastCRWSearchConfig + +__all__ = ["FastCRWSearchConfig"] diff --git a/litellm/llms/fastcrw/search/__init__.py b/litellm/llms/fastcrw/search/__init__.py new file mode 100644 index 000000000000..4f8023b2db48 --- /dev/null +++ b/litellm/llms/fastcrw/search/__init__.py @@ -0,0 +1,7 @@ +""" +fastCRW Search API module. +""" + +from litellm.llms.fastcrw.search.transformation import FastCRWSearchConfig + +__all__ = ["FastCRWSearchConfig"] diff --git a/litellm/llms/fastcrw/search/transformation.py b/litellm/llms/fastcrw/search/transformation.py new file mode 100644 index 000000000000..ce702266e7b7 --- /dev/null +++ b/litellm/llms/fastcrw/search/transformation.py @@ -0,0 +1,182 @@ +""" +Calls fastCRW's /v1/search endpoint to search the web. + +fastCRW is a Firecrawl-compatible web data engine (single Rust binary; self-host +or cloud). The search response uses the Firecrawl-compatible envelope +{ "success": true, "data": [ { "title", "url", "description", "markdown"? } ] }. + +fastCRW API Reference: https://fastcrw.com/docs/rest-api +""" + +from typing import Optional, TypedDict, Union + +import httpx + +from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj +from litellm.llms.base_llm.search.transformation import ( + BaseSearchConfig, + SearchResponse, + SearchResult, +) +from litellm.secret_managers.main import get_secret_str + + +class _FastCRWSearchRequestRequired(TypedDict): + """Required fields for fastCRW Search API request.""" + + query: str # Required - search query + + +class FastCRWSearchRequest(_FastCRWSearchRequestRequired, total=False): + """ + fastCRW Search API request format. + Based on: https://fastcrw.com/docs/rest-api + """ + + limit: int # Optional - maximum number of results to return + sources: list[ + str + ] # Optional - sources to search ('web', 'images'), default ['web'] + scrapeOptions: dict # Optional - options for scraping search results + + +class FastCRWSearchConfig(BaseSearchConfig): + FASTCRW_API_BASE = "https://fastcrw.com/api/v1" + + @staticmethod + def ui_friendly_name() -> str: + return "fastCRW" + + def validate_environment( + self, + headers: dict, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + **kwargs, + ) -> dict: + """ + Validate environment and return headers. + """ + api_key = api_key or get_secret_str("CRW_API_KEY") + if not api_key: + raise ValueError( + "CRW_API_KEY is not set. Set `CRW_API_KEY` environment variable." + ) + headers["Authorization"] = f"Bearer {api_key}" + headers["Content-Type"] = "application/json" + return headers + + def get_complete_url( + self, + api_base: Optional[str], + optional_params: dict, + data: Optional[Union[dict, list[dict]]] = None, + **kwargs, + ) -> str: + """ + Get complete URL for Search endpoint. + """ + api_base = api_base or get_secret_str("CRW_API_BASE") or self.FASTCRW_API_BASE + + # Append "/search" to the api base if it's not already there + if not api_base.endswith("/search"): + api_base = f"{api_base}/search" + + return api_base + + def transform_search_request( + self, + query: Union[str, list[str]], + optional_params: dict, + **kwargs, + ) -> dict: + """ + Transform Search request to fastCRW API format. + + Transforms Perplexity unified spec parameters: + - query -> query (same) + - max_results -> limit + + All other fastCRW-specific parameters are passed through as-is. + + Args: + query: Search query (string or list of strings). fastCRW only supports single string queries. + optional_params: Optional parameters for the request + + Returns: + Dict with typed request data following FastCRWSearchRequest spec + """ + if isinstance(query, list): + # fastCRW only supports single string queries, join with spaces + query = " ".join(query) + + request_data: FastCRWSearchRequest = { + "query": query, + } + + # Transform Perplexity unified spec parameters to fastCRW format + if "max_results" in optional_params: + request_data["limit"] = optional_params["max_results"] + + # Convert to dict before dynamic key assignments + result_data = dict(request_data) + + # pass through all other parameters as-is + for param, value in optional_params.items(): + if ( + param not in self.get_supported_perplexity_optional_params() + and param not in result_data + ): + result_data[param] = value + + # By default, request markdown content if not explicitly specified + # fastCRW doesn't return content unless explicitly requested via scrapeOptions + if "scrapeOptions" not in result_data: + result_data["scrapeOptions"] = { + "formats": ["markdown"], + "onlyMainContent": True, + } + + return result_data + + def transform_search_response( + self, + raw_response: httpx.Response, + logging_obj: LiteLLMLoggingObj, + **kwargs, + ) -> SearchResponse: + """ + Transform fastCRW API response to LiteLLM unified SearchResponse format. + + fastCRW (Firecrawl-compatible) returns: + {"success": true, "data": [{"url": "...", "title": "...", "description": "...", "markdown"?: "..."}, ...]} + + Args: + raw_response: Raw httpx response from fastCRW API + logging_obj: Logging object for tracking + + Returns: + SearchResponse with standardized format + """ + response_json = raw_response.json() + + results = [] + + data = response_json.get("data", []) + + if isinstance(data, list): + for result in data: + snippet = result.get("markdown") or result.get("description", "") + search_result = SearchResult( + title=result.get("title", ""), + url=result.get("url", ""), + snippet=snippet, + date=None, + last_updated=None, + ) + results.append(search_result) + + return SearchResponse( + results=results, + object="search", + ) diff --git a/litellm/llms/modelscope/chat/transformation.py b/litellm/llms/modelscope/chat/transformation.py new file mode 100644 index 000000000000..162ef1a236cc --- /dev/null +++ b/litellm/llms/modelscope/chat/transformation.py @@ -0,0 +1,93 @@ +""" +Translates from OpenAI's `/v1/chat/completions` to ModelScope's `/v1/chat/completions` +""" + +from typing import Any, Coroutine, Literal, Optional, Tuple, Union, cast, overload + +from typing_extensions import override + +from litellm.secret_managers.main import get_secret_str +from litellm.types.llms.openai import AllMessageValues + +from ...openai.chat.gpt_transformation import OpenAIGPTConfig + + +def _has_non_text_content(message: AllMessageValues) -> bool: + """Check if a message has non-text content items (e.g. image_url).""" + content = message.get("content") + if not isinstance(content, list): + return False + return any(item.get("type") != "text" for item in content) + + +class ModelScopeChatConfig(OpenAIGPTConfig): + DEFAULT_BASE_URL: str = "https://api-inference.modelscope.cn/v1" + + @overload + def _transform_messages( + self, messages: list[AllMessageValues], model: str, is_async: Literal[True] + ) -> Coroutine[Any, Any, list[AllMessageValues]]: ... + + @overload + def _transform_messages( + self, + messages: list[AllMessageValues], + model: str, + is_async: Literal[False] = False, + ) -> list[AllMessageValues]: ... + + def _transform_messages( + self, messages: list[AllMessageValues], model: str, is_async: bool = False + ) -> Union[list[AllMessageValues], Coroutine[Any, Any, list[AllMessageValues]]]: + """ + Flatten text-only content lists to strings for ModelScope. + + Messages with non-text content (e.g. image_url for vision models) + are kept as lists so the parent class can normalize them properly. + """ + messages = [cast(AllMessageValues, {**m}) for m in messages] + for message in messages: + if _has_non_text_content(message): + continue + content = message.get("content") + if isinstance(content, list): + message["content"] = "".join(item.get("text") or "" for item in content) + + if is_async: + return super()._transform_messages( + messages=messages, model=model, is_async=True + ) + else: + return super()._transform_messages( + messages=messages, model=model, is_async=False + ) + + def _get_openai_compatible_provider_info( + self, api_base: Optional[str], api_key: Optional[str] + ) -> Tuple[Optional[str], Optional[str]]: + api_base = ( + api_base or get_secret_str("MODELSCOPE_API_BASE") or self.DEFAULT_BASE_URL + ) # type: ignore + dynamic_api_key = api_key or get_secret_str("MODELSCOPE_API_KEY") + return api_base, dynamic_api_key + + @override + def get_complete_url( + self, + api_base: Optional[str], + api_key: Optional[str], + model: str, + optional_params: dict, + litellm_params: dict, + stream: Optional[bool] = None, + ) -> str: + """ + If api_base is not provided, use the default ModelScope /chat/completions endpoint. + """ + if not api_base: + api_base = self.DEFAULT_BASE_URL + + if not api_base.endswith("/chat/completions"): + api_base = f"{api_base}/chat/completions" + + return api_base diff --git a/litellm/llms/modelscope/image_generation/__init__.py b/litellm/llms/modelscope/image_generation/__init__.py new file mode 100644 index 000000000000..8b28ea962ce9 --- /dev/null +++ b/litellm/llms/modelscope/image_generation/__init__.py @@ -0,0 +1,31 @@ +""" +ModelScope Image Generation Module + +Factory function for getting the appropriate config class. +""" + +from litellm.llms.base_llm.image_generation.transformation import ( + BaseImageGenerationConfig, +) + +from .transformation import ModelScopeImageGenerationConfig + +__all__ = [ + "ModelScopeImageGenerationConfig", + "get_modelscope_image_generation_config", +] + + +def get_modelscope_image_generation_config( + model: str, +) -> BaseImageGenerationConfig: + """ + Get the ModelScope config for image generation. + + Args: + model: The model name (e.g., "modelscope/Qwen/Qwen-Image-Edit") + + Returns: + BaseImageGenerationConfig instance for ModelScope + """ + return ModelScopeImageGenerationConfig() diff --git a/litellm/llms/modelscope/image_generation/transformation.py b/litellm/llms/modelscope/image_generation/transformation.py new file mode 100644 index 000000000000..0d85f7796fb9 --- /dev/null +++ b/litellm/llms/modelscope/image_generation/transformation.py @@ -0,0 +1,248 @@ +""" +ModelScope Image Generation Config + +Handles transformation between OpenAI-compatible format and ModelScope API format. + +API Reference: https://modelscope.cn/docs/model-service/API-Inference/intro +""" + +from typing import TYPE_CHECKING, Optional, Union + +import httpx +from typing_extensions import override + +from litellm.llms.base_llm.chat.transformation import BaseLLMException +from litellm.llms.base_llm.image_generation.transformation import ( + BaseImageGenerationConfig, +) +from litellm.secret_managers.main import get_secret_str +from litellm.types.llms.openai import ( + AllMessageValues, + OpenAIImageGenerationOptionalParams, +) +from litellm.types.utils import ImageObject, ImageResponse + +if TYPE_CHECKING: + from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj + + LiteLLMLoggingObj = _LiteLLMLoggingObj +else: + LiteLLMLoggingObj = object + + +class ModelScopeImageGenerationConfig(BaseImageGenerationConfig): + """ + Configuration for ModelScope image generation. + + Supports text-to-image models like: + - Qwen/Qwen-Image-Edit + - And other ModelScope-hosted image generation models + """ + + DEFAULT_BASE_URL: str = "https://api-inference.modelscope.cn/v1" + + def get_supported_openai_params( + self, model: str + ) -> list[OpenAIImageGenerationOptionalParams]: + """ + Return list of OpenAI params supported by ModelScope. + + ModelScope supports standard OpenAI image generation parameters. + """ + return [ + "n", # Number of images to generate + "size", # Size of the generated images + "response_format", # url or b64_json + "user", # User identifier + ] + + def map_openai_params( + self, + non_default_params: dict, + optional_params: dict, + model: str, + drop_params: bool, + ) -> dict: + """ + Map OpenAI parameters to ModelScope parameters. + + ModelScope uses the same parameter names as OpenAI. + """ + supported_params = self.get_supported_openai_params(model) + if drop_params: + non_default_params = { + k: v for k, v in non_default_params.items() if k in supported_params + } + optional_params.update(non_default_params) + return optional_params + + @override + def get_complete_url( + self, + api_base: Optional[str], + api_key: Optional[str], + model: str, + optional_params: dict, + litellm_params: dict, + stream: Optional[bool] = None, + ) -> str: + """ + Get the complete URL for the ModelScope image generation API request. + """ + base_url: str = ( + api_base or get_secret_str("MODELSCOPE_API_BASE") or self.DEFAULT_BASE_URL + ) + base_url = base_url.rstrip("/") + + # Return the images endpoint + return f"{base_url}/images/generations" + + @override + def validate_environment( + self, + headers: dict, + model: str, + messages: list[AllMessageValues], + optional_params: dict, + litellm_params: dict, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + ) -> dict: + """ + Validate environment and set up headers for ModelScope. + """ + final_api_key: Optional[str] = api_key or get_secret_str("MODELSCOPE_API_KEY") + + if not final_api_key: + raise ValueError( + "MODELSCOPE_API_KEY is not set. " + "Please set it via environment variable or pass api_key parameter." + ) + + default_headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {final_api_key}", + } + + headers = {**headers, **default_headers} + return headers + + def transform_image_generation_request( + self, + model: str, + prompt: str, + optional_params: dict, + litellm_params: dict, + headers: dict, + ) -> dict: + """ + Transform OpenAI-style request to ModelScope request format. + + ModelScope uses the same format as OpenAI for image generation. + """ + # Build the request body (same as OpenAI) + request_data: dict = { + "model": model, + "prompt": prompt, + } + + # Add optional params + for key, value in optional_params.items(): + if key.startswith("_"): + continue + request_data[key] = value + + return request_data + + @override + def transform_image_generation_response( + self, + model: str, + raw_response: httpx.Response, + model_response: ImageResponse, + logging_obj: LiteLLMLoggingObj, + request_data: dict, + optional_params: dict, + litellm_params: dict, + encoding: object, + api_key: Optional[str] = None, + json_mode: Optional[bool] = None, + ) -> ImageResponse: + """ + Transform ModelScope response to OpenAI-compatible ImageResponse. + + ModelScope returns the same format as OpenAI: + {"created": timestamp, "data": [{"url": "..."}]} + """ + try: + response_data = raw_response.json() + except Exception as e: + raise self.get_error_class( + error_message=f"Error parsing ModelScope response: {e}", + status_code=raw_response.status_code, + headers=raw_response.headers, + ) + + # Check for errors in response + if "error" in response_data: + error_msg = response_data["error"].get( + "message", str(response_data["error"]) + ) + raise self.get_error_class( + error_message=f"ModelScope error: {error_msg}", + status_code=raw_response.status_code, + headers=raw_response.headers, + ) + + # Extract images from response + data_list = response_data.get("data", []) + if not model_response.data: + model_response.data = [] + + for item in data_list: + image_obj = ImageObject( + url=item.get("url"), + b64_json=item.get("b64_json"), + revised_prompt=item.get("revised_prompt"), + ) + model_response.data.append(image_obj) + + return model_response + + def get_error_class( + self, + error_message: str, + status_code: int, + headers: Union[dict, httpx.Headers], + ) -> BaseLLMException: + """Return the appropriate error class for ModelScope.""" + from litellm.exceptions import ( + AuthenticationError, + BadRequestError, + InternalServerError, + ) + + if status_code == 400: + return BadRequestError( # type: ignore[return-value] + message=error_message, + model="", + llm_provider="modelscope", + ) + elif status_code == 401: + return AuthenticationError( # type: ignore[return-value] + message=error_message, + model="", + llm_provider="modelscope", + ) + elif status_code >= 500: + return InternalServerError( # type: ignore[return-value] + message=error_message, + model="", + llm_provider="modelscope", + ) + else: + return BadRequestError( # type: ignore[return-value] + message=error_message, + model="", + llm_provider="modelscope", + ) diff --git a/litellm/llms/openai_like/providers.json b/litellm/llms/openai_like/providers.json index 303e9ba8f9ea..0dda047d1ca5 100644 --- a/litellm/llms/openai_like/providers.json +++ b/litellm/llms/openai_like/providers.json @@ -143,6 +143,14 @@ "force_store_false": true } }, + "libertai": { + "base_url": "https://api.libertai.io/v1", + "api_key_env": "LIBERTAI_API_KEY", + "api_base_env": "LIBERTAI_API_BASE", + "param_mappings": { + "max_completion_tokens": "max_tokens" + } + }, "empiriolabs": { "base_url": "https://api.empiriolabs.ai/v1", "api_key_env": "EMPIRIOLABS_API_KEY", diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json index 76a7c0640afb..f563ad0c5b5d 100644 --- a/litellm/model_prices_and_context_window_backup.json +++ b/litellm/model_prices_and_context_window_backup.json @@ -18822,6 +18822,38 @@ "supports_response_schema": true, "supports_vision": true }, + "github_copilot/mai-code-1-flash": { + "cache_read_input_token_cost": 7.5e-08, + "input_cost_per_token": 7.5e-07, + "litellm_provider": "github_copilot", + "max_input_tokens": 128000, + "max_output_tokens": 64000, + "max_tokens": 64000, + "mode": "chat", + "output_cost_per_token": 4.5e-06, + "supported_endpoints": [ + "/v1/chat/completions" + ], + "supports_function_calling": true, + "supports_parallel_function_calling": true, + "supports_response_schema": true + }, + "github_copilot/mai-code-1-flash-internal": { + "cache_read_input_token_cost": 7.5e-08, + "input_cost_per_token": 7.5e-07, + "litellm_provider": "github_copilot", + "max_input_tokens": 128000, + "max_output_tokens": 64000, + "max_tokens": 64000, + "mode": "chat", + "output_cost_per_token": 4.5e-06, + "supported_endpoints": [ + "/v1/chat/completions" + ], + "supports_function_calling": true, + "supports_parallel_function_calling": true, + "supports_response_schema": true + }, "github_copilot/text-embedding-3-small": { "litellm_provider": "github_copilot", "max_input_tokens": 8191, @@ -40784,6 +40816,174 @@ "litellm_provider": "llamagate", "mode": "embedding" }, + "libertai/hermes-3-8b-tee": { + "max_tokens": 16000, + "max_input_tokens": 16000, + "max_output_tokens": 16000, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 6e-07, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": false, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/gemma-4-31b-it": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 4e-07, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/gemma-4-31b-it-thinking": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 4e-07, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "supports_reasoning": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/qwen3.6-27b": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 5e-07, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/qwen3.6-27b-thinking": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 5e-07, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "supports_reasoning": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/qwen3.6-35b-a3b": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 5e-07, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/qwen3.6-35b-a3b-thinking": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 5e-07, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "supports_reasoning": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/qwen3.5-122b-a10b": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1.75e-06, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/qwen3.5-122b-a10b-thinking": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1.75e-06, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "supports_reasoning": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/deepseek-v4-flash": { + "max_tokens": 200000, + "max_input_tokens": 200000, + "max_output_tokens": 200000, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1.75e-06, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": false, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/deepseek-v4-flash-thinking": { + "max_tokens": 200000, + "max_input_tokens": 200000, + "max_output_tokens": 200000, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1.75e-06, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": false, + "supports_reasoning": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/bge-m3": { + "max_tokens": 8192, + "max_input_tokens": 8192, + "input_cost_per_token": 1e-08, + "output_cost_per_token": 0.0, + "litellm_provider": "libertai", + "mode": "embedding", + "source": "https://docs.libertai.io/apis/text/" + }, "sarvam/sarvam-m": { "cache_creation_input_token_cost": 0, "cache_creation_input_token_cost_above_1hr": 0, diff --git a/litellm/provider_endpoints_support_backup.json b/litellm/provider_endpoints_support_backup.json index e0eeb014c512..db6183edaa07 100644 --- a/litellm/provider_endpoints_support_backup.json +++ b/litellm/provider_endpoints_support_backup.json @@ -1288,6 +1288,23 @@ "interactions": true } }, + "libertai": { + "display_name": "LibertAI (`libertai`)", + "url": "https://docs.litellm.ai/docs/providers/libertai", + "endpoints": { + "chat_completions": true, + "messages": true, + "responses": false, + "embeddings": false, + "image_generations": false, + "audio_transcriptions": false, + "audio_speech": false, + "moderations": false, + "batches": false, + "rerank": false, + "a2a": false + } + }, "litellm_proxy": { "display_name": "LiteLLM Proxy (`litellm_proxy`)", "url": "https://docs.litellm.ai/docs/providers/litellm_proxy", diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.py index 90ad0f288084..8f330ada7d37 100644 --- a/litellm/proxy/common_request_processing.py +++ b/litellm/proxy/common_request_processing.py @@ -17,10 +17,12 @@ Union, ) +import anyio import httpx import orjson from fastapi import HTTPException, Request, status from fastapi.responses import JSONResponse, Response, StreamingResponse +from starlette.types import Receive, Scope, Send import litellm from litellm._logging import _redact_string, verbose_proxy_logger @@ -240,6 +242,64 @@ def _extract_error_from_sse_chunk(event_line: Union[str, bytes]) -> dict: return default_error +async def _aclose_upstream_response(response: Any) -> None: + """Release the upstream HTTP connection when a stream ends for any + reason, including client disconnect. Mirrors the finally block of + async_data_generator in proxy_server.py.""" + with anyio.CancelScope(shield=True): + if hasattr(response, "aclose"): + try: + await response.aclose() + except BaseException as e: + verbose_proxy_logger.debug( + "error closing upstream response stream: %s", e + ) + + +class _UpstreamClosingStreamingResponse(StreamingResponse): + """StreamingResponse that always closes its body iterator and the wrapped + upstream generator. + + When the client disconnects mid-stream, Starlette abandons the body + iterator without calling aclose(), leaving the upstream LLM connection + open until garbage collection; the backend (e.g. vLLM) keeps generating + into a dead pipe. The upstream generator is closed directly (not via the + body iterator) because aclose() on a never-started generator skips its + body, so a cascade through it would be a no-op if the client disconnects + before the first chunk is sent. + """ + + def __init__( + self, + content: AsyncGenerator[str, None], + *, + media_type: Optional[str] = None, + headers: Optional[dict] = None, + status_code: int = status.HTTP_200_OK, + upstream_generator: Optional[AsyncGenerator[str, None]] = None, + ) -> None: + super().__init__( + content, status_code=status_code, headers=headers, media_type=media_type + ) + self._upstream_generator = upstream_generator + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + try: + await super().__call__(scope, receive, send) + finally: + with anyio.CancelScope(shield=True): + for target in (self.body_iterator, self._upstream_generator): + aclose = getattr(target, "aclose", None) + if aclose is None: + continue + try: + await aclose() + except BaseException as e: + verbose_proxy_logger.debug( + "error closing streaming generator: %s", e + ) + + async def create_response( # noqa: PLR0915 generator: AsyncGenerator[str, None], media_type: str, @@ -366,11 +426,12 @@ async def combined_generator() -> AsyncGenerator[str, None]: with tracer.trace(DD_TRACER_STREAMING_CHUNK_YIELD_RESOURCE): yield chunk - return StreamingResponse( + return _UpstreamClosingStreamingResponse( combined_generator(), media_type=media_type, headers=streaming_headers, status_code=final_status_code, + upstream_generator=generator, ) @@ -1702,6 +1763,23 @@ async def _wrap_responses_stream_for_container_ownership( response=completed_obj, user_api_key_dict=user_api_key_dict, ) + else: + # Silent skip caused #30210: the proxy's Router wrapper + # of the responses streaming iterator wasn't propagating + # ``completed_response``, so this hook recorded nothing + # and follow-up /v1/containers//files calls 403'd + # for non-admin keys with no proxy-side hint. Log a + # warning so future regressions of the same shape + # surface in operator logs. + verbose_proxy_logger.warning( + "Container ownership recording skipped on streaming " + "/v1/responses: no completed_response on stream " + "iterator %s. If this stream created any tool " + "container (e.g. code_interpreter), follow-up " + "/v1/containers//files calls will 403 for " + "non-admin keys.", + type(original_stream_response).__name__, + ) except Exception as e: verbose_proxy_logger.exception( "Container ownership recording failed after streaming responses call: %s", @@ -2424,6 +2502,8 @@ async def async_streaming_data_generator( code=getattr(e, "status_code", 500), ) yield serialize_error(proxy_exception) + finally: + await _aclose_upstream_response(response) @staticmethod def async_sse_data_generator( diff --git a/litellm/proxy/management_endpoints/customer_endpoints.py b/litellm/proxy/management_endpoints/customer_endpoints.py index f1a34bb0ed49..50a1bc23a6d9 100644 --- a/litellm/proxy/management_endpoints/customer_endpoints.py +++ b/litellm/proxy/management_endpoints/customer_endpoints.py @@ -885,6 +885,19 @@ async def get_customer_daily_activity( """ Get daily activity for specific organizations or all accessible organizations. """ + if ( + user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN + and user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY + ): + raise HTTPException( + status_code=401, + detail={ + "error": "Admin-only endpoint. Your user role={}".format( + user_api_key_dict.user_role + ) + }, + ) + from litellm.proxy.proxy_server import prisma_client if prisma_client is None: diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.py index 1a0a57c71fd1..43a36fcb2f1b 100644 --- a/litellm/proxy/management_endpoints/team_endpoints.py +++ b/litellm/proxy/management_endpoints/team_endpoints.py @@ -4244,6 +4244,14 @@ async def _enforce_list_team_v2_access( status_code=403, detail={"error": "You can only view teams within your organizations."}, ) + # When the caller is an org admin querying their own teams (or no + # specific user), null out user_id so that + # _build_team_list_where_conditions scopes only by organization_id + # — org admins should see all teams in their orgs, not just teams + # they are a direct member of. Keep user_id when the org admin + # explicitly queries a *different* user's teams. + if user_id is None or user_id == user_api_key_dict.user_id: + user_id = None verbose_proxy_logger.debug( "list_team_v2: org admin access for user=%s, org_ids=%s, user_id_filter=%s", user_api_key_dict.user_id, diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.py index d3d306422161..5b5ff122c500 100644 --- a/litellm/responses/litellm_completion_transformation/transformation.py +++ b/litellm/responses/litellm_completion_transformation/transformation.py @@ -2,6 +2,7 @@ Handles transforming from Responses API -> LiteLLM completion (Chat Completion API) """ +import re from collections.abc import Sequence from typing import Any, Dict, List, Literal, Optional, Set, Tuple, Union, cast @@ -1554,6 +1555,20 @@ def _map_chat_completion_finish_reason_to_responses_status( # Default to completed for unknown finish reasons return "completed" + @staticmethod + def _tool_call_id_from_responses_item( + item_id: Optional[str], call_id: Optional[str] + ) -> str: + """Bedrock Mantle returns a non-unique, index-based ``call_id`` (``call_0``, + ``call_1``, ... that resets every response) alongside a unique ``id`` + (``fc_...``). ``call_id`` is the canonical Responses API correlation key, so + prefer it; fall back to the unique ``id`` only when ``call_id`` is absent or + in that degenerate index form, otherwise multi-turn tool calls collide and an + agent cannot correlate its tool results.""" + if call_id and re.fullmatch(r"call_\d+", call_id) is None: + return call_id + return item_id or call_id or "" + @staticmethod def convert_response_function_tool_call_to_chat_completion_tool_call( tool_call_item: Any, @@ -1601,7 +1616,10 @@ def convert_response_function_tool_call_to_chat_completion_tool_call( function_dict["provider_specific_fields"] = provider_specific_fields tool_call_dict: Dict[str, Any] = { - "id": tool_call_item.call_id, + "id": LiteLLMCompletionResponsesConfig._tool_call_id_from_responses_item( + getattr(tool_call_item, "id", None), + getattr(tool_call_item, "call_id", None), + ), "function": function_dict, "type": "function", "index": 0, diff --git a/litellm/router.py b/litellm/router.py index 805848583113..148c8cf5771a 100644 --- a/litellm/router.py +++ b/litellm/router.py @@ -2521,10 +2521,22 @@ async def _aresponses_streaming_iterator( from litellm.exceptions import MidStreamFallbackError from litellm.responses.streaming_iterator import ( BaseResponsesAPIStreamingIterator, + _get_openai_response_types, ) source_iterator = response + # Pre-resolve the set of terminal stream event types so the + # per-chunk type check inside FallbackResponsesStreamWrapper + # stays cheap; mirrors the source-iterator filter at + # responses/streaming_iterator.py:243-247. + _openai_types = _get_openai_response_types() + _RESPONSES_TERMINAL_EVENT_TYPES = ( + _openai_types.ResponsesAPIStreamEvents.RESPONSE_COMPLETED, + _openai_types.ResponsesAPIStreamEvents.RESPONSE_INCOMPLETE, + _openai_types.ResponsesAPIStreamEvents.RESPONSE_FAILED, + ) + class FallbackResponsesStreamWrapper(BaseResponsesAPIStreamingIterator): """ Subclasses BaseResponsesAPIStreamingIterator only for isinstance @@ -2550,9 +2562,16 @@ def __init__(self, async_generator: AsyncGenerator): # is missing many of these attributes — use getattr fallbacks # so wrapper construction never raises AttributeError. The # bridge stores the logging object as `litellm_logging_obj`. - self.response = getattr(source_iterator, "response", None) - self.model = getattr(source_iterator, "model", None) - self.logging_obj = getattr( + # base class declares non-Optional types for these + # fields but the bridge path (LiteLLMCompletionStreamingIterator) + # can legitimately omit them at runtime — keep the None + # fallback. Same lines passed mypy on the pre-fix file + # because the surrounding function body wasn't fully + # type-narrowed; the new typed terminal-event tuple above + # is what made these surface. + self.response = getattr(source_iterator, "response", None) # type: ignore[assignment] + self.model = getattr(source_iterator, "model", None) # type: ignore[assignment] + self.logging_obj = getattr( # type: ignore[assignment] source_iterator, "logging_obj", getattr(source_iterator, "litellm_logging_obj", None), @@ -2587,7 +2606,23 @@ def __aiter__(self): return self async def __anext__(self): - return await self._async_generator.__anext__() + chunk = await self._async_generator.__anext__() + # Sniff the terminal stream event off each forwarded chunk + # so ``self.completed_response`` is populated regardless of + # which inner iterator produced it (source_iterator, + # fallback_iterator, or any future wrapper). Without this + # the proxy's container-ownership hook (which reads + # ``getattr(stream_response, "completed_response", None)`` + # via _extract_completed_responses_response) silently + # records nothing on streaming /v1/responses calls — every + # follow-up /v1/containers//files call then 403s for + # the very key that created the container (#30210). + if ( + self.completed_response is None + and getattr(chunk, "type", None) in _RESPONSES_TERMINAL_EVENT_TYPES + ): + self.completed_response = chunk + return chunk async def aclose(self): # async generators always expose aclose — no defensive check needed. diff --git a/litellm/types/router.py b/litellm/types/router.py index 5047cee424bb..1611f1e5538c 100644 --- a/litellm/types/router.py +++ b/litellm/types/router.py @@ -166,6 +166,13 @@ class CredentialLiteLLMParams(BaseModel): api_key: Optional[str] = None api_base: Optional[str] = None api_version: Optional[str] = None + ## AZURE OAUTH ## + # Without this field, ``get_deployment_credentials_with_provider`` + # round-trips ``litellm_params`` through a strict Pydantic dump and + # silently drops the OAuth token before the files/batch/passthrough + # callers see it, breaking Azure deployments configured with + # ``azure_ad_token`` instead of a static ``api_key`` (#30235). + azure_ad_token: Optional[str] = None ## VERTEX AI ## vertex_project: Optional[str] = None vertex_location: Optional[str] = None diff --git a/litellm/types/utils.py b/litellm/types/utils.py index d3dc7eadb94b..a5032942011b 100644 --- a/litellm/types/utils.py +++ b/litellm/types/utils.py @@ -3338,6 +3338,7 @@ class LlmProviders(str, Enum): CODESTRAL = "codestral" TEXT_COMPLETION_CODESTRAL = "text-completion-codestral" DASHSCOPE = "dashscope" + MODELSCOPE = "modelscope" MOONSHOT = "moonshot" PUBLICAI = "publicai" V0 = "v0" @@ -3420,6 +3421,7 @@ class LlmProviders(str, Enum): PARASAIL = "parasail" XIAOMI_MIMO = "xiaomi_mimo" TENSORMESH = "tensormesh" + LIBERTAI = "libertai" LITELLM_AGENT = "litellm_agent" CURSOR = "cursor" BEDROCK_MANTLE = "bedrock_mantle" @@ -3455,6 +3457,7 @@ class SearchProviders(str, Enum): GOOGLE_PSE = "google_pse" DATAFORSEO = "dataforseo" FIRECRAWL = "firecrawl" + FASTCRW = "fastcrw" SEARXNG = "searxng" LINKUP = "linkup" DUCKDUCKGO = "duckduckgo" diff --git a/litellm/utils.py b/litellm/utils.py index 4c67abdf9378..3748cbd8b954 100644 --- a/litellm/utils.py +++ b/litellm/utils.py @@ -3015,6 +3015,21 @@ def register_model(model_cost: Union[str, dict]): # noqa: PLR0915 # custom pricing on subsequent cost lookups. if existing_model.get("litellm_provider") is None: existing_model.pop("litellm_provider", None) + # Same pattern for cost fields (#30198): ``_get_model_info_helper`` + # synthesizes ``input_cost_per_token`` / ``output_cost_per_token`` + # = 0 when they are absent from the raw entry. Writing those zeros + # back flips a sparse entry from "no cost keys" (priced via name) + # to "cost keys = 0" (free), which makes + # ``_is_cost_explicitly_configured`` return True and silently + # disables budget enforcement on the next re-registration. + _raw_entry = litellm.model_cost.get(model_cost_key) + if _raw_entry is None: + _raw_entry = litellm.model_cost.get(key) + if _raw_entry is None: + _raw_entry = {} + for _cost_field in ("input_cost_per_token", "output_cost_per_token"): + if _cost_field not in _raw_entry and _cost_field not in value: + existing_model.pop(_cost_field, None) ## override / add new keys to the existing model cost dictionary updated_dictionary = _update_dictionary(existing_model, value) litellm.model_cost.setdefault(model_cost_key, {}).update(updated_dictionary) @@ -6833,6 +6848,11 @@ def validate_environment( # noqa: PLR0915 keys_in_environment = True else: missing_keys.append("DASHSCOPE_API_KEY") + elif custom_llm_provider == "modelscope": + if "MODELSCOPE_API_KEY" in os.environ: + keys_in_environment = True + else: + missing_keys.append("MODELSCOPE_API_KEY") elif custom_llm_provider == "moonshot": if "MOONSHOT_API_KEY" in os.environ: keys_in_environment = True @@ -8504,6 +8524,7 @@ def _build_provider_config_map() -> dict[LlmProviders, tuple[Callable, bool]]: LlmProviders.NEBIUS: (lambda: litellm.NebiusConfig(), False), LlmProviders.WANDB: (lambda: litellm.WandbConfig(), False), LlmProviders.DASHSCOPE: (lambda: litellm.DashScopeChatConfig(), False), + LlmProviders.MODELSCOPE: (lambda: litellm.ModelScopeChatConfig(), False), LlmProviders.MOONSHOT: (lambda: litellm.MoonshotChatConfig(), False), LlmProviders.DOCKER_MODEL_RUNNER: ( lambda: litellm.DockerModelRunnerChatConfig(), @@ -9442,6 +9463,12 @@ def get_provider_image_generation_config( ) return get_dashscope_image_generation_config(model) + elif LlmProviders.MODELSCOPE == provider: + from litellm.llms.modelscope.image_generation import ( + get_modelscope_image_generation_config, + ) + + return get_modelscope_image_generation_config(model) return None @staticmethod @@ -9647,6 +9674,7 @@ def get_provider_search_config( from litellm.llms.dataforseo.search.transformation import DataForSEOSearchConfig from litellm.llms.duckduckgo.search.transformation import DuckDuckGoSearchConfig from litellm.llms.exa_ai.search.transformation import ExaAISearchConfig + from litellm.llms.fastcrw.search.transformation import FastCRWSearchConfig from litellm.llms.firecrawl.search.transformation import FirecrawlSearchConfig from litellm.llms.google_pse.search.transformation import GooglePSESearchConfig from litellm.llms.linkup.search.transformation import LinkupSearchConfig @@ -9669,6 +9697,7 @@ def get_provider_search_config( SearchProviders.GOOGLE_PSE: GooglePSESearchConfig, SearchProviders.DATAFORSEO: DataForSEOSearchConfig, SearchProviders.FIRECRAWL: FirecrawlSearchConfig, + SearchProviders.FASTCRW: FastCRWSearchConfig, SearchProviders.SEARXNG: SearXNGSearchConfig, SearchProviders.LINKUP: LinkupSearchConfig, SearchProviders.DUCKDUCKGO: DuckDuckGoSearchConfig, diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json index b181df941310..f0c15654cfe3 100644 --- a/model_prices_and_context_window.json +++ b/model_prices_and_context_window.json @@ -18822,6 +18822,38 @@ "supports_response_schema": true, "supports_vision": true }, + "github_copilot/mai-code-1-flash": { + "cache_read_input_token_cost": 7.5e-08, + "input_cost_per_token": 7.5e-07, + "litellm_provider": "github_copilot", + "max_input_tokens": 128000, + "max_output_tokens": 64000, + "max_tokens": 64000, + "mode": "chat", + "output_cost_per_token": 4.5e-06, + "supported_endpoints": [ + "/v1/chat/completions" + ], + "supports_function_calling": true, + "supports_parallel_function_calling": true, + "supports_response_schema": true + }, + "github_copilot/mai-code-1-flash-internal": { + "cache_read_input_token_cost": 7.5e-08, + "input_cost_per_token": 7.5e-07, + "litellm_provider": "github_copilot", + "max_input_tokens": 128000, + "max_output_tokens": 64000, + "max_tokens": 64000, + "mode": "chat", + "output_cost_per_token": 4.5e-06, + "supported_endpoints": [ + "/v1/chat/completions" + ], + "supports_function_calling": true, + "supports_parallel_function_calling": true, + "supports_response_schema": true + }, "github_copilot/text-embedding-3-small": { "litellm_provider": "github_copilot", "max_input_tokens": 8191, @@ -40986,6 +41018,174 @@ "litellm_provider": "llamagate", "mode": "embedding" }, + "libertai/hermes-3-8b-tee": { + "max_tokens": 16000, + "max_input_tokens": 16000, + "max_output_tokens": 16000, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 6e-07, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": false, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/gemma-4-31b-it": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 4e-07, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/gemma-4-31b-it-thinking": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 4e-07, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "supports_reasoning": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/qwen3.6-27b": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 5e-07, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/qwen3.6-27b-thinking": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 5e-07, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "supports_reasoning": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/qwen3.6-35b-a3b": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 5e-07, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/qwen3.6-35b-a3b-thinking": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 1.5e-07, + "output_cost_per_token": 5e-07, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "supports_reasoning": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/qwen3.5-122b-a10b": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1.75e-06, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/qwen3.5-122b-a10b-thinking": { + "max_tokens": 262144, + "max_input_tokens": 262144, + "max_output_tokens": 262144, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1.75e-06, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": true, + "supports_reasoning": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/deepseek-v4-flash": { + "max_tokens": 200000, + "max_input_tokens": 200000, + "max_output_tokens": 200000, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1.75e-06, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": false, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/deepseek-v4-flash-thinking": { + "max_tokens": 200000, + "max_input_tokens": 200000, + "max_output_tokens": 200000, + "input_cost_per_token": 2.5e-07, + "output_cost_per_token": 1.75e-06, + "litellm_provider": "libertai", + "mode": "chat", + "supports_function_calling": true, + "supports_tool_choice": true, + "supports_system_messages": true, + "supports_vision": false, + "supports_reasoning": true, + "source": "https://docs.libertai.io/apis/text/" + }, + "libertai/bge-m3": { + "max_tokens": 8192, + "max_input_tokens": 8192, + "input_cost_per_token": 1e-08, + "output_cost_per_token": 0.0, + "litellm_provider": "libertai", + "mode": "embedding", + "source": "https://docs.libertai.io/apis/text/" + }, "sarvam/sarvam-m": { "cache_creation_input_token_cost": 0, "cache_creation_input_token_cost_above_1hr": 0, diff --git a/provider_endpoints_support.json b/provider_endpoints_support.json index 2ad2b3ec9826..b90e5d2698d4 100644 --- a/provider_endpoints_support.json +++ b/provider_endpoints_support.json @@ -972,6 +972,23 @@ "search": true } }, + "fastcrw": { + "display_name": "fastCRW (`fastcrw`)", + "url": "https://docs.litellm.ai/docs/search/fastcrw", + "endpoints": { + "chat_completions": false, + "messages": false, + "responses": false, + "embeddings": false, + "image_generations": false, + "audio_transcriptions": false, + "audio_speech": false, + "moderations": false, + "batches": false, + "rerank": false, + "search": true + } + }, "linkup": { "display_name": "Linkup (`linkup`)", "url": "https://docs.litellm.ai/docs/search/linkup", @@ -1359,6 +1376,23 @@ "interactions": true } }, + "libertai": { + "display_name": "LibertAI (`libertai`)", + "url": "https://docs.litellm.ai/docs/providers/libertai", + "endpoints": { + "chat_completions": true, + "messages": true, + "responses": false, + "embeddings": false, + "image_generations": false, + "audio_transcriptions": false, + "audio_speech": false, + "moderations": false, + "batches": false, + "rerank": false, + "a2a": false + } + }, "litellm_proxy": { "display_name": "LiteLLM Proxy (`litellm_proxy`)", "url": "https://docs.litellm.ai/docs/providers/litellm_proxy", @@ -1468,6 +1502,24 @@ "interactions": true } }, + "modelscope": { + "display_name": "ModelScope (`modelscope`)", + "url": "https://docs.litellm.ai/docs/providers/modelscope", + "endpoints": { + "chat_completions": true, + "messages": true, + "responses": true, + "embeddings": false, + "image_generations": true, + "audio_transcriptions": false, + "audio_speech": false, + "moderations": false, + "batches": false, + "rerank": false, + "a2a": false, + "interactions": false + } + }, "moonshot": { "display_name": "Moonshot (`moonshot`)", "url": "https://docs.litellm.ai/docs/providers/moonshot", diff --git a/tests/code_coverage_tests/enforce_llms_folder_style.py b/tests/code_coverage_tests/enforce_llms_folder_style.py index 43ab81b6c604..cbf5cd5266ed 100644 --- a/tests/code_coverage_tests/enforce_llms_folder_style.py +++ b/tests/code_coverage_tests/enforce_llms_folder_style.py @@ -14,6 +14,7 @@ "exa_ai", "brave", "firecrawl", + "fastcrw", "searxng", "linkup", "duckduckgo", diff --git a/tests/test_anthropic_compaction_usage.py b/tests/test_anthropic_compaction_usage.py new file mode 100644 index 000000000000..1758a94fffc6 --- /dev/null +++ b/tests/test_anthropic_compaction_usage.py @@ -0,0 +1,96 @@ +from litellm.llms.anthropic.chat.transformation import AnthropicConfig + + +def test_anthropic_compaction_usage_calculation(): + """ + Test that calculate_usage correctly sums tokens from the iterations array + as requested in Issue #27060. + """ + anthropic_config = AnthropicConfig() + + # Mock usage object with compaction iterations + usage_object = { + "input_tokens": 100, # Top-level (excludes compaction) + "output_tokens": 50, # Top-level (excludes compaction) + "iterations": [ + { + "iteration": 1, + "type": "compaction", + "input_tokens": 1000, + "output_tokens": 500, + }, + { + "iteration": 2, + "type": "message", + "input_tokens": 100, + "output_tokens": 50, + }, + ], + } + + usage = anthropic_config.calculate_usage( + usage_object=usage_object, reasoning_content=None + ) + + # Assertions + # Total prompt tokens should be 1000 + 100 = 1100 + assert usage.prompt_tokens == 1100 + # Total completion tokens should be 500 + 50 = 550 + assert usage.completion_tokens == 550 + # Total tokens should be 1650 + assert usage.total_tokens == 1650 + + # Assert details + assert usage.prompt_tokens_details.text_tokens == 1100 + + # Assert iterations passthrough + assert usage.iterations is not None + assert len(usage.iterations) == 2 + assert usage.iterations[0]["type"] == "compaction" + + +def test_anthropic_compaction_usage_with_iteration_cache(): + """ + Test that calculate_usage correctly sums caching tokens FROM iterations. + This covers the specific case mentioned by JasonPan. + """ + anthropic_config = AnthropicConfig() + + usage_object = { + "input_tokens": 100, + "output_tokens": 50, + "iterations": [ + { + "type": "compaction", + "input_tokens": 500, + "output_tokens": 200, + "cache_creation_input_tokens": 50, + "cache_read_input_tokens": 17000, + }, + { + "type": "message", + "input_tokens": 100, + "output_tokens": 50, + "cache_creation_input_tokens": 10, + "cache_read_input_tokens": 20, + }, + ], + } + + usage = anthropic_config.calculate_usage( + usage_object=usage_object, reasoning_content=None + ) + + # input_tokens sum = 500 + 100 = 600 + # cache_creation sum = 50 + 10 = 60 + # cache_read sum = 17000 + 20 = 17020 + # Total prompt tokens = 600 + 60 + 17020 = 17680 + assert usage.prompt_tokens == 17680 + assert usage.completion_tokens == 250 + assert usage.prompt_tokens_details.cache_creation_tokens == 60 + assert usage.prompt_tokens_details.cached_tokens == 17020 + + +if __name__ == "__main__": + test_anthropic_compaction_usage_calculation() + test_anthropic_compaction_usage_with_iteration_cache() diff --git a/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py b/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py index 06457dfebffa..6a1de0586dd7 100644 --- a/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py +++ b/tests/test_litellm/completion_extras/litellm_responses_transformation/test_completion_extras_litellm_responses_transformation_transformation.py @@ -2819,3 +2819,37 @@ def test_reasoning_items_streaming_emitted_on_response_completed(): ri["encrypted_content"] == encrypted ), "encrypted_content must be preserved in streaming" assert ri["summary"][0]["text"] == summary_text + + +def test_streaming_function_call_tool_id_for_degenerate_call_id(): + """In streaming, Bedrock Mantle's function_call event carries a unique ``id`` + (``fc_...``) and a non-unique, index-based ``call_id`` (``call_0``). For that + degenerate form the chat tool-call chunk must use the unique ``id`` so multi-turn + streaming agents don't collapse every tool call to the same id (which makes the + agent loop). A normal (unique) ``call_id`` must be preserved. Regression for the + bedrock-mantle gpt-5.5 streaming path.""" + from litellm.completion_extras.litellm_responses_transformation.transformation import ( + OpenAiResponsesToChatCompletionStreamIterator, + ) + + def stream_tool_id(item_id, call_id): + chunk = { + "type": "response.output_item.added", + "output_index": 0, + "item": { + "type": "function_call", + "id": item_id, + "call_id": call_id, + "name": "get_weather", + "arguments": "", + }, + } + out = OpenAiResponsesToChatCompletionStreamIterator.translate_responses_chunk_to_openai_stream( + chunk + ) + tool_calls = out.model_dump()["choices"][0]["delta"]["tool_calls"] + assert tool_calls, "expected a tool_call chunk in the streaming delta" + return tool_calls[0]["id"] + + assert stream_tool_id("fc_unique_abc123", "call_0") == "fc_unique_abc123" + assert stream_tool_id("fc_2", "call_tokyo") == "call_tokyo" diff --git a/tests/test_litellm/integrations/test_custom_guardrail.py b/tests/test_litellm/integrations/test_custom_guardrail.py index 57fb0fe6714f..29e9f4529fce 100644 --- a/tests/test_litellm/integrations/test_custom_guardrail.py +++ b/tests/test_litellm/integrations/test_custom_guardrail.py @@ -363,6 +363,54 @@ def test_should_run_guardrail_with_disable_global_guardrail(self): result is False ), "Admin config in metadata must be respected when other metadata key is empty" + def test_should_run_guardrail_key_disable_global_not_overruled_by_team_guardrail_list( + self, + ): + """Key disable_global_guardrails must take precedence over the guardrail + appearing in the team's explicit guardrails list.""" + from litellm.types.guardrails import GuardrailEventHooks + + custom_guardrail = CustomGuardrail( + guardrail_name="global_guardrail", + default_on=True, + event_hook=GuardrailEventHooks.pre_call, + ) + + # Key disabled globals; team added the same guardrail to its explicit list + # (simulates what _add_guardrails_from_key_or_team_metadata produces). + data_key_disabled_team_listed = { + "model": "gpt-3.5-turbo", + "messages": [{"role": "user", "content": "test"}], + "metadata": { + "user_api_key_metadata": {"disable_global_guardrails": True}, + "guardrails": ["global_guardrail"], + }, + } + assert ( + custom_guardrail.should_run_guardrail( + data=data_key_disabled_team_listed, + event_type=GuardrailEventHooks.pre_call, + ) + is False + ), "Key disable_global_guardrails must win over team's explicit guardrail list" + + # Complementary: key NOT disabled, team added guardrail → should run + data_key_enabled_team_listed = { + "model": "gpt-3.5-turbo", + "messages": [{"role": "user", "content": "test"}], + "metadata": { + "user_api_key_metadata": {}, + "guardrails": ["global_guardrail"], + }, + } + assert ( + custom_guardrail.should_run_guardrail( + data=data_key_enabled_team_listed, + event_type=GuardrailEventHooks.pre_call, + ) + is True + ), "Guardrail in team's explicit list should run when key has not disabled globals" + def test_should_run_guardrail_with_opted_out_global_guardrails(self): """Test that per-guardrail opt-out only works from admin metadata""" from litellm.types.guardrails import GuardrailEventHooks diff --git a/tests/test_litellm/litellm_core_utils/test_fallback_utils.py b/tests/test_litellm/litellm_core_utils/test_fallback_utils.py index 0c542ff6a1b4..90a61696e9d9 100644 --- a/tests/test_litellm/litellm_core_utils/test_fallback_utils.py +++ b/tests/test_litellm/litellm_core_utils/test_fallback_utils.py @@ -1,7 +1,13 @@ +"""Tests for litellm.litellm_core_utils.fallback_utils.""" + import pytest +import httpx import litellm -from litellm.litellm_core_utils.fallback_utils import async_completion_with_fallbacks +from litellm.litellm_core_utils.core_helpers import process_response_headers +from litellm.litellm_core_utils.fallback_utils import ( + async_completion_with_fallbacks, +) @pytest.mark.asyncio @@ -41,3 +47,123 @@ async def _fake_acompletion(*, model: str, **kwargs): "primary-model", "fallback-model", ] + + +@pytest.mark.asyncio +async def test_async_completion_with_fallbacks_sets_attempted_fallbacks_header(): + """ + When a fallback succeeds, the response must carry the + `x-litellm-attempted-fallbacks` header so the proxy and other callers can + detect that a fallback occurred. Without it, + `_override_openai_response_model` stamps the requested model back over the + fallback model used. See issue #28241. + """ + response = await async_completion_with_fallbacks( + model="openai/primary-llm", + messages=[{"role": "user", "content": "hi"}], + api_key="fake-key", + mock_response=Exception("forced failure"), + kwargs={ + "fallbacks": [ + { + "model": "openai/backup-llm", + "api_key": "fake-key", + "mock_response": "backup-resp", + } + ] + }, + ) + + hidden_params = getattr(response, "_hidden_params", None) + assert isinstance(hidden_params, dict) + headers = hidden_params.get("additional_headers") or {} + assert headers.get("x-litellm-attempted-fallbacks") == 1 + + +@pytest.mark.asyncio +async def test_async_completion_with_fallbacks_header_is_zero_when_primary_succeeds(): + """ + When the primary model succeeds on the first attempt, the header should be + `0` (no fallback was used). This mirrors the existing router-level + semantics in `async_function_with_fallbacks`. + """ + response = await async_completion_with_fallbacks( + model="openai/primary-llm", + messages=[{"role": "user", "content": "hi"}], + api_key="fake-key", + mock_response="primary-resp", + kwargs={ + "fallbacks": [ + { + "model": "openai/backup-llm", + "api_key": "fake-key", + "mock_response": "backup-resp", + } + ] + }, + ) + + hidden_params = getattr(response, "_hidden_params", None) + assert isinstance(hidden_params, dict) + headers = hidden_params.get("additional_headers") or {} + assert headers.get("x-litellm-attempted-fallbacks") == 0 + assert response.choices[0].message.content == "primary-resp" + + +def test_process_response_headers_preserves_x_litellm_headers_when_internal(): + """ + `process_response_headers` must not add the `llm_provider-` prefix to + LiteLLM's own internal headers (anything starting with `x-litellm-`) when + the caller has marked the input as LiteLLM-owned. These are markers set by + LiteLLM (e.g. fallback / retry headers); the proxy and other callers look + up the bare key. + """ + result = process_response_headers( + { + "x-litellm-attempted-fallbacks": 1, + "x-litellm-model-group": "gpt-4", + "x-stainless-arch": "arm64", + }, + preserve_litellm_internal_headers=True, + ) + assert result["x-litellm-attempted-fallbacks"] == 1 + assert result["x-litellm-model-group"] == "gpt-4" + assert result["llm_provider-x-stainless-arch"] == "arm64" + + +def test_process_response_headers_prefixes_x_litellm_from_raw_provider(): + """ + On raw upstream-provider headers (default `preserve_litellm_internal_headers=False`), + a header whose name starts with `x-litellm-` MUST still get the + `llm_provider-` prefix. Otherwise a malicious provider could return + `x-litellm-attempted-fallbacks` and spoof a LiteLLM-internal marker, + bypassing the proxy model-override guard. + """ + result = process_response_headers( + { + "x-litellm-attempted-fallbacks": 99, + "x-stainless-arch": "arm64", + } + ) + assert "x-litellm-attempted-fallbacks" not in result + assert result["llm_provider-x-litellm-attempted-fallbacks"] == 99 + assert result["llm_provider-x-stainless-arch"] == "arm64" + + +def test_process_response_headers_ignores_preserve_flag_for_httpx_headers(): + """ + Some providers store raw httpx.Headers directly in _hidden_params["additional_headers"] + without a prior normalization pass. If preserve_litellm_internal_headers=True were + honored for httpx.Headers inputs, a provider returning x-litellm-attempted-fallbacks + could spoof it as a bare LiteLLM-internal marker and make the proxy skip + stamping the correct response model. The flag must be ignored for httpx.Headers. + """ + raw = httpx.Headers( + { + "x-litellm-attempted-fallbacks": "1", + "content-type": "application/json", + } + ) + result = process_response_headers(raw, preserve_litellm_internal_headers=True) + assert "x-litellm-attempted-fallbacks" not in result + assert result["llm_provider-x-litellm-attempted-fallbacks"] == "1" diff --git a/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py b/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py index c57941945285..b5eb7af88b38 100644 --- a/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py +++ b/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py @@ -8,7 +8,8 @@ 0, os.path.abspath("../../..") ) # Adds the parent directory to the system path -from litellm import stream_chunk_builder +from litellm import ChatCompletionUsageBlock, stream_chunk_builder +from litellm.types.utils import GenericStreamingChunk from litellm.litellm_core_utils.streaming_chunk_builder_utils import ChunkProcessor from litellm.types.utils import ( ChatCompletionDeltaToolCall, @@ -324,6 +325,42 @@ def test_cache_read_input_tokens_retained(): assert usage.cache_read_input_tokens == 11775 assert usage.prompt_tokens_details.cached_tokens == 11775 +def test_cache_read_input_tokens_retained_genericstreamingchunk(): + chunk1 = GenericStreamingChunk( + text="Test1", + is_finished=False, + finish_reason="", + usage=None, + index=1, + ) + + chunk2 = GenericStreamingChunk( + text="Test2", + is_finished=True, + finish_reason="stop", + usage=ChatCompletionUsageBlock( + completion_tokens=5, + prompt_tokens=1234, + total_tokens=1239, + completion_tokens_details=None, + prompt_tokens_details=PromptTokensDetails( + audio_tokens=None, cached_tokens=543 + ).model_dump(), + ), + index=2, + ) + + # Use dictionaries directly instead of ModelResponseStream + chunks = [chunk1, chunk2] + processor = ChunkProcessor(chunks=chunks) + + usage = processor.calculate_usage( + chunks=chunks, + model="gpt-5.5", + completion_output="", + ) + + assert usage.prompt_tokens_details.cached_tokens == 543 def test_stream_chunk_builder_litellm_usage_chunks(): """ diff --git a/tests/test_litellm/llms/base_llm/test_base_model_iterator.py b/tests/test_litellm/llms/base_llm/test_base_model_iterator.py index b7f12a92cccd..f54e71c7c3cd 100644 --- a/tests/test_litellm/llms/base_llm/test_base_model_iterator.py +++ b/tests/test_litellm/llms/base_llm/test_base_model_iterator.py @@ -221,3 +221,38 @@ async def async_gen(): assert len(chunks) == 1 assert "response.created" in chunks[0]["text"] + + +@pytest.mark.asyncio +async def test_aclose_closes_attached_http_response(): + """Regression for BerriAI/litellm#30244: CustomStreamWrapper.aclose() can + only release the upstream provider connection if the iterator exposes + aclose() and it reaches the underlying HTTP response. Without this, a + client disconnect leaves backends like vLLM generating into a dead pipe.""" + from unittest.mock import AsyncMock, MagicMock + + async def async_gen(): + yield "data: {}" + + iterator = BaseModelResponseIterator( + streaming_response=async_gen(), sync_stream=False + ) + http_response = MagicMock() + http_response.aclose = AsyncMock() + iterator.http_response = http_response + + await iterator.aclose() + + http_response.aclose.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_aclose_is_noop_without_http_response(): + async def async_gen(): + yield "data: {}" + + iterator = BaseModelResponseIterator( + streaming_response=async_gen(), sync_stream=False + ) + + await iterator.aclose() diff --git a/tests/test_litellm/llms/fastcrw/search/test_transformation.py b/tests/test_litellm/llms/fastcrw/search/test_transformation.py new file mode 100644 index 000000000000..adf8fec087c9 --- /dev/null +++ b/tests/test_litellm/llms/fastcrw/search/test_transformation.py @@ -0,0 +1,182 @@ +import os +from unittest.mock import Mock, patch + +import pytest + +import litellm +from litellm.llms.fastcrw.search.transformation import FastCRWSearchConfig + + +def _config() -> FastCRWSearchConfig: + return FastCRWSearchConfig() + + +def test_fastcrw_search_request_body(): + mock_response = Mock() + mock_response.status_code = 200 + mock_response.json.return_value = { + "success": True, + "data": [ + { + "title": "Test Title", + "url": "https://example.com", + "description": "Test description", + "markdown": "Test content", + } + ], + } + + with ( + patch.dict(os.environ, {"CRW_API_KEY": "test-api-key"}), + patch( + "litellm.llms.custom_httpx.http_handler.HTTPHandler.post", + return_value=mock_response, + ) as mock_post, + ): + response = litellm.search( + query="test query", + search_provider="fastcrw", + max_results=10, + ) + + assert mock_post.called + call_kwargs = mock_post.call_args.kwargs + assert call_kwargs.get("url", "").endswith("/search") + + request_body = call_kwargs.get("json") + assert request_body is not None + assert request_body["query"] == "test query" + assert request_body["limit"] == 10 + + assert len(response.results) == 1 + result = response.results[0] + assert result.title == "Test Title" + assert result.url == "https://example.com" + assert result.snippet == "Test content" + + +def test_ui_friendly_name(): + assert _config().ui_friendly_name() == "fastCRW" + + +def test_validate_environment_with_explicit_key(): + headers = _config().validate_environment({}, api_key="explicit-key") + assert headers["Authorization"] == "Bearer explicit-key" + assert headers["Content-Type"] == "application/json" + + +def test_validate_environment_reads_env_key(): + with patch.dict(os.environ, {"CRW_API_KEY": "env-key"}, clear=False): + headers = _config().validate_environment({}) + assert headers["Authorization"] == "Bearer env-key" + + +def test_validate_environment_missing_key_raises(): + with patch.dict(os.environ, {}, clear=True): + with pytest.raises(ValueError, match="CRW_API_KEY"): + _config().validate_environment({}) + + +def test_get_complete_url_default_base(): + with patch.dict(os.environ, {}, clear=True): + assert _config().get_complete_url(None, {}) == "https://fastcrw.com/api/v1/search" + + +def test_get_complete_url_appends_search(): + assert ( + _config().get_complete_url("https://self-hosted.local/api/v1", {}) + == "https://self-hosted.local/api/v1/search" + ) + + +def test_get_complete_url_does_not_double_append(): + assert ( + _config().get_complete_url("https://self-hosted.local/api/v1/search", {}) + == "https://self-hosted.local/api/v1/search" + ) + + +def test_get_complete_url_reads_env_base(): + with patch.dict( + os.environ, {"CRW_API_BASE": "https://env-base.local/v1"}, clear=True + ): + assert _config().get_complete_url(None, {}) == "https://env-base.local/v1/search" + + +def test_transform_search_request_basic(): + data = _config().transform_search_request("hello", {"max_results": 5}) + assert data["query"] == "hello" + assert data["limit"] == 5 + assert data["scrapeOptions"]["formats"] == ["markdown"] + assert data["scrapeOptions"]["onlyMainContent"] is True + + +def test_transform_search_request_joins_list_query(): + assert _config().transform_search_request(["foo", "bar"], {})["query"] == "foo bar" + + +def test_transform_search_request_passes_through_extra_params(): + data = _config().transform_search_request("q", {"sources": ["web", "images"]}) + assert data["sources"] == ["web", "images"] + + +def test_transform_search_request_preserves_explicit_scrape_options(): + custom = {"formats": ["html"]} + data = _config().transform_search_request("q", {"scrapeOptions": custom}) + assert data["scrapeOptions"] == custom + + +def _resp(payload): + r = Mock() + r.json.return_value = payload + return r + + +def test_transform_search_response_prefers_markdown(): + resp = _config().transform_search_response( + _resp( + { + "success": True, + "data": [ + { + "title": "T", + "url": "https://e.com", + "description": "d", + "markdown": "md", + } + ], + } + ), + logging_obj=Mock(), + ) + assert len(resp.results) == 1 + assert resp.results[0].snippet == "md" + + +def test_transform_search_response_falls_back_to_description(): + resp = _config().transform_search_response( + _resp( + { + "success": True, + "data": [ + {"title": "T", "url": "https://e.com", "description": "only-desc"} + ], + } + ), + logging_obj=Mock(), + ) + assert resp.results[0].snippet == "only-desc" + + +def test_transform_search_response_empty_data(): + resp = _config().transform_search_response( + _resp({"success": True, "data": []}), logging_obj=Mock() + ) + assert resp.results == [] + + +def test_transform_search_response_non_list_data(): + resp = _config().transform_search_response( + _resp({"success": True, "data": {"unexpected": "shape"}}), logging_obj=Mock() + ) + assert resp.results == [] diff --git a/tests/test_litellm/llms/modelscope/chat/test_modelscope_chat_transformation.py b/tests/test_litellm/llms/modelscope/chat/test_modelscope_chat_transformation.py new file mode 100644 index 000000000000..2767deae1763 --- /dev/null +++ b/tests/test_litellm/llms/modelscope/chat/test_modelscope_chat_transformation.py @@ -0,0 +1,394 @@ +""" +Unit tests for ModelScope configuration. + +These tests validate the ModelScopeChatConfig class which extends OpenAIGPTConfig. +ModelScope is an OpenAI-compatible provider with minor customizations. +""" + +import json +import os +import sys + +sys.path.insert( + 0, os.path.abspath("../../../../..") +) # Adds the parent directory to the system path + +from unittest.mock import patch + +import httpx +import pytest +import respx + +import litellm +from litellm import completion +from litellm.llms.modelscope.chat.transformation import ModelScopeChatConfig + +DEFAULT_MODEL = "Qwen/Qwen3.5-35B-A3B" + + +class TestModelScopeConfig: + """Test class for ModelScope functionality""" + + def test_default_api_base(self): + """Test that default API base is used when none is provided""" + config = ModelScopeChatConfig() + headers = {} + api_key = "fake-modelscope-key" + + result = config.validate_environment( + headers=headers, + model=DEFAULT_MODEL, + messages=[{"role": "user", "content": "Hey"}], + optional_params={}, + litellm_params={}, + api_key=api_key, + api_base=None, + ) + + assert result["Authorization"] == f"Bearer {api_key}" + assert result["Content-Type"] == "application/json" + + @pytest.mark.respx() + def test_modelscope_completion_mock(self, respx_mock): + """Mock test for basic ModelScope completion.""" + + litellm.disable_aiohttp_transport = True + + api_key = "fake-modelscope-key" + api_base = "https://api-inference.modelscope.cn/v1" + + respx_mock.post(f"{api_base}/chat/completions").respond( + json={ + "id": "chatcmpl-123", + "object": "chat.completion", + "created": 1677652288, + "model": DEFAULT_MODEL, + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": '```python\nprint("Hey from LiteLLM!")\n```', + }, + "finish_reason": "stop", + } + ], + "usage": { + "prompt_tokens": 9, + "completion_tokens": 12, + "total_tokens": 21, + }, + }, + status_code=200, + ) + + response = completion( + model=f"modelscope/{DEFAULT_MODEL}", + messages=[ + {"role": "user", "content": "write code for saying hey from LiteLLM"} + ], + api_key=api_key, + api_base=api_base, + ) + + assert response is not None + assert response.choices[0].message.content is not None + assert "```python" in response.choices[0].message.content + + # ── _transform_messages tests ────────────────────────────────────── + + def test_transform_messages_flattens_text_content_list(self): + """Content lists containing only text items should be flattened to a string.""" + config = ModelScopeChatConfig() + messages = [ + { + "role": "user", + "content": [ + {"type": "text", "text": "Hello"}, + {"type": "text", "text": " world"}, + ], + } + ] + + result = config._transform_messages(messages=messages, model=DEFAULT_MODEL) + + assert result[0]["content"] == "Hello world" + + def test_transform_messages_preserves_multimodal_content_list(self): + """Content lists with image_url should be preserved as lists for vision models.""" + config = ModelScopeChatConfig() + messages = [ + { + "role": "user", + "content": [ + {"type": "text", "text": "What is this?"}, + {"type": "image_url", "image_url": {"url": "https://example.com/img.png"}}, + ], + } + ] + + result = config._transform_messages(messages=messages, model=DEFAULT_MODEL) + + assert isinstance(result[0]["content"], list) + assert len(result[0]["content"]) == 2 + assert result[0]["content"][0]["type"] == "text" + assert result[0]["content"][1]["type"] == "image_url" + + def test_transform_messages_string_content_unchanged(self): + """Messages with string content should pass through unchanged.""" + config = ModelScopeChatConfig() + messages = [{"role": "user", "content": "Hello"}] + + result = config._transform_messages(messages=messages, model=DEFAULT_MODEL) + + assert result[0]["content"] == "Hello" + + def test_transform_messages_multi_turn(self): + """Multi-turn conversations should be handled correctly.""" + config = ModelScopeChatConfig() + messages = [ + {"role": "user", "content": "Hi"}, + {"role": "assistant", "content": "Hello!"}, + { + "role": "user", + "content": [ + {"type": "text", "text": "Tell me more"}, + ], + }, + ] + + result = config._transform_messages(messages=messages, model=DEFAULT_MODEL) + + assert result[0]["content"] == "Hi" + assert result[1]["content"] == "Hello!" + assert result[2]["content"] == "Tell me more" + + def test_transform_messages_multimodal_multi_turn(self): + """Multi-turn with mixed text-only and multimodal messages.""" + config = ModelScopeChatConfig() + messages = [ + {"role": "user", "content": "Hi"}, + {"role": "assistant", "content": "Hello!"}, + { + "role": "user", + "content": [ + {"type": "text", "text": "Describe this image"}, + {"type": "image_url", "image_url": {"url": "https://example.com/photo.jpg"}}, + ], + }, + ] + + result = config._transform_messages(messages=messages, model=DEFAULT_MODEL) + + assert result[0]["content"] == "Hi" + assert result[1]["content"] == "Hello!" + # Multimodal message should keep list format + assert isinstance(result[2]["content"], list) + assert result[2]["content"][1]["type"] == "image_url" + + # ── get_complete_url tests ───────────────────────────────────────── + + def test_get_complete_url_default(self): + """Default api_base should append /chat/completions.""" + config = ModelScopeChatConfig() + + url = config.get_complete_url( + api_base=None, + api_key="fake-key", + model=DEFAULT_MODEL, + optional_params={}, + litellm_params={}, + ) + + assert url == "https://api-inference.modelscope.cn/v1/chat/completions" + + def test_get_complete_url_custom_base(self): + """Custom api_base should append /chat/completions.""" + config = ModelScopeChatConfig() + + url = config.get_complete_url( + api_base="https://custom.modelscope.cn/v1", + api_key="fake-key", + model=DEFAULT_MODEL, + optional_params={}, + litellm_params={}, + ) + + assert url == "https://custom.modelscope.cn/v1/chat/completions" + + def test_get_complete_url_already_has_endpoint(self): + """api_base already ending in /chat/completions should not be doubled.""" + config = ModelScopeChatConfig() + + url = config.get_complete_url( + api_base="https://api-inference.modelscope.cn/v1/chat/completions", + api_key="fake-key", + model=DEFAULT_MODEL, + optional_params={}, + litellm_params={}, + ) + + assert url == "https://api-inference.modelscope.cn/v1/chat/completions" + assert url.count("/chat/completions") == 1 + + # ── _get_openai_compatible_provider_info tests ───────────────────── + + def test_get_provider_info_with_explicit_api_base(self): + """Explicit api_base and api_key should be returned as-is.""" + config = ModelScopeChatConfig() + + api_base, api_key = config._get_openai_compatible_provider_info( + api_base="https://custom.example.com/v1", + api_key="my-key", + ) + + assert api_base == "https://custom.example.com/v1" + assert api_key == "my-key" + + def test_get_provider_info_default_fallback(self): + """When no api_base or env var is set, DEFAULT_BASE_URL should be used.""" + config = ModelScopeChatConfig() + + with patch.dict(os.environ, {}, clear=False): + os.environ.pop("MODELSCOPE_API_BASE", None) + os.environ.pop("MODELSCOPE_API_KEY", None) + + api_base, api_key = config._get_openai_compatible_provider_info( + api_base=None, + api_key=None, + ) + + assert api_base == "https://api-inference.modelscope.cn/v1" + assert api_key is None + + def test_get_provider_info_env_var_fallback(self): + """MODELSCOPE_API_BASE env var should be used when api_base is not provided.""" + config = ModelScopeChatConfig() + + with patch.dict( + os.environ, + {"MODELSCOPE_API_BASE": "https://env.modelscope.cn/v1"}, + ): + api_base, _ = config._get_openai_compatible_provider_info( + api_base=None, + api_key=None, + ) + + assert api_base == "https://env.modelscope.cn/v1" + + # ── Mock HTTP tests ──────────────────────────────────────────────── + + @pytest.mark.respx() + def test_completion_with_text_content_list(self, respx_mock): + """Verify that text-only content list messages are flattened before sending.""" + litellm.disable_aiohttp_transport = True + + api_key = "fake-modelscope-key" + api_base = "https://api-inference.modelscope.cn/v1" + captured_request = {} + + def capture_request(request): + captured_request["body"] = request.content + return httpx.Response( + 200, + json={ + "id": "chatcmpl-456", + "object": "chat.completion", + "created": 1677652288, + "model": DEFAULT_MODEL, + "choices": [ + { + "index": 0, + "message": {"role": "assistant", "content": "Sure!"}, + "finish_reason": "stop", + } + ], + "usage": {"prompt_tokens": 5, "completion_tokens": 1, "total_tokens": 6}, + }, + ) + + respx_mock.post(f"{api_base}/chat/completions").mock(side_effect=capture_request) + + response = completion( + model=f"modelscope/{DEFAULT_MODEL}", + messages=[ + { + "role": "user", + "content": [ + {"type": "text", "text": "Hello"}, + {"type": "text", "text": " world"}, + ], + } + ], + api_key=api_key, + api_base=api_base, + ) + + assert response.choices[0].message.content == "Sure!" + + body = json.loads(captured_request["body"]) + assert isinstance(body["messages"][0]["content"], str) + assert body["messages"][0]["content"] == "Hello world" + + @pytest.mark.respx() + def test_completion_with_multimodal_messages(self, respx_mock): + """Verify that multimodal messages (text + image_url) are sent as content lists.""" + litellm.disable_aiohttp_transport = True + + api_key = "fake-modelscope-key" + api_base = "https://api-inference.modelscope.cn/v1" + captured_request = {} + + def capture_request(request): + captured_request["body"] = request.content + return httpx.Response( + 200, + json={ + "id": "chatcmpl-789", + "object": "chat.completion", + "created": 1677652288, + "model": DEFAULT_MODEL, + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": "A cat sitting on a couch.", + }, + "finish_reason": "stop", + } + ], + "usage": {"prompt_tokens": 100, "completion_tokens": 8, "total_tokens": 108}, + }, + ) + + respx_mock.post(f"{api_base}/chat/completions").mock(side_effect=capture_request) + + response = completion( + model=f"modelscope/{DEFAULT_MODEL}", + messages=[ + { + "role": "user", + "content": [ + {"type": "text", "text": "What is in this image?"}, + { + "type": "image_url", + "image_url": {"url": "https://example.com/cat.jpg"}, + }, + ], + } + ], + api_key=api_key, + api_base=api_base, + ) + + assert response.choices[0].message.content == "A cat sitting on a couch." + + body = json.loads(captured_request["body"]) + msg = body["messages"][0] + # Multimodal content should remain as a list + assert isinstance(msg["content"], list) + assert len(msg["content"]) == 2 + assert msg["content"][0] == {"type": "text", "text": "What is in this image?"} + assert msg["content"][1]["type"] == "image_url" + assert msg["content"][1]["image_url"]["url"] == "https://example.com/cat.jpg" diff --git a/tests/test_litellm/llms/modelscope/image_generation/test_modelscope_image_gen_transformation.py b/tests/test_litellm/llms/modelscope/image_generation/test_modelscope_image_gen_transformation.py new file mode 100644 index 000000000000..7f00f53c4516 --- /dev/null +++ b/tests/test_litellm/llms/modelscope/image_generation/test_modelscope_image_gen_transformation.py @@ -0,0 +1,456 @@ +""" +Unit tests for ModelScope image generation configuration. + +These tests validate the ModelScopeImageGenerationConfig class which handles +transformation between OpenAI-compatible format and ModelScope API format. +""" + +import os +import sys +from unittest.mock import MagicMock, patch + +import pytest + +sys.path.insert( + 0, os.path.abspath("../../../../..") +) # Adds the parent directory to the system path + +from litellm.llms.modelscope.image_generation.transformation import ( + ModelScopeImageGenerationConfig, +) +from litellm.types.utils import ImageResponse + + +class TestModelScopeImageGenerationTransformation: + def setup_method(self): + """Set up test fixtures before each test method.""" + self.config = ModelScopeImageGenerationConfig() + self.model = "modelscope/Qwen/Qwen-Image-Edit" + self.logging_obj = MagicMock() + + def test_get_supported_openai_params(self): + """Test that get_supported_openai_params returns correct parameters.""" + supported_params = self.config.get_supported_openai_params(self.model) + + assert "n" in supported_params + assert "size" in supported_params + assert "response_format" in supported_params + assert "user" in supported_params + + def test_map_openai_params(self): + """Test that map_openai_params correctly passes through parameters.""" + non_default_params = { + "n": 2, + "size": "1024x1024", + "response_format": "url", + } + optional_params = {} + + result = self.config.map_openai_params( + non_default_params=non_default_params, + optional_params=optional_params, + model=self.model, + drop_params=False, + ) + + assert result["n"] == 2 + assert result["size"] == "1024x1024" + assert result["response_format"] == "url" + + def test_map_openai_params_with_user(self): + """Test that map_openai_params correctly passes through user parameter.""" + non_default_params = {"user": "test-user-123"} + optional_params = {} + + result = self.config.map_openai_params( + non_default_params=non_default_params, + optional_params=optional_params, + model=self.model, + drop_params=False, + ) + + assert result["user"] == "test-user-123" + + def test_get_complete_url_default(self): + """Test that get_complete_url returns default ModelScope URL.""" + result = self.config.get_complete_url( + api_base=None, + api_key="test_key", + model=self.model, + optional_params={}, + litellm_params={}, + ) + + assert result == "https://api-inference.modelscope.cn/v1/images/generations" + + def test_get_complete_url_with_custom_base(self): + """Test that get_complete_url uses custom api_base.""" + custom_base = "https://custom.modelscope.cn/v1" + + result = self.config.get_complete_url( + api_base=custom_base, + api_key="test_key", + model=self.model, + optional_params={}, + litellm_params={}, + ) + + assert result == f"{custom_base}/images/generations" + + def test_get_complete_url_with_trailing_slash(self): + """Test that get_complete_url strips trailing slashes from base.""" + custom_base = "https://custom.modelscope.cn/v1/" + + result = self.config.get_complete_url( + api_base=custom_base, + api_key="test_key", + model=self.model, + optional_params={}, + litellm_params={}, + ) + + assert result == "https://custom.modelscope.cn/v1/images/generations" + + @patch("litellm.llms.modelscope.image_generation.transformation.get_secret_str") + def test_validate_environment_with_api_key(self, mock_get_secret): + """Test that validate_environment correctly sets authorization header.""" + headers = {} + api_key = "test_api_key" + + result = self.config.validate_environment( + headers=headers, + model=self.model, + messages=[], + optional_params={}, + litellm_params={}, + api_key=api_key, + ) + + assert result["Authorization"] == f"Bearer {api_key}" + assert result["Content-Type"] == "application/json" + mock_get_secret.assert_not_called() + + @patch("litellm.llms.modelscope.image_generation.transformation.get_secret_str") + def test_validate_environment_with_secret_key(self, mock_get_secret): + """Test that validate_environment uses secret API key when api_key is None.""" + mock_get_secret.return_value = "secret_api_key" + headers = {} + + result = self.config.validate_environment( + headers=headers, + model=self.model, + messages=[], + optional_params={}, + litellm_params={}, + api_key=None, + ) + + assert result["Authorization"] == "Bearer secret_api_key" + mock_get_secret.assert_called_once_with("MODELSCOPE_API_KEY") + + @patch("litellm.llms.modelscope.image_generation.transformation.get_secret_str") + def test_validate_environment_no_api_key(self, mock_get_secret): + """Test that validate_environment raises error when no API key is available.""" + mock_get_secret.return_value = None + headers = {} + + with pytest.raises(ValueError) as exc_info: + self.config.validate_environment( + headers=headers, + model=self.model, + messages=[], + optional_params={}, + litellm_params={}, + api_key=None, + ) + + assert "MODELSCOPE_API_KEY is not set" in str(exc_info.value) + + def test_transform_image_generation_request_basic(self): + """Test that transform_image_generation_request creates correct request body.""" + prompt = "A beautiful sunset over mountains" + optional_params = {} + + result = self.config.transform_image_generation_request( + model=self.model, + prompt=prompt, + optional_params=optional_params, + litellm_params={}, + headers={}, + ) + + assert result["model"] == self.model + assert result["prompt"] == prompt + + def test_transform_image_generation_request_with_optional_params(self): + """Test that transform_image_generation_request includes optional params.""" + prompt = "A beautiful sunset" + optional_params = { + "n": 2, + "size": "1024x1024", + "response_format": "b64_json", + } + + result = self.config.transform_image_generation_request( + model=self.model, + prompt=prompt, + optional_params=optional_params, + litellm_params={}, + headers={}, + ) + + assert result["model"] == self.model + assert result["prompt"] == prompt + assert result["n"] == 2 + assert result["size"] == "1024x1024" + assert result["response_format"] == "b64_json" + + def test_transform_image_generation_request_ignores_internal_params(self): + """Test that transform_image_generation_request ignores params starting with _.""" + prompt = "A beautiful sunset" + optional_params = { + "n": 2, + "_internal_param": "should_be_ignored", + } + + result = self.config.transform_image_generation_request( + model=self.model, + prompt=prompt, + optional_params=optional_params, + litellm_params={}, + headers={}, + ) + + assert result["model"] == self.model + assert result["n"] == 2 + assert "_internal_param" not in result + + def test_transform_image_generation_response_with_url_images(self): + """Test that transform_image_generation_response correctly extracts URL images.""" + response_data = { + "created": 1234567890, + "data": [ + {"url": "https://example.com/image1.png"}, + {"url": "https://example.com/image2.png"}, + ], + } + + mock_response = MagicMock() + mock_response.json.return_value = response_data + mock_response.status_code = 200 + mock_response.headers = {} + + model_response = ImageResponse(data=[]) + + result = self.config.transform_image_generation_response( + model=self.model, + raw_response=mock_response, + model_response=model_response, + logging_obj=self.logging_obj, + request_data={}, + optional_params={}, + litellm_params={}, + encoding=None, + ) + + assert len(result.data) == 2 + assert result.data[0].url == "https://example.com/image1.png" + assert result.data[1].url == "https://example.com/image2.png" + + def test_transform_image_generation_response_with_b64_json(self): + """Test that transform_image_generation_response correctly extracts base64 images.""" + response_data = { + "created": 1234567890, + "data": [ + {"b64_json": "iVBORw0KGgoAAAANS"}, + ], + } + + mock_response = MagicMock() + mock_response.json.return_value = response_data + mock_response.status_code = 200 + mock_response.headers = {} + + model_response = ImageResponse(data=[]) + + result = self.config.transform_image_generation_response( + model=self.model, + raw_response=mock_response, + model_response=model_response, + logging_obj=self.logging_obj, + request_data={}, + optional_params={}, + litellm_params={}, + encoding=None, + ) + + assert len(result.data) == 1 + assert result.data[0].b64_json == "iVBORw0KGgoAAAANS" + assert result.data[0].url is None + + def test_transform_image_generation_response_with_revised_prompt(self): + """Test that transform_image_generation_response extracts revised_prompt.""" + response_data = { + "created": 1234567890, + "data": [ + { + "url": "https://example.com/image.png", + "revised_prompt": "A detailed description of a beautiful sunset", + }, + ], + } + + mock_response = MagicMock() + mock_response.json.return_value = response_data + mock_response.status_code = 200 + mock_response.headers = {} + + model_response = ImageResponse(data=[]) + + result = self.config.transform_image_generation_response( + model=self.model, + raw_response=mock_response, + model_response=model_response, + logging_obj=self.logging_obj, + request_data={}, + optional_params={}, + litellm_params={}, + encoding=None, + ) + + assert len(result.data) == 1 + assert ( + result.data[0].revised_prompt + == "A detailed description of a beautiful sunset" + ) + + def test_transform_image_generation_response_empty_data(self): + """Test that transform_image_generation_response handles empty data array.""" + response_data = { + "created": 1234567890, + "data": [], + } + + mock_response = MagicMock() + mock_response.json.return_value = response_data + mock_response.status_code = 200 + mock_response.headers = {} + + model_response = ImageResponse(data=[]) + + result = self.config.transform_image_generation_response( + model=self.model, + raw_response=mock_response, + model_response=model_response, + logging_obj=self.logging_obj, + request_data={}, + optional_params={}, + litellm_params={}, + encoding=None, + ) + + assert len(result.data) == 0 + + def test_transform_image_generation_response_error_handling(self): + """Test that transform_image_generation_response raises error on API error.""" + response_data = { + "error": { + "message": "Invalid prompt provided", + "type": "invalid_request_error", + } + } + + mock_response = MagicMock() + mock_response.json.return_value = response_data + mock_response.status_code = 400 + mock_response.headers = {} + + model_response = ImageResponse(data=[]) + + with pytest.raises(Exception) as exc_info: + self.config.transform_image_generation_response( + model=self.model, + raw_response=mock_response, + model_response=model_response, + logging_obj=self.logging_obj, + request_data={}, + optional_params={}, + litellm_params={}, + encoding=None, + ) + + assert "ModelScope error" in str(exc_info.value) + assert "Invalid prompt provided" in str(exc_info.value) + + def test_transform_image_generation_response_json_error(self): + """Test that transform_image_generation_response raises error on invalid JSON.""" + import json + + mock_response = MagicMock() + mock_response.json.side_effect = json.JSONDecodeError("Invalid JSON", "", 0) + mock_response.status_code = 500 + mock_response.headers = {} + + model_response = ImageResponse(data=[]) + + with pytest.raises(Exception) as exc_info: + self.config.transform_image_generation_response( + model=self.model, + raw_response=mock_response, + model_response=model_response, + logging_obj=self.logging_obj, + request_data={}, + optional_params={}, + litellm_params={}, + encoding=None, + ) + + assert "Error parsing ModelScope response" in str(exc_info.value) + + def test_get_error_class_bad_request(self): + """Test that get_error_class returns BadRequestError for 400 status.""" + from litellm.exceptions import BadRequestError + + error = self.config.get_error_class( + error_message="Bad request", + status_code=400, + headers={"Content-Type": "application/json"}, + ) + + assert isinstance(error, BadRequestError) + + def test_get_error_class_authentication_error(self): + """Test that get_error_class returns AuthenticationError for 401 status.""" + from litellm.exceptions import AuthenticationError + + error = self.config.get_error_class( + error_message="Invalid API key", + status_code=401, + headers={"Content-Type": "application/json"}, + ) + + assert isinstance(error, AuthenticationError) + + def test_get_error_class_internal_server_error(self): + """Test that get_error_class returns InternalServerError for 500+ status.""" + from litellm.exceptions import InternalServerError + + error = self.config.get_error_class( + error_message="Internal server error", + status_code=500, + headers={"Content-Type": "application/json"}, + ) + + assert isinstance(error, InternalServerError) + + def test_get_error_class_default(self): + """Test that get_error_class returns BadRequestError for other status codes.""" + from litellm.exceptions import BadRequestError + + error = self.config.get_error_class( + error_message="Some error", + status_code=404, + headers={"Content-Type": "application/json"}, + ) + + assert isinstance(error, BadRequestError) diff --git a/tests/test_litellm/llms/openai_like/test_libertai_provider.py b/tests/test_litellm/llms/openai_like/test_libertai_provider.py new file mode 100644 index 000000000000..fdbe3046e9b7 --- /dev/null +++ b/tests/test_litellm/llms/openai_like/test_libertai_provider.py @@ -0,0 +1,131 @@ +""" +Tests for LibertAI provider configuration and integration. +""" + +import litellm + + +class TestLibertAIProviderConfig: + """Test LibertAI provider configuration""" + + def test_libertai_in_provider_list(self): + """Test that libertai is in the provider list""" + from litellm import LlmProviders + + assert hasattr(LlmProviders, "LIBERTAI") + assert LlmProviders.LIBERTAI.value == "libertai" + assert "libertai" in litellm.provider_list + + def test_libertai_json_config_exists(self): + """Test that libertai is configured in providers.json""" + from litellm.llms.openai_like.json_loader import JSONProviderRegistry + + assert JSONProviderRegistry.exists("libertai") + + libertai = JSONProviderRegistry.get("libertai") + assert libertai is not None + assert libertai.base_url == "https://api.libertai.io/v1" + assert libertai.api_key_env == "LIBERTAI_API_KEY" + assert libertai.api_base_env == "LIBERTAI_API_BASE" + assert libertai.param_mappings.get("max_completion_tokens") == "max_tokens" + + def test_libertai_provider_resolution(self): + """Test that provider resolution finds libertai and the default base URL""" + from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider + + model, provider, api_key, api_base = get_llm_provider( + model="libertai/qwen3.6-27b", + custom_llm_provider=None, + api_base=None, + api_key=None, + ) + + assert model == "qwen3.6-27b" + assert provider == "libertai" + assert api_base == "https://api.libertai.io/v1" + + def test_libertai_api_base_override(self): + """Test that an explicit api_base / api_key overrides the default""" + from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider + + model, provider, api_key, api_base = get_llm_provider( + model="libertai/qwen3.6-27b", + custom_llm_provider=None, + api_base="https://custom.example.com/v1", + api_key="sk-test", + ) + + assert provider == "libertai" + assert api_base == "https://custom.example.com/v1" + assert api_key == "sk-test" + + def test_libertai_model_cost_map(self): + """Test that libertai models are present in the model cost map""" + model_cost = litellm.model_cost + + assert "libertai/qwen3.6-27b" in model_cost + info = model_cost["libertai/qwen3.6-27b"] + assert info["litellm_provider"] == "libertai" + assert info["mode"] == "chat" + assert info["max_input_tokens"] == 262144 + assert info["max_output_tokens"] == 262144 + + # thinking variants are marked as reasoning models + assert ( + model_cost["libertai/qwen3.6-27b-thinking"].get("supports_reasoning") + is True + ) + + def test_libertai_router_config(self): + """Test that libertai can be used in Router configuration""" + from litellm import Router + + router = Router( + model_list=[ + { + "model_name": "libertai-chat", + "litellm_params": { + "model": "libertai/qwen3.6-27b", + "api_key": "test-key", + }, + } + ] + ) + + assert len(router.model_list) == 1 + assert router.model_list[0]["model_name"] == "libertai-chat" + + def test_libertai_model_modes(self): + """Chat models carry mode 'chat'; the embedding model carries mode 'embedding'.""" + model_cost = litellm.model_cost + + # chat model + assert model_cost["libertai/qwen3.6-27b"]["mode"] == "chat" + + # embedding model (bge-m3) must be normalized to mode 'embedding' so + # /embeddings routing and the supported-endpoints matrix stay consistent + assert "libertai/bge-m3" in model_cost + bge = model_cost["libertai/bge-m3"] + assert bge["litellm_provider"] == "libertai" + assert bge["mode"] == "embedding" + + def test_libertai_supported_endpoints_matrix(self): + """The runtime-served backup matrix (GET /public/supported_endpoints) lists libertai.""" + import json + from pathlib import Path + + import litellm as _litellm + + backup_path = ( + Path(_litellm.__file__).parent / "provider_endpoints_support_backup.json" + ) + matrix = json.loads(backup_path.read_text()) + + assert "libertai" in matrix["providers"] + endpoints = matrix["providers"]["libertai"]["endpoints"] + assert endpoints["chat_completions"] is True + # embeddings is advertised false: the JSON-configured-provider path only + # wires chat routing (the OpenAILike embedding handler is reached solely + # for the literal openai_like/llamafile/lm_studio providers), matching + # the llamagate precedent. bge-m3 stays in the cost map for metadata. + assert endpoints["embeddings"] is False diff --git a/tests/test_litellm/llms/vertex_ai/context_caching/test_vertex_ai_context_caching.py b/tests/test_litellm/llms/vertex_ai/context_caching/test_vertex_ai_context_caching.py index cc8b14e5514d..cf75964ddb73 100644 --- a/tests/test_litellm/llms/vertex_ai/context_caching/test_vertex_ai_context_caching.py +++ b/tests/test_litellm/llms/vertex_ai/context_caching/test_vertex_ai_context_caching.py @@ -1917,3 +1917,57 @@ def test_gemini_context_caching_without_api_base_ignores_model(self): assert "generativelanguage.googleapis.com" in url assert "cachedContents" in url + + +class TestContextCachingMultiRegionUrls: + """Regression coverage for #29571: multi-region vertex_location values + (`eu`, `us`) must resolve to the REP host (`aiplatform.{geo}.rep.googleapis.com`) + on the cachedContents endpoint, matching the inference path (already + fixed in #27293). Previously the URL was hardcoded to + `{location}-aiplatform.googleapis.com`, which doesn't exist for + multi-region locations and 404'd.""" + + def setup_method(self): + self.caching = ContextCachingEndpoints() + + @pytest.mark.parametrize("location", ["eu", "us"]) + def test_vertex_ai_multi_region_uses_rep_host(self, location): + _, url = self.caching._get_token_and_url_context_caching( + gemini_api_key=None, + custom_llm_provider="vertex_ai", + api_base=None, + vertex_project="my-project", + vertex_location=location, + vertex_auth_header="Bearer token", + ) + + assert url.startswith(f"https://aiplatform.{location}.rep.googleapis.com/") + assert f"/locations/{location}/cachedContents" in url + # Old broken host must no longer appear. + assert f"{location}-aiplatform.googleapis.com" not in url + + def test_vertex_ai_regional_still_uses_regional_host(self): + _, url = self.caching._get_token_and_url_context_caching( + gemini_api_key=None, + custom_llm_provider="vertex_ai", + api_base=None, + vertex_project="my-project", + vertex_location="us-central1", + vertex_auth_header="Bearer token", + ) + + assert url.startswith("https://us-central1-aiplatform.googleapis.com/") + assert "/locations/us-central1/cachedContents" in url + + def test_vertex_ai_global_still_uses_global_host(self): + _, url = self.caching._get_token_and_url_context_caching( + gemini_api_key=None, + custom_llm_provider="vertex_ai", + api_base=None, + vertex_project="my-project", + vertex_location="global", + vertex_auth_header="Bearer token", + ) + + assert url.startswith("https://aiplatform.googleapis.com/") + assert "/locations/global/cachedContents" in url diff --git a/tests/test_litellm/proxy/management_endpoints/test_customer_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_customer_endpoints.py index d8a674c2681a..6c5ccd3562f6 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_customer_endpoints.py +++ b/tests/test_litellm/proxy/management_endpoints/test_customer_endpoints.py @@ -409,3 +409,101 @@ async def test_get_customer_daily_activity_with_end_user_aliases(monkeypatch): "end-user-1": {"alias": "Customer One"}, "end-user-2": {"alias": "Customer Two"}, } + + +@pytest.mark.asyncio +async def test_get_customer_daily_activity_non_admin_is_rejected(monkeypatch): + """ + Security regression: any non-admin caller must receive 401 from + /customer/daily/activity and /end_user/daily/activity. + + Before this fix, the endpoint performed no role check. A caller with + user_role=INTERNAL_USER could omit end_user_ids, causing entity_id=None + to flow into get_daily_activity where the SQL builder treats it as no + filter — returning every tenant's spend across the full + LiteLLM_DailyEndUserSpend table. + + LiteLLM_EndUserTable has no per-tenant ownership column, so non-admin + scoping is not possible. The correct fix is admin-only, matching the + existing /customer/list gate. + """ + from litellm.proxy.management_endpoints import customer_endpoints + from litellm.proxy.management_endpoints.customer_endpoints import ( + get_customer_daily_activity, + ) + + mock_prisma_client = MagicMock() + monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client) + + get_daily_activity_mock = AsyncMock() + monkeypatch.setattr( + customer_endpoints, "get_daily_activity", get_daily_activity_mock + ) + + non_admin_key = UserAPIKeyAuth( + user_id="regular-user-abc", + user_role=LitellmUserRoles.INTERNAL_USER, + ) + + with pytest.raises(HTTPException) as exc_info: + await get_customer_daily_activity( + end_user_ids=None, + start_date="2025-01-01", + end_date="2025-01-31", + model=None, + api_key=None, + page=1, + page_size=10, + exclude_end_user_ids=None, + user_api_key_dict=non_admin_key, + ) + + assert exc_info.value.status_code == 401 + assert "Admin-only endpoint" in str(exc_info.value.detail) + get_daily_activity_mock.assert_not_called() + + +@pytest.mark.asyncio +async def test_get_customer_daily_activity_service_account_key_is_rejected(monkeypatch): + """ + Security regression: service-account keys (user_id=None, role=INTERNAL_USER) + must be rejected at the admin gate before reaching get_daily_activity. + + A service-account key with end_user_ids omitted is the worst-case caller: + entity_id=None and no user identity to scope by — the SQL builder would + return the full LiteLLM_DailyEndUserSpend table with no WHERE clause. + """ + from litellm.proxy.management_endpoints import customer_endpoints + from litellm.proxy.management_endpoints.customer_endpoints import ( + get_customer_daily_activity, + ) + + mock_prisma_client = MagicMock() + monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client) + + get_daily_activity_mock = AsyncMock() + monkeypatch.setattr( + customer_endpoints, "get_daily_activity", get_daily_activity_mock + ) + + service_account_key = UserAPIKeyAuth( + user_id=None, + user_role=LitellmUserRoles.INTERNAL_USER, + ) + + with pytest.raises(HTTPException) as exc_info: + await get_customer_daily_activity( + end_user_ids=None, + start_date="2025-01-01", + end_date="2025-01-31", + model=None, + api_key=None, + page=1, + page_size=10, + exclude_end_user_ids=None, + user_api_key_dict=service_account_key, + ) + + assert exc_info.value.status_code == 401 + assert "Admin-only endpoint" in str(exc_info.value.detail) + get_daily_activity_mock.assert_not_called() diff --git a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py index f0198320f22d..b81807ee19e6 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py +++ b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py @@ -3064,6 +3064,106 @@ async def test_list_team_v2_org_admin_sees_org_teams(): assert where["organization_id"] == {"in": ["org_A"]} +@pytest.mark.asyncio +async def test_list_team_v2_org_admin_own_user_id_sees_all_org_teams(): + """ + Test that an org admin whose own user_id is sent (as the UI does for + non-Admin roles) still sees all teams in their organization, not just + teams they are a direct member of. + + Regression test for https://github.com/BerriAI/litellm/issues/30215 + """ + from datetime import datetime + from unittest.mock import AsyncMock, Mock, patch + + from fastapi import Request + + from litellm.proxy._types import ( + LiteLLM_OrganizationMembershipTable, + LiteLLM_UserTable, + LitellmUserRoles, + UserAPIKeyAuth, + ) + from litellm.proxy.management_endpoints.team_endpoints import list_team_v2 + + mock_request = Mock(spec=Request) + mock_user_api_key_dict = UserAPIKeyAuth( + user_role=LitellmUserRoles.INTERNAL_USER, + user_id="org_admin_user", + ) + + mock_user = LiteLLM_UserTable( + user_id="org_admin_user", + teams=["team_1"], # direct member of only 1 team + organization_memberships=[ + LiteLLM_OrganizationMembershipTable( + user_id="org_admin_user", + organization_id="org_A", + user_role="org_admin", + spend=0.0, + created_at=datetime.now(), + updated_at=datetime.now(), + ), + ], + ) + + with ( + patch("litellm.proxy.proxy_server.prisma_client") as mock_prisma, + patch("litellm.proxy.proxy_server.user_api_key_cache"), + patch("litellm.proxy.proxy_server.proxy_logging_obj"), + patch( + "litellm.proxy.management_endpoints.team_endpoints.get_user_object", + new_callable=AsyncMock, + return_value=mock_user, + ), + ): + mock_db = Mock() + mock_prisma.db = mock_db + + mock_team_1 = Mock() + mock_team_1.model_dump.return_value = { + "team_id": "team_1", + "team_alias": "Team One", + "organization_id": "org_A", + "members_with_roles": [{"user_id": "org_admin_user", "role": "admin"}], + } + mock_team_2 = Mock() + mock_team_2.model_dump.return_value = { + "team_id": "team_2", + "team_alias": "Team Two", + "organization_id": "org_A", + "members_with_roles": [{"user_id": "other_user", "role": "user"}], + } + mock_db.litellm_teamtable.find_many = AsyncMock( + return_value=[mock_team_1, mock_team_2] + ) + mock_db.litellm_teamtable.count = AsyncMock(return_value=2) + mock_db.litellm_verificationtoken.group_by = AsyncMock(return_value=[]) + + # UI sends the caller's own user_id for non-Admin roles + result = await list_team_v2( + http_request=mock_request, + user_id="org_admin_user", # same as caller — UI sends this + organization_id=None, + team_id=None, + team_alias=None, + user_api_key_dict=mock_user_api_key_dict, + page=1, + page_size=10, + sort_by=None, + sort_order="asc", + status=None, + ) + + assert result["total"] == 2 + assert len(result["teams"]) == 2 + + # Verify the where clause scopes by org only — no team_id filter + where = mock_db.litellm_teamtable.find_many.call_args.kwargs["where"] + assert where["organization_id"] == {"in": ["org_A"]} + assert "team_id" not in where + + @pytest.mark.asyncio async def test_list_team_v2_org_admin_cannot_view_other_orgs(): """ diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py index 3a1d15ef79c5..9e77c6ecc9b7 100644 --- a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py +++ b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py @@ -359,6 +359,7 @@ def test_ui_view_request_response_forbids_non_admin_without_db(client, monkeypat "metadata.additional_usage_values.cache_read_input_tokens", "metadata.additional_usage_values.inference_geo", "metadata.additional_usage_values.speed", + "metadata.additional_usage_values.iterations", "metadata.litellm_overhead_time_ms", "metadata.cost_breakdown", "metadata.user_api_key", diff --git a/tests/test_litellm/proxy/test_common_request_processing.py b/tests/test_litellm/proxy/test_common_request_processing.py index ec186ffa795f..8c28749b1cbf 100644 --- a/tests/test_litellm/proxy/test_common_request_processing.py +++ b/tests/test_litellm/proxy/test_common_request_processing.py @@ -24,6 +24,7 @@ _is_azure_model_router_request, _override_openai_response_model, _parse_event_data_for_error, + _UpstreamClosingStreamingResponse, create_response, ) from litellm.proxy.dd_span_tagger import DDSpanTagger @@ -2415,6 +2416,186 @@ async def test_exception_without_status_code_defaults_to_500(self): assert proxy_exc.code == "500" +class TestStreamCloseOnDisconnect: + """ + Coverage for closing the upstream LLM stream when the client disconnects + mid-stream. Starlette abandons the response body iterator without calling + aclose(), so without these hooks the proxy->backend connection stays open + and the backend (e.g. vLLM) keeps generating into a dead pipe. + """ + + async def test_response_closes_body_iterator_when_task_cancelled(self): + """Cancellation landing in send() leaves the generator suspended at a + yield; only the response-level finally can close it.""" + closed = asyncio.Event() + + async def body(): + try: + while True: + yield "data: x\n\n" + finally: + closed.set() + + response = _UpstreamClosingStreamingResponse( + body(), media_type="text/event-stream" + ) + + async def receive(): + await asyncio.Event().wait() + + async def send(message): + if message["type"] == "http.response.body": + await asyncio.Event().wait() + + task = asyncio.create_task(response({"type": "http"}, receive, send)) + await asyncio.sleep(0.05) + assert not closed.is_set() + + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + assert closed.is_set() + + async def test_response_closes_body_iterator_on_http_disconnect(self): + closed = asyncio.Event() + disconnected = asyncio.Event() + body_sends = 0 + + async def body(): + try: + for i in range(1000): + yield f"data: {i}\n\n" + finally: + closed.set() + + response = _UpstreamClosingStreamingResponse( + body(), media_type="text/event-stream" + ) + + async def receive(): + await disconnected.wait() + return {"type": "http.disconnect"} + + async def send(message): + nonlocal body_sends + if message["type"] == "http.response.body": + body_sends += 1 + if body_sends == 3: + disconnected.set() + await asyncio.sleep(0.05) + + await response({"type": "http"}, receive, send) + + assert closed.is_set() + assert body_sends < 1000 + + async def test_upstream_closed_even_if_body_iterator_aclose_raises(self): + """A BaseException from body_iterator.aclose() (e.g. CancelledError) + must not prevent the upstream generator from being closed.""" + upstream_closed = asyncio.Event() + + class ExplodingIterator: + def __aiter__(self): + return self + + async def __anext__(self): + raise StopAsyncIteration + + async def aclose(self): + raise asyncio.CancelledError() + + async def upstream(): + try: + yield "data: a\n\n" + finally: + upstream_closed.set() + + upstream_gen = upstream() + await upstream_gen.__anext__() + response = _UpstreamClosingStreamingResponse( + ExplodingIterator(), + media_type="text/event-stream", + upstream_generator=upstream_gen, + ) + + async def receive(): + await asyncio.Event().wait() + + async def send(message): + pass + + await response({"type": "http"}, receive, send) + + assert upstream_closed.is_set() + + async def test_create_response_closes_wrapped_generator_on_cancellation(self): + """End to end through create_response: the upstream-facing generator + must be closed even when the body iterator was never started (client + gone before the first chunk could be sent).""" + inner_closed = asyncio.Event() + + async def wrapped(): + try: + while True: + yield "data: a\n\n" + finally: + inner_closed.set() + + response = await create_response( + generator=wrapped(), media_type="text/event-stream", headers={} + ) + + async def receive(): + await asyncio.Event().wait() + + async def send(message): + await asyncio.Event().wait() + + task = asyncio.create_task(response({"type": "http"}, receive, send)) + await asyncio.sleep(0.05) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + assert inner_closed.is_set() + + async def test_async_streaming_data_generator_closes_upstream_on_early_close( + self, + ): + class FakeUpstream: + def __init__(self): + self.aclosed = False + + def __aiter__(self): + return self + + async def __anext__(self): + return {"type": "chunk"} + + async def aclose(self): + self.aclosed = True + + ProxyLogging._callback_capabilities_cache.clear() + upstream = FakeUpstream() + gen = ProxyBaseLLMRequestProcessing.async_streaming_data_generator( + response=upstream, + user_api_key_dict=MagicMock(spec=UserAPIKeyAuth), + request_data={"model": "mock-model"}, + proxy_logging_obj=ProxyLogging(user_api_key_cache=MagicMock()), + serialize_chunk=lambda c: "data: x\n\n", + serialize_error=lambda e: "data: error\n\n", + ) + + await gen.__anext__() + await gen.__anext__() + assert not upstream.aclosed + + await gen.aclose() + + assert upstream.aclosed + + class TestHandleLLMApiExceptionRetryAfter: """RouterRateLimitError cooldown_time must surface as a retry-after header.""" diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py index 960fca205ceb..a0b1676068b0 100644 --- a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py +++ b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py @@ -2275,3 +2275,28 @@ def test_cache_control_preserved_for_input_image_block(self): assert isinstance(result, list) assert len(result) == 1 assert result[0]["cache_control"] == {"type": "ephemeral"} + + +def test_function_call_tool_id_falls_back_to_unique_id_for_degenerate_call_id(): + """Bedrock Mantle returns a non-unique, index-based ``call_id`` (``call_0`` that + resets every response) alongside a unique ``id`` (``fc_...``). For that degenerate + form the converter must expose the unique ``id``; otherwise every tool call across + an agent's turns collapses to the same id, the agent cannot correlate its tool + results, and it loops re-issuing the same call. A normal (unique) ``call_id`` must + be preserved, since it is the canonical Responses API correlation key. Regression + for the bedrock-mantle gpt-5.5 non-streaming path.""" + from types import SimpleNamespace + + convert = ( + LiteLLMCompletionResponsesConfig.convert_response_function_tool_call_to_chat_completion_tool_call + ) + + mantle = SimpleNamespace( + id="fc_unique_abc123", call_id="call_0", name="get_weather", arguments="{}" + ) + assert convert(mantle)["id"] == "fc_unique_abc123" + + openai = SimpleNamespace( + id="fc_2", call_id="call_tokyo", name="get_weather", arguments="{}" + ) + assert convert(openai)["id"] == "call_tokyo" diff --git a/tests/test_litellm/test_azure_ad_token_credential_resolution.py b/tests/test_litellm/test_azure_ad_token_credential_resolution.py new file mode 100644 index 000000000000..958b236c9b3d --- /dev/null +++ b/tests/test_litellm/test_azure_ad_token_credential_resolution.py @@ -0,0 +1,145 @@ +""" +Regression for #30235. + +``Router.get_deployment_credentials_with_provider`` (router.py:8954) is +used by the proxy's ``/v1/files``, ``/v1/batches`` and passthrough +routing code paths to resolve the upstream credentials for a deployment +by model_id:: + + return CredentialLiteLLMParams( + **deployment.litellm_params.model_dump(exclude_none=True) + ).model_dump(exclude_none=True) + +That re-validation is strict. Any field NOT declared on +``CredentialLiteLLMParams`` gets dropped on the way through, even when +it was present on the original ``litellm_params``. + +Pre-fix, ``azure_ad_token`` was undeclared, so Azure deployments +configured with OAuth/M2M (``azure_ad_token`` in place of ``api_key``) +silently lost their token on every file upload and the proxy returned:: + + Missing credentials. Please pass one of api_key, azure_ad_token, + azure_ad_token_provider, ... + +Tests below pin two things: +1. ``CredentialLiteLLMParams`` directly accepts and round-trips + ``azure_ad_token``. +2. ``Router.get_deployment_credentials_with_provider`` preserves + ``azure_ad_token`` from a deployment's ``litellm_params``. +""" + +from unittest.mock import MagicMock, patch + +import pytest + + +class TestCredentialLiteLLMParamsAzureAdToken: + def test_azure_ad_token_round_trips_through_model_dump(self): + from litellm.types.router import CredentialLiteLLMParams + + params = CredentialLiteLLMParams( + api_base="https://my.openai.azure.com", + api_version="2024-08-01-preview", + azure_ad_token="oauth-bearer-token-xyz", + ) + dumped = params.model_dump(exclude_none=True) + assert dumped["azure_ad_token"] == "oauth-bearer-token-xyz", ( + "azure_ad_token dropped from CredentialLiteLLMParams.model_dump() — " + "every callsite that round-trips litellm_params through this class " + "will lose the token (#30235)" + ) + + def test_azure_ad_token_is_optional(self): + """Adding the field must not break deployments that don't use it + — confirm the default is None and it's excluded by + ``exclude_none``.""" + from litellm.types.router import CredentialLiteLLMParams + + params = CredentialLiteLLMParams(api_key="sk-static") + dumped = params.model_dump(exclude_none=True) + assert "azure_ad_token" not in dumped + assert dumped["api_key"] == "sk-static" + + def test_round_trip_preserves_full_credential_shape(self): + """The Router's get_deployment_credentials_with_provider pattern: + construct from a dict that has azure_ad_token alongside other + fields, dump, expect azure_ad_token to ride through alongside + the other declared fields.""" + from litellm.types.router import CredentialLiteLLMParams + + source = { + "api_base": "https://my.openai.azure.com", + "api_version": "2024-08-01-preview", + "azure_ad_token": "tok-123", + "api_key": None, # M2M deployment has no static key + } + rebuilt = CredentialLiteLLMParams( + **{k: v for k, v in source.items() if v is not None} + ).model_dump(exclude_none=True) + assert rebuilt.get("azure_ad_token") == "tok-123" + assert rebuilt.get("api_base") == "https://my.openai.azure.com" + assert "api_key" not in rebuilt + + +class TestRouterCredentialResolution: + """The actual fix surface: Router.get_deployment_credentials_with_provider + must preserve azure_ad_token on the resolved credentials dict so the + files endpoint can forward it to the Azure files client.""" + + def test_credentials_preserve_azure_ad_token(self): + from litellm import Router + + deployment_id = "azure-m2m-deployment-fixed-uuid" + router = Router( + model_list=[ + { + "model_name": "gpt-4o-azure-m2m", + "litellm_params": { + "model": "azure/gpt-4o", + "api_base": "https://my.openai.azure.com", + "api_version": "2024-08-01-preview", + "azure_ad_token": "tok-azure-m2m-xyz", + }, + "model_info": {"id": deployment_id}, + } + ] + ) + + credentials = router.get_deployment_credentials_with_provider( + model_id=deployment_id + ) + assert credentials is not None + assert credentials.get("azure_ad_token") == "tok-azure-m2m-xyz", ( + "Router credential resolution dropped azure_ad_token; the " + "files / batches / passthrough callers will not be able to " + "authenticate against Azure (#30235)" + ) + + def test_credentials_static_api_key_unaffected(self): + """Don't break the pre-fix happy path: a deployment with a + static api_key (no azure_ad_token) keeps its api_key and + azure_ad_token doesn't appear in the dump.""" + from litellm import Router + + deployment_id = "azure-static-key-deployment-fixed-uuid" + router = Router( + model_list=[ + { + "model_name": "gpt-4o-azure-static", + "litellm_params": { + "model": "azure/gpt-4o", + "api_base": "https://my.openai.azure.com", + "api_version": "2024-08-01-preview", + "api_key": "sk-static-key", + }, + "model_info": {"id": deployment_id}, + } + ] + ) + + credentials = router.get_deployment_credentials_with_provider( + model_id=deployment_id + ) + assert credentials is not None + assert credentials.get("api_key") == "sk-static-key" + assert "azure_ad_token" not in credentials diff --git a/tests/test_litellm/test_cost_calculator.py b/tests/test_litellm/test_cost_calculator.py index ad08029c2c43..6d9185ffcf20 100644 --- a/tests/test_litellm/test_cost_calculator.py +++ b/tests/test_litellm/test_cost_calculator.py @@ -180,6 +180,43 @@ def test_openrouter_qwen36_plus_model_info(): assert model_info["supports_vision"] is True +@pytest.mark.parametrize( + "model", + [ + "github_copilot/mai-code-1-flash", + "github_copilot/mai-code-1-flash-internal", + ], +) +def test_github_copilot_mai_code_1_flash_pricing(model): + os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True" + litellm.model_cost = litellm.get_model_cost_map(url="") + + model_info = litellm.model_cost.get(model) + + assert model_info is not None, f"Missing model pricing entry: {model}" + assert model_info["litellm_provider"] == "github_copilot" + assert model_info["mode"] == "chat" + assert model_info["input_cost_per_token"] == 7.5e-07 + assert model_info["cache_read_input_token_cost"] == 7.5e-08 + assert model_info["output_cost_per_token"] == 4.5e-06 + assert model_info["supported_endpoints"] == ["/v1/chat/completions"] + + prompt_usd, completion_usd = cost_per_token( + model=model, + prompt_tokens=1000, + completion_tokens=500, + custom_llm_provider="github_copilot", + usage_object=Usage( + prompt_tokens=1000, + completion_tokens=500, + prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=200), + ), + ) + + assert prompt_usd == pytest.approx((800 * 7.5e-07) + (200 * 7.5e-08)) + assert completion_usd == pytest.approx(500 * 4.5e-06) + + def test_cost_calculator_with_usage(monkeypatch): os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True" litellm.model_cost = litellm.get_model_cost_map(url="") @@ -385,7 +422,7 @@ def test_handle_realtime_stream_cost_calculation(): ) assert cost == 0.0 # No usage, no cost - + def test_realtime_stream_combines_text_and_audio_token_details(): """Realtime response.done usage with input_token_details / output_token_details.""" from litellm.cost_calculator import RealtimeAPITokenUsageProcessor diff --git a/tests/test_litellm/test_register_model_zero_cost_persistence.py b/tests/test_litellm/test_register_model_zero_cost_persistence.py new file mode 100644 index 000000000000..15c8721a7f1f --- /dev/null +++ b/tests/test_litellm/test_register_model_zero_cost_persistence.py @@ -0,0 +1,187 @@ +""" +Regression for #30198. + +``register_model`` calls ``get_model_info(key)`` to fetch the existing +entry, then ``_update_dictionary`` merges its own ``value`` over it and +the result is written back into ``litellm.model_cost``. + +``_get_model_info_helper`` synthesizes ``input_cost_per_token`` and +``output_cost_per_token`` as 0 when the cost keys are missing from the +raw entry (the "price unknown" and "free" cases share the same +representation). So on the SECOND ``register_model`` call against an +already-present sparse entry (e.g. router model id with only +``{"id": ..., "db_model": True}``), the synthesized zeros get written +back, and the entry flips from "no cost keys" → "cost keys = 0". + +That defeats ``_is_cost_explicitly_configured`` (added in #24949), which +checks whether the cost keys are present in the raw entry — after the +write-back they are. ``_is_model_cost_zero`` then returns ``True`` and +``common_checks`` skips every tag / key / team / user / org budget check +for the group. Spend keeps recording (cost calc resolves by model name), +so the symptom is silent: requests that should 429 keep returning 200. + +Tests below replicate the Router-built-twice scenario from the report +and confirm the sparse entry stays sparse. +""" + +import importlib +import os +import sys +from typing import Any, Dict + +import pytest + + +@pytest.fixture(autouse=True) +def _restore_model_cost(): + import litellm + + original = dict(litellm.model_cost) + try: + yield + finally: + litellm.model_cost.clear() + litellm.model_cost.update(original) + + +def _sparse_router_value(model_cost_key: str) -> Dict[str, Any]: + # Mirrors what Router builds for a db_model deployment with no custom + # pricing (litellm/router.py:_create_deployment). + return { + "model_name": "gpt-4o-mini", + "litellm_params": { + "model": "gpt-4o-mini", + "custom_llm_provider": "openai", + "api_key": "sk-test", + }, + "model_info": {"id": model_cost_key, "db_model": True}, + } + + +def test_first_registration_leaves_sparse_entry_without_cost_keys(): + """First ``register_model`` call against an unknown key must NOT add + cost keys to the entry — otherwise the very first registration would + already poison the map.""" + import litellm + + key = "fixed-uuid-30198-first" + litellm.model_cost.pop(key, None) + + litellm.register_model({key: {"litellm_provider": "openai"}}) + + entry = litellm.model_cost.get(key, {}) + assert "input_cost_per_token" not in entry, entry + assert "output_cost_per_token" not in entry, entry + + +def test_second_registration_does_not_persist_synthesized_zero_costs(): + """The #30198 bug: re-registering the same sparse entry made + ``get_model_info`` synthesize cost = 0 and write it back. Verify the + entry stays clean after a second pass.""" + import litellm + + key = "fixed-uuid-30198-double-register" + litellm.model_cost.pop(key, None) + + payload = {key: {"litellm_provider": "openai"}} + litellm.register_model(payload) + litellm.register_model(payload) + + entry = litellm.model_cost.get(key, {}) + assert "input_cost_per_token" not in entry, ( + "second register_model() persisted a synthesized zero " + "input_cost_per_token; this disables budget enforcement" + ) + assert "output_cost_per_token" not in entry, ( + "second register_model() persisted a synthesized zero " + "output_cost_per_token; this disables budget enforcement" + ) + + +def test_explicit_zero_cost_in_value_is_preserved(): + """If the caller actually wants the model marked free, the explicit + zero must survive the dedup. The fix must only strip SYNTHESIZED + zeros, not caller-provided ones.""" + import litellm + + key = "fixed-uuid-30198-explicit-zero" + litellm.model_cost.pop(key, None) + + litellm.register_model( + { + key: { + "litellm_provider": "openai", + "input_cost_per_token": 0, + "output_cost_per_token": 0, + } + } + ) + + entry = litellm.model_cost[key] + assert entry["input_cost_per_token"] == 0 + assert entry["output_cost_per_token"] == 0 + + # Re-registering with the same explicit zeros must keep them. + litellm.register_model( + { + key: { + "litellm_provider": "openai", + "input_cost_per_token": 0, + "output_cost_per_token": 0, + } + } + ) + entry = litellm.model_cost[key] + assert entry["input_cost_per_token"] == 0 + assert entry["output_cost_per_token"] == 0 + + +def test_real_pricing_for_known_model_survives_re_registration(): + """A model with built-in pricing (e.g. gpt-4o-mini) must keep its + real per-token rates across repeated registrations of an empty + payload that names the same key.""" + import litellm + + base_in = litellm.model_cost["gpt-4o-mini"]["input_cost_per_token"] + base_out = litellm.model_cost["gpt-4o-mini"]["output_cost_per_token"] + assert base_in > 0 and base_out > 0 + + litellm.register_model({"gpt-4o-mini": {"litellm_provider": "openai"}}) + litellm.register_model({"gpt-4o-mini": {"litellm_provider": "openai"}}) + + assert litellm.model_cost["gpt-4o-mini"]["input_cost_per_token"] == base_in + assert litellm.model_cost["gpt-4o-mini"]["output_cost_per_token"] == base_out + + +def test_router_double_init_keeps_db_model_entry_sparse(): + """End-to-end repro from the issue body: building Router twice on + the same model_list must not flip the per-deployment entry to + cost=0. This is the exact production symptom (#30198).""" + import litellm + from litellm import Router + + deployment_id = "fixed-uuid-30198-router-init" + litellm.model_cost.pop(deployment_id, None) + + model_list = [_sparse_router_value(deployment_id)] + + Router(model_list=model_list) + after_first = dict(litellm.model_cost.get(deployment_id, {})) + + Router(model_list=model_list) + after_second = dict(litellm.model_cost.get(deployment_id, {})) + + # Cost keys must not appear AT ALL on a sparse db_model deployment + # (matches the pre-bug shape) — the bug rewrites them as 0. + for snapshot, label in ( + (after_first, "first Router()"), + (after_second, "second Router()"), + ): + assert "input_cost_per_token" not in snapshot, ( + f"{label} persisted input_cost_per_token={snapshot.get('input_cost_per_token')!r} " + f"on a sparse db_model entry; this disables budget enforcement" + ) + assert "output_cost_per_token" not in snapshot, ( + f"{label} persisted output_cost_per_token={snapshot.get('output_cost_per_token')!r} " + f"on a sparse db_model entry; this disables budget enforcement" + ) diff --git a/tests/test_litellm/test_responses_streaming_container_ownership.py b/tests/test_litellm/test_responses_streaming_container_ownership.py new file mode 100644 index 000000000000..07cc309798b6 --- /dev/null +++ b/tests/test_litellm/test_responses_streaming_container_ownership.py @@ -0,0 +1,261 @@ +""" +Regression for #30210. + +When streaming /v1/responses goes through the proxy + Router, the +streaming iterator is wrapped by ``Router._aresponses_streaming_iterator`` +which returns ``FallbackResponsesStreamWrapper``. That wrapper set +``self.completed_response = None`` in __init__ and never updated it, +so the proxy's container-ownership hook (which reads +``getattr(stream_response, "completed_response", None)`` via +``ProxyBaseLLMRequestProcessing._extract_completed_responses_response``) +saw None on every streaming call and silently recorded nothing — +follow-up ``GET /v1/containers//files`` then 403'd for the very +key that created the container. + +Tests below construct the wrapper from a fake async generator that +yields one terminal ``response.completed`` chunk and assert the +wrapper now carries that chunk on ``completed_response`` so the +proxy hook can walk it. +""" + +import asyncio +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest + + +def _make_wrapper_class(): + """Pull ``FallbackResponsesStreamWrapper`` out by running + ``Router._aresponses_streaming_iterator`` long enough to construct + the class then return it. Mirrors how the wrapper is actually + instantiated in production.""" + from litellm.router import Router + from litellm.responses.streaming_iterator import ( + BaseResponsesAPIStreamingIterator, + ) + + # Minimal source iterator stub with every attribute the wrapper + # copies in __init__ (see router.py:2552-2583). + source = SimpleNamespace( + response=None, + model="openai/gpt-5.5", + logging_obj=None, + responses_api_provider_config=None, + start_time=None, + litellm_metadata=None, + custom_llm_provider="openai", + request_data={}, + call_type="aresponses", + _hidden_params={}, + ) + + # The class is defined inside _aresponses_streaming_iterator; capture + # it by patching FallbackResponsesStreamWrapper into a sentinel on + # construction. + captured = {} + + real_router_module = __import__("litellm.router", fromlist=["Router"]) + + async def _drive(): + async def empty_gen(): + if False: + yield # pragma: no cover + return + + router = Router( + model_list=[ + { + "model_name": "openai/gpt-5.5", + "litellm_params": {"model": "openai/gpt-5.5", "api_key": "sk-test"}, + } + ] + ) + wrapped = await router._aresponses_streaming_iterator( + response=source, # type: ignore[arg-type] + initial_kwargs={}, + ) + captured["wrapper_cls"] = type(wrapped) + captured["instance"] = wrapped + + asyncio.run(_drive()) + return captured["wrapper_cls"], captured["instance"] + + +def _terminal_chunk(event_type: str): + """A SimpleNamespace shaped like the openai responses-api terminal + event chunks the wrapper inspects (.type attribute).""" + return SimpleNamespace( + type=event_type, + response=SimpleNamespace( + id="resp_test", + output=[], + container={"id": "cntr_test", "type": "code_interpreter"}, + ), + ) + + +def _non_terminal_chunk(event_type: str = "response.output_text.delta"): + return SimpleNamespace(type=event_type, delta="hello") + + +class TestStreamWrapperCapturesTerminalEvent: + def test_terminal_completed_event_is_recorded_on_wrapper(self): + """The #30210 bug: a forwarded ``response.completed`` chunk used + to leave ``completed_response`` at None on the wrapper. Verify + it now carries the chunk.""" + wrapper_cls, _ = _make_wrapper_class() + + async def gen(): + yield _non_terminal_chunk() + yield _terminal_chunk("response.completed") + + wrapper = wrapper_cls(gen()) + # Drain the wrapper. + out = asyncio.run(_drain(wrapper)) + assert len(out) == 2 + assert wrapper.completed_response is not None, ( + "FallbackResponsesStreamWrapper.completed_response is still None " + "after a response.completed chunk passed through — the proxy " + "container-ownership hook will 403 follow-up file lookups (#30210)" + ) + assert wrapper.completed_response.type == "response.completed" + + def test_terminal_incomplete_event_is_recorded(self): + wrapper_cls, _ = _make_wrapper_class() + + async def gen(): + yield _terminal_chunk("response.incomplete") + + wrapper = wrapper_cls(gen()) + asyncio.run(_drain(wrapper)) + assert wrapper.completed_response is not None + assert wrapper.completed_response.type == "response.incomplete" + + def test_terminal_failed_event_is_recorded(self): + wrapper_cls, _ = _make_wrapper_class() + + async def gen(): + yield _terminal_chunk("response.failed") + + wrapper = wrapper_cls(gen()) + asyncio.run(_drain(wrapper)) + assert wrapper.completed_response is not None + assert wrapper.completed_response.type == "response.failed" + + def test_non_terminal_chunks_do_not_set_completed_response(self): + wrapper_cls, _ = _make_wrapper_class() + + async def gen(): + yield _non_terminal_chunk("response.output_text.delta") + yield _non_terminal_chunk("response.code_interpreter.in_progress") + + wrapper = wrapper_cls(gen()) + asyncio.run(_drain(wrapper)) + assert ( + wrapper.completed_response is None + ), "non-terminal chunks must not set completed_response" + + def test_first_terminal_event_wins(self): + """Real streams only emit one terminal event, but defend against + future producers emitting more: keep the first one (the inner + source iterator behaves the same way).""" + wrapper_cls, _ = _make_wrapper_class() + + first = _terminal_chunk("response.completed") + first.response.id = "resp_first" + second = _terminal_chunk("response.completed") + second.response.id = "resp_second" + + async def gen(): + yield first + yield second + + wrapper = wrapper_cls(gen()) + asyncio.run(_drain(wrapper)) + assert wrapper.completed_response.response.id == "resp_first" + + +class TestProxyOwnershipHookReadsCompletedResponse: + """End-to-end: the proxy hook reads exactly the attribute the + wrapper now populates. Pin that the helper still extracts the + response correctly so the ownership recording path doesn't break.""" + + def test_extract_returns_inner_response_object(self): + from litellm.proxy.common_request_processing import ( + ProxyBaseLLMRequestProcessing, + ) + + wrapper_cls, _ = _make_wrapper_class() + + async def gen(): + yield _terminal_chunk("response.completed") + + wrapper = wrapper_cls(gen()) + asyncio.run(_drain(wrapper)) + + extracted = ProxyBaseLLMRequestProcessing._extract_completed_responses_response( + wrapper + ) + assert extracted is not None + assert extracted.id == "resp_test" + assert extracted.container["id"] == "cntr_test" + + +class TestSilentSkipNowLogged: + """Reporter's secondary ask: when completed_response is None, the + ownership hook silently dropped on the floor. Make sure the new + warning fires so operators see a hint instead of a mute 403.""" + + def test_warning_logged_when_completed_response_missing(self, caplog): + import logging + from litellm.proxy.common_request_processing import ( + ProxyBaseLLMRequestProcessing, + ) + + # Wrap a generator that produces NO terminal event so the + # wrapper stays at completed_response=None — same shape as the + # pre-fix bug. + wrapper_cls, _ = _make_wrapper_class() + + async def gen(): + yield _non_terminal_chunk() + + wrapper = wrapper_cls(gen()) + + async def driver(): + async def inner_gen(): + async for c in wrapper: + yield c + + # Patch _record_container_owners_from_responses_if_needed to + # a noop async so the warning branch is exercised in + # isolation. + with patch.object( + ProxyBaseLLMRequestProcessing, + "_record_container_owners_from_responses_if_needed", + new=MagicMock(), + ): + wrapped = ProxyBaseLLMRequestProcessing._wrap_responses_stream_for_container_ownership( + original_stream_response=wrapper, + wrapped_generator=inner_gen(), + user_api_key_dict=MagicMock(), + ) + async for _ in wrapped: + pass + + with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"): + asyncio.run(driver()) + + assert any( + "Container ownership recording skipped on streaming /v1/responses" + in r.message + for r in caplog.records + ), "silent-skip warning never fired despite completed_response=None" + + +async def _drain(it): + out = [] + async for chunk in it: + out.append(chunk) + return out diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts index d95a918a3b05..ef1b6e669f8b 100644 --- a/ui/litellm-dashboard/src/lib/http/schema.d.ts +++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts @@ -24993,6 +24993,8 @@ export interface components { aws_region_name?: string | null; /** Aws Secret Access Key */ aws_secret_access_key?: string | null; + /** Azure Ad Token */ + azure_ad_token?: string | null; /** Budget Duration */ budget_duration?: string | null; /** Cache Creation Input Audio Token Cost */ @@ -32632,6 +32634,8 @@ export interface components { aws_region_name?: string | null; /** Aws Secret Access Key */ aws_secret_access_key?: string | null; + /** Azure Ad Token */ + azure_ad_token?: string | null; /** Budget Duration */ budget_duration?: string | null; /** Cache Creation Input Audio Token Cost */ From 9c775e7304cb33a89a09bb9be31404c6230e633b Mon Sep 17 00:00:00 2001 From: Mateo Wang <277851410+mateo-berri@users.noreply.github.com> Date: Tue, 16 Jun 2026 12:07:22 -0700 Subject: [PATCH 6/7] ci(lint): add blanket-noqa, dataclass-default, and unused-noqa Ruff rules (#30516) * ci(lint): enforce blanket-noqa, dataclass-default, and unused-noqa rules Enable PGH004 (blanket-noqa), RUF008 (mutable-dataclass-default), RUF009 (function-call-in-dataclass-default-argument), and RUF100 (unused-noqa) in ruff.toml, and clean up every resulting violation. RUF008/RUF009 were already clean. PGH004/RUF100 surfaced ~335 stale or blanket noqas: blanket `# noqa` are now scoped to the rule they actually suppress (mostly T201), dead directives are removed, and inapplicable codes are trimmed (e.g. F401 dropped from `import *`). lint.external lists rules enforced outside this config (the strict-rule gate via ruff-strict.toml and upstream litellm's own ruff config) so RUF100 keeps the noqa directives that protect them instead of stripping coverage this config can't see. * ci(lint): trim RUF100 external list to load-bearing codes only Drop the 9 precautionary strict-gate codes (ANN001/002/003/401, B006, PLR0913, PLW0603, RUF012, TID251) that have zero `# noqa` references in the gated source. Keep only the 11 codes with live suppressions so RUF100 doesn't flag them as unused. Future strict-gate suppressions can re-add codes here (or fix the underlying issue) as needed. --- litellm/_logging.py | 2 +- litellm/_redis.py | 2 +- litellm/caching/caching.py | 4 +- .../transformation.py | 2 +- .../SlackAlerting/slack_alerting.py | 2 +- litellm/integrations/lunary.py | 6 +- .../websearch_interception/handler.py | 4 +- litellm/integrations/weights_biases.py | 7 +- .../exception_mapping_utils.py | 16 ++-- .../get_llm_provider_logic.py | 10 +-- litellm/litellm_core_utils/litellm_logging.py | 2 +- .../litellm_core_utils/streaming_handler.py | 4 +- litellm/llms/azure/azure.py | 2 +- litellm/llms/azure/completion/handler.py | 2 +- .../base_invoke_transformation.py | 2 +- litellm/llms/bytez/chat/transformation.py | 2 +- litellm/llms/sagemaker/completion/handler.py | 2 +- .../llms/vertex_ai/vertex_ai_non_gemini.py | 2 +- litellm/main.py | 4 +- .../proxy/anthropic_endpoints/endpoints.py | 2 +- litellm/proxy/auth/login_utils.py | 2 +- litellm/proxy/common_utils/debug_utils.py | 8 +- litellm/proxy/db/check_migration.py | 2 +- .../guardrails/guardrail_hooks/presidio.py | 4 +- litellm/proxy/hooks/batch_redis_get.py | 2 +- .../proxy/hooks/parallel_request_limiter.py | 4 +- .../proxy/hooks/prompt_injection_detection.py | 2 +- .../internal_user_endpoints.py | 4 +- .../key_management_endpoints.py | 6 +- .../policy_endpoints/__init__.py | 2 +- .../management_endpoints/team_endpoints.py | 2 +- litellm/proxy/management_endpoints/ui_sso.py | 6 +- .../cohere_passthrough_logging_handler.py | 2 +- litellm/proxy/post_call_rules.py | 2 +- litellm/proxy/proxy_cli.py | 80 +++++++++---------- litellm/proxy/proxy_server.py | 76 +++++++++--------- litellm/proxy/utils.py | 10 +-- litellm/router.py | 2 +- .../evals/eval_complexity_router.py | 48 +++++------ litellm/router_strategy/lowest_tpm_rpm_v2.py | 2 +- litellm/utils.py | 4 +- litellm/videos/main.py | 8 +- ruff.toml | 12 ++- 43 files changed, 188 insertions(+), 181 deletions(-) diff --git a/litellm/_logging.py b/litellm/_logging.py index 6b99f50e0140..bb743c328781 100644 --- a/litellm/_logging.py +++ b/litellm/_logging.py @@ -419,7 +419,7 @@ def _enable_debugging(): def print_verbose(print_statement): try: if set_verbose: - print(redact_secrets(str(print_statement))) # noqa + print(redact_secrets(str(print_statement))) # noqa: T201 except Exception: pass diff --git a/litellm/_redis.py b/litellm/_redis.py index 5ab551453bb3..e2b04f795cb4 100644 --- a/litellm/_redis.py +++ b/litellm/_redis.py @@ -567,7 +567,7 @@ def get_redis_client(**env_overrides): return redis.Redis(**redis_kwargs) -def get_redis_async_client( # noqa: PLR0915 +def get_redis_async_client( connection_pool: Optional[async_redis.BlockingConnectionPool] = None, **env_overrides, ) -> Union[async_redis.Redis, async_redis.RedisCluster]: diff --git a/litellm/caching/caching.py b/litellm/caching/caching.py index b6cfc8e79072..997ad10bc33b 100644 --- a/litellm/caching/caching.py +++ b/litellm/caching/caching.py @@ -27,7 +27,7 @@ from .azure_blob_cache import AzureBlobCache from .base_cache import BaseCache from .disk_cache import DiskCache -from .dual_cache import DualCache # noqa +from .dual_cache import DualCache # noqa: F401 from .gcs_cache import GCSCache from .in_memory_cache import InMemoryCache from .qdrant_semantic_cache import QdrantSemanticCache @@ -41,7 +41,7 @@ def print_verbose(print_statement): try: verbose_logger.debug(print_statement) if litellm.set_verbose: - print(print_statement) # noqa + print(print_statement) # noqa: T201 except Exception: pass diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py index 78826f822bc0..dabf09f8b2a4 100644 --- a/litellm/completion_extras/litellm_responses_transformation/transformation.py +++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py @@ -693,7 +693,7 @@ def _recover_output_items_from_logging( original_response = model_call_details.get("original_response") return cls._recover_output_items_from_raw_sse(original_response) - def transform_response( # noqa: PLR0915 + def transform_response( self, model: str, raw_response: "BaseModel", diff --git a/litellm/integrations/SlackAlerting/slack_alerting.py b/litellm/integrations/SlackAlerting/slack_alerting.py index 390af2cb6e64..e7be004e62e4 100644 --- a/litellm/integrations/SlackAlerting/slack_alerting.py +++ b/litellm/integrations/SlackAlerting/slack_alerting.py @@ -1179,7 +1179,7 @@ async def send_webhook_alert(self, webhook_event: WebhookEvent) -> bool: if response.status_code == 200: return True else: - print("Error sending webhook alert. Error=", response.text) # noqa + print("Error sending webhook alert. Error=", response.text) # noqa: T201 return False diff --git a/litellm/integrations/lunary.py b/litellm/integrations/lunary.py index b24a24e08812..7b1cbc32d43e 100644 --- a/litellm/integrations/lunary.py +++ b/litellm/integrations/lunary.py @@ -75,16 +75,16 @@ def __init__(self): version = importlib.metadata.version("lunary") # type: ignore # if version < 0.1.43 then raise ImportError if packaging.version.Version(version) < packaging.version.Version("0.1.43"): # type: ignore - print( # noqa + print( # noqa: T201 "Lunary version outdated. Required: >= 0.1.43. Upgrade via 'pip install lunary --upgrade'" ) raise ImportError self.lunary_client = lunary except ImportError: - print( # noqa + print( # noqa: T201 "Lunary not installed. Please install it using 'pip install lunary'" - ) # noqa + ) raise ImportError def log_event( diff --git a/litellm/integrations/websearch_interception/handler.py b/litellm/integrations/websearch_interception/handler.py index 79f9b16bba01..f29b378fcdec 100644 --- a/litellm/integrations/websearch_interception/handler.py +++ b/litellm/integrations/websearch_interception/handler.py @@ -1128,7 +1128,7 @@ async def _execute_search(self, query: str) -> Tuple[str, Optional[SearchRespons ) raise - async def _execute_chat_completion_agentic_loop( # noqa: PLR0915 + async def _execute_chat_completion_agentic_loop( self, model: str, messages: List[Dict], @@ -1159,7 +1159,7 @@ async def _execute_chat_completion_agentic_loop( # noqa: PLR0915 **request_patch.kwargs, ) - async def _build_chat_completion_request_patch( # noqa: PLR0915 + async def _build_chat_completion_request_patch( self, model: str, messages: List[Dict], diff --git a/litellm/integrations/weights_biases.py b/litellm/integrations/weights_biases.py index e9539d27e97e..5f087fe219a2 100644 --- a/litellm/integrations/weights_biases.py +++ b/litellm/integrations/weights_biases.py @@ -21,10 +21,11 @@ class OpenAIResponse(Protocol[K, V]): # type: ignore # contains a (known) object attribute object: Literal["chat.completion", "edit", "text_completion"] - def __getitem__(self, key: K) -> V: ... # noqa + def __getitem__(self, key: K) -> V: ... - def get(self, key: K, default: Optional[V] = None) -> Optional[V]: # noqa - ... # pragma: no cover + def get( + self, key: K, default: Optional[V] = None + ) -> Optional[V]: ... # pragma: no cover class OpenAIRequestResponseResolver: def __call__( diff --git a/litellm/litellm_core_utils/exception_mapping_utils.py b/litellm/litellm_core_utils/exception_mapping_utils.py index ffaa51409167..0d35da9fa1a7 100644 --- a/litellm/litellm_core_utils/exception_mapping_utils.py +++ b/litellm/litellm_core_utils/exception_mapping_utils.py @@ -250,14 +250,14 @@ def exception_type( # type: ignore # noqa: PLR0915 exception_mapping_worked = False exception_provider = custom_llm_provider if litellm.suppress_debug_info is False: - print() # noqa - print( # noqa - "\033[1;31mGive Feedback / Get Help: https://github.com/BerriAI/litellm/issues/new\033[0m" # noqa - ) # noqa - print( # noqa - "LiteLLM.Info: If you need to debug this error, use `litellm._turn_on_debug()'." # noqa - ) # noqa - print() # noqa + print() # noqa: T201 + print( # noqa: T201 + "\033[1;31mGive Feedback / Get Help: https://github.com/BerriAI/litellm/issues/new\033[0m" + ) + print( # noqa: T201 + "LiteLLM.Info: If you need to debug this error, use `litellm._turn_on_debug()'." + ) + print() # noqa: T201 litellm_response_headers = _get_response_headers( original_exception=original_exception diff --git a/litellm/litellm_core_utils/get_llm_provider_logic.py b/litellm/litellm_core_utils/get_llm_provider_logic.py index 80ee406b7e7f..182c5117a3ee 100644 --- a/litellm/litellm_core_utils/get_llm_provider_logic.py +++ b/litellm/litellm_core_utils/get_llm_provider_logic.py @@ -529,11 +529,11 @@ def get_llm_provider( # noqa: PLR0915 custom_llm_provider = "sap" if not custom_llm_provider: if litellm.suppress_debug_info is False: - print() # noqa - print( # noqa - "\033[1;31mProvider List: https://docs.litellm.ai/docs/providers\033[0m" # noqa - ) # noqa - print() # noqa + print() # noqa: T201 + print( # noqa: T201 + "\033[1;31mProvider List: https://docs.litellm.ai/docs/providers\033[0m" + ) + print() # noqa: T201 error_str = f"LLM Provider NOT provided. Pass in the LLM provider you are trying to call. You passed model={model}\n Pass model as E.g. For 'Huggingface' inference endpoints pass in `completion(model='huggingface/starcoder',..)` Learn more: https://docs.litellm.ai/docs/providers" # maps to openai.NotFoundError, this is raised when openai does not recognize the llm raise litellm.exceptions.BadRequestError( # type: ignore diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py index 2cc8e794d40a..3c525f743ede 100644 --- a/litellm/litellm_core_utils/litellm_logging.py +++ b/litellm/litellm_core_utils/litellm_logging.py @@ -5893,7 +5893,7 @@ def get_standard_logging_object_payload( def emit_standard_logging_payload(payload: StandardLoggingPayload): if os.getenv("LITELLM_PRINT_STANDARD_LOGGING_PAYLOAD"): - print(json.dumps(payload, indent=4)) # noqa + print(json.dumps(payload, indent=4)) # noqa: T201 def get_standard_logging_metadata( diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.py index 2d0bd88c79f9..7e4bf895a799 100644 --- a/litellm/litellm_core_utils/streaming_handler.py +++ b/litellm/litellm_core_utils/streaming_handler.py @@ -92,7 +92,7 @@ def is_async_iterable(obj: Any) -> bool: def print_verbose(print_statement): try: if litellm.set_verbose: - print(print_statement) # noqa + print(print_statement) # noqa: T201 except Exception: pass @@ -967,7 +967,7 @@ def _handle_special_delta_attributes( delta, model_response.choices[0].delta, attribute ) - def return_processed_chunk_logic( # noqa + def return_processed_chunk_logic( # noqa: PLR0915, C901 self, completion_obj: Dict[str, Any], model_response: ModelResponseStream, diff --git a/litellm/llms/azure/azure.py b/litellm/llms/azure/azure.py index 56cf035d0f71..5be3ce22832d 100644 --- a/litellm/llms/azure/azure.py +++ b/litellm/llms/azure/azure.py @@ -189,7 +189,7 @@ async def make_azure_openai_chat_completion_request( except Exception as e: raise e - def completion( # noqa: PLR0915 + def completion( self, model: str, messages: list, diff --git a/litellm/llms/azure/completion/handler.py b/litellm/llms/azure/completion/handler.py index 05d5e2f6c68e..b8d1ad71d46b 100644 --- a/litellm/llms/azure/completion/handler.py +++ b/litellm/llms/azure/completion/handler.py @@ -25,7 +25,7 @@ def validate_environment(self, api_key, azure_ad_token): headers["Authorization"] = f"Bearer {azure_ad_token}" return headers - def completion( # noqa: PLR0915 + def completion( self, model: str, messages: list, diff --git a/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py index 6bb2da1ad448..8fc2375c224c 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py @@ -257,7 +257,7 @@ def transform_request( return request_data - def transform_response( # noqa: PLR0915 + def transform_response( self, model: str, raw_response: httpx.Response, diff --git a/litellm/llms/bytez/chat/transformation.py b/litellm/llms/bytez/chat/transformation.py index 5b08670f9f28..7d9afe01fa6f 100644 --- a/litellm/llms/bytez/chat/transformation.py +++ b/litellm/llms/bytez/chat/transformation.py @@ -191,7 +191,7 @@ def transform_response( api_key: Optional[str] = None, json_mode: Optional[bool] = None, ) -> ModelResponse: - json = raw_response.json() # noqa: F811 + json = raw_response.json() error = json.get("error") diff --git a/litellm/llms/sagemaker/completion/handler.py b/litellm/llms/sagemaker/completion/handler.py index de7be18e8bad..aa4663666c23 100644 --- a/litellm/llms/sagemaker/completion/handler.py +++ b/litellm/llms/sagemaker/completion/handler.py @@ -138,7 +138,7 @@ def _prepare_request( return prepped_request - def completion( # noqa: PLR0915 + def completion( self, model: str, messages: list, diff --git a/litellm/llms/vertex_ai/vertex_ai_non_gemini.py b/litellm/llms/vertex_ai/vertex_ai_non_gemini.py index cfbab584f6ad..222820d7ee51 100644 --- a/litellm/llms/vertex_ai/vertex_ai_non_gemini.py +++ b/litellm/llms/vertex_ai/vertex_ai_non_gemini.py @@ -650,7 +650,7 @@ async def async_completion( # noqa: PLR0915 raise VertexAIError(status_code=500, message=str(e)) -async def async_streaming( # noqa: PLR0915 +async def async_streaming( llm_model, mode: str, prompt: str, diff --git a/litellm/main.py b/litellm/main.py index 18dcdfcd6beb..a1bade9bb1fc 100644 --- a/litellm/main.py +++ b/litellm/main.py @@ -392,7 +392,7 @@ async def create(self, messages, model=None, **kwargs): @tracer.wrap() @client -async def acompletion( # noqa: PLR0915 +async def acompletion( model: str, # Optional OpenAI params: see https://platform.openai.com/docs/api-reference/chat/create messages: List = [], @@ -7572,7 +7572,7 @@ def print_verbose(print_statement): try: verbose_logger.debug(print_statement) if litellm.set_verbose: - print(print_statement) # noqa + print(print_statement) # noqa: T201 except Exception: pass diff --git a/litellm/proxy/anthropic_endpoints/endpoints.py b/litellm/proxy/anthropic_endpoints/endpoints.py index 900386f3d7b3..1995ff275c9d 100644 --- a/litellm/proxy/anthropic_endpoints/endpoints.py +++ b/litellm/proxy/anthropic_endpoints/endpoints.py @@ -28,7 +28,7 @@ tags=["[beta] Anthropic `/v1/messages`"], dependencies=[Depends(user_api_key_auth)], ) -async def anthropic_response( # noqa: PLR0915 +async def anthropic_response( fastapi_response: Response, request: Request, user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), diff --git a/litellm/proxy/auth/login_utils.py b/litellm/proxy/auth/login_utils.py index d0818b953634..bd2e75604306 100644 --- a/litellm/proxy/auth/login_utils.py +++ b/litellm/proxy/auth/login_utils.py @@ -103,7 +103,7 @@ def __init__( self.login_method = login_method -async def authenticate_user( # noqa: PLR0915 +async def authenticate_user( username: str, password: str, master_key: Optional[str], diff --git a/litellm/proxy/common_utils/debug_utils.py b/litellm/proxy/common_utils/debug_utils.py index 9b2c3ddce46f..4cc62e1adbd4 100644 --- a/litellm/proxy/common_utils/debug_utils.py +++ b/litellm/proxy/common_utils/debug_utils.py @@ -92,12 +92,12 @@ async def get_active_tasks_stats(): try: import objgraph # type: ignore - print("growth of objects") # noqa + print("growth of objects") # noqa: T201 objgraph.show_growth() - print("\n\nMost common types") # noqa + print("\n\nMost common types") # noqa: T201 objgraph.show_most_common_types() roots = objgraph.get_leaking_objects() - print("\n\nLeaking objects") # noqa + print("\n\nLeaking objects") # noqa: T201 objgraph.show_most_common_types(objects=roots) except ImportError: raise ImportError( @@ -739,7 +739,7 @@ async def get_otel_spans(): else: recorded_spans = [] - print("Spans: ", recorded_spans) # noqa + print("Spans: ", recorded_spans) # noqa: T201 most_recent_parent = None most_recent_start_time = 1000000 diff --git a/litellm/proxy/db/check_migration.py b/litellm/proxy/db/check_migration.py index bf180c1132d4..2aacaed8aff1 100644 --- a/litellm/proxy/db/check_migration.py +++ b/litellm/proxy/db/check_migration.py @@ -54,7 +54,7 @@ def check_prisma_schema_diff_helper(db_url: str) -> Tuple[bool, List[str]]: subprocess.CalledProcessError: If the Prisma command fails. Exception: For any other errors during execution. """ - verbose_logger.debug("Checking for Prisma schema diff...") # noqa: T201 + verbose_logger.debug("Checking for Prisma schema diff...") try: result = subprocess.run( [ diff --git a/litellm/proxy/guardrails/guardrail_hooks/presidio.py b/litellm/proxy/guardrails/guardrail_hooks/presidio.py index e723c07e3c46..7d6d1adb05e7 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/presidio.py +++ b/litellm/proxy/guardrails/guardrail_hooks/presidio.py @@ -28,7 +28,7 @@ import aiohttp -import litellm # noqa: E401 +import litellm from litellm import get_secret from litellm._logging import verbose_proxy_logger from litellm.types.utils import GenericGuardrailAPIInputs @@ -1432,7 +1432,7 @@ def print_verbose(self, print_statement): try: verbose_proxy_logger.debug(print_statement) if litellm.set_verbose: - print(print_statement) # noqa + print(print_statement) # noqa: T201 except Exception: pass diff --git a/litellm/proxy/hooks/batch_redis_get.py b/litellm/proxy/hooks/batch_redis_get.py index c608317f4ebe..f734b19681da 100644 --- a/litellm/proxy/hooks/batch_redis_get.py +++ b/litellm/proxy/hooks/batch_redis_get.py @@ -33,7 +33,7 @@ def print_verbose( elif debug_level == "INFO": verbose_proxy_logger.debug(print_statement) if litellm.set_verbose is True: - print(print_statement) # noqa + print(print_statement) # noqa: T201 async def async_pre_call_hook( self, diff --git a/litellm/proxy/hooks/parallel_request_limiter.py b/litellm/proxy/hooks/parallel_request_limiter.py index 874e5aa19391..23af23e78bd2 100644 --- a/litellm/proxy/hooks/parallel_request_limiter.py +++ b/litellm/proxy/hooks/parallel_request_limiter.py @@ -50,7 +50,7 @@ def print_verbose(self, print_statement): try: verbose_proxy_logger.debug(print_statement) if litellm.set_verbose: - print(print_statement) # noqa + print(print_statement) # noqa: T201 except Exception: pass @@ -769,7 +769,7 @@ async def async_log_success_event( # noqa: PLR0915 litellm_parent_otel_span=litellm_parent_otel_span, ) except Exception as e: - self.print_verbose(e) # noqa + self.print_verbose(e) async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): try: diff --git a/litellm/proxy/hooks/prompt_injection_detection.py b/litellm/proxy/hooks/prompt_injection_detection.py index f1b688948f29..6678ccd7e0b2 100644 --- a/litellm/proxy/hooks/prompt_injection_detection.py +++ b/litellm/proxy/hooks/prompt_injection_detection.py @@ -72,7 +72,7 @@ def print_verbose(self, print_statement, level: Literal["INFO", "DEBUG"] = "DEBU verbose_proxy_logger.debug(print_statement) if litellm.set_verbose is True: - print(print_statement) # noqa + print(print_statement) # noqa: T201 def update_environment(self, router: Optional[Router] = None): self.llm_router = router diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.py index b3a5c66e9e16..ba7013570fe4 100644 --- a/litellm/proxy/management_endpoints/internal_user_endpoints.py +++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py @@ -755,7 +755,7 @@ def _build_user_info_response( response_model=UserInfoResponse, ) @management_endpoint_wrapper -async def user_info( # noqa: PLR0915 +async def user_info( request: Request, user_id: Optional[str] = fastapi.Query( default=None, description="User ID in the request parameters" @@ -1082,7 +1082,7 @@ def _process_keys_for_user_info( continue try: - _key: dict = key.model_dump() # noqa + _key: dict = key.model_dump() except Exception: # if using pydantic v1 _key = key.dict() diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index c980f6f52605..b0210e1123fb 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -2428,7 +2428,7 @@ async def _validate_update_key_data( "/key/update", tags=["key management"], dependencies=[Depends(user_api_key_auth)] ) @management_endpoint_wrapper -async def update_key_fn( # noqa: PLR0915 +async def update_key_fn( request: Request, data: UpdateKeyRequest, user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), @@ -3377,7 +3377,7 @@ async def info_key_fn( ) ## REMOVE HASHED TOKEN INFO BEFORE RETURNING ## try: - key_info = key_info.model_dump() # noqa + key_info = key_info.model_dump() except Exception: # if using pydantic v1 key_info = key_info.dict() @@ -4412,7 +4412,7 @@ async def _execute_virtual_key_regeneration( dependencies=[Depends(user_api_key_auth)], ) @management_endpoint_wrapper -async def regenerate_key_fn( # noqa: PLR0915 +async def regenerate_key_fn( key: Optional[str] = None, data: Optional[RegenerateKeyRequest] = None, user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), diff --git a/litellm/proxy/management_endpoints/policy_endpoints/__init__.py b/litellm/proxy/management_endpoints/policy_endpoints/__init__.py index 157d15c27107..862c92bace98 100644 --- a/litellm/proxy/management_endpoints/policy_endpoints/__init__.py +++ b/litellm/proxy/management_endpoints/policy_endpoints/__init__.py @@ -7,7 +7,7 @@ are imported directly into this namespace. """ -from litellm.proxy.management_endpoints.policy_endpoints.endpoints import * # noqa: F401, F403 +from litellm.proxy.management_endpoints.policy_endpoints.endpoints import * # noqa: F403 from litellm.proxy.management_endpoints.policy_endpoints.endpoints import ( # noqa: F401 _build_all_names_per_competitor, _build_comparison_blocked_words, diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.py index 43a36fcb2f1b..85b640d6b6ce 100644 --- a/litellm/proxy/management_endpoints/team_endpoints.py +++ b/litellm/proxy/management_endpoints/team_endpoints.py @@ -3647,7 +3647,7 @@ async def team_info( ## REMOVE HASHED TOKEN INFO before returning ## for key in keys: try: - key = key.model_dump() # noqa + key = key.model_dump() except Exception: # if using pydantic v1 key = key.dict() diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.py index 4812bed2f21c..5af1dd321ed9 100644 --- a/litellm/proxy/management_endpoints/ui_sso.py +++ b/litellm/proxy/management_endpoints/ui_sso.py @@ -114,7 +114,7 @@ from litellm.repositories.team_repository import TeamRepository from litellm.repositories.user_repository import UserRepository from litellm.secret_managers.main import get_secret_bool, str_to_bool -from litellm.types.proxy.management_endpoints.ui_sso import * # noqa: F403, F401 +from litellm.types.proxy.management_endpoints.ui_sso import * # noqa: F403 from litellm.types.proxy.management_endpoints.ui_sso import ( DefaultTeamSSOParams, MicrosoftGraphAPIUserGroupDirectoryObject, @@ -829,7 +829,7 @@ async def google_login( key: Optional[str] = None, existing_key: Optional[str] = None, return_to: Optional[str] = None, -): # noqa: PLR0915 +): """ Create Proxy API Keys using Google Workspace SSO. Requires setting PROXY_BASE_URL in .env PROXY_BASE_URL should be the your deployed proxy endpoint, e.g. PROXY_BASE_URL="https://litellm-production-7002.up.railway.app/" @@ -1833,7 +1833,7 @@ async def check_and_update_if_proxy_admin_id( @router.get("/sso/callback", tags=["experimental"], include_in_schema=False) -async def auth_callback(request: Request, state: Optional[str] = None): # noqa: PLR0915 +async def auth_callback(request: Request, state: Optional[str] = None): """Verify login""" verbose_proxy_logger.info(f"Starting SSO callback with state: {state}") diff --git a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/cohere_passthrough_logging_handler.py b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/cohere_passthrough_logging_handler.py index adb1278fee5b..0875f1d55081 100644 --- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/cohere_passthrough_logging_handler.py +++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/cohere_passthrough_logging_handler.py @@ -71,7 +71,7 @@ def _build_complete_streaming_response( complete_streaming_response = stream_chunk_builder(chunks=all_openai_chunks) return complete_streaming_response - def cohere_passthrough_handler( # noqa: PLR0915 + def cohere_passthrough_handler( self, httpx_response: httpx.Response, response_body: dict, diff --git a/litellm/proxy/post_call_rules.py b/litellm/proxy/post_call_rules.py index 23ec93f5b30d..6200bee4d7b1 100644 --- a/litellm/proxy/post_call_rules.py +++ b/litellm/proxy/post_call_rules.py @@ -1,5 +1,5 @@ def post_response_rule(input): # receives the model response - print(f"post_response_rule:input={input}") # noqa + print(f"post_response_rule:input={input}") # noqa: T201 if len(input) < 200: return { "decision": False, diff --git a/litellm/proxy/proxy_cli.py b/litellm/proxy/proxy_cli.py index 8c3fa952903c..bd9746d2a471 100644 --- a/litellm/proxy/proxy_cli.py +++ b/litellm/proxy/proxy_cli.py @@ -102,9 +102,9 @@ def _echo_litellm_version(): @staticmethod def _run_health_check(host, port): - print("\nLiteLLM: Health Testing models in config") # noqa + print("\nLiteLLM: Health Testing models in config") response = httpx.get(url=f"http://{host}:{port}/health") - print(json.dumps(response.json(), indent=4)) # noqa + print(json.dumps(response.json(), indent=4)) @staticmethod def _run_test_chat_completion( @@ -138,7 +138,7 @@ def _run_test_chat_completion( ) click.echo(f"\nLiteLLM: response from proxy {response}") - print( # noqa + print( f"\n LiteLLM: Making a test ChatCompletions + streaming r equest to proxy. Model={request_model}" ) @@ -154,11 +154,11 @@ def _run_test_chat_completion( ) for chunk in stream_response: click.echo(f"LiteLLM: streaming response from proxy {chunk}") - print("\n making completion request to proxy") # noqa + print("\n making completion request to proxy") completion_response = client.completions.create( model=request_model, prompt="this is a test request, write a short poem" ) - print(completion_response) # noqa + print(completion_response) @staticmethod def _get_default_unvicorn_init_args( @@ -184,7 +184,7 @@ def _get_default_unvicorn_init_args( "port": port, } if log_config is not None: - print(f"Using log_config: {log_config}") # noqa + print(f"Using log_config: {log_config}") uvicorn_args["log_config"] = log_config elif litellm.json_logs: # Use JSON log config for uvicorn to ensure all logs (including exceptions) are JSON @@ -198,7 +198,7 @@ def _get_default_unvicorn_init_args( ): uvicorn_args["timeout_worker_healthcheck"] = timeout_worker_healthcheck else: - print( # noqa + print( f"\033[1;33mLiteLLM Proxy: --timeout_worker_healthcheck " f"requires uvicorn>=0.37.0, but installed uvicorn=={uvicorn.__version__}. " f"Ignoring the flag.\033[0m" @@ -304,15 +304,15 @@ def _init_hypercorn_server( from hypercorn.asyncio import serve from hypercorn.config import Config - print( # noqa - f"\033[1;32mLiteLLM Proxy: Starting server on {host}:{port} using Hypercorn\033[0m\n" # noqa - ) # noqa + print( + f"\033[1;32mLiteLLM Proxy: Starting server on {host}:{port} using Hypercorn\033[0m\n" + ) config = Config() config.bind = [f"{host}:{port}"] if ssl_certfile_path is not None and ssl_keyfile_path is not None: - print( # noqa - f"\033[1;32mLiteLLM Proxy: Using SSL with certfile: {ssl_certfile_path} and keyfile: {ssl_keyfile_path}\033[0m\n" # noqa + print( + f"\033[1;32mLiteLLM Proxy: Using SSL with certfile: {ssl_certfile_path} and keyfile: {ssl_keyfile_path}\033[0m\n" ) config.certfile = ssl_certfile_path config.keyfile = ssl_keyfile_path @@ -342,16 +342,16 @@ def _init_granian_server( from granian import Granian from granian.constants import Interfaces - print( # noqa + print( f"\033[1;32mLiteLLM Proxy: Starting server on {host}:{port} using Granian\033[0m\n" ) if max_requests_before_restart is not None: - print( # noqa + print( "\033[1;33mLiteLLM: --max_requests_before_restart is not supported by Granian " "(Granian uses workers_lifetime in seconds, not a per-request limit).\033[0m\n" ) if ciphers is not None: - print( # noqa + print( "\033[1;33mLiteLLM: --ciphers is not applied when using --run_granian.\033[0m\n" ) @@ -366,7 +366,7 @@ def _init_granian_server( if granian_runtime_threads is not None: kwargs["runtime_threads"] = granian_runtime_threads if ssl_certfile_path is not None and ssl_keyfile_path is not None: - print( # noqa + print( f"\033[1;32mLiteLLM Proxy: Using SSL with certfile: {ssl_certfile_path} and keyfile: {ssl_keyfile_path}\033[0m\n" ) kwargs["ssl_cert"] = Path(ssl_certfile_path) @@ -419,19 +419,19 @@ def __init__(self, app, options=None): }' \n """ - print() # noqa - print( # noqa + print() + print( '\033[1;34mLiteLLM: Test your local proxy with: "litellm --test" This runs an openai.ChatCompletion request to your proxy [In a new terminal tab]\033[0m\n' ) - print( # noqa + print( f"\033[1;34mLiteLLM: Curl Command Test for your local proxy\n {curl_command} \033[0m\n" ) - print( # noqa + print( "\033[1;34mDocs: https://docs.litellm.ai/docs/simple_proxy\033[0m\n" - ) # noqa - print( # noqa + ) + print( f"\033[1;34mSee all Router/Swagger docs on http://0.0.0.0:{port} \033[0m\n" - ) # noqa + ) def load_config(self): # note: This Loads the gunicorn config - has nothing to do with LiteLLM Proxy config @@ -451,8 +451,8 @@ def load(self): # gunicorn app function return self.application - print( # noqa - f"\033[1;32mLiteLLM Proxy: Starting server on {host}:{port} with {num_workers} workers\033[0m\n" # noqa + print( + f"\033[1;32mLiteLLM Proxy: Starting server on {host}:{port} with {num_workers} workers\033[0m\n" ) gunicorn_options = { "bind": f"{host}:{port}", @@ -478,8 +478,8 @@ def child_exit(server, worker): gunicorn_options["child_exit"] = child_exit if ssl_certfile_path is not None and ssl_keyfile_path is not None: - print( # noqa - f"\033[1;32mLiteLLM Proxy: Using SSL with certfile: {ssl_certfile_path} and keyfile: {ssl_keyfile_path}\033[0m\n" # noqa + print( + f"\033[1;32mLiteLLM Proxy: Using SSL with certfile: {ssl_certfile_path} and keyfile: {ssl_keyfile_path}\033[0m\n" ) gunicorn_options["certfile"] = ssl_certfile_path gunicorn_options["keyfile"] = ssl_keyfile_path @@ -496,7 +496,7 @@ def _run_ollama_serve(): except Exception as e: print(f""" LiteLLM Warning: proxy started with `ollama` model\n`ollama serve` failed with Exception{e}. \nEnsure you run `ollama serve` - """) # noqa # noqa + """) @staticmethod def _is_port_in_use(port): @@ -557,7 +557,7 @@ def _maybe_setup_prometheus_multiproc_dir( os.makedirs(multiproc_dir, exist_ok=True) wipe_directory(multiproc_dir) action = "Auto-created" if auto_created else "Using existing" - print(f"LiteLLM: {action} PROMETHEUS_MULTIPROC_DIR={multiproc_dir}") # noqa + print(f"LiteLLM: {action} PROMETHEUS_MULTIPROC_DIR={multiproc_dir}") @click.command() @@ -1185,7 +1185,7 @@ def run_server( # noqa: PLR0915 check_prisma_schema_diff(db_url=None) else: if not use_v2_migration_resolver: - print( # noqa + print( "\033[1;33mLiteLLM Proxy: Using default (v1) migration resolver. " "If your deployment has seen schema thrashing during rolling " "deploys, try --use_v2_migration_resolver (safer: avoids the " @@ -1201,7 +1201,7 @@ def run_server( # noqa: PLR0915 # (e.g. non-idempotent failures, permission issues). # v1 never raises here, so this only fires when the # operator opted into v2. - print( # noqa + print( "\033[1;31mLiteLLM Proxy: Database migration cannot proceed. " f"{e}\033[0m", file=sys.stderr, @@ -1210,19 +1210,19 @@ def run_server( # noqa: PLR0915 sys.exit(2) if not setup_ok: if enforce_prisma_migration_check: - print( # noqa + print( "\033[1;31mLiteLLM Proxy: Database setup failed after multiple retries. " "The proxy cannot start safely. Please check your database connection and migration status.\033[0m" ) sys.exit(1) else: - print( # noqa + print( "\033[1;33mLiteLLM Proxy: Database migration failed but continuing startup. " "Set --enforce_prisma_migration_check or ENFORCE_PRISMA_MIGRATION_CHECK=true to exit on failure.\033[0m" ) else: - print( # noqa - f"Unable to connect to DB. DATABASE_URL found in environment, but prisma package not found." # noqa + print( + f"Unable to connect to DB. DATABASE_URL found in environment, but prisma package not found." # noqa: F541 ) if port == 4000 and ProxyInitializationHelpers._is_port_in_use(port): port = random.randint(1024, 49152) @@ -1233,7 +1233,7 @@ def run_server( # noqa: PLR0915 litellm._turn_on_debug() # DO NOT DELETE - enables global variables to work across files - from litellm.proxy.proxy_server import app # noqa + from litellm.proxy.proxy_server import app # Auto-create PROMETHEUS_MULTIPROC_DIR for multi-worker setups ProxyInitializationHelpers._maybe_setup_prometheus_multiproc_dir( @@ -1243,9 +1243,7 @@ def run_server( # noqa: PLR0915 # Skip server startup if requested (after all setup is done) if skip_server_startup: - print( # noqa - "LiteLLM: Setup complete. Skipping server startup as requested." - ) + print("LiteLLM: Setup complete. Skipping server startup as requested.") return running_uvicorn = run_gunicorn is False and run_hypercorn is False @@ -1263,8 +1261,8 @@ def run_server( # noqa: PLR0915 uvicorn_args["limit_max_requests"] = max_requests_before_restart if run_gunicorn is False and run_hypercorn is False and run_granian is False: if ssl_certfile_path is not None and ssl_keyfile_path is not None: - print( # noqa - f"\033[1;32mLiteLLM Proxy: Using SSL with certfile: {ssl_certfile_path} and keyfile: {ssl_keyfile_path}\033[0m\n" # noqa + print( + f"\033[1;32mLiteLLM Proxy: Using SSL with certfile: {ssl_certfile_path} and keyfile: {ssl_keyfile_path}\033[0m\n" ) uvicorn_args["ssl_keyfile"] = ssl_keyfile_path uvicorn_args["ssl_certfile"] = ssl_certfile_path diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py index 0d6374fec690..1f765aa8d633 100644 --- a/litellm/proxy/proxy_server.py +++ b/litellm/proxy/proxy_server.py @@ -180,26 +180,26 @@ def generate_feedback_box(): # Select a random message message = random.choice(list_of_messages) - print() # noqa - print("\033[1;37m" + "#" + "-" * box_width + "#\033[0m") # noqa - print("\033[1;37m" + "#" + " " * box_width + "#\033[0m") # noqa - print("\033[1;37m" + "# {:^59} #\033[0m".format(message)) # noqa - print( # noqa + print() # noqa: T201 + print("\033[1;37m" + "#" + "-" * box_width + "#\033[0m") # noqa: T201 + print("\033[1;37m" + "#" + " " * box_width + "#\033[0m") # noqa: T201 + print("\033[1;37m" + "# {:^59} #\033[0m".format(message)) # noqa: T201 + print( # noqa: T201 "\033[1;37m" + "# {:^59} #\033[0m".format("https://github.com/BerriAI/litellm/issues/new") - ) # noqa - print("\033[1;37m" + "#" + " " * box_width + "#\033[0m") # noqa - print("\033[1;37m" + "#" + "-" * box_width + "#\033[0m") # noqa - print() # noqa - print(" Thank you for using LiteLLM! - Krrish & Ishaan") # noqa - print() # noqa - print() # noqa - print() # noqa - print( # noqa + ) + print("\033[1;37m" + "#" + " " * box_width + "#\033[0m") # noqa: T201 + print("\033[1;37m" + "#" + "-" * box_width + "#\033[0m") # noqa: T201 + print() # noqa: T201 + print(" Thank you for using LiteLLM! - Krrish & Ishaan") # noqa: T201 + print() # noqa: T201 + print() # noqa: T201 + print() # noqa: T201 + print( # noqa: T201 "\033[1;31mGive Feedback / Get Help: https://github.com/BerriAI/litellm/issues/new\033[0m" - ) # noqa - print() # noqa - print() # noqa + ) + print() # noqa: T201 + print() # noqa: T201 import contextlib @@ -3805,9 +3805,9 @@ def parse_search_tools(self, config: dict) -> Optional[List[SearchToolTypedDict] search_tools_parsed: List[SearchToolTypedDict] = [] - print( # noqa + print( # noqa: T201 "\033[32mLiteLLM: Proxy initialized with Search Tools:\033[0m" - ) # noqa + ) for search_tool in search_tools_raw: # Display loaded search tool @@ -3815,7 +3815,9 @@ def parse_search_tools(self, config: dict) -> Optional[List[SearchToolTypedDict] search_provider = search_tool.get("litellm_params", {}).get( "search_provider", "" ) - print(f"\033[32m {search_tool_name} ({search_provider})\033[0m") # noqa + print( # noqa: T201 + f"\033[32m {search_tool_name} ({search_provider})\033[0m" + ) # Handle os.environ/ variables in litellm_params litellm_params = search_tool.get("litellm_params", {}) @@ -3925,7 +3927,7 @@ async def load_config( # noqa: PLR0915 reset_color_code = "\033[0m" for key, value in litellm_settings.items(): if key == "cache" and value is True: - print(f"{blue_color_code}\nSetting Cache on Proxy") # noqa + print(f"{blue_color_code}\nSetting Cache on Proxy") # noqa: T201 from litellm.caching.caching import Cache cache_params = {} @@ -4120,9 +4122,9 @@ async def load_config( # noqa: PLR0915 "mounting metrics endpoint" ) PrometheusLogger._mount_metrics_endpoint() - print( # noqa + print( # noqa: T201 f"{blue_color_code} Initialized Success Callbacks - {litellm.success_callback} {reset_color_code}" - ) # noqa + ) elif key == "failure_callback": litellm.failure_callback = [] @@ -4141,9 +4143,9 @@ async def load_config( # noqa: PLR0915 litellm.logging_callback_manager.add_litellm_failure_callback( callback ) - print( # noqa + print( # noqa: T201 f"{blue_color_code} Initialized Failure Callbacks - {litellm.failure_callback} {reset_color_code}" - ) # noqa + ) elif key == "audit_log_callbacks": from litellm.proxy.management_helpers.audit_logs import ( reset_audit_log_callback_cache, @@ -4167,9 +4169,9 @@ async def load_config( # noqa: PLR0915 "store_audit_logs", litellm.store_audit_logs ) if _store_audit_logs: - print( # noqa + print( # noqa: T201 f"{blue_color_code} Initialized Audit Log Callbacks - {litellm.audit_log_callbacks} {reset_color_code}" - ) # noqa + ) else: verbose_proxy_logger.warning( "'audit_log_callbacks' is configured but 'store_audit_logs' is not enabled. " @@ -4516,15 +4518,15 @@ async def load_config( # noqa: PLR0915 model_list = config.get("model_list", None) if model_list: router_params["model_list"] = model_list - print( # noqa + print( # noqa: T201 "\033[32mLiteLLM: Proxy initialized with Config, Set models:\033[0m" - ) # noqa + ) for model in model_list: ### LOAD FROM os.environ/ ### for k, v in model["litellm_params"].items(): if isinstance(v, str) and v.startswith("os.environ/"): model["litellm_params"][k] = get_secret(v) - print(f"\033[32m {model.get('model_name', '')}\033[0m") # noqa + print(f"\033[32m {model.get('model_name', '')}\033[0m") # noqa: T201 litellm_model_name = model["litellm_params"]["model"] litellm_model_api_base = model["litellm_params"].get("api_base", None) if "ollama" in litellm_model_name and litellm_model_api_base is None: @@ -7996,7 +7998,7 @@ async def _initialize_slack_alerting_jobs( and proxy_logging_obj.slack_alerting_instance.alerting is not None and prisma_client is not None ): - print("Alerting: Initializing Weekly/Monthly Spend Reports") # noqa + print("Alerting: Initializing Weekly/Monthly Spend Reports") # noqa: T201 spend_report_frequency: str = ( general_settings.get("spend_report_frequency", "7d") or "7d" ) @@ -8490,7 +8492,7 @@ async def model_info( tags=["chat/completions"], responses={200: {"description": "Successful response"}, **ERROR_RESPONSES}, ) # azure compatible endpoint -async def chat_completion( # noqa: PLR0915 +async def chat_completion( request: Request, fastapi_response: Response, model: Optional[str] = None, @@ -8894,7 +8896,7 @@ async def completion( # noqa: PLR0915 response_class=ORJSONResponse, tags=["embeddings"], ) # azure compatible endpoint -async def embeddings( # noqa: PLR0915 +async def embeddings( request: Request, fastapi_response: Response, model: Optional[str] = None, @@ -12640,7 +12642,7 @@ def _get_proxy_model_info(model: dict) -> dict: tags=["model management"], dependencies=[Depends(user_api_key_auth)], ) -async def model_info_v1( # noqa: PLR0915 +async def model_info_v1( user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth), litellm_model_id: Optional[str] = None, include_team_models: Optional[bool] = fastapi.Query( @@ -13370,7 +13372,7 @@ async def fallback_login(request: Request): @router.post( "/login", include_in_schema=False ) # hidden since this is a helper for UI sso login -async def login(request: Request): # noqa: PLR0915 +async def login(request: Request): global premium_user, general_settings, master_key from litellm.proxy.auth.login_utils import authenticate_user, create_ui_token_object from litellm.proxy.utils import get_custom_url @@ -13420,7 +13422,7 @@ async def login(request: Request): # noqa: PLR0915 @router.post( "/v2/login", include_in_schema=False ) # hidden helper for UI logins via API -async def login_v2(request: Request): # noqa: PLR0915 +async def login_v2(request: Request): global premium_user, general_settings, master_key from litellm.proxy.auth.login_utils import authenticate_user, create_ui_token_object from litellm.proxy.utils import get_custom_url @@ -13495,7 +13497,7 @@ async def login_v2(request: Request): # noqa: PLR0915 @router.post( "/v3/login", include_in_schema=False ) # control-plane login — always returns token in body for cross-origin use -async def login_v3(request: Request): # noqa: PLR0915 +async def login_v3(request: Request): global premium_user, general_settings, master_key from litellm.proxy.auth.login_utils import authenticate_user, create_ui_token_object from litellm.proxy.utils import get_custom_url diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py index 4638922ec6ad..74f12a1eeb18 100644 --- a/litellm/proxy/utils.py +++ b/litellm/proxy/utils.py @@ -191,7 +191,7 @@ def print_verbose(print_statement): verbose_proxy_logger.debug("{}\n{}".format(print_statement, traceback.format_exc())) if litellm.set_verbose: - print(f"LiteLLM Proxy: {_redact_string(str(print_statement))}") # noqa + print(f"LiteLLM Proxy: {_redact_string(str(print_statement))}") # noqa: T201 def _get_email_logger_class(): @@ -3347,7 +3347,7 @@ async def _query_first_with_cached_plan_fallback( on_backoff=on_backoff, # specifying the function to call on backoff ) @log_db_metrics - async def get_data( # noqa: PLR0915 + async def get_data( self, token: Optional[Union[str, list]] = None, user_id: Optional[str] = None, @@ -3790,7 +3790,7 @@ def jsonify_team_object(self, db_data: dict): max_time=10, # maximum total time to retry for on_backoff=on_backoff, # specifying the function to call on backoff ) - async def insert_data( # noqa: PLR0915 + async def insert_data( self, data: dict, table_name: Literal[ @@ -3940,7 +3940,7 @@ async def insert_data( # noqa: PLR0915 max_time=10, # maximum total time to retry for on_backoff=on_backoff, # specifying the function to call on backoff ) - async def update_data( # noqa: PLR0915 + async def update_data( self, token: Optional[str] = None, data: dict = {}, @@ -5516,7 +5516,7 @@ def disable_spend_updates() -> bool: return False -async def update_spend( # noqa: PLR0915 +async def update_spend( prisma_client: PrismaClient, db_writer_client: Optional[AsyncHTTPHandler], proxy_logging_obj: ProxyLogging, diff --git a/litellm/router.py b/litellm/router.py index 148c8cf5771a..5c4dc3eb9435 100644 --- a/litellm/router.py +++ b/litellm/router.py @@ -2726,7 +2726,7 @@ async def stream_with_fallbacks(): return FallbackResponsesStreamWrapper(stream_with_fallbacks()) - def _completion_streaming_iterator( # noqa: PLR0915 + def _completion_streaming_iterator( self, model_response: CustomStreamWrapper, messages: List[Dict[str, str]], diff --git a/litellm/router_strategy/complexity_router/evals/eval_complexity_router.py b/litellm/router_strategy/complexity_router/evals/eval_complexity_router.py index 939ecdd2d225..6c9318e83bb2 100644 --- a/litellm/router_strategy/complexity_router/evals/eval_complexity_router.py +++ b/litellm/router_strategy/complexity_router/evals/eval_complexity_router.py @@ -250,10 +250,10 @@ def run_eval() -> Tuple[int, int, List[dict]]: total = len(EVAL_CASES) failures = [] - print("=" * 70) # noqa: T201 - print("COMPLEXITY ROUTER EVALUATION") # noqa: T201 - print("=" * 70) # noqa: T201 - print() # noqa: T201 + print("=" * 70) + print("COMPLEXITY ROUTER EVALUATION") + print("=" * 70) + print() for i, case in enumerate(EVAL_CASES, 1): tier, score, signals = router.classify(case.prompt, case.system_prompt) @@ -292,33 +292,33 @@ def run_eval() -> Tuple[int, int, List[dict]]: ) # Print result - print(f"[{i:2d}] {status} | {case.description}") # noqa: T201 + print(f"[{i:2d}] {status} | {case.description}") print( f" Expected: {case.expected_tier.value:10s} | Got: {tier.value:10s} | Score: {score:+.3f}" - ) # noqa: T201 + ) if signals: - print(f" Signals: {', '.join(signals)}") # noqa: T201 + print(f" Signals: {', '.join(signals)}") if not is_pass: - print(f" Prompt: {case.prompt[:60]}...") # noqa: T201 - print() # noqa: T201 + print(f" Prompt: {case.prompt[:60]}...") + print() # Summary - print("=" * 70) # noqa: T201 - print(f"RESULTS: {passed}/{total} passed ({100*passed/total:.1f}%)") # noqa: T201 - print("=" * 70) # noqa: T201 + print("=" * 70) + print(f"RESULTS: {passed}/{total} passed ({100*passed/total:.1f}%)") + print("=" * 70) if failures: - print("\nFAILURES:") # noqa: T201 - print("-" * 70) # noqa: T201 + print("\nFAILURES:") + print("-" * 70) for f in failures: - print(f"Case {f['case']}: {f['description']}") # noqa: T201 + print(f"Case {f['case']}: {f['description']}") print( f" Expected: {f['expected']}, Got: {f['actual']} (score: {f['score']})" - ) # noqa: T201 - print(f" Signals: {f['signals']}") # noqa: T201 + ) + print(f" Signals: {f['signals']}") if f["acceptable"]: - print(f" Acceptable: {f['acceptable']}") # noqa: T201 - print() # noqa: T201 + print(f" Acceptable: {f['acceptable']}") + print() return passed, total, failures @@ -330,17 +330,13 @@ def main(): # Exit with error code if too many failures pass_rate = passed / total if pass_rate < 0.80: - print( - f"\n❌ EVAL FAILED: Pass rate {pass_rate:.1%} is below 80% threshold" - ) # noqa: T201 + print(f"\n❌ EVAL FAILED: Pass rate {pass_rate:.1%} is below 80% threshold") sys.exit(1) elif pass_rate < 0.90: - print( - f"\n⚠️ EVAL WARNING: Pass rate {pass_rate:.1%} is below 90%" - ) # noqa: T201 + print(f"\n⚠️ EVAL WARNING: Pass rate {pass_rate:.1%} is below 90%") sys.exit(0) else: - print(f"\n✅ EVAL PASSED: Pass rate {pass_rate:.1%}") # noqa: T201 + print(f"\n✅ EVAL PASSED: Pass rate {pass_rate:.1%}") sys.exit(0) diff --git a/litellm/router_strategy/lowest_tpm_rpm_v2.py b/litellm/router_strategy/lowest_tpm_rpm_v2.py index 23e8896cd5f0..22664dcb7047 100644 --- a/litellm/router_strategy/lowest_tpm_rpm_v2.py +++ b/litellm/router_strategy/lowest_tpm_rpm_v2.py @@ -380,7 +380,7 @@ def _return_potential_deployments( potential_deployments = [_deployment] return potential_deployments - def _common_checks_available_deployment( # noqa: PLR0915 + def _common_checks_available_deployment( self, model_group: str, healthy_deployments: list, diff --git a/litellm/utils.py b/litellm/utils.py index 3748cbd8b954..ee7d952008eb 100644 --- a/litellm/utils.py +++ b/litellm/utils.py @@ -488,7 +488,7 @@ def print_verbose( elif log_level == "ERROR": verbose_logger.error(print_statement) if litellm.set_verbose is True and logger_only is False: - print(print_statement) # noqa + print(print_statement) # noqa: T201 except Exception: pass @@ -8630,7 +8630,7 @@ def _get_langflow_config() -> BaseConfig: return LangFlowConfig() @staticmethod - def get_provider_chat_config( # noqa: PLR0915 + def get_provider_chat_config( model: str, provider: LlmProviders, base_model: Optional[str] = None, diff --git a/litellm/videos/main.py b/litellm/videos/main.py index a61fe99d5848..b087f1e88d85 100644 --- a/litellm/videos/main.py +++ b/litellm/videos/main.py @@ -159,7 +159,7 @@ def video_generation( @client -def video_generation( # noqa: PLR0915 +def video_generation( prompt: str, model: Optional[str] = None, input_reference: Optional[FileTypes] = None, @@ -569,7 +569,7 @@ def video_remix( @client -def video_remix( # noqa: PLR0915 +def video_remix( video_id: str, prompt: str, timeout=600, # default to 10 minutes @@ -790,7 +790,7 @@ def video_list( @client -def video_list( # noqa: PLR0915 +def video_list( after: Optional[str] = None, limit: Optional[int] = None, order: Optional[str] = None, @@ -993,7 +993,7 @@ def video_status( @client -def video_status( # noqa: PLR0915 +def video_status( video_id: str, timeout=600, # default to 10 minutes custom_llm_provider=None, diff --git a/ruff.toml b/ruff.toml index 6c854b7ad03f..7baa1c5f92d6 100644 --- a/ruff.toml +++ b/ruff.toml @@ -1,5 +1,15 @@ lint.ignore = ["F405", "E402", "E501", "F403"] -lint.extend-select = ["E501", "PLR0915", "T20"] +lint.extend-select = ["E501", "PLR0915", "T20", "PGH004", "RUF008", "RUF009", "RUF100"] +# RUF100 (unused-noqa) only knows the rules enabled in THIS config, so it would strip +# `# noqa` directives that protect rules enforced elsewhere. List those codes as external +# so RUF100 leaves their directives alone: the strict gate (ruff-strict.toml) and upstream +# litellm's own ruff config both rely on suppressions this config can't see. +lint.external = [ + # Enforced by the strict-rule gate (scripts/ruff_strict_gate.py + ruff-strict.toml) + "C901", + # Enforced by upstream litellm's ruff config, but not run in this repo's CI + "PLC0415", "E402", "BLE001", "ARG002", "S102", "S324", "S606", "D401", "F403", "F405", +] line-length = 120 exclude = ["litellm/types/*", "litellm/__init__.py", "litellm/proxy/example_config_yaml/*", "tests/*"] From d0c2e8781034edb19f7dcedee28e895057782721 Mon Sep 17 00:00:00 2001 From: Mateo Wang <277851410+mateo-berri@users.noreply.github.com> Date: Tue, 16 Jun 2026 12:07:46 -0700 Subject: [PATCH 7/7] ci: ratchet lint and type-check gates (ruff preview, ANN, mypy, basedpyright) (#30379) * ci: enable ruff preview rules under the budgeted strict gate Turn on ruff preview in the strict-budget lane (ruff-strict.toml) only, leaving the clean gate (ruff.toml) untouched so make lint-ruff stays at zero. Enumerate the 118 firing codes explicitly with explicit-preview-rules so the gate is deterministic and stable across ruff upgrades rather than depending on preview auto-selecting the broad catalog. Grandfather the existing 58438 violations into ruff-strict-budget.json as per-rule baselines with headroom, so only net-new violations fail CI. The existing ten rules keep their hand-tuned slack; the new rules get slack 10 when the baseline is 50 or more and 3 otherwise. * ci: add ANN return-type rules to the budgeted strict gate Add ANN201/202/204/205/206 (missing return annotations) to the strict lane and grandfather the existing counts into ruff-strict-budget.json so the codebase ratchets toward explicit return types without breaking CI. * ci: add mypy (disallow_untyped_defs) and basedpyright strict gates with baselines Add two type-check gates, each grandfathering the current tree so only net-new violations fail CI, matching the ruff strict-budget ratchet. mypy gains disallow_untyped_defs in litellm/mypy.ini (the config the CI invocation actually reads; the root [tool.mypy] is not picked up from the litellm/ working dir). The 4885 existing missing-annotation errors are captured in litellm/.mypy-baseline.txt and the run is piped through mypy-baseline filter so new untyped defs are rejected. basedpyright runs in strict mode over litellm/, with enableTypeIgnoreComments disabled so it only honors '# pyright: ignore' and never polices mypy's '# type: ignore'. The existing strict diagnostics are grandfathered into .basedpyright/baseline.json. Both tools are pinned in the dev group and uv.lock; the lint workflow and Makefile run them filtered through their baselines, with lint-mypy-baseline-update and lint-basedpyright-baseline-update to ratchet. * ci: raise lint job timeout to 15m for the basedpyright strict pass * ci: pin pythonVersion 3.12 and regenerate baselines against merged base Merge litellm_internal_staging so the baselines cover code the CI merge includes (e.g. the cisco_ai_defense guardrail), which otherwise tripped the mypy gate with 3 ungrandfathered no-untyped-def errors. Pin pythonVersion 3.12 in pyrightconfig so basedpyright's strict analysis is reproducible across interpreter versions (CI runs 3.12). * ci: regenerate basedpyright baseline against the frozen lint env The previous baseline was generated with optional provider deps (azure, google, anthropic, mcp, numpydoc, google-genai) installed locally, so CI's dev-only env surfaced ~3500 reportUnknown*/reportMissingTypeStubs errors not in the baseline. Regenerate after uv sync --frozen so the baseline reflects the same dependency set the lint job sees. * ci: regenerate basedpyright baseline on python 3.12 frozen env The prior baseline still carried proxy-dev packages (e.g. prisma) that the lint job's dev-only, python 3.12 env lacks, leaving 2 unresolved-import errors ungrandfathered. Regenerate in a python 3.12 venv synced to the frozen lock with default groups only, so the baseline matches exactly what CI sees. * ci: replace type-check baselines with per-file count budgets The mypy and basedpyright baselines were position-sensitive (and the basedpyright one was a 27MB file), so ordinary line shifts churned them. Replace both with a per-file count gate: scripts/type_check_gate.py reduces each tool's output to errors-per-file and checks it against a committed {file: max} budget, ignoring line and column numbers. A file fails only when it gains more errors than its ceiling; debt can't be shuffled between files because each file has its own cap and new files default to zero. Budgets (mypy-file-budget.json 48K, basedpyright-file-budget.json 96K) are generated in the python 3.12 frozen lint env so they match CI. Drops the mypy-baseline dependency; basedpyright runs without its native baseline. ratchet via make lint-mypy-budget-update / lint-basedpyright-budget-update. * ci: add a small per-file slack to the type-check gate Allow each file to drift PER_FILE_SLACK (5) errors past its recorded count before failing, so a basedpyright inference ripple in an unrelated file doesn't break the build over a couple of errors. Budgets still record exact counts; the tolerance is applied at check time. * ci: move type-check slack into the budget json and trim lint timeout Make slack declarative: the budget is now {"slack": N, "files": {path: count}} so the tolerance is tuned in JSON without editing the script, mirroring how ruff-strict-budget.json carries its slack. --update preserves the existing slack. Also drop the lint job timeout from 15m to 10m; the mypy and basedpyright passes add ~2m, leaving the job around 4-5m, so 10m is a comfortable margin. * ci: collapse fully-adopted ruff categories and drop inert preview flag ANN (all nine non-removed rules) and BLE (its only rule) were spelled out code-by-code; replace each with its category selector, which is exactly equivalent in 0.15.3 (the removed ANN101/ANN102 are skipped by a category selector and error when named explicitly). explicit-preview-rules was inert: every selected rule is stable and nothing is selected by category, so the flag had nothing to gate. Verified the strict-rule counts are identical before and after (62379 each, zero per-rule drift), so no budget change. * ci: drop redundant pyright dev dependency Nothing invokes bare pyright in the Makefile, the linting workflow, or scripts; the basedpyright gate added on this branch is the only type checker that runs. basedpyright is a superset fork that reads the same pyrightconfig.json and honors the same "# pyright: ignore" comments, so pyright==1.1.408 in the ci group was dead weight. Regenerated uv.lock under the same exclude-newer cutoff so the only change is removing pyright and its package stanza * ci: un-weaken mypy and error on Any in basedpyright mypy: enable warn_return_any, drop the valid-type silencer, and stop globally ignoring missing first-party imports via [mypy-litellm.*] ignore_missing_imports = False, which surfaced eight real broken litellm.* imports the blanket ignore was hiding; third-party imports stay ignored. The per-file budget moves 4888 -> 5799 (902 no-any-return, 1 valid-type, 8 import-not-found), all grandfathered so only net-new errors fail and the ceilings ratchet down basedpyright: error on reportExplicitAny and reportAny. The per-file budget moves 117033 -> 148946 (6931 explicit-Any, 24954 Any-typed expressions), grandfathered the same way * ci: add Any-discipline gate on changed lines under litellm/ Add scripts/check_any_discipline.py, a type-aware gate that fails when a changed line holds a value typed Any -- including the X | Any unions that mypy --strict / basedpyright accept (e.g. re.Match.group() -> str | Any, json.loads() -> Any, bare dict -> dict[Any, Any]). It reuses the repo's mypyc-compiled mypy 1.19 via a custom generic AST walker (mypyc precludes subclassing TraverserVisitor), loads litellm/mypy.ini for parity with lint-mypy, and uses a dedicated incremental cache (.mypy_cache_any) with mtime+hash invalidation to force re-checks. Scope is changed-lines-only so editing a legacy file never forces cleaning its existing Any debt; suppress a genuine typed/untyped boundary with # any-ok: (ANY002 requires the reason). Wire it into the Makefile (lint-any, lint, lint-dev), a parallel any-discipline CI job with its own actions/cache, .gitignore, and the CLAUDE.md / CONTRIBUTING.md docs. * ci: move Any-gate codes into the shared LIT namespace Renumber the Any-discipline checker into the LIT*** scheme owned by scripts/check_type_discipline.py (PR #30500) so the two checkers share one rule namespace and suppression convention: ANY001 -> LIT002 (Any-typed value; LIT002 was the retired/free slot) ANY002 -> LIT005 (any-ok without a reason; the shared suppression-reason code) ANY000 -> LIT000 (setup/build/read error; the shared error code) Messages and behavior are unchanged; LIT005's text already matches the " requires a reason" shape used for cast-ok/guard-ok. * ci: gate mypy and basedpyright per error rule, not per file Switch the mypy/basedpyright budget gate from per-file error counts to per-rule-code totals, mirroring the {rule: {baseline, slack}} shape of ruff-strict-budget.json. A rule fails when its codebase-wide error count exceeds baseline + slack, so violations are tracked by category rather than by file location. scripts/type_check_gate.py now parses mypy from its text output (trailing [code]) and basedpyright from --outputjson (the JSON `rule` field), since basedpyright's wrapped text diagnostics mis-attribute the rule on continuation lines. Replace the *-file-budget.json files with freshly captured *-code-budget.json baselines and update the Makefile, CI, and CLAUDE.md accordingly. * docs: prefer Pydantic validation over any-ok suppression Point the Any-discipline guidance at validating Any with Pydantic (a model or TypeAdapter that returns a typed value or raises) and frame # any-ok as a last resort that should ideally never be used. * chore: remove extraneous comment * chore: make the CLAUDE.md more concise * chore: clean up bloated CONTRIBUTING.md additions * chore: make Makefile more concise * ci: add the lint-budget-update target CLAUDE.md references CLAUDE.md tells contributors to run make lint-budget-update, but the target was never defined. Add it as an aggregate that re-captures the ruff, mypy, and basedpyright budgets in one shot. * ci: recapture mypy and basedpyright budgets in the lint env The per-rule baselines were captured in a richer dependency env than the CI lint job's uv sync --frozen, so CI resolved fewer types and reported more errors than the budgets allowed (no-any-return 902 over cap 900, plus several basedpyright reportUnknown* rules). Regenerate both in the frozen env so they grandfather the true CI debt: mypy 5786 -> 5799 (no-any-return 890 -> 902, valid-type 1 restored), basedpyright 146213 -> 148942. * ci: check out PR head sha in lint and any-discipline jobs The default pull_request checkout uses refs/pull/N/merge, which folds the latest base commits into HEAD. The diff-based gates (ruff delta, Any discipline) then diff against the event's older base.sha and blame base's own new commits on this branch; staging's otel-v2 and streaming changes (#30326, #30485) tripped the Any gate on files this branch never touched. Checking out the PR head sha makes the gates diff the real branch tip against base, and pins the tree the mypy/basedpyright budgets were captured against so their counts stay deterministic as the base advances. * ci(lint): renumber Any-typed-value rule LIT002 -> LIT009 Free up LIT002 for the sibling type-discipline gate (check_type_discipline.py, #30500), which groups its mutable-collection family at LIT001 (annotation) and LIT002 (construction). This gate's Any-typed-value rule moves to LIT009 so the shared LIT namespace stays contiguous with no holes; LIT000 and LIT005 are unchanged. * style: rename lint-strict-budget -> lint-ruff-budget * ci: harden type-check gates against silent passes (greptile review) type_check_gate.py: refuse to certify a vacuous run. The CI pipe swallows the tool's exit code ('tool || true'), so a crashed mypy/basedpyright that emits nothing would parse to zero errors, breach no ceiling, and pass. is_vacuous_run() now fails when nothing was parsed but the budget expects errors. Also wrap basedpyright's json.loads in a JSONDecodeError handler that prints the offending output instead of dumping a raw traceback. check_any_discipline.py: ALL_LINES was None, which dict.get() also returns for a path absent from the line map, so a path-normalisation mismatch could let a violation on an unchanged file pass the scope filter. Make ALL_LINES a distinct sentinel object so 'whole file' and 'path missing' are unambiguous. Adds tests for all three. --- .github/workflows/test-linting.yml | 63 +- .gitignore | 1 + CLAUDE.md | 8 +- CONTRIBUTING.md | 1 + Makefile | 39 +- basedpyright-code-budget.json | 194 ++++++ litellm/mypy.ini | 7 +- mypy-code-budget.json | 18 + pyproject.toml | 2 +- pyrightconfig.json | 9 +- ruff-strict-budget.json | 502 +++++++++++++++- ruff-strict.toml | 3 +- scripts/check_any_discipline.py | 556 ++++++++++++++++++ scripts/type_check_gate.py | 196 ++++++ .../test_litellm/test_check_any_discipline.py | 41 ++ tests/test_litellm/test_type_check_gate.py | 133 +++++ uv.lock | 47 +- 17 files changed, 1773 insertions(+), 47 deletions(-) create mode 100644 basedpyright-code-budget.json create mode 100644 mypy-code-budget.json create mode 100644 scripts/check_any_discipline.py create mode 100644 scripts/type_check_gate.py create mode 100644 tests/test_litellm/test_check_any_discipline.py create mode 100644 tests/test_litellm/test_type_check_gate.py diff --git a/.github/workflows/test-linting.yml b/.github/workflows/test-linting.yml index f212dd9d15e1..2e967f3ed3f6 100644 --- a/.github/workflows/test-linting.yml +++ b/.github/workflows/test-linting.yml @@ -14,11 +14,15 @@ permissions: jobs: lint: runs-on: ubuntu-latest - timeout-minutes: 5 + timeout-minutes: 10 steps: - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 + # Check out the PR head, not the default refs/pull/N/merge: the merge ref + # folds in newer base commits, which the diff-based gates (ruff delta, + # Any-discipline) would otherwise blame on this branch. with: + ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 0 clean: true persist-credentials: false @@ -80,8 +84,11 @@ jobs: - name: Run MyPy type checking run: | cd litellm - uv run --no-sync mypy . - cd .. + (uv run --no-sync mypy . || true) | uv run --no-sync python ../scripts/type_check_gate.py --tool mypy + + - name: Run basedpyright type checking + run: | + (uv run --no-sync basedpyright --outputjson || true) | uv run --no-sync python scripts/type_check_gate.py --tool basedpyright - name: Check for circular imports run: | @@ -93,6 +100,56 @@ jobs: run: | uv run --no-sync python -c "from litellm import *" || (echo '🚨 import failed, this means you introduced unprotected imports! 🚨'; exit 1) + any-discipline: + # Separate job: the first run cold-builds litellm's type cache (~2 min, ~3 GB), + # so keep it off the main lint job's time budget. Subsequent runs reuse the + # cached .mypy_cache_any and only re-type-check the changed files. + runs-on: ubuntu-latest + timeout-minutes: 10 + + steps: + - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 + # Check out the PR head, not the default refs/pull/N/merge: the merge ref + # folds in newer base commits, which the diff-based gates (ruff delta, + # Any-discipline) would otherwise blame on this branch. + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + clean: true + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + with: + python-version: "3.12" + + - name: Set up uv + uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 + with: + version: "0.10.9" + + - name: Install dependencies + run: | + uv sync --frozen + + # Keyed on deps + mypy config (which fix the type cache's validity), not on + # source content, so changed files always differ from the restored cache. + # The gate also defensively invalidates each target's cache entry, so + # correctness never depends on cache freshness -- this is purely for speed. + - name: Restore Any-gate type cache + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: .mypy_cache_any + key: any-mypy-cache-${{ runner.os }}-py3.12-${{ hashFiles('uv.lock', 'litellm/mypy.ini') }} + restore-keys: | + any-mypy-cache-${{ runner.os }}-py3.12- + + - name: Check Any discipline on changed lines + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + uv run --no-sync python scripts/check_any_discipline.py --changed --base "$BASE_SHA" + secret-scan: runs-on: ubuntu-latest timeout-minutes: 5 diff --git a/.gitignore b/.gitignore index 572830d35f63..54ae53bb2c90 100644 --- a/.gitignore +++ b/.gitignore @@ -75,6 +75,7 @@ tests/local_testing/log.txt litellm/proxy/_new_new_secret_config.yaml litellm/proxy/custom_guardrail.py **/.mypy_cache/ +**/.mypy_cache_any/ litellm/proxy/application.log tests/llm_translation/vertex_test_account.json tests/llm_translation/test_vertex_key.json diff --git a/CLAUDE.md b/CLAUDE.md index 32fd0aadddbc..48dc3d81d94d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,7 +36,11 @@ Don't hesitate to use values in .env to get needed API keys and other secrets, a Run tests, format your code, and lint your code before each commit -When you fix strict-rule violations gated by `ruff-strict-budget.json`, run `make lint-strict-budget-update` and commit the lowered baselines so the ceilings ratchet down instead of leaving stale headroom +When you fix violations gated by `ruff-strict-budget.json`, `mypy-code-budget.json`, or `basedpyright-code-budget.json`, run `make lint-budget-update` and commit the lowered baselines so the ceilings ratchet down instead of leaving stale headroom + +If you're trying to create a new function that relies on untyped stuff, instead of adding more Any's and bringing it closer to the max, just validate it in the caller with Pydantic (a model or `TypeAdapter` that returns the typed thing or raises will do) and then pass the now typed variable in + +The Any-discipline gate (`make lint-any`, also a CI job) fails when a line you changed under `litellm/` holds a value typed `Any`, including the `X | Any`. Ideally `# any-ok: ` is never used; treat it as a last resort for a genuine typed/untyped boundary that Pydantic truly can't model Ask to commit and push your work when you're done (or if you're confident that your code is good and works, just do it) @@ -67,8 +71,6 @@ Follow these coding conventions for new/updated code (a three-line fix in a lega - No file sprawl: deliberate file and folder structure - Standard over hand-rolled: use the official SDK or a library where one exists; where none does, follow industry standards instead of inventing local conventions -if you're trying to create a new function that relies on untyped stuff, instead of adding more Any's and bringing it closer to the max, just validate it in the caller (a simple function that returns the typed thing or raises will do) and then pass the now typed variable in - Follow conventional commits for commit names and PR titles ## Think Before Coding diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2177c764806e..97a8d53f831c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -155,6 +155,7 @@ Individual linting commands: make format-check # Check Black formatting make lint-ruff # Run Ruff linting make lint-mypy # Run MyPy type checking +make lint-any # Fail on Any-typed values on changed lines make check-circular-imports # Check for circular imports make check-import-safety # Check import safety ``` diff --git a/Makefile b/Makefile index fe4be29f9b68..f0563b273c2c 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,8 @@ test-unit-integrations test-unit-core-utils test-unit-other test-unit-root \ test-proxy-unit-a test-proxy-unit-b test-integration test-unit-helm \ info lint lint-dev format \ - lint-strict-budget lint-strict-budget-update \ + lint-mypy lint-mypy-budget-update lint-basedpyright lint-basedpyright-budget-update \ + lint-ruff-budget lint-ruff-budget-update lint-budget-update lint-any \ install-dev install-proxy-dev install-test-deps install-hooks \ install-helm-unittest check-circular-imports check-import-safety @@ -23,10 +24,15 @@ help: @echo " make format-check - Check Black code formatting (matches CI)" @echo " make lint - Run all linting (Ruff, MyPy, Black check, circular imports, import safety)" @echo " make lint-ruff - Run Ruff linting only" - @echo " make lint-mypy - Run MyPy type checking only" + @echo " make lint-mypy - Run MyPy (disallow_untyped_defs), gated by per-rule error counts" + @echo " make lint-mypy-budget-update - Re-capture the MyPy per-rule budget (ratchet)" + @echo " make lint-basedpyright - Run basedpyright strict, gated by per-rule error counts" + @echo " make lint-basedpyright-budget-update - Re-capture the basedpyright per-rule budget (ratchet)" @echo " make lint-black - Check Black formatting (matches CI)" - @echo " make lint-strict-budget - Gate the codebase total of each strict ruff rule against its ceiling" - @echo " make lint-strict-budget-update - Re-capture per-rule baselines in ruff-strict-budget.json (ratchet)" + @echo " make lint-ruff-budget - Gate the codebase total of each strict ruff rule against its ceiling" + @echo " make lint-ruff-budget-update - Re-capture per-rule baselines in ruff-strict-budget.json (ratchet)" + @echo " make lint-budget-update - Re-capture all three ratchet budgets (ruff + mypy + basedpyright)" + @echo " make lint-any - Fail if changed lines under litellm/ hold an Any-typed value" @echo " make check-circular-imports - Check for circular imports" @echo " make check-import-safety - Check import safety" @echo " make test - Run all tests" @@ -121,16 +127,31 @@ lint-ruff-FULL-dev: install-dev else echo "No changed .py files to check."; fi lint-mypy: install-dev - cd litellm && $(UV_RUN) mypy . --ignore-missing-imports && cd .. + cd litellm && ($(UV_RUN) mypy . || true) | $(UV_RUN) python ../scripts/type_check_gate.py --tool mypy + +lint-mypy-budget-update: install-dev + cd litellm && ($(UV_RUN) mypy . || true) | $(UV_RUN) python ../scripts/type_check_gate.py --tool mypy --update + +lint-basedpyright: install-dev + ($(UV_RUN) basedpyright --outputjson || true) | $(UV_RUN) python scripts/type_check_gate.py --tool basedpyright + +lint-basedpyright-budget-update: install-dev + ($(UV_RUN) basedpyright --outputjson || true) | $(UV_RUN) python scripts/type_check_gate.py --tool basedpyright --update lint-black: format-check -lint-strict-budget: install-dev +lint-ruff-budget: install-dev $(UV_RUN) python scripts/ruff_strict_gate.py -lint-strict-budget-update: install-dev +lint-ruff-budget-update: install-dev $(UV_RUN) python scripts/ruff_strict_gate.py --update +# Ratchet all three budgets in one shot (ruff strict + mypy + basedpyright) +lint-budget-update: lint-ruff-budget-update lint-mypy-budget-update lint-basedpyright-budget-update + +lint-any: install-dev + $(UV_RUN) python scripts/check_any_discipline.py --changed + check-circular-imports: install-dev cd litellm && $(UV_RUN) python ../tests/documentation_tests/test_circular_imports.py && cd .. @@ -138,10 +159,10 @@ check-import-safety: install-dev @$(UV_RUN) python -c "from litellm import *; print('[from litellm import *] OK! no issues!');" || (echo '🚨 import failed, this means you introduced unprotected imports! 🚨'; exit 1) # Combined linting (matches test-linting.yml workflow) -lint: format-check lint-ruff lint-mypy check-circular-imports check-import-safety lint-strict-budget +lint: format-check lint-ruff lint-mypy lint-basedpyright check-circular-imports check-import-safety lint-ruff-budget lint-any # Faster linting for local development (only checks changed code) -lint-dev: lint-format-changed lint-mypy check-circular-imports check-import-safety +lint-dev: lint-format-changed lint-mypy lint-any check-circular-imports check-import-safety # Testing targets test: install-test-deps diff --git a/basedpyright-code-budget.json b/basedpyright-code-budget.json new file mode 100644 index 000000000000..b531e0e17df8 --- /dev/null +++ b/basedpyright-code-budget.json @@ -0,0 +1,194 @@ +{ + "reportAny": { + "baseline": 24954, + "slack": 10 + }, + "reportArgumentType": { + "baseline": 1863, + "slack": 3 + }, + "reportAssignmentType": { + "baseline": 220, + "slack": 3 + }, + "reportAttributeAccessIssue": { + "baseline": 335, + "slack": 3 + }, + "reportCallIssue": { + "baseline": 77, + "slack": 10 + }, + "reportConstantRedefinition": { + "baseline": 39, + "slack": 3 + }, + "reportDeprecated": { + "baseline": 217, + "slack": 10 + }, + "reportDuplicateImport": { + "baseline": 28, + "slack": 3 + }, + "reportExplicitAny": { + "baseline": 6931, + "slack": 10 + }, + "reportFunctionMemberAccess": { + "baseline": 7, + "slack": 3 + }, + "reportGeneralTypeIssues": { + "baseline": 151, + "slack": 3 + }, + "reportIncompatibleMethodOverride": { + "baseline": 52, + "slack": 10 + }, + "reportIncompatibleVariableOverride": { + "baseline": 8, + "slack": 3 + }, + "reportInconsistentOverload": { + "baseline": 12, + "slack": 3 + }, + "reportIndexIssue": { + "baseline": 26, + "slack": 3 + }, + "reportInvalidTypeForm": { + "baseline": 23, + "slack": 3 + }, + "reportInvalidTypeVarUse": { + "baseline": 2, + "slack": 3 + }, + "reportMatchNotExhaustive": { + "baseline": 1, + "slack": 3 + }, + "reportMissingParameterType": { + "baseline": 3933, + "slack": 10 + }, + "reportMissingTypeArgument": { + "baseline": 10612, + "slack": 10 + }, + "reportMissingTypeStubs": { + "baseline": 27, + "slack": 10 + }, + "reportOperatorIssue": { + "baseline": 6, + "slack": 3 + }, + "reportOptionalCall": { + "baseline": 4, + "slack": 3 + }, + "reportOptionalIterable": { + "baseline": 3, + "slack": 3 + }, + "reportOptionalMemberAccess": { + "baseline": 724, + "slack": 10 + }, + "reportOptionalOperand": { + "baseline": 3, + "slack": 3 + }, + "reportOptionalSubscript": { + "baseline": 11, + "slack": 3 + }, + "reportPossiblyUnboundVariable": { + "baseline": 52, + "slack": 10 + }, + "reportPrivateUsage": { + "baseline": 1625, + "slack": 10 + }, + "reportRedeclaration": { + "baseline": 8, + "slack": 3 + }, + "reportReturnType": { + "baseline": 118, + "slack": 10 + }, + "reportTypedDictNotRequiredAccess": { + "baseline": 20, + "slack": 3 + }, + "reportUndefinedVariable": { + "baseline": 2, + "slack": 3 + }, + "reportUnknownArgumentType": { + "baseline": 30603, + "slack": 10 + }, + "reportUnknownLambdaType": { + "baseline": 76, + "slack": 10 + }, + "reportUnknownMemberType": { + "baseline": 27322, + "slack": 10 + }, + "reportUnknownParameterType": { + "baseline": 13636, + "slack": 10 + }, + "reportUnknownVariableType": { + "baseline": 21776, + "slack": 10 + }, + "reportUnnecessaryCast": { + "baseline": 118, + "slack": 10 + }, + "reportUnnecessaryComparison": { + "baseline": 680, + "slack": 10 + }, + "reportUnnecessaryContains": { + "baseline": 4, + "slack": 3 + }, + "reportUnnecessaryIsInstance": { + "baseline": 807, + "slack": 10 + }, + "reportUntypedBaseClass": { + "baseline": 110, + "slack": 3 + }, + "reportUntypedFunctionDecorator": { + "baseline": 22, + "slack": 3 + }, + "reportUnusedClass": { + "baseline": 22, + "slack": 3 + }, + "reportUnusedFunction": { + "baseline": 137, + "slack": 10 + }, + "reportUnusedImport": { + "baseline": 670, + "slack": 10 + }, + "reportUnusedVariable": { + "baseline": 865, + "slack": 10 + } +} diff --git a/litellm/mypy.ini b/litellm/mypy.ini index 4702b591124b..b65e11bab427 100644 --- a/litellm/mypy.ini +++ b/litellm/mypy.ini @@ -1,13 +1,16 @@ [mypy] -warn_return_any = False +warn_return_any = True ignore_missing_imports = True +disallow_untyped_defs = True mypy_path = litellm/stubs namespace_packages = True disable_error_code = - valid-type, annotation-unchecked, import-untyped +[mypy-litellm.*] +ignore_missing_imports = False + [mypy-google.*] ignore_missing_imports = True diff --git a/mypy-code-budget.json b/mypy-code-budget.json new file mode 100644 index 000000000000..2cae0d661e95 --- /dev/null +++ b/mypy-code-budget.json @@ -0,0 +1,18 @@ +{ + "import-not-found": { + "baseline": 8, + "slack": 3 + }, + "no-any-return": { + "baseline": 902, + "slack": 10 + }, + "no-untyped-def": { + "baseline": 4888, + "slack": 10 + }, + "valid-type": { + "baseline": 1, + "slack": 3 + } +} diff --git a/pyproject.toml b/pyproject.toml index 6429b810969a..8b1386aaf87a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -149,6 +149,7 @@ dev = [ "flake8==7.3.0", "black==26.3.1", "mypy==1.19.0", + "basedpyright==1.39.7", "pytest==9.0.3", "pytest-mock==3.15.1", "pytest-asyncio==1.3.0", @@ -220,7 +221,6 @@ ci = [ "blockbuster==1.5.26", "beautifulsoup4==4.14.3", "pylint==4.0.5", - "pyright==1.1.408", "langchain-mcp-adapters==0.2.1", "langchain-openai==1.1.14", "langgraph==1.0.10", diff --git a/pyrightconfig.json b/pyrightconfig.json index f930e44d305c..97f099d5b2c4 100644 --- a/pyrightconfig.json +++ b/pyrightconfig.json @@ -1,7 +1,12 @@ { + "include": ["litellm"], "ignore": [], "exclude": ["**/node_modules", "**/__pycache__", "litellm/types/utils.py", "litellm/proxy/_types.py"], + "pythonVersion": "3.12", + "typeCheckingMode": "strict", + "enableTypeIgnoreComments": false, "reportMissingImports": false, - "reportPrivateImportUsage": false + "reportPrivateImportUsage": false, + "reportExplicitAny": "error", + "reportAny": "error" } - \ No newline at end of file diff --git a/ruff-strict-budget.json b/ruff-strict-budget.json index 6363b72353f9..bb02ec015694 100644 --- a/ruff-strict-budget.json +++ b/ruff-strict-budget.json @@ -1,12 +1,494 @@ { - "ANN001": { "baseline": 2865, "slack": 10 }, - "ANN002": { "baseline": 64, "slack": 3 }, - "ANN003": { "baseline": 759, "slack": 10 }, - "ANN401": { "baseline": 1885, "slack": 10 }, - "B006": { "baseline": 180, "slack": 3 }, - "C901": { "baseline": 301, "slack": 3 }, - "PLR0913": { "baseline": 1813, "slack": 3 }, - "PLW0603": { "baseline": 183, "slack": 3 }, - "RUF012": { "baseline": 158, "slack": 3 }, - "TID251": { "baseline": 2404, "slack": 10 } + "ANN001": { + "baseline": 2865, + "slack": 10 + }, + "ANN002": { + "baseline": 64, + "slack": 3 + }, + "ANN003": { + "baseline": 759, + "slack": 10 + }, + "ANN201": { + "baseline": 1944, + "slack": 10 + }, + "ANN202": { + "baseline": 858, + "slack": 10 + }, + "ANN204": { + "baseline": 658, + "slack": 10 + }, + "ANN205": { + "baseline": 117, + "slack": 10 + }, + "ANN206": { + "baseline": 120, + "slack": 10 + }, + "ANN401": { + "baseline": 1886, + "slack": 10 + }, + "ASYNC230": { + "baseline": 11, + "slack": 3 + }, + "B004": { + "baseline": 1, + "slack": 3 + }, + "B006": { + "baseline": 180, + "slack": 3 + }, + "B008": { + "baseline": 490, + "slack": 10 + }, + "B009": { + "baseline": 79, + "slack": 10 + }, + "B010": { + "baseline": 187, + "slack": 10 + }, + "B018": { + "baseline": 2, + "slack": 3 + }, + "B019": { + "baseline": 1, + "slack": 3 + }, + "B021": { + "baseline": 1, + "slack": 3 + }, + "B026": { + "baseline": 3, + "slack": 3 + }, + "B033": { + "baseline": 1, + "slack": 3 + }, + "BLE001": { + "baseline": 2854, + "slack": 10 + }, + "C401": { + "baseline": 8, + "slack": 3 + }, + "C404": { + "baseline": 1, + "slack": 3 + }, + "C405": { + "baseline": 20, + "slack": 3 + }, + "C408": { + "baseline": 11, + "slack": 3 + }, + "C414": { + "baseline": 4, + "slack": 3 + }, + "C419": { + "baseline": 1, + "slack": 3 + }, + "C901": { + "baseline": 301, + "slack": 3 + }, + "D419": { + "baseline": 6, + "slack": 3 + }, + "DTZ001": { + "baseline": 2, + "slack": 3 + }, + "DTZ003": { + "baseline": 30, + "slack": 3 + }, + "DTZ005": { + "baseline": 229, + "slack": 10 + }, + "DTZ006": { + "baseline": 10, + "slack": 3 + }, + "DTZ007": { + "baseline": 20, + "slack": 3 + }, + "DTZ011": { + "baseline": 3, + "slack": 3 + }, + "EXE001": { + "baseline": 4, + "slack": 3 + }, + "EXE002": { + "baseline": 3, + "slack": 3 + }, + "F401": { + "baseline": 20, + "slack": 3 + }, + "FURB136": { + "baseline": 1, + "slack": 3 + }, + "FURB168": { + "baseline": 1, + "slack": 3 + }, + "FURB188": { + "baseline": 49, + "slack": 3 + }, + "I001": { + "baseline": 258, + "slack": 10 + }, + "LOG015": { + "baseline": 5, + "slack": 3 + }, + "N999": { + "baseline": 1, + "slack": 3 + }, + "PERF102": { + "baseline": 27, + "slack": 3 + }, + "PERF401": { + "baseline": 136, + "slack": 10 + }, + "PERF402": { + "baseline": 6, + "slack": 3 + }, + "PERF403": { + "baseline": 69, + "slack": 10 + }, + "PIE790": { + "baseline": 263, + "slack": 10 + }, + "PIE800": { + "baseline": 1, + "slack": 3 + }, + "PIE804": { + "baseline": 21, + "slack": 3 + }, + "PIE810": { + "baseline": 41, + "slack": 3 + }, + "PLC0206": { + "baseline": 28, + "slack": 3 + }, + "PLC0208": { + "baseline": 1, + "slack": 3 + }, + "PLC0414": { + "baseline": 35, + "slack": 3 + }, + "PLR0124": { + "baseline": 1, + "slack": 3 + }, + "PLR0206": { + "baseline": 1, + "slack": 3 + }, + "PLR0402": { + "baseline": 6, + "slack": 3 + }, + "PLR0913": { + "baseline": 1813, + "slack": 3 + }, + "PLR1704": { + "baseline": 3, + "slack": 3 + }, + "PLR1711": { + "baseline": 31, + "slack": 3 + }, + "PLR1714": { + "baseline": 252, + "slack": 10 + }, + "PLR1730": { + "baseline": 7, + "slack": 3 + }, + "PLR2044": { + "baseline": 1, + "slack": 3 + }, + "PLW0127": { + "baseline": 41, + "slack": 3 + }, + "PLW0133": { + "baseline": 1, + "slack": 3 + }, + "PLW0602": { + "baseline": 215, + "slack": 10 + }, + "PLW0603": { + "baseline": 183, + "slack": 3 + }, + "PLW1508": { + "baseline": 188, + "slack": 10 + }, + "PLW1510": { + "baseline": 2, + "slack": 3 + }, + "PYI030": { + "baseline": 2, + "slack": 3 + }, + "PYI036": { + "baseline": 2, + "slack": 3 + }, + "PYI041": { + "baseline": 9, + "slack": 3 + }, + "PYI064": { + "baseline": 2, + "slack": 3 + }, + "RET501": { + "baseline": 35, + "slack": 3 + }, + "RET504": { + "baseline": 709, + "slack": 10 + }, + "RUF010": { + "baseline": 844, + "slack": 10 + }, + "RUF012": { + "baseline": 158, + "slack": 3 + }, + "RUF015": { + "baseline": 8, + "slack": 3 + }, + "RUF019": { + "baseline": 38, + "slack": 3 + }, + "RUF022": { + "baseline": 80, + "slack": 10 + }, + "RUF023": { + "baseline": 2, + "slack": 3 + }, + "RUF046": { + "baseline": 5, + "slack": 3 + }, + "RUF051": { + "baseline": 3, + "slack": 3 + }, + "RUF059": { + "baseline": 69, + "slack": 10 + }, + "RUF100": { + "baseline": 465, + "slack": 10 + }, + "S110": { + "baseline": 222, + "slack": 10 + }, + "S112": { + "baseline": 21, + "slack": 3 + }, + "SIM101": { + "baseline": 58, + "slack": 10 + }, + "SIM102": { + "baseline": 311, + "slack": 10 + }, + "SIM103": { + "baseline": 119, + "slack": 10 + }, + "SIM113": { + "baseline": 3, + "slack": 3 + }, + "SIM114": { + "baseline": 103, + "slack": 10 + }, + "SIM115": { + "baseline": 2, + "slack": 3 + }, + "SIM117": { + "baseline": 7, + "slack": 3 + }, + "SIM118": { + "baseline": 104, + "slack": 10 + }, + "SIM201": { + "baseline": 1, + "slack": 3 + }, + "SIM210": { + "baseline": 9, + "slack": 3 + }, + "SIM211": { + "baseline": 1, + "slack": 3 + }, + "SIM222": { + "baseline": 1, + "slack": 3 + }, + "SIM401": { + "baseline": 9, + "slack": 3 + }, + "TC004": { + "baseline": 5, + "slack": 3 + }, + "TC005": { + "baseline": 6, + "slack": 3 + }, + "TID251": { + "baseline": 2405, + "slack": 10 + }, + "TRY002": { + "baseline": 528, + "slack": 10 + }, + "TRY004": { + "baseline": 93, + "slack": 10 + }, + "TRY201": { + "baseline": 409, + "slack": 10 + }, + "TRY203": { + "baseline": 113, + "slack": 10 + }, + "TRY300": { + "baseline": 853, + "slack": 10 + }, + "UP006": { + "baseline": 12941, + "slack": 10 + }, + "UP007": { + "baseline": 2520, + "slack": 10 + }, + "UP008": { + "baseline": 2, + "slack": 3 + }, + "UP012": { + "baseline": 4, + "slack": 3 + }, + "UP018": { + "baseline": 18, + "slack": 3 + }, + "UP024": { + "baseline": 12, + "slack": 3 + }, + "UP028": { + "baseline": 2, + "slack": 3 + }, + "UP031": { + "baseline": 2, + "slack": 3 + }, + "UP032": { + "baseline": 609, + "slack": 10 + }, + "UP034": { + "baseline": 1, + "slack": 3 + }, + "UP035": { + "baseline": 2250, + "slack": 10 + }, + "UP036": { + "baseline": 1, + "slack": 3 + }, + "UP037": { + "baseline": 100, + "slack": 10 + }, + "UP045": { + "baseline": 18417, + "slack": 10 + } } diff --git a/ruff-strict.toml b/ruff-strict.toml index 03145255ebf5..8d517615244e 100644 --- a/ruff-strict.toml +++ b/ruff-strict.toml @@ -1,7 +1,8 @@ extend = "ruff.toml" [lint] -select = ["ANN001", "ANN002", "ANN003", "ANN401", "B006", "C901", "PLR0913", "PLW0603", "RUF012", "TID251"] +preview = true +select = ["ANN", "ASYNC230", "B004", "B006", "B008", "B009", "B010", "B018", "B019", "B021", "B026", "B033", "BLE", "C401", "C404", "C405", "C408", "C414", "C419", "C901", "D419", "DTZ001", "DTZ003", "DTZ005", "DTZ006", "DTZ007", "DTZ011", "EXE001", "EXE002", "F401", "FURB136", "FURB168", "FURB188", "I001", "LOG015", "N999", "PERF102", "PERF401", "PERF402", "PERF403", "PIE790", "PIE800", "PIE804", "PIE810", "PLC0206", "PLC0208", "PLC0414", "PLR0124", "PLR0206", "PLR0402", "PLR0913", "PLR1704", "PLR1711", "PLR1714", "PLR1730", "PLR2044", "PLW0127", "PLW0133", "PLW0602", "PLW0603", "PLW1508", "PLW1510", "PYI030", "PYI036", "PYI041", "PYI064", "RET501", "RET504", "RUF010", "RUF012", "RUF015", "RUF019", "RUF022", "RUF023", "RUF046", "RUF051", "RUF059", "RUF100", "S110", "S112", "SIM101", "SIM102", "SIM103", "SIM113", "SIM114", "SIM115", "SIM117", "SIM118", "SIM201", "SIM210", "SIM211", "SIM222", "SIM401", "TC004", "TC005", "TID251", "TRY002", "TRY004", "TRY201", "TRY203", "TRY300", "UP006", "UP007", "UP008", "UP012", "UP018", "UP024", "UP028", "UP031", "UP032", "UP034", "UP035", "UP036", "UP037", "UP045"] extend-select = [] [lint.mccabe] diff --git a/scripts/check_any_discipline.py b/scripts/check_any_discipline.py new file mode 100644 index 000000000000..3185953d473d --- /dev/null +++ b/scripts/check_any_discipline.py @@ -0,0 +1,556 @@ +#!/usr/bin/env python3 +"""Any-discipline gate: fail when a *changed* file holds a value typed `Any`. + +Where ruff, `mypy --strict`, and even basedpyright's `reportAny` stop short, this +catches the case that actually bites: a *union* hiding an `Any`. For example +`re.Match.group()` -> `str | Any`, `json.loads()` -> `Any`, and bare `list`/`dict` +-> `list[Any]`/`dict[..., Any]`. Any value whose inferred type *contains* `Any` +(recursively, through unions / generics / tuples) is reported. + +Scope: changed-only, changed-lines +---------------------------------- +litellm already contains a large amount of pre-existing `Any` (a single legacy +file can have >100 findings), and a whole-tree scan would have to re-export types +for litellm's entire import closure on every run (~2 min, ~3 GB). So this gate is +*changed-only* and reports a finding only on a line that the diff against +`--base` actually adds or edits (untracked files count as wholly new). A brand +new file is therefore checked in full, while editing a legacy file only requires +*your* lines to be clean -- you can't introduce an `X | Any`, but you aren't +forced to clean the file's existing debt. This mirrors how `ruff_strict_gate.py` +blames a change only for the violations it introduces; cold legacy code is left +to the ratchet gates (mypy/basedpyright/ruff budgets). + +How it works +------------ +It loads `litellm/mypy.ini` (the same config `make lint-mypy` uses, so findings +match what developers already see), builds the changed files with mypy asking for +its exported expression->type map, and walks each file's AST applying a recursive +"contains Any" predicate -- the test `mypy --disallow-any-expr` uses internally +but applies inconsistently (python/mypy#12856). + +mypy only re-exports types for modules it re-type-checks, so for each target we +invalidate just its cached hash (deps stay warm) to force a fast re-check against +a persisted incremental cache (.mypy_cache_any). + +Rules +----- +Codes share the `LIT***` namespace with `scripts/check_type_discipline.py` (PR +#30500), which owns LIT001/002/003/004/006/007/008. This gate claims the rest: +LIT009 A value expression's inferred type is, or contains, `Any`. + Suppress with `# any-ok: ` on the offending line. +LIT005 An `# any-ok` suppression without a reason (the shared + suppression-needs-a-reason code, same as `# cast-ok` / `# guard-ok`). +LIT000 Setup failure: mypy could not build, or a target file could not be read. + +`Any`s produced purely by an already-reported error, and the special-form / +implementation-artifact internal `Any`s, are ignored. A bound method *reference* +whose signature mentions `Any` is not flagged -- only the value its call produces. + +Usage +----- + # gate mode (CI / pre-push): check changed lines under litellm/ + uv run --no-sync python scripts/check_any_discipline.py --changed --base origin/litellm_internal_staging + + # whole-file spot-check (no line filter), paths relative to repo root + uv run --no-sync python scripts/check_any_discipline.py litellm/budget_manager.py + +Exit code 1 if any Any-tainted value is found, 2 on a setup/usage error. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import subprocess +import sys +import tokenize +from collections.abc import Iterable, Sequence +from pathlib import Path +from typing import NamedTuple + +try: + from mypy import build + from mypy.config_parser import parse_config_file + from mypy.find_sources import create_source_list + from mypy.fscache import FileSystemCache + from mypy.modulefinder import BuildSource + from mypy.nodes import AssignmentStmt, Expression, NameExpr, Node + from mypy.options import Options + from mypy.types import ( + AnyType, + CallableType, + Instance, + Overloaded, + TupleType, + Type, + TypeOfAny, + UnionType, + get_proper_type, + ) +except ImportError: # pragma: no cover - environment guard + sys.stderr.write( + "check_any_discipline: mypy is not importable in this interpreter.\n" + "Run it through the project environment, e.g.\n" + " uv run --no-sync python scripts/check_any_discipline.py --changed\n" + ) + raise SystemExit(2) + + +REPO_ROOT = Path(__file__).resolve().parent.parent +LITELLM_DIR = REPO_ROOT / "litellm" +MYPY_INI = LITELLM_DIR / "mypy.ini" +CACHE_DIR = REPO_ROOT / ".mypy_cache_any" +PY_TAG = f"{sys.version_info.major}.{sys.version_info.minor}" +DEFAULT_BASE = "origin/litellm_internal_staging" + +MIN_REASON_LEN = 3 +ANY_OK_RE = re.compile(r"#\s*any-ok(?::\s*(?P.*))?") +_HUNK_RE = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@") + +# Files allowed to surface `Any` (the typed/untyped boundary). A finding is +# skipped if any fragment below is a substring of the file's posix path. Keep +# this tight -- prefer a line-level `# any-ok: ` over a blanket exemption. +BOUNDARY_PATHS: frozenset[str] = frozenset() + +# `Any` kinds that are not actionable: produced by an already-reported error, or +# an internal placeholder that never corresponds to a concrete runtime value. +# NOTE: `special_form` is deliberately NOT here. In mypy 1.19 the `Any` in +# typeshed unions like `re.Match.group() -> str | Any` is tagged `special_form`, +# and that union is the headline case this gate exists to catch. +_HARMLESS_ANY = frozenset( + kind + for kind in ( + TypeOfAny.from_error, + getattr(TypeOfAny, "implementation_artifact", None), + ) + if kind is not None +) + +# AST attributes that point OUTSIDE the syntactic subtree (a RefExpr's resolved +# definition, a node's TypeInfo). Skipping exactly these two makes a generic +# child-walk equivalent to mypy's TraverserVisitor -- validated to the node +# against ExtendedTraverserVisitor across the full grammar (see commit notes). +_NON_SYNTACTIC_ATTRS = frozenset({"node", "info"}) + + +class Violation(NamedTuple): + path: Path + line: int + col: int + code: str + message: str + + def render(self) -> str: + return f"{self.path}:{self.line}:{self.col}: {self.code} {self.message}" + + +# --------------------------------------------------------------------------- # +# The "contains Any" predicate +# --------------------------------------------------------------------------- # + + +def contains_any(t: Type, _seen: set[int] | None = None) -> bool: + """True if a *value* of type ``t`` carries `Any` anywhere meaningful.""" + seen = _seen if _seen is not None else set() + p = get_proper_type(t) + if id(p) in seen: + return False + seen.add(id(p)) + + # A function/method *reference* whose signature mentions Any is not itself an + # unsafe value -- only its eventual call result is. Don't recurse into it. + if isinstance(p, (CallableType, Overloaded)): + return False + if isinstance(p, AnyType): + return p.type_of_any not in _HARMLESS_ANY + if isinstance(p, UnionType): + return any(contains_any(item, seen) for item in p.items) + if isinstance(p, Instance): + return any(contains_any(arg, seen) for arg in p.args) + if isinstance(p, TupleType): + return any(contains_any(item, seen) for item in p.items) + return False + + +# --------------------------------------------------------------------------- # +# Generic, leak-free AST walk (works under a mypyc-compiled mypy, which forbids +# subclassing TraverserVisitor) +# --------------------------------------------------------------------------- # + + +def _walk_file(tree: Node) -> tuple[list[Expression], set[int]]: + """Return (every Expression in `tree`, ids of simple assignment-target names). + + The walk follows only syntactic children (every attribute except the two + non-syntactic back-references), so it never escapes the module. Simple + ``x = `` name targets are collected separately so we don't double-report + the assigned name as an echo of an Any rvalue. + """ + exprs: list[Expression] = [] + skip_lvalues: set[int] = set() + stack: list[object] = [tree] + seen: set[int] = set() + while stack: + n = stack.pop() + if isinstance(n, Node): + if id(n) in seen: + continue + seen.add(id(n)) + if isinstance(n, Expression): + exprs.append(n) + if isinstance(n, AssignmentStmt): + for lvalue in n.lvalues: + if isinstance(lvalue, NameExpr): + skip_lvalues.add(id(lvalue)) + for name in dir(n): + if name.startswith("__") or name in _NON_SYNTACTIC_ATTRS: + continue + try: + val = getattr(n, name) + except Exception: + continue + if callable(val): + continue + if isinstance(val, (Node, list, tuple)): + stack.append(val) + elif isinstance(n, (list, tuple)): + stack.extend(n) + return exprs, skip_lvalues + + +def find_any_in_tree(tree: Node, idmap: dict[int, Type]) -> list[tuple[int, int, str]]: + exprs, skip_lvalues = _walk_file(tree) + findings: list[tuple[int, int, str]] = [] + for expr in exprs: + if id(expr) in skip_lvalues: + continue + t = idmap.get(id(expr)) + if t is not None and contains_any(t): + findings.append((expr.line, expr.column, str(get_proper_type(t)))) + + out: list[tuple[int, int, str]] = [] + seen_pos: set[tuple[int, int]] = set() + for line, col, typ in sorted(findings): + if line < 1 or (line, col) in seen_pos: + continue + seen_pos.add((line, col)) + out.append((line, col, typ)) + return out + + +# --------------------------------------------------------------------------- # +# Comment scanning (LIT005 + any-ok suppression) +# --------------------------------------------------------------------------- # + + +def _reason_ok(reason: str | None) -> bool: + return reason is not None and len(reason.strip()) >= MIN_REASON_LEN + + +def scan_any_ok( + path: Path, source: str +) -> tuple[frozenset[int], tuple[Violation, ...]]: + """Return (lines with a valid any-ok suppression, LIT005 violations).""" + try: + tokens = tokenize.generate_tokens( + iter(source.splitlines(keepends=True)).__next__ + ) + comments = tuple( + (t.start[0], t.string) for t in tokens if t.type == tokenize.COMMENT + ) + except tokenize.TokenError: + return frozenset(), () + + ok_lines: set[int] = set() + violations: list[Violation] = [] + for line, text in comments: + m = ANY_OK_RE.search(text) + if m is None: + continue + if _reason_ok(m.group("reason")): + ok_lines.add(line) + else: + violations.append( + Violation( + path, + line, + 0, + "LIT005", + "any-ok requires a reason: `# any-ok: `", + ) + ) + return frozenset(ok_lines), tuple(violations) + + +# --------------------------------------------------------------------------- # +# mypy build (parity with `make lint-mypy`) + forced target re-check +# --------------------------------------------------------------------------- # + + +def _build_options() -> Options: + opts = Options() + if MYPY_INI.exists(): + parse_config_file(opts, lambda: None, str(MYPY_INI), sys.stdout, sys.stderr) + opts.export_types = True + opts.preserve_asts = True + opts.incremental = True + opts.cache_dir = str(CACHE_DIR) + opts.show_traceback = False + return opts + + +def _meta_path(module: str) -> Path: + return CACHE_DIR / PY_TAG / (module.replace(".", os.sep) + ".meta.json") + + +def _force_recheck(sources: Sequence[BuildSource]) -> None: + """Invalidate each target's cached entry so mypy re-type-checks (and thus + re-exports types + preserves the AST for) exactly these modules, while their + dependencies stay warm. A missing entry is a cold build for that module. + + mypy trusts a cache entry whenever the source mtime matches the cached one + (it never re-hashes on that fast path), so we must break BOTH: zero the + cached mtime to force a re-hash, and corrupt the cached hash so the re-hash + mismatches and the module is treated as changed.""" + for src in sources: + if not src.module: + continue + meta = _meta_path(src.module) + if not meta.exists(): + continue + try: + data = json.loads(meta.read_text()) + data["hash"] = "0" * 40 + data["mtime"] = 0 + meta.write_text(json.dumps(data)) + except (OSError, ValueError): + continue + + +def check_files(rel_paths: Sequence[str]) -> tuple[Violation, ...]: + """`rel_paths` are relative to the litellm package dir (the build cwd).""" + prev_cwd = Path.cwd() + os.chdir(LITELLM_DIR) + try: + opts = _build_options() + fscache = FileSystemCache() + sources = create_source_list(list(rel_paths), opts, fscache) + _force_recheck(sources) + try: + res = build.build(sources, options=opts, fscache=fscache) + except build.CompileError as exc: + joined = "; ".join(exc.messages[:3]) or "blocking error" + return ( + Violation( + Path(rel_paths[0]), + 0, + 0, + "LIT000", + f"mypy could not build: {joined}", + ), + ) + idmap = {id(expr): t for expr, t in res.types.items()} + # Resolve trees to absolute source paths while cwd is the build dir, since + # mypy stores the paths it was given (relative to this cwd). + trees: dict[str, Node] = {} + for state in res.graph.values(): + if state.path and state.tree is not None: + trees[os.path.realpath(state.path)] = state.tree + finally: + os.chdir(prev_cwd) + + out: list[Violation] = [] + for rel in rel_paths: + abs_path = (LITELLM_DIR / rel).resolve() + report_path = abs_path.relative_to(REPO_ROOT) + if _is_boundary(report_path): + continue + try: + source = abs_path.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError) as exc: + out.append( + Violation(report_path, 0, 0, "LIT000", f"could not read file: {exc}") + ) + continue + + ok_lines, ok_violations = scan_any_ok(report_path, source) + out.extend(ok_violations) + tree = trees.get(os.path.realpath(abs_path)) + if tree is None: + continue + for line, col, typ in find_any_in_tree(tree, idmap): + if line in ok_lines: + continue + out.append( + Violation( + report_path, + line, + col, + "LIT009", + f"value type contains Any -> {typ}", + ) + ) + return tuple(out) + + +# --------------------------------------------------------------------------- # +# File selection (changed-only, changed-lines) + driver +# --------------------------------------------------------------------------- # + + +class _AllLines: + """Sentinel: a wholly new / untracked file -- every line is in scope. + + A distinct object, not None, so that `line_map.get(path)` returning None for + a path absent from the map is never mistaken for "whole file in scope".""" + + +# A changed file's in-scope lines: a specific set, or every line. +LineScope = set[int] | _AllLines +ALL_LINES = _AllLines() + + +def _is_boundary(path: Path) -> bool: + posix = path.as_posix() + return any(frag in posix for frag in BOUNDARY_PATHS) + + +def _git(*args: str) -> list[str]: + result = subprocess.run( + ["git", "-C", str(REPO_ROOT), *args], + capture_output=True, + text=True, + check=True, + ) + return result.stdout.splitlines() + + +def _parse_added_lines(diff_text: str) -> dict[str, set[int]]: + """Map repo-relative path -> set of new-file line numbers the diff adds/edits.""" + changed: dict[str, set[int]] = {} + path: str | None = None + for line in diff_text.splitlines(): + if line.startswith("+++ b/"): + path = line[6:] + elif path and (m := _HUNK_RE.match(line)): + start = int(m.group(1)) + count = int(m.group(2)) if m.group(2) is not None else 1 + if count: + changed.setdefault(path, set()).update(range(start, start + count)) + return changed + + +def changed_line_map(base: str) -> dict[str, LineScope] | None: + """Repo-relative `.py` path under litellm/ -> changed line numbers (or + ALL_LINES for untracked files). Compares the working tree to the merge-base + with `base`, so it covers committed-on-branch + unstaged edits. None if git + is unavailable / not a repo.""" + try: + merge_base = _git("merge-base", base, "HEAD") + point = merge_base[0].strip() if merge_base else base + diff = "\n".join( + _git( + "diff", + "--unified=0", + "--no-color", + "--diff-filter=d", + point, + "--", + "litellm", + ) + ) + untracked = _git("ls-files", "--others", "--exclude-standard", "--", "litellm") + except (subprocess.CalledProcessError, FileNotFoundError): + return None + + out: dict[str, LineScope] = {} + for name, lines in _parse_added_lines(diff).items(): + if name.endswith(".py") and (REPO_ROOT / name).exists(): + out[name] = lines + for name in untracked: + if name.endswith(".py") and (REPO_ROOT / name).exists(): + out[name] = ALL_LINES + return out + + +def _to_litellm_relative(paths: Iterable[Path]) -> list[str]: + rels: list[str] = [] + for p in sorted(paths): + try: + rels.append(p.resolve().relative_to(LITELLM_DIR).as_posix()) + except ValueError: + continue + return rels + + +def _in_scope(v: Violation, line_map: dict[str, LineScope] | None) -> bool: + """A finding survives if line filtering is off (explicit paths), it's a build + error, or its line is one the diff added/edited.""" + if line_map is None or v.code == "LIT000": + return True + lines = line_map.get(v.path.as_posix()) + return lines is ALL_LINES or (lines is not None and v.line in lines) + + +def main(argv: Sequence[str]) -> int: + parser = argparse.ArgumentParser( + description="Any-discipline gate (changed-only, changed-lines)." + ) + parser.add_argument( + "paths", + nargs="*", + help="explicit files (repo-root relative); whole-file, no line filter", + ) + parser.add_argument( + "--changed", + action="store_true", + help="check changed lines under litellm/ vs --base", + ) + parser.add_argument("--base", default=os.environ.get("ANY_GATE_BASE", DEFAULT_BASE)) + args = parser.parse_args(list(argv)) + + line_map: dict[str, LineScope] | None = None + if args.changed: + line_map = changed_line_map(args.base) + if line_map is None: + print( + "check_any_discipline: not a git repository; nothing to check", + file=sys.stderr, + ) + return 0 + rel_paths = _to_litellm_relative( + (REPO_ROOT / name).resolve() for name in line_map + ) + elif args.paths: + rel_paths = _to_litellm_relative((REPO_ROOT / p).resolve() for p in args.paths) + else: + parser.error("pass --changed or explicit file paths") + return 2 + + if not rel_paths: + print("OK: no changed Python lines under litellm/ to check") + return 0 + + violations = tuple(v for v in check_files(rel_paths) if _in_scope(v, line_map)) + + for v in sorted(violations): + print(v.render()) + + if violations: + n = len(violations) + print( + f"\nFAIL: {n} Any-discipline violation(s) on changed lines.\n" + "Give the value a concrete type, or annotate the line `# any-ok: `.", + file=sys.stderr, + ) + return 1 + print( + f"OK: {len(rel_paths)} changed file(s) under litellm/ have no Any-typed values on changed lines" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/scripts/type_check_gate.py b/scripts/type_check_gate.py new file mode 100644 index 000000000000..5ff485f0b0f3 --- /dev/null +++ b/scripts/type_check_gate.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +"""Per-rule count gate for mypy and basedpyright. + +Each tool's output is reduced to a count of errors per *rule* (mypy error codes +like ``arg-type``, basedpyright rules like ``reportAny``) and checked against a +committed budget of the form ``{rule: {baseline, slack}}``, the same shape as +``ruff-strict-budget.json``. A rule fails when its codebase-wide total exceeds +``baseline + slack``. Counts ignore file, line, and column, so a violation +moving anywhere in the tree is invisible; only the per-rule total moves the +needle. + +Unlike ``ruff_strict_gate.py`` this does *not* re-run the tool on the merge base +to compute a delta: a second mypy/basedpyright pass is minutes and gigabytes, +whereas ruff is milliseconds. The committed budget is the baseline instead -- +exactly how the previous per-file gate worked -- so keep it fresh with +``--update`` (ratchet), which re-captures every rule's count from the current +tree while preserving each rule's slack. Tool output is read from stdin, so the +caller decides how to invoke the tool (and from which cwd). + +mypy is parsed from its text output (one error per line, the rule code in a +trailing ``[bracket]``). basedpyright is parsed from ``--outputjson``: its text +diagnostics routinely wrap across lines, leaving the ``(reportRule)`` on a +continuation line away from the ``- error:`` marker, so line parsing +mis-attributes ~60% of errors -- the JSON carries an unambiguous ``rule`` field. +""" + +import argparse +import json +import re +import sys +from collections import Counter +from pathlib import Path +from typing import Iterable, Mapping, NamedTuple + +REPO_ROOT = Path(__file__).resolve().parent.parent + +# mypy: one error per line, e.g. `path:12: error: msg [arg-type]`. ERROR_LINE +# recognizes the line; MYPY_CODE pulls the trailing [code]. Kept separate so an +# error emitted without a code is still counted (under UNCODED), never dropped. +MYPY_ERROR = re.compile(r"^(?P.+?):\d+: error:") +MYPY_CODE = re.compile(r"\[(?P[a-z][a-z0-9-]*)\]\s*$") + +# Bucket for an error whose rule code we couldn't read (a mypy error with no +# code, or a basedpyright diagnostic with no `rule`). Counted so it's gated. +UNCODED = "" + +# Ceiling for a rule that shows up at HEAD but isn't in the budget at all -- a +# brand-new error category (new construct, or a tool/version change). baseline +# is treated as 0, so the rule fails once it clears this much slack. +DEFAULT_SLACK = 10 + + +class Breach(NamedTuple): + code: str + total: int + cap: int + + +def _seed_slack(baseline: int) -> int: + """Slack written for a rule first captured into a budget; busy rules get + more headroom, mirroring the tiering in ruff-strict-budget.json. Existing + rules keep whatever slack their JSON already declares.""" + return 10 if baseline >= 50 else 3 + + +def _to_repo_relative(raw: str) -> str | None: + path = Path(raw) + absolute = path if path.is_absolute() else Path.cwd() / path + try: + return absolute.resolve().relative_to(REPO_ROOT).as_posix() + except ValueError: + return None + + +def count_mypy(lines: Iterable[str]) -> dict[str, int]: + """Count in-repo mypy errors per rule code from text output. Errors for + files outside the repo (third-party stubs) are ignored, as before.""" + counts: Counter[str] = Counter() + for raw in lines: + line = raw.rstrip("\n") + match = MYPY_ERROR.match(line) + if match is None or _to_repo_relative(match.group("file")) is None: + continue + code = MYPY_CODE.search(line) + counts[code.group("code") if code else UNCODED] += 1 + return dict(counts) + + +def count_basedpyright(payload: str) -> dict[str, int]: + """Count in-repo basedpyright errors per rule from `--outputjson`. Warnings + and information are ignored; only `severity == "error"` is gated.""" + try: + data = json.loads(payload or "{}") + except json.JSONDecodeError as exc: + sys.stderr.write( + f"basedpyright did not emit valid JSON ({exc}); it likely crashed or " + f"printed text before the JSON. First 500 chars of its output:\n" + f"{payload[:500]}\n" + ) + raise SystemExit(1) from exc + counts: Counter[str] = Counter() + for diag in data.get("generalDiagnostics", []): + if diag.get("severity") != "error": + continue + if _to_repo_relative(diag.get("file", "")) is None: + continue + counts[diag.get("rule") or UNCODED] += 1 + return dict(counts) + + +def count_errors(stdin_text: str, tool: str) -> dict[str, int]: + if tool == "basedpyright": + return count_basedpyright(stdin_text) + return count_mypy(stdin_text.splitlines()) + + +def evaluate( + counts: Mapping[str, int], budget: Mapping[str, Mapping[str, int]] +) -> list[Breach]: + breaches = [] + for code, total in counts.items(): + spec = budget.get(code) + cap = spec["baseline"] + spec["slack"] if spec else DEFAULT_SLACK + if total > cap: + breaches.append(Breach(code, total, cap)) + return sorted(breaches) + + +def is_vacuous_run( + counts: Mapping[str, int], budget: Mapping[str, Mapping[str, int]] +) -> bool: + """True when nothing was parsed but the budget expects errors -- the + signature of a type checker that crashed or produced no output. The CI pipe + swallows the tool's exit code (`tool || true`), so without this guard an + empty run would clear every ceiling and pass silently.""" + return not counts and any(spec["baseline"] for spec in budget.values()) + + +def budget_path(tool: str) -> Path: + return REPO_ROOT / f"{tool}-code-budget.json" + + +def cmd_update(tool: str, counts: Mapping[str, int]) -> None: + path = budget_path(tool) + existing = json.loads(path.read_text()) if path.exists() else {} + budget = { + code: { + "baseline": count, + "slack": ( + existing[code]["slack"] if code in existing else _seed_slack(count) + ), + } + for code, count in sorted(counts.items()) + } + path.write_text(json.dumps(budget, indent=2, sort_keys=True) + "\n") + print( + f"Re-captured {tool} per-rule budget: {len(budget)} rules, {sum(counts.values())} errors total" + ) + + +def cmd_check(tool: str, counts: Mapping[str, int]) -> None: + budget = json.loads(budget_path(tool).read_text()) + if is_vacuous_run(counts, budget): + expected = sum(spec["baseline"] for spec in budget.values()) + print( + f"FAIL: {tool} produced no errors, but {budget_path(tool).name} expects " + f"~{expected}. The type checker almost certainly crashed or emitted " + f"nothing; refusing to certify a vacuous run." + ) + raise SystemExit(1) + breaches = evaluate(counts, budget) + if not breaches: + print( + f"OK: every rule is within its {tool} ceiling ({sum(counts.values())} errors total)" + ) + return + print(f"FAIL: {tool} errors exceed the per-rule ceiling:") + for breach in breaches: + print(f" {breach.code}: {breach.total} errors over cap {breach.cap}") + print( + f"Resolve the new errors, or run 'make lint-{tool}-budget-update' if the ceiling should move." + ) + raise SystemExit(1) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--tool", choices=("mypy", "basedpyright"), required=True) + parser.add_argument("--update", action="store_true") + args = parser.parse_args() + counts = count_errors(sys.stdin.read(), args.tool) + cmd_update(args.tool, counts) if args.update else cmd_check(args.tool, counts) + + +if __name__ == "__main__": + main() diff --git a/tests/test_litellm/test_check_any_discipline.py b/tests/test_litellm/test_check_any_discipline.py new file mode 100644 index 000000000000..d022eebac073 --- /dev/null +++ b/tests/test_litellm/test_check_any_discipline.py @@ -0,0 +1,41 @@ +import importlib.util +from pathlib import Path + +_MODULE_PATH = ( + Path(__file__).resolve().parents[2] / "scripts" / "check_any_discipline.py" +) +_spec = importlib.util.spec_from_file_location("check_any_discipline", _MODULE_PATH) +mod = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(mod) + +Violation = mod.Violation + + +def _v(path="litellm/x.py", line=10, code="LIT009"): + return Violation(Path(path), line, 0, code, "Any-typed value") + + +def test_violation_on_a_changed_line_is_in_scope(): + assert mod._in_scope(_v(line=10), {"litellm/x.py": {10, 11}}) is True + + +def test_violation_on_an_unchanged_line_of_a_changed_file_is_out_of_scope(): + assert mod._in_scope(_v(line=99), {"litellm/x.py": {10, 11}}) is False + + +def test_whole_new_file_puts_every_line_in_scope(): + assert mod._in_scope(_v(line=99999), {"litellm/x.py": mod.ALL_LINES}) is True + + +def test_file_absent_from_line_map_is_out_of_scope(): + # Regression: ALL_LINES is a distinct sentinel, so a path missing from the map + # (line_map.get -> None) is NOT mistaken for "whole file in scope". + assert mod._in_scope(_v(path="litellm/other.py"), {"litellm/x.py": {1}}) is False + + +def test_no_line_map_means_no_line_filtering(): + assert mod._in_scope(_v(line=12345), None) is True + + +def test_build_error_is_always_in_scope(): + assert mod._in_scope(_v(code="LIT000", line=1), {"litellm/x.py": {2}}) is True diff --git a/tests/test_litellm/test_type_check_gate.py b/tests/test_litellm/test_type_check_gate.py new file mode 100644 index 000000000000..eb01bd3b93e2 --- /dev/null +++ b/tests/test_litellm/test_type_check_gate.py @@ -0,0 +1,133 @@ +import importlib.util +import json +from pathlib import Path + +_MODULE_PATH = Path(__file__).resolve().parents[2] / "scripts" / "type_check_gate.py" +_spec = importlib.util.spec_from_file_location("type_check_gate", _MODULE_PATH) +gate = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(gate) + +ROOT = gate.REPO_ROOT + + +def test_mypy_counts_per_code_ignoring_lines_notes_and_summary(): + text = "\n".join( + [ + f"{ROOT}/litellm/utils.py:10: error: missing annotation [no-untyped-def]", + f"{ROOT}/litellm/utils.py:9999: error: missing annotation [no-untyped-def]", + f"{ROOT}/litellm/main.py:5: error: Returning Any [no-any-return]", + f"{ROOT}/litellm/main.py:5: note: see here", + "Found 3 errors in 2 files (checked 100 source files)", + ] + ) + assert gate.count_errors(text, "mypy") == { + "no-untyped-def": 2, + "no-any-return": 1, + } + + +def _bpr(file, severity, rule): + diag = {"file": str(file), "severity": severity, "message": "msg"} + if rule is not None: + diag["rule"] = rule + return diag + + +def test_basedpyright_counts_per_rule_from_json_not_warnings(): + # basedpyright wraps long messages across lines, so the (reportRule) lands on + # a continuation line away from the `- error:` marker; --outputjson avoids it. + payload = json.dumps( + { + "generalDiagnostics": [ + _bpr(f"{ROOT}/litellm/utils.py", "error", "reportUnknownVariableType"), + _bpr(f"{ROOT}/litellm/utils.py", "error", "reportUnknownVariableType"), + _bpr(f"{ROOT}/litellm/main.py", "error", "reportArgumentType"), + _bpr(f"{ROOT}/litellm/main.py", "warning", "reportUnusedImport"), + ] + } + ) + assert gate.count_errors(payload, "basedpyright") == { + "reportUnknownVariableType": 2, + "reportArgumentType": 1, + } + + +def test_basedpyright_error_without_a_rule_is_bucketed(): + payload = json.dumps( + {"generalDiagnostics": [_bpr(f"{ROOT}/litellm/x.py", "error", None)]} + ) + assert gate.count_errors(payload, "basedpyright") == {gate.UNCODED: 1} + + +def test_mypy_error_without_a_code_is_bucketed_so_it_is_still_gated(): + text = f"{ROOT}/litellm/x.py:1: error: something broke with no code" + assert gate.count_errors(text, "mypy") == {gate.UNCODED: 1} + + +def test_paths_outside_repo_are_skipped(): + text = "/tmp/elsewhere.py:1: error: missing annotation [no-untyped-def]" + assert gate.count_errors(text, "mypy") == {} + payload = json.dumps( + { + "generalDiagnostics": [ + _bpr("/tmp/elsewhere.py", "error", "reportArgumentType") + ] + } + ) + assert gate.count_errors(payload, "basedpyright") == {} + + +def test_at_or_under_ceiling_passes(): + budget = {"no-any-return": {"baseline": 5, "slack": 0}} + assert gate.evaluate({"no-any-return": 5}, budget) == [] + + +def test_one_more_error_than_ceiling_fails(): + budget = {"no-any-return": {"baseline": 5, "slack": 0}} + assert gate.evaluate({"no-any-return": 6}, budget) == [ + gate.Breach("no-any-return", 6, 5) + ] + + +def test_slack_absorbs_small_increase_then_fails_past_it(): + budget = {"arg-type": {"baseline": 5, "slack": 5}} + assert gate.evaluate({"arg-type": 10}, budget) == [] + assert gate.evaluate({"arg-type": 11}, budget) == [gate.Breach("arg-type", 11, 10)] + + +def test_unbudgeted_new_code_uses_default_slack(): + assert gate.evaluate({"brand-new": gate.DEFAULT_SLACK}, {}) == [] + assert gate.evaluate({"brand-new": gate.DEFAULT_SLACK + 1}, {}) == [ + gate.Breach("brand-new", gate.DEFAULT_SLACK + 1, gate.DEFAULT_SLACK) + ] + + +def test_no_output_against_a_nonempty_budget_is_a_vacuous_run(): + # A crashed type checker emits nothing; the gate must not certify it as clean. + budget = {"no-untyped-def": {"baseline": 4888, "slack": 10}} + assert gate.is_vacuous_run({}, budget) is True + + +def test_genuine_zero_and_empty_budget_are_not_vacuous(): + assert gate.is_vacuous_run({}, {}) is False + assert ( + gate.is_vacuous_run({}, {"no-untyped-def": {"baseline": 0, "slack": 3}}) + is False + ) + assert ( + gate.is_vacuous_run({"arg-type": 1}, {"arg-type": {"baseline": 9, "slack": 1}}) + is False + ) + + +def test_malformed_basedpyright_json_exits_loudly_not_as_zero_errors(): + import pytest + + with pytest.raises(SystemExit): + gate.count_errors("startup warning\n{not json", "basedpyright") + + +def test_empty_basedpyright_payload_counts_zero(): + # Empty (not malformed) output parses to zero; the vacuous-run guard, not the + # parser, is what rejects an empty run. + assert gate.count_errors("", "basedpyright") == {} diff --git a/uv.lock b/uv.lock index 0efaa74cddb5..bc796e6ed07e 100644 --- a/uv.lock +++ b/uv.lock @@ -9,7 +9,7 @@ resolution-markers = [ ] [options] -exclude-newer = "2026-06-10T00:35:00.40525Z" +exclude-newer = "2026-06-11T06:56:06.940919973Z" exclude-newer-span = "P3D" [manifest] @@ -540,6 +540,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a0/59/76ab57e3fe74484f48a53f8e337171b4a2349e506eabe136d7e01d059086/backports_asyncio_runner-1.2.0-py3-none-any.whl", hash = "sha256:0da0a936a8aeb554eccb426dc55af3ba63bcdc69fa1a600b5bb305413a4477b5", size = 12313, upload-time = "2025-07-02T02:27:14.263Z" }, ] +[[package]] +name = "basedpyright" +version = "1.39.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nodejs-wheel-binaries" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/2f/e5/0d685b5808436c628ab8b9edad6810b889d11044a962bc42b128543910ea/basedpyright-1.39.7.tar.gz", hash = "sha256:688d913a19c417870c164c630ed9cdd83a8d8b484b30ab8e99f5dec4ae9604a6", size = 25503256, upload-time = "2026-06-07T11:33:27.266Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a1/f4/5b1e8ea279ce8f97a6bb1518c84fa25f5794022053ce10eab22ad3f0b51b/basedpyright-1.39.7-py3-none-any.whl", hash = "sha256:81266deb6044c9be98fb4555e4b7b1a521d8aee06b66e80858d183b0e3991140", size = 13182666, upload-time = "2026-06-07T11:33:24.119Z" }, +] + [[package]] name = "beautifulsoup4" version = "4.14.3" @@ -3416,13 +3428,13 @@ ci = [ { name = "pyarrow" }, { name = "pygithub" }, { name = "pylint" }, - { name = "pyright" }, { name = "pytest-codspeed" }, { name = "pytest-retry" }, { name = "tenacity" }, { name = "traceloop-sdk" }, ] dev = [ + { name = "basedpyright" }, { name = "black" }, { name = "diff-cover" }, { name = "fakeredis" }, @@ -3584,13 +3596,13 @@ ci = [ { name = "pyarrow", specifier = "==23.0.1" }, { name = "pygithub", specifier = "==2.8.1" }, { name = "pylint", specifier = "==4.0.5" }, - { name = "pyright", specifier = "==1.1.408" }, { name = "pytest-codspeed", specifier = "==4.3.0" }, { name = "pytest-retry", specifier = "==1.7.0" }, { name = "tenacity", specifier = "==8.5.0" }, { name = "traceloop-sdk", specifier = "==0.33.12" }, ] dev = [ + { name = "basedpyright", specifier = "==1.39.7" }, { name = "black", specifier = "==26.3.1" }, { name = "diff-cover", specifier = "==9.7.2" }, { name = "fakeredis", specifier = "==2.34.1" }, @@ -4270,6 +4282,22 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/88/b2/d0896bdcdc8d28a7fc5717c305f1a861c26e18c05047949fb371034d98bd/nodeenv-1.10.0-py2.py3-none-any.whl", hash = "sha256:5bb13e3eed2923615535339b3c620e76779af4cb4c6a90deccc9e36b274d3827", size = 23438, upload-time = "2025-12-20T14:08:52.782Z" }, ] +[[package]] +name = "nodejs-wheel-binaries" +version = "24.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a3/22/2a5beb4e21417c73233d9f65cf6f3e96e891b80d2f550a8f630ebc6b88c6/nodejs_wheel_binaries-24.16.0.tar.gz", hash = "sha256:c973cb69dc5fd16e6f6dc6e579e2c3d5534e2a1f57619dddf5ba070efa7dde37", size = 8056, upload-time = "2026-05-30T16:52:09.807Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/83/d1/68b43b53cd0fa83ae6fd406705023ca988d9e0ca41c724d82e66fbeb2ef6/nodejs_wheel_binaries-24.16.0-py2.py3-none-macosx_13_0_arm64.whl", hash = "sha256:d9f8f677dcf30e37ac244f07869726abe043f01eb0f45722b1df31cc2af7093c", size = 55666374, upload-time = "2026-05-30T16:51:39.588Z" }, + { url = "https://files.pythonhosted.org/packages/e9/b2/40a989159599080da485de966c4c2d207e852ac7aa7864702626d96c8bf5/nodejs_wheel_binaries-24.16.0-py2.py3-none-macosx_13_0_x86_64.whl", hash = "sha256:3d0370fe7120ce9697a4f60d40480d2bd8808d9f30131458d5afc0040d4e5a51", size = 55838487, upload-time = "2026-05-30T16:51:43.383Z" }, + { url = "https://files.pythonhosted.org/packages/d7/a7/cd42174fb5ff6faff7fa8d326a18914d8f232098ab5de055b57c16fa13ca/nodejs_wheel_binaries-24.16.0-py2.py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:85dc92bbb79c851569c5925dcc2a4c915a034efab375f99e4e7e6bbe9cca8342", size = 60179540, upload-time = "2026-05-30T16:51:47.036Z" }, + { url = "https://files.pythonhosted.org/packages/2b/95/c8a1f9ae140aa28df8744d984d01d4b3af7cdd6555af12127f40ceb45a7d/nodejs_wheel_binaries-24.16.0-py2.py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:2f3036292811514ba847b3708492644764f88a833ac425c5f55007014308ddfd", size = 60716262, upload-time = "2026-05-30T16:51:50.711Z" }, + { url = "https://files.pythonhosted.org/packages/64/c9/7c35b3737f59e36d0249c265397b7bff570519b95301d6e16ea361e904ad/nodejs_wheel_binaries-24.16.0-py2.py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:db8a8a76ebd2b28ecbfc9ad464baa3707241b9e050a30e2efdf6f60c0f886502", size = 62230592, upload-time = "2026-05-30T16:51:55Z" }, + { url = "https://files.pythonhosted.org/packages/04/96/d931255cf9d11a84d6b54d882dba7434646467d568ccf070ea3418638df3/nodejs_wheel_binaries-24.16.0-py2.py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:f1a3d8f7b4491cbbd023ba3fc4e901fcca2d9fb80d57f24ba3890de8b1dbac03", size = 62841759, upload-time = "2026-05-30T16:51:59.407Z" }, + { url = "https://files.pythonhosted.org/packages/a2/7b/8b7a3f41bc255411be30b6d7d288aab8ffd9ea2055db8555ced3548007b9/nodejs_wheel_binaries-24.16.0-py2.py3-none-win_amd64.whl", hash = "sha256:bb136be9944f0662dcf1120f45193a6b75b13fac378971a95cc42c9f879a81aa", size = 42027734, upload-time = "2026-05-30T16:52:03.348Z" }, + { url = "https://files.pythonhosted.org/packages/17/66/1ed71f1f529b8ca727d42c7ceb9db0bef145ce4a13dfc86fb50aa44f3be6/nodejs_wheel_binaries-24.16.0-py2.py3-none-win_arm64.whl", hash = "sha256:8308940b5edd0a50dc5267ea36ba21c9f668e83fe0d9f293937174d3a7e31c36", size = 39714528, upload-time = "2026-05-30T16:52:06.421Z" }, +] + [[package]] name = "numpy" version = "1.26.4" @@ -6082,19 +6110,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/5a/dc/491b7661614ab97483abf2056be1deee4dc2490ecbf7bff9ab5cdbac86e1/pyreadline3-3.5.4-py3-none-any.whl", hash = "sha256:eaf8e6cc3c49bcccf145fc6067ba8643d1df34d604a1ec0eccbf7a18e6d3fae6", size = 83178, upload-time = "2024-09-19T02:40:08.598Z" }, ] -[[package]] -name = "pyright" -version = "1.1.408" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "nodeenv" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/74/b2/5db700e52554b8f025faa9c3c624c59f1f6c8841ba81ab97641b54322f16/pyright-1.1.408.tar.gz", hash = "sha256:f28f2321f96852fa50b5829ea492f6adb0e6954568d1caa3f3af3a5f555eb684", size = 4400578, upload-time = "2026-01-08T08:07:38.795Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0c/82/a2c93e32800940d9573fb28c346772a14778b84ba7524e691b324620ab89/pyright-1.1.408-py3-none-any.whl", hash = "sha256:090b32865f4fdb1e0e6cd82bf5618480d48eecd2eb2e70f960982a3d9a4c17c1", size = 6399144, upload-time = "2026-01-08T08:07:37.082Z" }, -] - [[package]] name = "pyroscope-io" version = "0.8.16"