The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
3[Fix] CI/CD - logging_testing (#18204)
Alexsander Hamir2e7b55474730
diff --git a/litellm/caching/redis_cache.py b/litellm/caching/redis_cache.pyindex a988a81b6f0..ea7e3f5a979 100644--- a/litellm/caching/redis_cache.py+++ b/litellm/caching/redis_cache.py@@ -146,9 +146,17 @@ class RedisCache(BaseCache):except Exception:pass- ### ASYNC HEALTH PING ###+ self._setup_health_pings()++ if litellm.default_redis_ttl is not None:+ super().__init__(default_ttl=int(litellm.default_redis_ttl))+ else:+ super().__init__() # defaults to 60s++ def _setup_health_pings(self):+ """Setup async and sync health pings for Redis."""+ # ASYNC HEALTH PINGtry:- # asyncio.get_running_loop().create_task(self.ping())_ = asyncio.get_running_loop().create_task(self.ping())except Exception as e:if "no running event loop" in str(e):@@ -160,24 +168,9 @@ class RedisCache(BaseCache):"Error connecting to Async Redis client - {}".format(str(e)),extra={"error": str(e)},)- # Non-blocking service health monitoring for async Redis init failures- try:- loop = asyncio.get_running_loop()- start_time = time.time()- end_time = start_time- loop.create_task(- self.service_logger_obj.async_service_failure_hook(- service=ServiceTypes.REDIS,- duration=end_time - start_time,- error=e,- call_type="redis_async_ping",- )- )- except Exception:- # If no event loop or hook fails, ignore to keep init non-blocking- pass+ self._handle_async_ping_error(e)- ### SYNC HEALTH PING ###+ # SYNC HEALTH PINGtry:if hasattr(self.redis_client, "ping"):self.redis_client.ping() # type: ignore@@ -185,27 +178,41 @@ class RedisCache(BaseCache):verbose_logger.error("Error connecting to Sync Redis client", extra={"error": str(e)})- # Non-blocking service health monitoring for sync Redis init failures- try:- loop = asyncio.get_running_loop()- start_time = time.time()- end_time = start_time- loop.create_task(- self.service_logger_obj.async_service_failure_hook(- service=ServiceTypes.REDIS,- duration=end_time - start_time,- error=e,- call_type="redis_sync_ping",- )+ self._handle_sync_ping_error(e)++ def _handle_async_ping_error(self, e: Exception):+ """Handle async ping error with service failure hook."""+ try:+ loop = asyncio.get_running_loop()+ start_time = time.time()+ end_time = start_time+ loop.create_task(+ self.service_logger_obj.async_service_failure_hook(+ service=ServiceTypes.REDIS,+ duration=end_time - start_time,+ error=e,+ call_type="redis_async_ping",)- except Exception:- # If no event loop or hook fails, ignore to keep init non-blocking- pass+ )+ except Exception:+ pass- if litellm.default_redis_ttl is not None:- super().__init__(default_ttl=int(litellm.default_redis_ttl))- else:- super().__init__() # defaults to 60s+ def _handle_sync_ping_error(self, e: Exception):+ """Handle sync ping error with service failure hook."""+ try:+ loop = asyncio.get_running_loop()+ start_time = time.time()+ end_time = start_time+ loop.create_task(+ self.service_logger_obj.async_service_failure_hook(+ service=ServiceTypes.REDIS,+ duration=end_time - start_time,+ error=e,+ call_type="redis_sync_ping",+ )+ )+ except Exception:+ passdef _get_async_client_cache_key(self) -> str:"""diff --git a/litellm/integrations/arize/arize_phoenix.py b/litellm/integrations/arize/arize_phoenix.pyindex c0cd8cbf913..cd345a7f76d 100644--- a/litellm/integrations/arize/arize_phoenix.py+++ b/litellm/integrations/arize/arize_phoenix.py@@ -1,12 +1,10 @@import osfrom typing import TYPE_CHECKING, Any, Optional, Union-from datetime import datetimefrom litellm._logging import verbose_loggerfrom litellm.integrations.arize import _utilsfrom litellm.integrations.arize._utils import ArizeOTELAttributesfrom litellm.types.integrations.arize_phoenix import ArizePhoenixConfig-from litellm.types.services import ServiceLoggerPayloadfrom litellm.integrations.opentelemetry import OpenTelemetryif TYPE_CHECKING:diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.pyindex 6a0223b35ba..e2e90abeb1b 100644--- a/litellm/proxy/auth/auth_checks.py+++ b/litellm/proxy/auth/auth_checks.py@@ -176,6 +176,15 @@ async def common_checks()## 4.2 check team member budget, if team key+ await _check_team_member_budget(+ team_object=team_object,+ user_object=user_object,+ valid_token=valid_token,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )+# 5. If end_user ('user' passed to /chat/completions, /embeddings endpoint) is in budgetif end_user_object is not None and end_user_object.litellm_budget_table is not None:end_user_budget = end_user_object.litellm_budget_table.max_budget@@ -2027,6 +2036,46 @@ async def _virtual_key_max_budget_alert_check()+async def _check_team_member_budget(+ team_object: Optional[LiteLLM_TeamTable],+ user_object: Optional[LiteLLM_UserTable],+ valid_token: Optional[UserAPIKeyAuth],+ prisma_client: Optional[PrismaClient],+ user_api_key_cache: DualCache,+ proxy_logging_obj: ProxyLogging,+):+ """Check if team member is over their max budget within the team."""+ if (+ team_object is not None+ and team_object.team_id is not None+ and user_object is not None+ and valid_token is not None+ and valid_token.user_id is not None+ ):+ team_membership = await get_team_membership(+ user_id=valid_token.user_id,+ team_id=team_object.team_id,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ proxy_logging_obj=proxy_logging_obj,+ )++ if (+ team_membership is not None+ and team_membership.litellm_budget_table is not None+ and team_membership.litellm_budget_table.max_budget is not None+ ):+ team_member_budget = team_membership.litellm_budget_table.max_budget+ team_member_spend = team_membership.spend or 0.0++ if team_member_spend > team_member_budget:+ raise litellm.BudgetExceededError(+ current_cost=team_member_spend,+ max_budget=team_member_budget,+ message=f"Budget has been exceeded! User={valid_token.user_id} in Team={team_object.team_id} Current cost: {team_member_spend}, Max budget: {team_member_budget}",+ )++async def _team_max_budget_check(team_object: Optional[LiteLLM_TeamTable],valid_token: Optional[UserAPIKeyAuth],diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.pyindex 5d96c389b61..49eacb32a0b 100644--- a/litellm/responses/litellm_completion_transformation/transformation.py+++ b/litellm/responses/litellm_completion_transformation/transformation.py@@ -480,10 +480,10 @@ class LiteLLMCompletionResponsesConfig:function: dict = _tool_use_definition.get("function") or {}tool_call_chunk = ChatCompletionToolCallChunk(id=_tool_use_definition.get("id") or "",- type=_tool_use_definition.get("type") or "function",+ type=cast(Literal["function"], _tool_use_definition.get("type") or "function"),function=ChatCompletionToolCallFunctionChunk(name=function.get("name") or "",- arguments=function.get("arguments") or "",+ arguments=str(function.get("arguments") or ""),),index=0,)@@ -527,7 +527,7 @@ class LiteLLMCompletionResponsesConfig:type="function",function=ChatCompletionToolCallFunctionChunk(name=function_call.get("name") or "",- arguments=function_call.get("arguments") or "",+ arguments=str(function_call.get("arguments") or ""),),index=0,)diff --git a/litellm/router_strategy/lowest_tpm_rpm.py b/litellm/router_strategy/lowest_tpm_rpm.pyindex 1bd065a3e42..93d3c8e0415 100644--- a/litellm/router_strategy/lowest_tpm_rpm.py+++ b/litellm/router_strategy/lowest_tpm_rpm.py@@ -103,7 +103,10 @@ class LowestTPMLoggingHandler(CustomLogger):"model_group", None)- id = kwargs["litellm_params"].get("model_info", {}).get("id", None)+ model_info = kwargs["litellm_params"].get("model_info")+ id = None+ if model_info is not None and isinstance(model_info, dict):+ id = model_info.get("id", None)if model_group is None or id is None:returnelif isinstance(id, int):diff --git a/tests/logging_callback_tests/test_langsmith_unit_test.py b/tests/logging_callback_tests/test_langsmith_unit_test.pyindex 4a1807ec83a..e63ce9f8b38 100644--- a/tests/logging_callback_tests/test_langsmith_unit_test.py+++ b/tests/logging_callback_tests/test_langsmith_unit_test.py@@ -210,11 +210,20 @@ async def test_langsmith_key_based_logging(mocker):"""try:# Mock the httpx post request- mock_post = mocker.patch(- "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.post"+ # We need to mock get_async_httpx_client to return a mock AsyncHTTPHandler+ # because LangsmithLogger creates its own instance+ mock_async_httpx_handler = AsyncMock()+ mock_response = MagicMock() # Use MagicMock for response to allow sync methods+ mock_response.status_code = 200+ mock_response.raise_for_status = MagicMock() # raise_for_status is sync in httpx+ mock_response.text = ""+ mock_async_httpx_handler.post = AsyncMock(return_value=mock_response)++ mock_get_client = mocker.patch(+ "litellm.integrations.langsmith.get_async_httpx_client",+ return_value=mock_async_httpx_handler)- mock_post.return_value.status_code = 200- mock_post.return_value.raise_for_status = lambda: None+litellm.set_verbose = Truelitellm.DEFAULT_FLUSH_INTERVAL_SECONDS = 1@@ -234,8 +243,8 @@ async def test_langsmith_key_based_logging(mocker):print("done sleeping 3 seconds...")# Verify the post request was made with correct parameters- mock_post.assert_called_once()- call_args = mock_post.call_args+ mock_async_httpx_handler.post.assert_called_once()+ call_args = mock_async_httpx_handler.post.call_argsprint("call_args", call_args)diff --git a/tests/test_litellm/proxy/auth/test_team_member_budget.py b/tests/test_litellm/proxy/auth/test_team_member_budget.pynew file mode 100644index 00000000000..b46331624f8--- /dev/null+++ b/tests/test_litellm/proxy/auth/test_team_member_budget.py@@ -0,0 +1,364 @@+"""+Unit tests for team member budget checks in common_checks.+These tests verify the team member budget enforcement without requiring a proxy server.+"""+import pytest+from unittest.mock import AsyncMock, MagicMock, patch+from fastapi import Request++import litellm+from litellm.proxy._types import (+ LiteLLM_BudgetTable,+ LiteLLM_TeamMembership,+ LiteLLM_TeamTable,+ LiteLLM_UserTable,+ UserAPIKeyAuth,+)+from litellm.proxy.auth.auth_checks import common_checks, get_team_membership+++async def test_team_member_budget_check_exceeds_budget():+ """Test that common_checks raises BudgetExceededError when team member spend exceeds budget."""+ request_body = {+ "model": "gpt-3.5-turbo",+ "messages": [{"role": "user", "content": "test"}],+ }++ # Create team object+ team_object = LiteLLM_TeamTable(+ team_id="test-team-1",+ team_alias="Test Team",+ spend=0.0,+ max_budget=None,+ )++ # Create user object+ user_object = LiteLLM_UserTable(+ user_id="test-user-1",+ spend=0.0,+ max_budget=None,+ )++ # Create valid token+ valid_token = UserAPIKeyAuth(+ token="test-token",+ user_id="test-user-1",+ team_id="test-team-1",+ models=["gpt-3.5-turbo"],+ )++ # Create team membership with budget exceeded+ team_membership = LiteLLM_TeamMembership(+ user_id="test-user-1",+ team_id="test-team-1",+ spend=0.0000002, # Exceeds budget+ litellm_budget_table=LiteLLM_BudgetTable(+ max_budget=0.0000001, # Very small budget+ ),+ )++ mock_request = MagicMock(spec=Request)+ mock_prisma_client = MagicMock()+ mock_user_api_key_cache = MagicMock()+ mock_proxy_logging_obj = MagicMock()++ # Mock get_team_membership to return our team membership+ with patch(+ "litellm.proxy.auth.auth_checks.get_team_membership",+ new_callable=AsyncMock,+ return_value=team_membership,+ ), patch(+ "litellm.proxy.proxy_server.prisma_client", mock_prisma_client+ ), patch(+ "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache+ ):+ # Should raise BudgetExceededError+ with pytest.raises(litellm.BudgetExceededError) as exc_info:+ await common_checks(+ request_body=request_body,+ team_object=team_object,+ user_object=user_object,+ end_user_object=None,+ global_proxy_spend=None,+ general_settings={},+ route="/chat/completions",+ llm_router=None,+ proxy_logging_obj=mock_proxy_logging_obj,+ valid_token=valid_token,+ request=mock_request,+ )++ # Verify error message contains expected text+ assert "Budget has been exceeded" in str(exc_info.value)+ assert "test-user-1" in str(exc_info.value)+ assert "test-team-1" in str(exc_info.value)+++async def test_team_member_budget_check_within_budget():+ """Test that common_checks passes when team member spend is within budget."""+ request_body = {+ "model": "gpt-3.5-turbo",+ "messages": [{"role": "user", "content": "test"}],+ }++ # Create team object+ team_object = LiteLLM_TeamTable(+ team_id="test-team-1",+ team_alias="Test Team",+ spend=0.0,+ max_budget=None,+ )++ # Create user object+ user_object = LiteLLM_UserTable(+ user_id="test-user-1",+ spend=0.0,+ max_budget=None,+ )++ # Create valid token+ valid_token = UserAPIKeyAuth(+ token="test-token",+ user_id="test-user-1",+ team_id="test-team-1",+ models=["gpt-3.5-turbo"],+ )++ # Create team membership within budget+ team_membership = LiteLLM_TeamMembership(+ user_id="test-user-1",+ team_id="test-team-1",+ spend=0.00000005, # Within budget+ litellm_budget_table=LiteLLM_BudgetTable(+ max_budget=0.0000001,+ ),+ )++ mock_request = MagicMock(spec=Request)+ mock_prisma_client = MagicMock()+ mock_user_api_key_cache = MagicMock()+ mock_proxy_logging_obj = MagicMock()++ # Mock get_team_membership to return our team membership+ with patch(+ "litellm.proxy.auth.auth_checks.get_team_membership",+ new_callable=AsyncMock,+ return_value=team_membership,+ ), patch(+ "litellm.proxy.proxy_server.prisma_client", mock_prisma_client+ ), patch(+ "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache+ ):+ # Should not raise an exception+ result = await common_checks(+ request_body=request_body,+ team_object=team_object,+ user_object=user_object,+ end_user_object=None,+ global_proxy_spend=None,+ general_settings={},+ route="/chat/completions",+ llm_router=None,+ proxy_logging_obj=mock_proxy_logging_obj,+ valid_token=valid_token,+ request=mock_request,+ )++ assert result is True+++async def test_team_member_budget_check_no_budget_set():+ """Test that common_checks passes when team member has no budget set."""+ request_body = {+ "model": "gpt-3.5-turbo",+ "messages": [{"role": "user", "content": "test"}],+ }++ # Create team object+ team_object = LiteLLM_TeamTable(+ team_id="test-team-1",+ team_alias="Test Team",+ spend=0.0,+ max_budget=None,+ )++ # Create user object+ user_object = LiteLLM_UserTable(+ user_id="test-user-1",+ spend=0.0,+ max_budget=None,+ )++ # Create valid token+ valid_token = UserAPIKeyAuth(+ token="test-token",+ user_id="test-user-1",+ team_id="test-team-1",+ models=["gpt-3.5-turbo"],+ )++ # Create team membership without budget+ team_membership = LiteLLM_TeamMembership(+ user_id="test-user-1",+ team_id="test-team-1",+ spend=0.0,+ litellm_budget_table=None, # No budget set+ )++ mock_request = MagicMock(spec=Request)+ mock_prisma_client = MagicMock()+ mock_user_api_key_cache = MagicMock()+ mock_proxy_logging_obj = MagicMock()++ # Mock get_team_membership to return our team membership+ with patch(+ "litellm.proxy.auth.auth_checks.get_team_membership",+ new_callable=AsyncMock,+ return_value=team_membership,+ ), patch(+ "litellm.proxy.proxy_server.prisma_client", mock_prisma_client+ ), patch(+ "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache+ ):+ # Should not raise an exception (no budget means no limit)+ result = await common_checks(+ request_body=request_body,+ team_object=team_object,+ user_object=user_object,+ end_user_object=None,+ global_proxy_spend=None,+ general_settings={},+ route="/chat/completions",+ llm_router=None,+ proxy_logging_obj=mock_proxy_logging_obj,+ valid_token=valid_token,+ request=mock_request,+ )++ assert result is True+++async def test_team_member_budget_check_no_team_membership():+ """Test that common_checks passes when team membership doesn't exist."""+ request_body = {+ "model": "gpt-3.5-turbo",+ "messages": [{"role": "user", "content": "test"}],+ }++ # Create team object+ team_object = LiteLLM_TeamTable(+ team_id="test-team-1",+ team_alias="Test Team",+ spend=0.0,+ max_budget=None,+ )++ # Create user object+ user_object = LiteLLM_UserTable(+ user_id="test-user-1",+ spend=0.0,+ max_budget=None,+ )++ # Create valid token+ valid_token = UserAPIKeyAuth(+ token="test-token",+ user_id="test-user-1",+ team_id="test-team-1",+ models=["gpt-3.5-turbo"],+ )++ mock_request = MagicMock(spec=Request)+ mock_prisma_client = MagicMock()+ mock_user_api_key_cache = MagicMock()+ mock_proxy_logging_obj = MagicMock()++ # Mock get_team_membership to return None (no membership)+ with patch(+ "litellm.proxy.auth.auth_checks.get_team_membership",+ new_callable=AsyncMock,+ return_value=None,+ ), patch(+ "litellm.proxy.proxy_server.prisma_client", mock_prisma_client+ ), patch(+ "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache+ ):+ # Should not raise an exception (no membership means no budget check)+ result = await common_checks(+ request_body=request_body,+ team_object=team_object,+ user_object=user_object,+ end_user_object=None,+ global_proxy_spend=None,+ general_settings={},+ route="/chat/completions",+ llm_router=None,+ proxy_logging_obj=mock_proxy_logging_obj,+ valid_token=valid_token,+ request=mock_request,+ )++ assert result is True+++async def test_team_member_budget_check_personal_key_not_team():+ """Test that team member budget check is skipped for personal keys (no team)."""+ request_body = {+ "model": "gpt-3.5-turbo",+ "messages": [{"role": "user", "content": "test"}],+ }++ # No team object (personal key)+ team_object = None++ # Create user object+ user_object = LiteLLM_UserTable(+ user_id="test-user-1",+ spend=0.0,+ max_budget=None,+ )++ # Create valid token without team+ valid_token = UserAPIKeyAuth(+ token="test-token",+ user_id="test-user-1",+ team_id=None, # Personal key+ models=["gpt-3.5-turbo"],+ )++ mock_request = MagicMock(spec=Request)+ mock_prisma_client = MagicMock()+ mock_user_api_key_cache = MagicMock()+ mock_proxy_logging_obj = MagicMock()++ # get_team_membership should not be called for personal keys+ with patch(+ "litellm.proxy.auth.auth_checks.get_team_membership",+ new_callable=AsyncMock,+ ) as mock_get_team_membership, patch(+ "litellm.proxy.proxy_server.prisma_client", mock_prisma_client+ ), patch(+ "litellm.proxy.proxy_server.user_api_key_cache", mock_user_api_key_cache+ ):+ result = await common_checks(+ request_body=request_body,+ team_object=team_object,+ user_object=user_object,+ end_user_object=None,+ global_proxy_spend=None,+ general_settings={},+ route="/chat/completions",+ llm_router=None,+ proxy_logging_obj=mock_proxy_logging_obj,+ valid_token=valid_token,+ request=mock_request,+ )++ # Should pass and get_team_membership should not be called+ assert result is True+ mock_get_team_membership.assert_not_called()