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
(Fix) - Slack Alerting , don't send duplicate spend report when used on multi instance settings (#7546)
Ishaan Jaffd1b101b9d764
diff --git a/litellm/integrations/SlackAlerting/slack_alerting.py b/litellm/integrations/SlackAlerting/slack_alerting.pyindex 526610f0af3..97e1081767d 100644--- a/litellm/integrations/SlackAlerting/slack_alerting.py+++ b/litellm/integrations/SlackAlerting/slack_alerting.py@@ -17,6 +17,7 @@ import litellm.typesfrom litellm._logging import verbose_logger, verbose_proxy_loggerfrom litellm.caching.caching import DualCachefrom litellm.integrations.custom_batch_logger import CustomBatchLogger+from litellm.litellm_core_utils.duration_parser import duration_in_secondsfrom litellm.litellm_core_utils.exception_mapping_utils import (_add_key_name_and_team_to_alert,)@@ -1557,11 +1558,15 @@ Model Info:await asyncio.sleep(interval)return- async def send_weekly_spend_report(self, time_range: str = "7d"):+ async def send_weekly_spend_report(+ self,+ time_range: str = "7d",+ ):"""Send a spend report for a configurable time range.- :param time_range: A string specifying the time range, e.g., "1d", "7d", "30d"+ Args:+ time_range: A string specifying the time range for the report, e.g., "1d", "7d", "30d""""if self.alerting is None or "spend_reports" not in self.alert_types:return@@ -1579,6 +1584,10 @@ Model Info:todays_date = datetime.datetime.now().date()start_date = todays_date - datetime.timedelta(days=days)+ _event_cache_key = f"weekly_spend_report_sent_{start_date.strftime('%Y-%m-%d')}_{todays_date.strftime('%Y-%m-%d')}"+ if await self.internal_usage_cache.async_get_cache(key=_event_cache_key):+ return+_resp = await _get_spend_report_for_time_range(start_date=start_date.strftime("%Y-%m-%d"),end_date=todays_date.strftime("%Y-%m-%d"),@@ -1610,6 +1619,13 @@ Model Info:alert_type=AlertType.spend_reports,alerting_metadata={},)++ await self.internal_usage_cache.async_set_cache(+ key=_event_cache_key,+ value="SENT",+ ttl=duration_in_seconds(time_range),+ )+except ValueError as ve:verbose_proxy_logger.error(f"Invalid time range format: {ve}")except Exception as e:@@ -1631,6 +1647,10 @@ Model Info:days=last_day_of_month - 1)+ _event_cache_key = f"monthly_spend_report_sent_{first_day_of_month.strftime('%Y-%m-%d')}_{last_day_of_month.strftime('%Y-%m-%d')}"+ if await self.internal_usage_cache.async_get_cache(key=_event_cache_key):+ return+_resp = await _get_spend_report_for_time_range(start_date=first_day_of_month.strftime("%Y-%m-%d"),end_date=last_day_of_month.strftime("%Y-%m-%d"),@@ -1669,6 +1689,13 @@ Model Info:alert_type=AlertType.spend_reports,alerting_metadata={},)++ await self.internal_usage_cache.async_set_cache(+ key=_event_cache_key,+ value="SENT",+ ttl=(30 * 24 * 60 * 60), # 1 month+ )+except Exception as e:verbose_proxy_logger.exception("Error sending weekly spend report %s", e)diff --git a/tests/logging_callback_tests/test_alerting.py b/tests/logging_callback_tests/test_alerting.pyindex c095a1619ec..88fd13c6810 100644--- a/tests/logging_callback_tests/test_alerting.py+++ b/tests/logging_callback_tests/test_alerting.py@@ -925,3 +925,59 @@ async def test_print_alerting_payload_warning():# Clean upverbose_proxy_logger.removeHandler(handler)log_stream.close()++[email protected]("report_type", ["weekly", "monthly"])+async def test_spend_report_cache(report_type):+ """+ Test that spend reports are only sent once within their period+ """+ # Mock prisma client response+ mock_spend_data = [+ {"team_alias": "team1", "total_spend": 100.0},+ {"team_alias": "team2", "total_spend": 200.0},+ ]++ mock_tag_data = [+ {"individual_request_tag": "tag1", "total_spend": 150.0},+ {"individual_request_tag": "tag2", "total_spend": 150.0},+ ]++ with patch("litellm.proxy.proxy_server.prisma_client") as mock_prisma:+ # Setup mock for database query+ mock_prisma.db.query_raw = AsyncMock(+ side_effect=[mock_spend_data, mock_tag_data]+ )++ slack_alerting = SlackAlerting(+ alerting=["webhook"], internal_usage_cache=DualCache()+ )++ user_info = CallInfo(+ token="test_token",+ spend=100,+ max_budget=1000,+ user_id="[email protected]",+ user_email="[email protected]",+ key_alias="test-key",+ )++ with patch.object(+ slack_alerting, "send_alert", new=AsyncMock()+ ) as mock_send_alert:+ # First call should send alert+ if report_type == "weekly":+ await slack_alerting.send_weekly_spend_report()+ else:+ await slack_alerting.send_monthly_spend_report()++ mock_send_alert.assert_called_once()+ mock_send_alert.reset_mock()++ # Second call should not send alert (cached)+ if report_type == "weekly":+ await slack_alerting.send_weekly_spend_report()+ else:+ await slack_alerting.send_monthly_spend_report()+ mock_send_alert.assert_not_called()