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
Team Members - reset budget, if duration set + Prometheus - support tag based metrics (#12534)
Krish Dholakia749051105bb0
diff --git a/docs/my-website/docs/proxy/prometheus.md b/docs/my-website/docs/proxy/prometheus.mdindex e4ef6f183c0..a6cbe2bc384 100644--- a/docs/my-website/docs/proxy/prometheus.md+++ b/docs/my-website/docs/proxy/prometheus.md@@ -197,7 +197,9 @@ litellm_settings:Track custom metrics on prometheus on all events mentioned above.-1. Define the custom metrics in the `config.yaml`+### Custom Metadata Labels++1. Define the custom metadata labels in the `config.yaml````yamlmodel_list:@@ -243,6 +245,69 @@ curl -L -X POST 'http://0.0.0.0:4000/v1/chat/completions' \... "metadata_foo": "hello world" ...```+### Custom Tags++Track specific tags as prometheus labels for better filtering and monitoring.++1. Define the custom tags in the `config.yaml`++```yaml+model_list:+ - model_name: openai/gpt-4o+ litellm_params:+ model: openai/gpt-4o+ api_key: os.environ/OPENAI_API_KEY++litellm_settings:+ callbacks: ["prometheus"]+ custom_prometheus_metadata_labels: ["metadata.foo", "metadata.bar"]+ custom_prometheus_tags: ["prod", "staging", "batch-job"]+```++2. Make a request with tags++```bash+curl -L -X POST 'http://0.0.0.0:4000/v1/chat/completions' \+-H 'Content-Type: application/json' \+-H 'Authorization: Bearer <LITELLM_API_KEY>' \+-d '{+ "model": "openai/gpt-4o",+ "messages": [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "What's in this image?"+ }+ ]+ }+ ],+ "max_tokens": 300,+ "metadata": {+ "tags": ["prod", "user-facing"]+ }+}'+```++3. Check your `/metrics` endpoint for the custom tag metrics++```+... "tag_prod": "true", "tag_staging": "false", "tag_batch_job": "false" ...+```++**How Custom Tags Work:**+- Each configured tag becomes a boolean label in prometheus metrics+- If a tag is present in the request, the label value is `"true"`+- If a tag is not present in the request, the label value is `"false"`+- Tag names are sanitized for prometheus compatibility (e.g., `"batch-job"` becomes `"tag_batch_job"`)++**Use Cases:**+- Environment tracking (`prod`, `staging`, `dev`)+- Request type classification (`batch-job`, `user-facing`, `background`)+- Feature flags (`new-feature`, `beta-users`)+- Team or service identification (`team-a`, `service-xyz`)+## Configuring Metrics and Labelsdiff --git a/litellm/__init__.py b/litellm/__init__.pyindex a4ad0e7638f..f3661c92125 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -322,6 +322,7 @@ disable_end_user_cost_tracking: Optional[bool] = Nonedisable_end_user_cost_tracking_prometheus_only: Optional[bool] = Noneenable_end_user_cost_tracking_prometheus_only: Optional[bool] = Nonecustom_prometheus_metadata_labels: List[str] = []+custom_prometheus_tags: List[str] = []prometheus_metrics_config: Optional[List] = Nonedisable_add_prefix_to_prompt: bool = (False # used by anthropic, to disable adding prefix to prompt@@ -673,6 +674,7 @@ def add_known_models():elif value.get("litellm_provider") == "dashscope":dashscope_models.append(key)+add_known_models()# known openai compatible endpoints - we'll eventually move this list to the model_prices_and_context_window.json dictionarydiff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.pyindex 050eb0ed536..f1a155bc962 100644--- a/litellm/integrations/prometheus.py+++ b/litellm/integrations/prometheus.py@@ -2233,6 +2233,13 @@ def prometheus_label_factory(if key in supported_enum_labels:filtered_labels[key] = value+ # Add custom tags if configured+ if enum_values.tags is not None:+ custom_tag_labels = get_custom_labels_from_tags(enum_values.tags)+ for key, value in custom_tag_labels.items():+ if key in supported_enum_labels:+ filtered_labels[key] = value+for label in supported_enum_labels:if label not in filtered_labels:filtered_labels[label] = None@@ -2267,3 +2274,27 @@ def get_custom_labels_from_metadata(metadata: dict) -> Dict[str, str]:result[original_key.replace(".", "_")] = valuereturn result+++def get_custom_labels_from_tags(tags: List[str]) -> Dict[str, str]:+ """+ Get custom labels from tags based on admin configuration+ """+ configured_tags = litellm.custom_prometheus_tags+ if configured_tags is None or len(configured_tags) == 0:+ return {}++ result: Dict[str, str] = {}++ # Map each configured tag to its presence in the request tags+ for configured_tag in configured_tags:+ # Create a safe prometheus label name+ label_name = f"tag_{configured_tag}".replace("-", "_").replace(".", "_")++ # Check if this tag is present in the request tags+ if configured_tag in tags:+ result[label_name] = "true"+ else:+ result[label_name] = "false"++ return resultdiff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yamlindex 318f8c407ce..a20ebe15c08 100644--- a/litellm/proxy/_new_secret_config.yaml+++ b/litellm/proxy/_new_secret_config.yaml@@ -14,4 +14,8 @@ guardrails:default_on: truelitellm_settings:- callbacks: ["langfuse_otel"]\ No newline at end of file+ default_internal_user_params:+ teams:+ - team_id: "team_id_1"+ max_budget_in_team: 100+ user_role: "user"\ No newline at end of filediff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.pyindex 1549bd9e20d..83de641fbf7 100644--- a/litellm/proxy/management_endpoints/internal_user_endpoints.py+++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py@@ -246,6 +246,36 @@ def check_if_default_team_set() -> Optional[Union[List[str], List[NewUserRequestreturn None+async def add_new_user_to_default_team(+ user_id: str,+ user_email: Optional[str],+ user_api_key_dict: UserAPIKeyAuth,+ teams: Union[List[str], List[NewUserRequestTeam]],+ prisma_client: "PrismaClient",+):+ tasks = []+ for team in teams:+ user_role: Literal["user", "admin"] = "user"+ if isinstance(team, str):+ team_id = team+ elif isinstance(team, NewUserRequestTeam):+ team_id = team.team_id+ user_role = team.user_role+ else:+ raise ValueError(f"Invalid team type: {type(team)}")++ tasks.append(+ _add_user_to_team(+ user_id=user_id,+ team_id=team_id,+ user_email=user_email,+ user_api_key_dict=user_api_key_dict,+ user_role=user_role,+ )+ )+ await asyncio.gather(*tasks, return_exceptions=True)++@router.post("/user/new",tags=["Internal User management"],@@ -362,30 +392,13 @@ async def new_user(user_role="user",)elif teams is not None:- tasks = []- for team in teams:- max_budget_in_team: Optional[float] = None- user_role: Literal["user", "admin"] = "user"- if isinstance(team, str):- team_id = team- elif isinstance(team, NewUserRequestTeam):- team_id = team.team_id- max_budget_in_team = team.max_budget_in_team- user_role = team.user_role- else:- raise ValueError(f"Invalid team type: {type(team)}")-- tasks.append(- _add_user_to_team(- user_id=cast(str, response.get("user_id")),- team_id=team_id,- user_email=data.user_email,- user_api_key_dict=user_api_key_dict,- max_budget_in_team=max_budget_in_team,- user_role=user_role,- )- )- await asyncio.gather(*tasks, return_exceptions=True)+ await add_new_user_to_default_team(+ user_id=cast(str, response.get("user_id")),+ user_email=data.user_email,+ user_api_key_dict=user_api_key_dict,+ teams=teams,+ prisma_client=prisma_client,+ )user_id = cast(Optional[str], response.get("user_id", None))diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 6d250bb8ae2..9f4d4ee0f9e 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -643,6 +643,8 @@ async def proxy_startup_event(app: FastAPI):proxy_logging_obj=proxy_logging_obj,)+ await ProxyStartupEvent._update_default_team_member_budget()+## [Optional] Initialize dd tracerProxyStartupEvent._init_dd_tracer()@@ -1901,6 +1903,7 @@ class ProxyConfig:raise Exception(f"Invalid value set for upperbound_key_generate_params - value={value}")+else:verbose_proxy_logger.debug(f"{blue_color_code} setting litellm.{key}={value}{reset_color_code}"@@ -3364,6 +3367,23 @@ class ProxyStartupEvent:))+ @classmethod+ async def _update_default_team_member_budget(cls):+ """Update the default team member budget"""+ if litellm.default_internal_user_params is None:+ return++ _teams = litellm.default_internal_user_params.get("teams") or []+ if _teams and all(isinstance(team, dict) for team in _teams):+ from litellm.proxy.ui_crud_endpoints.proxy_setting_endpoints import (+ update_default_team_member_budget,+ )++ teams_pydantic_obj = [NewUserRequestTeam(**team) for team in _teams]+ await update_default_team_member_budget(+ teams=teams_pydantic_obj, user_api_key_dict=UserAPIKeyAuth(token=hash_token(master_key)) # type: ignore+ )+@classmethodasync def initialize_scheduled_background_jobs(cls,@@ -3390,6 +3410,7 @@ class ProxyStartupEvent:proxy_logging_obj=proxy_logging_obj,prisma_client=prisma_client,)+scheduler.add_job(budget_reset_job.reset_budget,"interval",diff --git a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.pyindex 884afd02bc4..d12816bc330 100644--- a/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py+++ b/litellm/proxy/ui_crud_endpoints/proxy_setting_endpoints.py@@ -244,6 +244,29 @@ async def get_default_team_settings():)+async def update_default_team_member_budget(+ teams: List[NewUserRequestTeam], user_api_key_dict: UserAPIKeyAuth+):+ """+ 1. Update the max member budget for the team+ """+ from fastapi import Request++ from litellm.proxy.management_endpoints.team_endpoints import update_team++ for team in teams:+ team_id = team.team_id+ max_budget_in_team = team.max_budget_in_team+ await update_team(+ data=UpdateTeamRequest(+ team_id=team_id,+ team_member_budget=max_budget_in_team,+ ),+ user_api_key_dict=user_api_key_dict,+ http_request=Request(scope={"type": "http"}),+ )++async def _update_litellm_setting(settings: Union[DefaultInternalUserParams, DefaultTeamSSOParams],settings_key: str,@@ -288,11 +311,21 @@ async def _update_litellm_setting(tags=["SSO Settings"],dependencies=[Depends(user_api_key_auth)],)-async def update_internal_user_settings(settings: DefaultInternalUserParams):+async def update_internal_user_settings(+ settings: DefaultInternalUserParams,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+):"""Update the default internal user parameters for SSO users.These settings will be applied to new users who sign in via SSO."""+ if settings.teams is not None and all(+ isinstance(team, NewUserRequestTeam) for team in settings.teams+ ):+ await update_default_team_member_budget(+ settings.teams, user_api_key_dict=user_api_key_dict # type: ignore+ )+return await _update_litellm_setting(settings=settings,settings_key="default_internal_user_params",diff --git a/litellm/types/integrations/prometheus.py b/litellm/types/integrations/prometheus.pyindex 45644f73b50..d91b593d09d 100644--- a/litellm/types/integrations/prometheus.py+++ b/litellm/types/integrations/prometheus.py@@ -11,21 +11,23 @@ import litellm@dataclassclass MetricValidationError:"""Error for invalid metric name"""+metric_name: strvalid_metrics: Tuple[str, ...]-+@propertydef message(self) -> str:return f"Invalid metric name: {self.metric_name}"-@dataclass+@dataclassclass LabelValidationError:"""Error for invalid labels on a metric"""+metric_name: strinvalid_labels: List[str]valid_labels: List[str]-+@propertydef message(self) -> str:return f"Invalid labels for metric '{self.metric_name}': {self.invalid_labels}"@@ -34,13 +36,14 @@ class LabelValidationError:@dataclassclass ValidationResults:"""Container for all validation results"""+metric_errors: List[MetricValidationError]label_errors: List[LabelValidationError]-+@propertydef has_errors(self) -> bool:return bool(self.metric_errors or self.label_errors)-+@propertydef all_error_messages(self) -> List[str]:messages = [error.message for error in self.metric_errors]@@ -345,10 +348,25 @@ class PrometheusMetricLabels:@staticmethoddef get_labels(label_name: DEFINED_PROMETHEUS_METRICS) -> List[str]:default_labels = getattr(PrometheusMetricLabels, label_name)- return default_labels + [- metric.replace(".", "_")- for metric in litellm.custom_prometheus_metadata_labels- ]+ custom_labels = []++ # Add custom metadata labels+ custom_labels.extend(+ [+ metric.replace(".", "_")+ for metric in litellm.custom_prometheus_metadata_labels+ ]+ )++ # Add custom tags labels+ custom_labels.extend(+ [+ f"tag_{tag}".replace("-", "_").replace(".", "_")+ for tag in litellm.custom_prometheus_tags+ ]+ )++ return default_labels + custom_labelsfrom typing import List, Optionaldiff --git a/tests/logging_callback_tests/test_prometheus_unit_tests.py b/tests/logging_callback_tests/test_prometheus_unit_tests.pyindex 456cf7fe388..6451f30e416 100644--- a/tests/logging_callback_tests/test_prometheus_unit_tests.py+++ b/tests/logging_callback_tests/test_prometheus_unit_tests.py@@ -1090,6 +1090,48 @@ def test_get_custom_labels_from_metadata(monkeypatch):}+def test_get_custom_labels_from_metadata_tags(monkeypatch):+ monkeypatch.setattr("litellm.custom_prometheus_metadata_labels", [])+ metadata = {"foo": "bar", "bar": "baz", "taz": "qux"}+ assert get_custom_labels_from_metadata(metadata) == {}+++def test_get_custom_labels_from_tags(monkeypatch):+ from litellm.integrations.prometheus import get_custom_labels_from_tags++ monkeypatch.setattr(+ "litellm.custom_prometheus_tags", ["prod", "test-env", "batch.job"]+ )+ tags = ["prod", "debug", "batch.job"]+ result = get_custom_labels_from_tags(tags)+ assert result == {+ "tag_prod": "true",+ "tag_test_env": "false", # not in request tags+ "tag_batch_job": "true", # dot replaced with underscore+ }+++def test_get_custom_labels_from_tags_empty_config(monkeypatch):+ from litellm.integrations.prometheus import get_custom_labels_from_tags++ monkeypatch.setattr("litellm.custom_prometheus_tags", [])+ tags = ["prod", "debug"]+ result = get_custom_labels_from_tags(tags)+ assert result == {}+++def test_get_custom_labels_from_tags_no_tags(monkeypatch):+ from litellm.integrations.prometheus import get_custom_labels_from_tags++ monkeypatch.setattr("litellm.custom_prometheus_tags", ["prod", "test"])+ tags = []+ result = get_custom_labels_from_tags(tags)+ assert result == {+ "tag_prod": "false",+ "tag_test": "false",+ }++@pytest.mark.asyncio(scope="session")async def test_initialize_remaining_budget_metrics(prometheus_logger):"""@@ -1487,18 +1529,74 @@ def test_set_team_budget_metrics_with_custom_labels(prometheus_logger, monkeypat100.0)- # Verify budget reset metric includes custom labels- budget_reset_calls = (- prometheus_logger.litellm_team_budget_remaining_hours_metric.labels.call_args_list++def test_prometheus_label_factory_with_custom_tags(monkeypatch):+ """+ Test that prometheus_label_factory correctly handles custom tags+ """+ from litellm.integrations.prometheus import prometheus_label_factory+ from litellm.types.integrations.prometheus import UserAPIKeyLabelValues++ # Set custom tags configuration+ monkeypatch.setattr("litellm.custom_prometheus_tags", ["prod", "test-env"])++ # Create enum_values with tags+ enum_values = UserAPIKeyLabelValues(+ hashed_api_key="key123",+ team="team1",+ tags=["prod", "debug"], # Only "prod" is in our custom_prometheus_tags+ )++ # Test with supported labels including custom tags+ supported_labels = ["hashed_api_key", "team", "tag_prod", "tag_test_env"]++ result = prometheus_label_factory(+ supported_enum_labels=supported_labels,+ enum_values=enum_values,)- assert len(budget_reset_calls) == 1- assert budget_reset_calls[0][1] == {++ expected = {+ "hashed_api_key": "key123","team": "team1",- "team_alias": "alias1",- "metadata_organization": None,- "metadata_environment": None,+ "tag_prod": "true", # present in tags+ "tag_test_env": "false", # not present in tags}+ assert result == expected+++def test_prometheus_label_factory_with_no_custom_tags(monkeypatch):+ """+ Test that prometheus_label_factory works when no custom tags are configured+ """+ from litellm.integrations.prometheus import prometheus_label_factory+ from litellm.types.integrations.prometheus import UserAPIKeyLabelValues++ # Set empty custom tags configuration+ monkeypatch.setattr("litellm.custom_prometheus_tags", [])++ # Create enum_values with tags+ enum_values = UserAPIKeyLabelValues(+ hashed_api_key="key123",+ team="team1",+ tags=["prod", "debug"],+ )++ # Test with basic supported labels (no custom tags)+ supported_labels = ["hashed_api_key", "team"]++ result = prometheus_label_factory(+ supported_enum_labels=supported_labels,+ enum_values=enum_values,+ )++ expected = {+ "hashed_api_key": "key123",+ "team": "team1",+ }++ assert result == expected+def test_get_exception_class_name(prometheus_logger):"""@@ -1628,7 +1726,11 @@ def test_set_llm_deployment_success_metrics_with_label_filtering():)# Should only contain the filtered labels that are supported for this metric- expected_filtered_labels = {"litellm_model_name", "api_provider", "hashed_api_key"}+ expected_filtered_labels = {+ "litellm_model_name",+ "api_provider",+ "hashed_api_key",+ }actual_labels = set(k for k in overhead_labels.keys() if k is not None)# Verify that only expected labels are present (subset of configured labels)diff --git a/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.pyindex d87225e4d8d..1ce5d24c8c0 100644--- a/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py@@ -460,7 +460,6 @@ async def test_new_user_default_teams_flow(mocker):assert team_call_kwargs["user_id"] == "test-user-123"assert team_call_kwargs["team_id"] == "96fed65b-0182-4ff4-8429-2721cd7d42af"assert team_call_kwargs["user_email"] == "[email protected]"- assert team_call_kwargs["max_budget_in_team"] == 100assert team_call_kwargs["user_role"] == "user"# Verify response structure