Skip to content

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]

(Feat) - emit `litellm_team_budget_reset_at_metric` and `litellm_api_key_budget_remaining_hours_metric` on prometheus (#7946)

Ishaan Jaff1719dc23c7cd
diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.py
index 908667571c8..f496dc707cb 100644
--- a/litellm/integrations/prometheus.py
+++ b/litellm/integrations/prometheus.py
@@ -4,21 +4,16 @@
import asyncio
import sys
from datetime import datetime, timedelta
-from typing import TYPE_CHECKING, Any, List, Optional, cast
+from typing import List, Optional, cast
import litellm
from litellm._logging import print_verbose, verbose_logger
from litellm.integrations.custom_logger import CustomLogger
-from litellm.proxy._types import UserAPIKeyAuth
+from litellm.proxy._types import LiteLLM_TeamTable, UserAPIKeyAuth
from litellm.types.integrations.prometheus import *
from litellm.types.utils import StandardLoggingPayload
from litellm.utils import get_end_user_id_for_cost_tracking
-if TYPE_CHECKING:
- from litellm.proxy._types import LiteLLM_TeamTable
-else:
- LiteLLM_TeamTable = Any
-
class PrometheusLogger(CustomLogger):
# Class variables or attributes
@@ -139,28 +134,53 @@ class PrometheusLogger(CustomLogger):
self.litellm_remaining_team_budget_metric = Gauge(
"litellm_remaining_team_budget_metric",
"Remaining budget for team",
- labelnames=["team_id", "team_alias"],
- )
-
- # Remaining Budget for API Key
- self.litellm_remaining_api_key_budget_metric = Gauge(
- "litellm_remaining_api_key_budget_metric",
- "Remaining budget for api key",
- labelnames=["hashed_api_key", "api_key_alias"],
+ labelnames=PrometheusMetricLabels.get_labels(
+ label_name="litellm_remaining_team_budget_metric"
+ ),
)
# Max Budget for Team
self.litellm_team_max_budget_metric = Gauge(
"litellm_team_max_budget_metric",
"Maximum budget set for team",
- labelnames=["team_id", "team_alias"],
+ labelnames=PrometheusMetricLabels.get_labels(
+ label_name="litellm_team_max_budget_metric"
+ ),
+ )
+
+ # Team Budget Reset At
+ self.litellm_team_budget_remaining_hours_metric = Gauge(
+ "litellm_team_budget_remaining_hours_metric",
+ "Remaining days for team budget to be reset",
+ labelnames=PrometheusMetricLabels.get_labels(
+ label_name="litellm_team_budget_remaining_hours_metric"
+ ),
+ )
+
+ # Remaining Budget for API Key
+ self.litellm_remaining_api_key_budget_metric = Gauge(
+ "litellm_remaining_api_key_budget_metric",
+ "Remaining budget for api key",
+ labelnames=PrometheusMetricLabels.get_labels(
+ label_name="litellm_remaining_api_key_budget_metric"
+ ),
)
# Max Budget for API Key
self.litellm_api_key_max_budget_metric = Gauge(
"litellm_api_key_max_budget_metric",
"Maximum budget set for api key",
- labelnames=["hashed_api_key", "api_key_alias"],
+ labelnames=PrometheusMetricLabels.get_labels(
+ label_name="litellm_api_key_max_budget_metric"
+ ),
+ )
+
+ self.litellm_api_key_budget_remaining_hours_metric = Gauge(
+ "litellm_api_key_budget_remaining_hours_metric",
+ "Remaining hours for api key budget to be reset",
+ labelnames=PrometheusMetricLabels.get_labels(
+ label_name="litellm_api_key_budget_remaining_hours_metric"
+ ),
)
########################################
@@ -457,12 +477,13 @@ class PrometheusLogger(CustomLogger):
)
# remaining budget metrics
- self._increment_remaining_budget_metrics(
+ await self._increment_remaining_budget_metrics(
user_api_team=user_api_team,
user_api_team_alias=user_api_team_alias,
user_api_key=user_api_key,
user_api_key_alias=user_api_key_alias,
litellm_params=litellm_params,
+ response_cost=response_cost,
)
# set proxy virtual key rpm/tpm metrics
@@ -552,13 +573,14 @@ class PrometheusLogger(CustomLogger):
standard_logging_payload["completion_tokens"]
)
- def _increment_remaining_budget_metrics(
+ async def _increment_remaining_budget_metrics(
self,
user_api_team: Optional[str],
user_api_team_alias: Optional[str],
user_api_key: Optional[str],
user_api_key_alias: Optional[str],
litellm_params: dict,
+ response_cost: float,
):
_team_spend = litellm_params.get("metadata", {}).get(
"user_api_key_team_spend", None
@@ -566,9 +588,6 @@ class PrometheusLogger(CustomLogger):
_team_max_budget = litellm_params.get("metadata", {}).get(
"user_api_key_team_max_budget", None
)
- _remaining_team_budget = self._safe_get_remaining_budget(
- max_budget=_team_max_budget, spend=_team_spend
- )
_api_key_spend = litellm_params.get("metadata", {}).get(
"user_api_key_spend", None
@@ -576,29 +595,21 @@ class PrometheusLogger(CustomLogger):
_api_key_max_budget = litellm_params.get("metadata", {}).get(
"user_api_key_max_budget", None
)
- _remaining_api_key_budget = self._safe_get_remaining_budget(
- max_budget=_api_key_max_budget, spend=_api_key_spend
+ await self._set_api_key_budget_metrics_after_api_request(
+ user_api_key=user_api_key,
+ user_api_key_alias=user_api_key_alias,
+ response_cost=response_cost,
+ key_max_budget=_api_key_max_budget,
+ key_spend=_api_key_spend,
)
- # Remaining Budget Metrics
- self.litellm_remaining_team_budget_metric.labels(
- user_api_team, user_api_team_alias
- ).set(_remaining_team_budget)
-
- # Max Budget Metrics
- if _team_max_budget is not None:
- self.litellm_team_max_budget_metric.labels(
- user_api_team, user_api_team_alias
- ).set(_team_max_budget)
- self.litellm_remaining_api_key_budget_metric.labels(
- user_api_key, user_api_key_alias
- ).set(_remaining_api_key_budget)
-
- # Max Budget Metrics for API Key
- if _api_key_max_budget is not None:
- self.litellm_api_key_max_budget_metric.labels(
- user_api_key, user_api_key_alias
- ).set(_api_key_max_budget)
+ await self._set_team_budget_metrics_after_api_request(
+ user_api_team=user_api_team,
+ user_api_team_alias=user_api_team_alias,
+ team_spend=_team_spend,
+ team_max_budget=_team_max_budget,
+ response_cost=response_cost,
+ )
def _increment_top_level_request_and_spend_metrics(
self,
@@ -1343,33 +1354,223 @@ class PrometheusLogger(CustomLogger):
total_pages = (total_count + page_size - 1) // page_size
# Set metrics for first page of teams
- await self._set_team_budget_metrics(teams)
+ await self._set_team_list_budget_metrics(teams)
# Get and set metrics for remaining pages
for page in range(2, total_pages + 1):
teams, _ = await get_paginated_teams(
prisma_client=prisma_client, page_size=page_size, page=page
)
- await self._set_team_budget_metrics(teams)
+ await self._set_team_list_budget_metrics(teams)
except Exception as e:
verbose_logger.exception(
f"Error initializing team budget metrics: {str(e)}"
)
- async def _set_team_budget_metrics(self, teams: List[LiteLLM_TeamTable]):
+ async def _set_team_list_budget_metrics(self, teams: List[LiteLLM_TeamTable]):
"""Helper function to set budget metrics for a list of teams"""
for team in teams:
- if team.max_budget is not None:
- self.litellm_remaining_team_budget_metric.labels(
- team.team_id,
- team.team_alias or "",
- ).set(
- self._safe_get_remaining_budget(
- max_budget=team.max_budget,
- spend=team.spend,
- )
+ self._set_team_budget_metrics(team)
+
+ async def _set_team_budget_metrics_after_api_request(
+ self,
+ user_api_team: Optional[str],
+ user_api_team_alias: Optional[str],
+ team_spend: float,
+ team_max_budget: float,
+ response_cost: float,
+ ):
+ """
+ Set team budget metrics after an LLM API request
+
+ - Assemble a LiteLLM_TeamTable object
+ - looks up team info from db if not available in metadata
+ - Set team budget metrics
+ """
+ if user_api_team:
+ team_object = await self._assemble_team_object(
+ team_id=user_api_team,
+ team_alias=user_api_team_alias or "",
+ spend=team_spend,
+ max_budget=team_max_budget,
+ response_cost=response_cost,
+ )
+
+ self._set_team_budget_metrics(team_object)
+
+ async def _assemble_team_object(
+ self,
+ team_id: str,
+ team_alias: str,
+ spend: Optional[float],
+ max_budget: Optional[float],
+ response_cost: float,
+ ) -> LiteLLM_TeamTable:
+ """
+ Assemble a LiteLLM_TeamTable object
+
+ for fields not available in metadata, we fetch from db
+ Fields not available in metadata:
+ - `budget_reset_at`
+ """
+ from litellm.proxy.auth.auth_checks import get_team_object
+ from litellm.proxy.proxy_server import prisma_client, user_api_key_cache
+
+ _total_team_spend = (spend or 0) + response_cost
+ team_object = LiteLLM_TeamTable(
+ team_id=team_id,
+ team_alias=team_alias,
+ spend=_total_team_spend,
+ max_budget=max_budget,
+ )
+ try:
+ team_info = await get_team_object(
+ team_id=team_id,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ )
+ except Exception as e:
+ verbose_logger.exception(
+ f"[Non-Blocking] Prometheus: Error getting team info: {str(e)}"
+ )
+ return team_object
+
+ if team_info:
+ team_object.budget_reset_at = team_info.budget_reset_at
+
+ return team_object
+
+ def _set_team_budget_metrics(
+ self,
+ team: LiteLLM_TeamTable,
+ ):
+ """
+ Set team budget metrics for a single team
+
+ - Remaining Budget
+ - Max Budget
+ - Budget Reset At
+ """
+ self.litellm_remaining_team_budget_metric.labels(
+ team.team_id,
+ team.team_alias or "",
+ ).set(
+ self._safe_get_remaining_budget(
+ max_budget=team.max_budget,
+ spend=team.spend,
+ )
+ )
+
+ if team.max_budget is not None:
+ self.litellm_team_max_budget_metric.labels(
+ team.team_id,
+ team.team_alias or "",
+ ).set(team.max_budget)
+
+ if team.budget_reset_at is not None:
+ self.litellm_team_budget_remaining_hours_metric.labels(
+ team.team_id,
+ team.team_alias or "",
+ ).set(
+ self._get_remaining_hours_for_budget_reset(
+ budget_reset_at=team.budget_reset_at
+ )
+ )
+
+ def _set_key_budget_metrics(self, user_api_key_dict: UserAPIKeyAuth):
+ """
+ Set virtual key budget metrics
+
+ - Remaining Budget
+ - Max Budget
+ - Budget Reset At
+ """
+ self.litellm_remaining_api_key_budget_metric.labels(
+ user_api_key_dict.token, user_api_key_dict.key_alias
+ ).set(
+ self._safe_get_remaining_budget(
+ max_budget=user_api_key_dict.max_budget,
+ spend=user_api_key_dict.spend,
+ )
+ )
+
+ if user_api_key_dict.max_budget is not None:
+ self.litellm_api_key_max_budget_metric.labels(
+ user_api_key_dict.token, user_api_key_dict.key_alias
+ ).set(user_api_key_dict.max_budget)
+
+ if user_api_key_dict.budget_reset_at is not None:
+ self.litellm_api_key_budget_remaining_hours_metric.labels(
+ user_api_key_dict.token, user_api_key_dict.key_alias
+ ).set(
+ self._get_remaining_hours_for_budget_reset(
+ budget_reset_at=user_api_key_dict.budget_reset_at
)
+ )
+
+ async def _set_api_key_budget_metrics_after_api_request(
+ self,
+ user_api_key: Optional[str],
+ user_api_key_alias: Optional[str],
+ response_cost: float,
+ key_max_budget: float,
+ key_spend: Optional[float],
+ ):
+ if user_api_key:
+ user_api_key_dict = await self._assemble_key_object(
+ user_api_key=user_api_key,
+ user_api_key_alias=user_api_key_alias or "",
+ key_max_budget=key_max_budget,
+ key_spend=key_spend,
+ response_cost=response_cost,
+ )
+ self._set_key_budget_metrics(user_api_key_dict)
+
+ async def _assemble_key_object(
+ self,
+ user_api_key: str,
+ user_api_key_alias: str,
+ key_max_budget: float,
+ key_spend: Optional[float],
+ response_cost: float,
+ ) -> UserAPIKeyAuth:
+ """
+ Assemble a UserAPIKeyAuth object
+ """
+ from litellm.proxy.auth.auth_checks import get_key_object
+ from litellm.proxy.proxy_server import prisma_client, user_api_key_cache
+
+ _total_key_spend = (key_spend or 0) + response_cost
+ user_api_key_dict = UserAPIKeyAuth(
+ token=user_api_key,
+ key_alias=user_api_key_alias,
+ max_budget=key_max_budget,
+ spend=_total_key_spend,
+ )
+ try:
+ if user_api_key_dict.token:
+ key_object = await get_key_object(
+ hashed_token=user_api_key_dict.token,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ )
+ if key_object:
+ user_api_key_dict.budget_reset_at = key_object.budget_reset_at
+ except Exception as e:
+ verbose_logger.exception(
+ f"[Non-Blocking] Prometheus: Error getting key info: {str(e)}"
+ )
+
+ return user_api_key_dict
+
+ def _get_remaining_hours_for_budget_reset(self, budget_reset_at: datetime) -> float:
+ """
+ Get remaining hours for budget reset
+ """
+ return (
+ budget_reset_at - datetime.now(budget_reset_at.tzinfo)
+ ).total_seconds() / 3600
def prometheus_label_factory(
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.py
index 491778fe34b..317c7fddc40 100644
--- a/litellm/proxy/auth/auth_checks.py
+++ b/litellm/proxy/auth/auth_checks.py
@@ -637,6 +637,9 @@ async def get_team_object(
- Check if team id in proxy Team Table
- if valid, return LiteLLM_TeamTable object with defined limits
- if not, then raise an error
+
+ Raises:
+ - Exception: If team doesn't exist in db or cache
"""
if prisma_client is None:
raise Exception(
diff --git a/litellm/types/integrations/prometheus.py b/litellm/types/integrations/prometheus.py
index ea32ee9e8b6..a7bfce711f9 100644
--- a/litellm/types/integrations/prometheus.py
+++ b/litellm/types/integrations/prometheus.py
@@ -83,7 +83,10 @@ DEFINED_PROMETHEUS_METRICS = Literal[
"litellm_deployment_failed_fallbacks",
"litellm_remaining_team_budget_metric",
"litellm_team_max_budget_metric",
- "litellm_team_budget_reset_at_metric",
+ "litellm_team_budget_remaining_hours_metric",
+ "litellm_remaining_api_key_budget_metric",
+ "litellm_api_key_max_budget_metric",
+ "litellm_api_key_budget_remaining_hours_metric",
]
@@ -199,11 +202,22 @@ class PrometheusMetricLabels:
UserAPIKeyLabelNames.TEAM_ALIAS.value,
]
- litellm_team_budget_reset_at_metric = [
+ litellm_team_budget_remaining_hours_metric = [
UserAPIKeyLabelNames.TEAM.value,
UserAPIKeyLabelNames.TEAM_ALIAS.value,
]
+ litellm_remaining_api_key_budget_metric = [
+ UserAPIKeyLabelNames.API_KEY_HASH.value,
+ UserAPIKeyLabelNames.API_KEY_ALIAS.value,
+ ]
+
+ litellm_api_key_max_budget_metric = litellm_remaining_api_key_budget_metric
+
+ litellm_api_key_budget_remaining_hours_metric = (
+ litellm_remaining_api_key_budget_metric
+ )
+
@staticmethod
def get_labels(label_name: DEFINED_PROMETHEUS_METRICS) -> List[str]:
default_labels = getattr(PrometheusMetricLabels, label_name)
diff --git a/tests/logging_callback_tests/test_prometheus_unit_tests.py b/tests/logging_callback_tests/test_prometheus_unit_tests.py
index 36be0104d76..7307050d0fa 100644
--- a/tests/logging_callback_tests/test_prometheus_unit_tests.py
+++ b/tests/logging_callback_tests/test_prometheus_unit_tests.py
@@ -251,64 +251,106 @@ def test_increment_token_metrics(prometheus_logger):
)
-def test_increment_remaining_budget_metrics(prometheus_logger):
+async def test_increment_remaining_budget_metrics(prometheus_logger):
"""
Test the increment_remaining_budget_metrics method
- team and api key remaining budget metrics are set to the difference between max budget and spend
- team and api key max budget metrics are set to their respective max budgets
+ - team and api key remaining hours metrics are set based on budget reset timestamps
"""
+ # Mock all budget-related metrics
prometheus_logger.litellm_remaining_team_budget_metric = MagicMock()
prometheus_logger.litellm_remaining_api_key_budget_metric = MagicMock()
prometheus_logger.litellm_team_max_budget_metric = MagicMock()
prometheus_logger.litellm_api_key_max_budget_metric = MagicMock()
+ prometheus_logger.litellm_team_budget_remaining_hours_metric = MagicMock()
+ prometheus_logger.litellm_api_key_budget_remaining_hours_metric = MagicMock()
- litellm_params = {
- "metadata": {
- "user_api_key_team_spend": 50,
- "user_api_key_team_max_budget": 100,
- "user_api_key_spend": 25,
- "user_api_key_max_budget": 75,
+ # Create a future budget reset time for testing
+ future_reset_time_team = datetime.now() + timedelta(hours=10)
+ future_reset_time_key = datetime.now() + timedelta(hours=12)
+ # Mock the get_team_object and get_key_object functions to return objects with budget reset times
+ with patch(
+ "litellm.proxy.auth.auth_checks.get_team_object"
+ ) as mock_get_team, patch(
+ "litellm.proxy.auth.auth_checks.get_key_object"
+ ) as mock_get_key:
+
+ mock_get_team.return_value = MagicMock(budget_reset_at=future_reset_time_team)
+ mock_get_key.return_value = MagicMock(budget_reset_at=future_reset_time_key)
+
+ litellm_params = {
+ "metadata": {
+ "user_api_key_team_spend": 50,
+ "user_api_key_team_max_budget": 100,
+ "user_api_key_spend": 25,
+ "user_api_key_max_budget": 75,
+ }
}
- }
- prometheus_logger._increment_remaining_budget_metrics(
- user_api_team="team1",
- user_api_team_alias="team_alias1",
- user_api_key="key1",
- user_api_key_alias="alias1",
- litellm_params=litellm_params,
- )
+ await prometheus_logger._increment_remaining_budget_metrics(
+ user_api_team="team1",
+ user_api_team_alias="team_alias1",
+ user_api_key="key1",
+ user_api_key_alias="alias1",
+ litellm_params=litellm_params,
+ response_cost=10,
+ )
- # Test remaining budget metrics
- prometheus_logger.litellm_remaining_team_budget_metric.labels.assert_called_once_with(
- "team1", "team_alias1"
- )
- prometheus_logger.litellm_remaining_team_budget_metric.labels().set.assert_called_once_with(
- 50 # 100 - 50
- )
+ # Test remaining budget metrics
+ prometheus_logger.litellm_remaining_team_budget_metric.labels.assert_called_once_with(
+ "team1", "team_alias1"
+ )
+ prometheus_logger.litellm_remaining_team_budget_metric.labels().set.assert_called_once_with(
+ 40 # 100 - (50 + 10)
+ )
- prometheus_logger.litellm_remaining_api_key_budget_metric.labels.assert_called_once_with(
- "key1", "alias1"
- )
- prometheus_logger.litellm_remaining_api_key_budget_metric.labels().set.assert_called_once_with(
- 50 # 75 - 25
- )
+ prometheus_logger.litellm_remaining_api_key_budget_metric.labels.assert_called_once_with(
+ "key1", "alias1"
+ )
+ prometheus_logger.litellm_remaining_api_key_budget_metric.labels().set.assert_called_once_with(
+ 40 # 75 - (25 + 10)
+ )
- # Test max budget metrics
- prometheus_logger.litellm_team_max_budget_metric.labels.assert_called_once_with(
- "team1", "team_alias1"
- )
- prometheus_logger.litellm_team_max_budget_metric.labels().set.assert_called_once_with(
- 100
- )
+ # Test max budget metrics
+ prometheus_logger.litellm_team_max_budget_metric.labels.assert_called_once_with(
+ "team1", "team_alias1"
+ )
+ prometheus_logger.litellm_team_max_budget_metric.labels().set.assert_called_once_with(
+ 100
+ )
- prometheus_logger.litellm_api_key_max_budget_metric.labels.assert_called_once_with(
- "key1", "alias1"
- )
- prometheus_logger.litellm_api_key_max_budget_metric.labels().set.assert_called_once_with(
- 75
- )
+ prometheus_logger.litellm_api_key_max_budget_metric.labels.assert_called_once_with(
+ "key1", "alias1"
+ )
+ prometheus_logger.litellm_api_key_max_budget_metric.labels().set.assert_called_once_with(
+ 75
+ )
+
+ # Test remaining hours metrics
+ prometheus_logger.litellm_team_budget_remaining_hours_metric.labels.assert_called_once_with(
+ "team1", "team_alias1"
+ )
+ # The remaining hours should be approximately 10 (with some small difference due to test execution time)
+ remaining_hours_call = prometheus_logger.litellm_team_budget_remaining_hours_metric.labels().set.call_args[
+ 0
+ ][
+ 0
+ ]
+ assert 9.9 <= remaining_hours_call <= 10.0
+
+ prometheus_logger.litellm_api_key_budget_remaining_hours_metric.labels.assert_called_once_with(
+ "key1", "alias1"
+ )
+ # The remaining hours should be approximately 10 (with some small difference due to test execution time)
+ remaining_hours_call = prometheus_logger.litellm_api_key_budget_remaining_hours_metric.labels().set.call_args[
+ 0
+ ][
+ 0
+ ]
+ assert 11.9 <= remaining_hours_call <= 12.0
def test_set_latency_metrics(prometheus_logger):
@@ -944,31 +986,86 @@ async def test_initialize_remaining_budget_metrics(prometheus_logger):
"litellm.proxy.management_endpoints.team_endpoints.get_paginated_teams"
) as mock_get_teams:
- # Create mock team data
+ # Create mock team data with proper datetime objects for budget_reset_at
+ future_reset = datetime.now() + timedelta(hours=24) # Reset 24 hours from now
mock_teams = [
- MagicMock(team_id="team1", team_alias="alias1", max_budget=100, spend=30),
- MagicMock(team_id="team2", team_alias="alias2", max_budget=200, spend=50),
- MagicMock(team_id="team3", team_alias=None, max_budget=300, spend=100),
+ MagicMock(
+ team_id="team1",
+ team_alias="alias1",
+ max_budget=100,
+ spend=30,
+ budget_reset_at=future_reset,
+ ),
+ MagicMock(
+ team_id="team2",
+ team_alias="alias2",
+ max_budget=200,
+ spend=50,
+ budget_reset_at=future_reset,
+ ),
+ MagicMock(
+ team_id="team3",
+ team_alias=None,
+ max_budget=300,
+ spend=100,
+ budget_reset_at=future_reset,
+ ),
]
# Mock get_paginated_teams to return our test data
mock_get_teams.return_value = (mock_teams, len(mock_teams))
- # Mock the Prometheus metric
+ # Mock the Prometheus metrics
prometheus_logger.litellm_remaining_team_budget_metric = MagicMock()
+ prometheus_logger.litellm_team_budget_remaining_hours_metric = MagicMock()
# Call the function
await prometheus_logger._initialize_remaining_budget_metrics()
- # Verify the metric was set correctly for each team
- expected_calls = [
+ # Verify the remaining budget metric was set correctly for each team
+ expected_budget_calls = [
call.labels("team1", "alias1").set(70), # 100 - 30
call.labels("team2", "alias2").set(150), # 200 - 50
call.labels("team3", "").set(200), # 300 - 100
]
prometheus_logger.litellm_remaining_team_budget_metric.assert_has_calls(
- expected_calls, any_order=True
+ expected_budget_calls, any_order=True
+ )
+
+ # Get all the calls made to the hours metric
+ hours_calls = (
+ prometheus_logger.litellm_team_budget_remaining_hours_metric.mock_calls
+ )
+
+ # Verify the structure and approximate values of the hours calls
+ assert len(hours_calls) == 6 # 3 teams * 2 calls each (labels + set)
+
+ # Helper function to extract hours value from call
+ def get_hours_from_call(call_obj):
+ if "set" in str(call_obj):
+ return call_obj[1][0] # Extract the hours value
+ return None
+
+ # Verify each team's hours are approximately 24 (within reasonable bounds)
+ hours_values = [
+ get_hours_from_call(call)
+ for call in hours_calls
+ if get_hours_from_call(call) is not None
+ ]
+ for hours in hours_values:
+ assert (
+ 23.9 <= hours <= 24.0
+ ), f"Hours value {hours} not within expected range"
+
+ # Verify the labels were called with correct team information
+ label_calls = [
+ call.labels("team1", "alias1"),
+ call.labels("team2", "alias2"),
+ call.labels("team3", ""),
+ ]
+ prometheus_logger.litellm_team_budget_remaining_hours_metric.assert_has_calls(
+ label_calls, any_order=True
)
diff --git a/tests/otel_tests/test_prometheus.py b/tests/otel_tests/test_prometheus.py
index 678140d3e00..7e26138f121 100644
--- a/tests/otel_tests/test_prometheus.py
+++ b/tests/otel_tests/test_prometheus.py
@@ -8,6 +8,9 @@ import asyncio
import uuid
import os
import sys
+from openai import AsyncOpenAI
+import time
+from typing import Dict, Any
sys.path.insert(
0, os.path.abspath("../..")
@@ -235,3 +238,291 @@ async def test_proxy_fallback_metrics():
'litellm_deployment_failed_fallbacks_total{api_key_alias="None",exception_class="RateLimitError",exception_status="429",fallback_model="unknown-model",hashed_api_key="88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b",requested_model="fake-azure-endpoint",team="None",team_alias="None"} 1.0'
in metrics
)
+
+
+async def create_test_team(
+ session: aiohttp.ClientSession, team_data: Dict[str, Any]
+) -> str:
+ """Create a new team and return the team_id"""
+ url = "http://0.0.0.0:4000/team/new"
+ headers = {
+ "Authorization": "Bearer sk-1234",
+ "Content-Type": "application/json",
+ }
+
+ async with session.post(url, headers=headers, json=team_data) as response:
+ assert (
+ response.status == 200
+ ), f"Failed to create team. Status: {response.status}"
+ team_info = await response.json()
+ return team_info["team_id"]
+
+
+async def get_prometheus_metrics(session: aiohttp.ClientSession) -> str:
+ """Fetch current prometheus metrics"""
+ async with session.get("http://0.0.0.0:4000/metrics") as response:
+ assert response.status == 200
+ return await response.text()
+
+
+def extract_budget_metrics(metrics_text: str, team_id: str) -> Dict[str, float]:
+ """Extract budget-related metrics for a specific team"""
+ import re
+
+ metrics = {}
+
+ # Get remaining budget
+ remaining_pattern = f'litellm_remaining_team_budget_metric{{team="{team_id}",team_alias="[^"]*"}} ([0-9.]+)'
+ remaining_match = re.search(remaining_pattern, metrics_text)
+ metrics["remaining"] = float(remaining_match.group(1)) if remaining_match else None
+
+ # Get total budget
+ total_pattern = f'litellm_team_max_budget_metric{{team="{team_id}",team_alias="[^"]*"}} ([0-9.]+)'
+ total_match = re.search(total_pattern, metrics_text)
+ metrics["total"] = float(total_match.group(1)) if total_match else None
+
+ # Get remaining hours
+ hours_pattern = f'litellm_team_budget_remaining_hours_metric{{team="{team_id}",team_alias="[^"]*"}} ([0-9.]+)'
+ hours_match = re.search(hours_pattern, metrics_text)
+ metrics["remaining_hours"] = float(hours_match.group(1)) if hours_match else None
+
+ return metrics
+
+
+async def create_test_key(session: aiohttp.ClientSession, team_id: str) -> str:
+ """Generate a new key for the team and return it"""
+ url = "http://0.0.0.0:4000/key/generate"
+ headers = {
+ "Authorization": "Bearer sk-1234",
+ "Content-Type": "application/json",
+ }
+ data = {
+ "team_id": team_id,
+ }
+
+ async with session.post(url, headers=headers, json=data) as response:
+ assert (
+ response.status == 200
+ ), f"Failed to generate key. Status: {response.status}"
+ key_info = await response.json()
+ return key_info["key"]
+
+
+async def get_team_info(session: aiohttp.ClientSession, team_id: str) -> Dict[str, Any]:
+ """Fetch team info and return the response"""
+ url = f"http://0.0.0.0:4000/team/info?team_id={team_id}"
+ headers = {
+ "Authorization": "Bearer sk-1234",
+ }
+
+ async with session.get(url, headers=headers) as response:
+ assert (
+ response.status == 200
+ ), f"Failed to get team info. Status: {response.status}"
+ return await response.json()
+
+
+async def test_team_budget_metrics():
+ """
+ Test team budget tracking metrics:
+ 1. Create a team with max_budget
+ 2. Generate a key for the team
+ 3. Make chat completion requests using OpenAI SDK with team's key
+ 4. Verify budget decreases over time
+ 5. Verify request costs are being tracked correctly
+ 6. Verify prometheus metrics match /team/info spend data
+ """
+ async with aiohttp.ClientSession() as session:
+ # Setup test team
+ team_data = {
+ "team_alias": "budget_test_team",
+ "max_budget": 10,
+ "budget_duration": "7d",
+ }
+ team_id = await create_test_team(session, team_data)
+ print("team_id", team_id)
+ # Generate key for the team
+ team_key = await create_test_key(session, team_id)
+
+ # Initialize OpenAI client with team's key
+ client = AsyncOpenAI(base_url="http://0.0.0.0:4000", api_key=team_key)
+
+ # Make initial request and check budget
+ await client.chat.completions.create(
+ model="fake-openai-endpoint",
+ messages=[{"role": "user", "content": f"Hello {uuid.uuid4()}"}],
+ )
+
+ await asyncio.sleep(11) # Wait for metrics to update
+
+ # Get metrics after request
+ metrics_after_first = await get_prometheus_metrics(session)
+ print("metrics_after_first", metrics_after_first)
+ first_budget = extract_budget_metrics(metrics_after_first, team_id)
+
+ print(f"Budget after 1 request: {first_budget}")
+ assert (
+ first_budget["remaining"] < 10.0
+ ), "remaining budget should be less than 10.0 after first request"
+ assert first_budget["total"] == 10.0, "Total budget metric is incorrect"
+ print("first_budget['remaining_hours']", first_budget["remaining_hours"])
+ # Verify remaining hours matches 7 days (with small delta for processing time)
+ assert (
+ abs(first_budget["remaining_hours"] - (7 * 24)) <= 0.1
+ ), "Budget remaining hours should be approximately 7 days (168 hours)"
+
+ # Get team info and verify spend matches prometheus metrics
+ team_info = await get_team_info(session, team_id)
+ print("team_info", team_info)
+ _team_info_data = team_info["team_info"]
+
+ # Calculate spend from prometheus (total - remaining)
+ team_info_spend = float(_team_info_data["spend"])
+ team_info_max_budget = float(_team_info_data["max_budget"])
+ team_info_remaining_budget = team_info_max_budget - team_info_spend
+ print("\n\n\n###### Final budget metrics ######\n\n\n")
+ print("team_info_remaining_budget", team_info_remaining_budget)
+ print("prometheus_remaining_budget", first_budget["remaining"])
+ print(
+ "diff between team_info_remaining_budget and prometheus_remaining_budget",
+ team_info_remaining_budget - first_budget["remaining"],
+ )
+
+ # Verify spends match within a small delta (floating point comparison)
+ assert (
+ abs(team_info_remaining_budget - first_budget["remaining"]) <= 0.00000
+ ), f"Spend mismatch: Prometheus={team_info_remaining_budget}, Team Info={first_budget['remaining']}"
+
+
+async def create_test_key_with_budget(
+ session: aiohttp.ClientSession, budget_data: Dict[str, Any]
+) -> str:
+ """Generate a new key with budget constraints and return it"""
+ url = "http://0.0.0.0:4000/key/generate"
+ headers = {
+ "Authorization": "Bearer sk-1234",
+ "Content-Type": "application/json",
+ }
+ print("budget_data", budget_data)
+
+ async with session.post(url, headers=headers, json=budget_data) as response:
+ assert (
+ response.status == 200
+ ), f"Failed to generate key. Status: {response.status}"
+ key_info = await response.json()
+ return key_info["key"]
+
+
+async def get_key_info(session: aiohttp.ClientSession, key: str) -> Dict[str, Any]:
+ """Fetch key info and return the response"""
+ url = "http://0.0.0.0:4000/key/info"
+ headers = {
+ "Authorization": f"Bearer {key}",
+ }
+
+ async with session.get(url, headers=headers) as response:
+ assert (
+ response.status == 200
+ ), f"Failed to get key info. Status: {response.status}"
+ return await response.json()
+
+
+def extract_key_budget_metrics(metrics_text: str, key_id: str) -> Dict[str, float]:
+ """Extract budget-related metrics for a specific key"""
+ import re
+
+ metrics = {}
+
+ # Get remaining budget
+ remaining_pattern = f'litellm_remaining_api_key_budget_metric{{api_key_alias="[^"]*",hashed_api_key="{key_id}"}} ([0-9.]+)'
+ remaining_match = re.search(remaining_pattern, metrics_text)
+ metrics["remaining"] = float(remaining_match.group(1)) if remaining_match else None
+
+ # Get total budget
+ total_pattern = f'litellm_api_key_max_budget_metric{{api_key_alias="[^"]*",hashed_api_key="{key_id}"}} ([0-9.]+)'
+ total_match = re.search(total_pattern, metrics_text)
+ metrics["total"] = float(total_match.group(1)) if total_match else None
+
+ # Get remaining hours
+ hours_pattern = f'litellm_api_key_budget_remaining_hours_metric{{api_key_alias="[^"]*",hashed_api_key="{key_id}"}} ([0-9.]+)'
+ hours_match = re.search(hours_pattern, metrics_text)
+ metrics["remaining_hours"] = float(hours_match.group(1)) if hours_match else None
+
+ return metrics
+
+
+async def test_key_budget_metrics():
+ """
+ Test key budget tracking metrics:
+ 1. Create a key with max_budget
+ 2. Make chat completion requests using OpenAI SDK with the key
+ 3. Verify budget decreases over time
+ 4. Verify request costs are being tracked correctly
+ 5. Verify prometheus metrics match /key/info spend data
+ """
+ async with aiohttp.ClientSession() as session:
+ # Setup test key with unique alias
+ unique_alias = f"budget_test_key_{uuid.uuid4()}"
+ key_data = {
+ "key_alias": unique_alias,
+ "max_budget": 10,
+ "budget_duration": "7d",
+ }
+ key = await create_test_key_with_budget(session, key_data)
+
+ # Extract key_id from the key info
+ key_info = await get_key_info(session, key)
+ print("key_info", key_info)
+ key_id = key_info["key"]
+ print("key_id", key_id)
+
+ # Initialize OpenAI client with the key
+ client = AsyncOpenAI(base_url="http://0.0.0.0:4000", api_key=key)
+
+ # Make initial request and check budget
+ await client.chat.completions.create(
+ model="fake-openai-endpoint",
+ messages=[{"role": "user", "content": f"Hello {uuid.uuid4()}"}],
+ )
+
+ await asyncio.sleep(11) # Wait for metrics to update
+
+ # Get metrics after request
+ metrics_after_first = await get_prometheus_metrics(session)
+ print("metrics_after_first request", metrics_after_first)
+ first_budget = extract_key_budget_metrics(metrics_after_first, key_id)
+
+ print(f"Budget after 1 request: {first_budget}")
+ assert (
+ first_budget["remaining"] < 10.0
+ ), "remaining budget should be less than 10.0 after first request"
+ assert first_budget["total"] == 10.0, "Total budget metric is incorrect"
+ print("first_budget['remaining_hours']", first_budget["remaining_hours"])
+ # Verify remaining hours matches 7 days (with small delta for processing time)
+ assert (
+ abs(first_budget["remaining_hours"] - (7 * 24)) <= 0.1
+ ), "Budget remaining hours should be approximately 7 days (168 hours)"
+
+ # Get key info and verify spend matches prometheus metrics
+ key_info = await get_key_info(session, key)
+ print("key_info", key_info)
+ _key_info_data = key_info["info"]
+
+ # Calculate spend from prometheus (total - remaining)
+ key_info_spend = float(_key_info_data["spend"])
+ key_info_max_budget = float(_key_info_data["max_budget"])
+ key_info_remaining_budget = key_info_max_budget - key_info_spend
+ print("\n\n\n###### Final budget metrics ######\n\n\n")
+ print("key_info_remaining_budget", key_info_remaining_budget)
+ print("prometheus_remaining_budget", first_budget["remaining"])
+ print(
+ "diff between key_info_remaining_budget and prometheus_remaining_budget",
+ key_info_remaining_budget - first_budget["remaining"],
+ )
+
+ # Verify spends match within a small delta (floating point comparison)
+ assert (
+ abs(key_info_remaining_budget - first_budget["remaining"]) <= 0.00000
+ ), f"Spend mismatch: Prometheus={key_info_remaining_budget}, Key Info={first_budget['remaining']}"