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(prometheus): sanitize label values to prevent metric scrape failures (#20600)
michelligabriele35eb3030982e
diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.pyindex 0a61dab0680..1675201f1f1 100644--- a/litellm/integrations/prometheus.py+++ b/litellm/integrations/prometheus.py@@ -29,7 +29,10 @@ from litellm.proxy._types import (UserAPIKeyAuth,)from litellm.types.integrations.prometheus import *-from litellm.types.integrations.prometheus import _sanitize_prometheus_label_name+from litellm.types.integrations.prometheus import (+ _sanitize_prometheus_label_name,+ _sanitize_prometheus_label_value,+)from litellm.types.utils import StandardLoggingPayloadif TYPE_CHECKING:@@ -1276,11 +1279,17 @@ class PrometheusLogger(CustomLogger):)self.litellm_remaining_api_key_requests_for_model.labels(- user_api_key, user_api_key_alias, model_group, model_id+ _sanitize_prometheus_label_value(user_api_key),+ _sanitize_prometheus_label_value(user_api_key_alias),+ _sanitize_prometheus_label_value(model_group),+ _sanitize_prometheus_label_value(model_id),).set(remaining_requests)self.litellm_remaining_api_key_tokens_for_model.labels(- user_api_key, user_api_key_alias, model_group, model_id+ _sanitize_prometheus_label_value(user_api_key),+ _sanitize_prometheus_label_value(user_api_key_alias),+ _sanitize_prometheus_label_value(model_group),+ _sanitize_prometheus_label_value(model_id),).set(remaining_tokens)def _set_latency_metrics(@@ -1401,14 +1410,14 @@ class PrometheusLogger(CustomLogger):try:self.litellm_llm_api_failed_requests_metric.labels(- end_user_id,- user_api_key,- user_api_key_alias,- model,- user_api_team,- user_api_team_alias,- user_id,- standard_logging_payload.get("model_id", ""),+ _sanitize_prometheus_label_value(end_user_id),+ _sanitize_prometheus_label_value(user_api_key),+ _sanitize_prometheus_label_value(user_api_key_alias),+ _sanitize_prometheus_label_value(model),+ _sanitize_prometheus_label_value(user_api_team),+ _sanitize_prometheus_label_value(user_api_team_alias),+ _sanitize_prometheus_label_value(user_id),+ _sanitize_prometheus_label_value(standard_logging_payload.get("model_id", "")),).inc()self.set_llm_deployment_failure_metrics(kwargs)except Exception as e:@@ -2354,7 +2363,11 @@ class PrometheusLogger(CustomLogger):increment metric when litellm.Router / load balancing logic places a deployment in cool down"""self.litellm_deployment_cooled_down.labels(- litellm_model_name, model_id, api_base, api_provider, exception_status+ _sanitize_prometheus_label_value(litellm_model_name),+ _sanitize_prometheus_label_value(model_id),+ _sanitize_prometheus_label_value(api_base),+ _sanitize_prometheus_label_value(api_provider),+ _sanitize_prometheus_label_value(exception_status),).inc()def increment_callback_logging_failure(@@ -3074,9 +3087,10 @@ def prometheus_label_factory(# Extract dictionary from Pydantic objectenum_dict = enum_values.model_dump()- # Filter supported labels+ # Filter supported labels and sanitize values to prevent breaking+ # the Prometheus text format (e.g. U+2028 Line Separator in label values)filtered_labels = {- label: value+ label: _sanitize_prometheus_label_value(value)for label, value in enum_dict.items()if label in supported_enum_labels}@@ -3094,14 +3108,14 @@ def prometheus_label_factory(# check sanitized keysanitized_key = _sanitize_prometheus_label_name(key)if sanitized_key in supported_enum_labels:- filtered_labels[sanitized_key] = value+ filtered_labels[sanitized_key] = _sanitize_prometheus_label_value(value)# Add custom tags if configuredif 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+ filtered_labels[key] = _sanitize_prometheus_label_value(value)for label in supported_enum_labels:if label not in filtered_labels:diff --git a/litellm/types/integrations/prometheus.py b/litellm/types/integrations/prometheus.pyindex 146c390363b..fd788af9ac1 100644--- a/litellm/types/integrations/prometheus.py+++ b/litellm/types/integrations/prometheus.py@@ -1,7 +1,7 @@import refrom dataclasses import dataclassfrom enum import Enum-from typing import Dict, List, Literal, Optional, Tuple+from typing import Any, Dict, List, Literal, Optional, Tuplefrom pydantic import BaseModel, Fieldfrom typing_extensions import Annotated@@ -41,6 +41,38 @@ def _sanitize_prometheus_label_name(label: str) -> str:return sanitized+def _sanitize_prometheus_label_value(value: Optional[Any]) -> Optional[str]:+ """+ Sanitize a label value for Prometheus text format compatibility.++ Removes or replaces characters that break the Prometheus exposition format:+ - U+2028 (Line Separator) and U+2029 (Paragraph Separator) are removed+ - Carriage returns are removed+ - Newlines are replaced with spaces+ - Backslashes and double quotes are escaped per Prometheus spec+ """+ if value is None:+ return None++ # Coerce non-string values (int, bool, etc.) to str before sanitizing+ if not isinstance(value, str):+ value = str(value)++ # Remove Unicode line/paragraph separators that break text format+ value = value.replace("\u2028", "").replace("\u2029", "")++ # Remove carriage returns+ value = value.replace("\r", "")++ # Replace newlines with spaces+ value = value.replace("\n", " ")++ # Escape backslashes and double quotes per Prometheus exposition format+ value = value.replace("\\", "\\\\").replace('"', '\\"')++ return value++@dataclassclass MetricValidationError:"""Error for invalid metric name"""diff --git a/tests/test_litellm/integrations/test_prometheus_labels.py b/tests/test_litellm/integrations/test_prometheus_labels.pyindex 9d4626b88a5..2553eb06271 100644--- a/tests/test_litellm/integrations/test_prometheus_labels.py+++ b/tests/test_litellm/integrations/test_prometheus_labels.py@@ -292,6 +292,87 @@ def test_prometheus_metrics_use_normalized_routes():print("✅ Prometheus metrics use normalized routes in labels")+def test_prometheus_label_value_sanitization():+ """+ Test that Prometheus label values are sanitized to prevent breaking+ the Prometheus text format.++ Issue: Unicode Line Separator (U+2028) in label values (e.g. from a+ malformed model name) breaks the Prometheus exposition format, causing+ scrapers like Datadog to fail parsing the entire /metrics endpoint.+ """+ from litellm.integrations.prometheus import (+ PrometheusLogger,+ UserAPIKeyLabelValues,+ prometheus_label_factory,+ )+ from unittest.mock import MagicMock++ prometheus_logger = MagicMock()+ prometheus_logger.get_labels_for_metric = (+ PrometheusLogger.get_labels_for_metric.__get__(prometheus_logger)+ )++ # Simulate a model name with U+2028 (Unicode Line Separator) appended+ # and an api_key_alias with newlines and quotes+ enum_values = UserAPIKeyLabelValues(+ requested_model="claude-haiku-4-5-20251001\u2028",+ api_key_alias='My Key "test"\nwith newline',+ route="/v1/chat/completions",+ status_code="400",+ )++ labels = prometheus_label_factory(+ supported_enum_labels=prometheus_logger.get_labels_for_metric(+ metric_name="litellm_proxy_total_requests_metric"+ ),+ enum_values=enum_values,+ )++ # U+2028 must be stripped+ assert "\u2028" not in labels["requested_model"], (+ f"U+2028 should be removed from label value, got: {repr(labels['requested_model'])}"+ )+ assert labels["requested_model"] == "claude-haiku-4-5-20251001"++ # Newlines must be replaced with spaces, quotes must be escaped+ assert "\n" not in labels["api_key_alias"]+ assert labels["api_key_alias"] == 'My Key \\"test\\" with newline'++ print("✅ Prometheus label values are properly sanitized")+++def test_prometheus_label_value_sanitization_unicode_paragraph_separator():+ """Test that U+2029 (Paragraph Separator) is also stripped."""+ from litellm.types.integrations.prometheus import _sanitize_prometheus_label_value++ result = _sanitize_prometheus_label_value("model\u2029name")+ assert result == "modelname"+ assert "\u2029" not in result++ print("✅ U+2029 Paragraph Separator is stripped")+++def test_prometheus_label_value_sanitization_none():+ """Test that None values pass through unchanged."""+ from litellm.types.integrations.prometheus import _sanitize_prometheus_label_value++ assert _sanitize_prometheus_label_value(None) is None++ print("✅ None values pass through unchanged")+++def test_prometheus_label_value_sanitization_non_string_types():+ """Test that non-string values (int, bool, etc.) are coerced to str."""+ from litellm.types.integrations.prometheus import _sanitize_prometheus_label_value++ assert _sanitize_prometheus_label_value(200) == "200"+ assert _sanitize_prometheus_label_value(True) == "True"+ assert _sanitize_prometheus_label_value(3.14) == "3.14"++ print("✅ Non-string values are coerced to str")++if __name__ == "__main__":test_user_email_in_required_metrics()test_user_email_label_exists()@@ -301,4 +382,8 @@ if __name__ == "__main__":test_route_normalization_preserves_static_routes()test_route_normalization_other_dynamic_apis()test_prometheus_metrics_use_normalized_routes()+ test_prometheus_label_value_sanitization()+ test_prometheus_label_value_sanitization_unicode_paragraph_separator()+ test_prometheus_label_value_sanitization_none()+ test_prometheus_label_value_sanitization_non_string_types()print("\n✅ All prometheus label tests passed!")