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: Add Prometheus metrics for request queue time and guardrails (#17973)

Hamza Qureshi9c544949f8c2
diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.py
index c01f7481277..b49395e074a 100644
--- a/litellm/integrations/prometheus.py
+++ b/litellm/integrations/prometheus.py
@@ -14,6 +14,7 @@ from typing import (
Literal,
Optional,
Tuple,
+ Union,
cast,
)
@@ -44,6 +45,7 @@ def _get_cached_end_user_id_for_cost_tracking():
global _get_end_user_id_for_cost_tracking
if _get_end_user_id_for_cost_tracking is None:
from litellm.utils import get_end_user_id_for_cost_tracking
+
_get_end_user_id_for_cost_tracking = get_end_user_id_for_cost_tracking
return _get_end_user_id_for_cost_tracking
@@ -237,6 +239,36 @@ class PrometheusLogger(CustomLogger):
),
buckets=LATENCY_BUCKETS,
)
+
+ # Request queue time metric
+ self.litellm_request_queue_time_metric = self._histogram_factory(
+ "litellm_request_queue_time_seconds",
+ "Time spent in request queue before processing starts (seconds)",
+ labelnames=self.get_labels_for_metric(
+ "litellm_request_queue_time_seconds"
+ ),
+ buckets=LATENCY_BUCKETS,
+ )
+
+ # Guardrail metrics
+ self.litellm_guardrail_latency_metric = self._histogram_factory(
+ "litellm_guardrail_latency_seconds",
+ "Latency (seconds) for guardrail execution",
+ labelnames=["guardrail_name", "status", "error_type", "hook_type"],
+ buckets=LATENCY_BUCKETS,
+ )
+
+ self.litellm_guardrail_errors_total = self._counter_factory(
+ "litellm_guardrail_errors_total",
+ "Total number of errors encountered during guardrail execution",
+ labelnames=["guardrail_name", "error_type", "hook_type"],
+ )
+
+ self.litellm_guardrail_requests_total = self._counter_factory(
+ "litellm_guardrail_requests_total",
+ "Total number of guardrail invocations",
+ labelnames=["guardrail_name", "status", "hook_type"],
+ )
# llm api provider budget metrics
self.litellm_provider_remaining_budget_metric = self._gauge_factory(
"litellm_provider_remaining_budget_metric",
@@ -795,7 +827,7 @@ class PrometheusLogger(CustomLogger):
litellm_params = kwargs.get("litellm_params", {}) or {}
_metadata = litellm_params.get("metadata", {})
get_end_user_id_for_cost_tracking = _get_cached_end_user_id_for_cost_tracking()
-
+
end_user_id = get_end_user_id_for_cost_tracking(
litellm_params, service_type="prometheus"
)
@@ -1182,6 +1214,22 @@ class PrometheusLogger(CustomLogger):
total_time_seconds
)
+ # request queue time (time from arrival to processing start)
+ _litellm_params = kwargs.get("litellm_params", {}) or {}
+ queue_time_seconds = _litellm_params.get("metadata", {}).get(
+ "queue_time_seconds"
+ )
+ if queue_time_seconds is not None and queue_time_seconds >= 0:
+ _labels = prometheus_label_factory(
+ supported_enum_labels=self.get_labels_for_metric(
+ metric_name="litellm_request_queue_time_seconds"
+ ),
+ enum_values=enum_values,
+ )
+ self.litellm_request_queue_time_metric.labels(**_labels).observe(
+ queue_time_seconds
+ )
+
async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):
from litellm.types.utils import StandardLoggingPayload
@@ -1196,7 +1244,7 @@ class PrometheusLogger(CustomLogger):
)
litellm_params = kwargs.get("litellm_params", {}) or {}
get_end_user_id_for_cost_tracking = _get_cached_end_user_id_for_cost_tracking()
-
+
end_user_id = get_end_user_id_for_cost_tracking(
litellm_params, service_type="prometheus"
)
@@ -1398,7 +1446,6 @@ class PrometheusLogger(CustomLogger):
api_provider=llm_provider or "",
)
if exception is not None:
-
_labels = prometheus_label_factory(
supported_enum_labels=self.get_labels_for_metric(
metric_name="litellm_deployment_failure_responses"
@@ -1431,12 +1478,11 @@ class PrometheusLogger(CustomLogger):
enum_values: UserAPIKeyLabelValues,
output_tokens: float = 1.0,
):
-
try:
verbose_logger.debug("setting remaining tokens requests metric")
- standard_logging_payload: Optional[StandardLoggingPayload] = (
- request_kwargs.get("standard_logging_object")
- )
+ standard_logging_payload: Optional[
+ StandardLoggingPayload
+ ] = request_kwargs.get("standard_logging_object")
if standard_logging_payload is None:
return
@@ -1571,6 +1617,50 @@ class PrometheusLogger(CustomLogger):
)
return
+ def _record_guardrail_metrics(
+ self,
+ guardrail_name: str,
+ latency_seconds: float,
+ status: str,
+ error_type: Optional[str],
+ hook_type: str,
+ ):
+ """
+ Record guardrail metrics for prometheus.
+
+ Args:
+ guardrail_name: Name of the guardrail
+ latency_seconds: Execution latency in seconds
+ status: "success" or "error"
+ error_type: Type of error if any, None otherwise
+ hook_type: "pre_call", "during_call", or "post_call"
+ """
+ try:
+ # Record latency
+ self.litellm_guardrail_latency_metric.labels(
+ guardrail_name=guardrail_name,
+ status=status,
+ error_type=error_type or "none",
+ hook_type=hook_type,
+ ).observe(latency_seconds)
+
+ # Record request count
+ self.litellm_guardrail_requests_total.labels(
+ guardrail_name=guardrail_name,
+ status=status,
+ hook_type=hook_type,
+ ).inc()
+
+ # Record error count if there was an error
+ if status == "error" and error_type:
+ self.litellm_guardrail_errors_total.labels(
+ guardrail_name=guardrail_name,
+ error_type=error_type,
+ hook_type=hook_type,
+ ).inc()
+ except Exception as e:
+ verbose_logger.debug(f"Error recording guardrail metrics: {str(e)}")
+
@staticmethod
def _get_exception_class_name(exception: Exception) -> str:
exception_class_name = ""
@@ -2208,10 +2298,10 @@ class PrometheusLogger(CustomLogger):
from litellm.constants import PROMETHEUS_BUDGET_METRICS_REFRESH_INTERVAL_MINUTES
from litellm.integrations.custom_logger import CustomLogger
- prometheus_loggers: List[CustomLogger] = (
- litellm.logging_callback_manager.get_custom_loggers_for_type(
- callback_type=PrometheusLogger
- )
+ prometheus_loggers: List[
+ CustomLogger
+ ] = litellm.logging_callback_manager.get_custom_loggers_for_type(
+ callback_type=PrometheusLogger
)
# we need to get the initialized prometheus logger instance(s) and call logger.initialize_remaining_budget_metrics() on them
verbose_logger.debug("found %s prometheus loggers", len(prometheus_loggers))
@@ -2283,7 +2373,7 @@ def prometheus_label_factory(
if UserAPIKeyLabelNames.END_USER.value in filtered_labels:
get_end_user_id_for_cost_tracking = _get_cached_end_user_id_for_cost_tracking()
-
+
filtered_labels["end_user"] = get_end_user_id_for_cost_tracking(
litellm_params={"user_api_key_end_user_id": enum_values.end_user},
service_type="prometheus",
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.py
index 537b48f06ed..ae7cb612c9c 100644
--- a/litellm/proxy/common_request_processing.py
+++ b/litellm/proxy/common_request_processing.py
@@ -237,7 +237,11 @@ class ProxyBaseLLMRequestProcessing:
if response_cost is not None:
try:
# Convert response_cost to float if it's a string
- cost_value = float(response_cost) if isinstance(response_cost, str) else response_cost
+ cost_value = (
+ float(response_cost)
+ if isinstance(response_cost, str)
+ else response_cost
+ )
if cost_value > 0:
updated_spend = current_spend + cost_value
except (ValueError, TypeError):
@@ -376,6 +380,16 @@ class ProxyBaseLLMRequestProcessing:
) -> Tuple[dict, LiteLLMLoggingObj]:
start_time = datetime.now() # start before calling guardrail hooks
+ # Calculate request queue time if arrival_time is available
+ # Use start_time.timestamp() to avoid extra time.time() call for better performance
+ proxy_server_request = self.data.get("proxy_server_request", {})
+ arrival_time = proxy_server_request.get("arrival_time")
+ queue_time_seconds = None
+ if arrival_time is not None:
+ # Convert start_time (datetime) to timestamp for calculation
+ processing_start_time = start_time.timestamp()
+ queue_time_seconds = processing_start_time - arrival_time
+
self.data = await add_litellm_data_to_request(
data=self.data,
request=request,
@@ -385,6 +399,19 @@ class ProxyBaseLLMRequestProcessing:
proxy_config=proxy_config,
)
+ # Store queue time in metadata after add_litellm_data_to_request to ensure it's preserved
+ if queue_time_seconds is not None:
+ from litellm.proxy.litellm_pre_call_utils import _get_metadata_variable_name
+
+ _metadata_variable_name = _get_metadata_variable_name(request)
+ if _metadata_variable_name not in self.data:
+ self.data[_metadata_variable_name] = {}
+ if not isinstance(self.data[_metadata_variable_name], dict):
+ self.data[_metadata_variable_name] = {}
+ self.data[_metadata_variable_name][
+ "queue_time_seconds"
+ ] = queue_time_seconds
+
self.data["model"] = (
general_settings.get("completion_model", None) # server default
or user_model # model name passed via cli args
@@ -1155,9 +1182,9 @@ class ProxyBaseLLMRequestProcessing:
# Add cache-related fields to **params (handled by Usage.__init__)
if cache_creation_input_tokens is not None:
- usage_kwargs["cache_creation_input_tokens"] = (
- cache_creation_input_tokens
- )
+ usage_kwargs[
+ "cache_creation_input_tokens"
+ ] = cache_creation_input_tokens
if cache_read_input_tokens is not None:
usage_kwargs["cache_read_input_tokens"] = cache_read_input_tokens
diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.py
index 5b5723efc3d..3f844f21eb0 100644
--- a/litellm/proxy/litellm_pre_call_utils.py
+++ b/litellm/proxy/litellm_pre_call_utils.py
@@ -161,7 +161,6 @@ class KeyAndTeamLoggingSettings:
@staticmethod
def get_team_dynamic_logging_settings(user_api_key_dict: UserAPIKeyAuth):
-
if (
user_api_key_dict.team_metadata is not None
and "logging" in user_api_key_dict.team_metadata
@@ -174,12 +173,12 @@ def _get_dynamic_logging_metadata(
user_api_key_dict: UserAPIKeyAuth, proxy_config: ProxyConfig
) -> Optional[TeamCallbackMetadata]:
callback_settings_obj: Optional[TeamCallbackMetadata] = None
- key_dynamic_logging_settings: Optional[dict] = (
- KeyAndTeamLoggingSettings.get_key_dynamic_logging_settings(user_api_key_dict)
- )
- team_dynamic_logging_settings: Optional[dict] = (
- KeyAndTeamLoggingSettings.get_team_dynamic_logging_settings(user_api_key_dict)
- )
+ key_dynamic_logging_settings: Optional[
+ dict
+ ] = KeyAndTeamLoggingSettings.get_key_dynamic_logging_settings(user_api_key_dict)
+ team_dynamic_logging_settings: Optional[
+ dict
+ ] = KeyAndTeamLoggingSettings.get_team_dynamic_logging_settings(user_api_key_dict)
#########################################################################################
# Key-based callbacks
#########################################################################################
@@ -462,7 +461,6 @@ class LiteLLMProxyRequestSetup:
team_id=user_api_key_dict.team_id,
) # handles aliases, wildcards, etc.
):
-
_headers = LiteLLMProxyRequestSetup.add_headers_to_llm_call(
headers, user_api_key_dict
)
@@ -663,11 +661,11 @@ class LiteLLMProxyRequestSetup:
## KEY-LEVEL SPEND LOGS / TAGS
if "tags" in key_metadata and key_metadata["tags"] is not None:
- data[_metadata_variable_name]["tags"] = (
- LiteLLMProxyRequestSetup._merge_tags(
- request_tags=data[_metadata_variable_name].get("tags"),
- tags_to_add=key_metadata["tags"],
- )
+ data[_metadata_variable_name][
+ "tags"
+ ] = LiteLLMProxyRequestSetup._merge_tags(
+ request_tags=data[_metadata_variable_name].get("tags"),
+ tags_to_add=key_metadata["tags"],
)
if "disable_global_guardrails" in key_metadata and isinstance(
key_metadata["disable_global_guardrails"], bool
@@ -815,11 +813,14 @@ async def add_litellm_data_to_request( # noqa: PLR0915
# Init - Proxy Server Request
# we do this as soon as entering so we track the original request
##########################################################
+ # Track arrival time for queue time metric
+ arrival_time = time.time()
data["proxy_server_request"] = {
"url": str(request.url),
"method": request.method,
"headers": _headers,
"body": copy.copy(data), # use copy instead of deepcopy
+ "arrival_time": arrival_time, # Track when request arrived at proxy
}
safe_add_api_version_from_query_params(data, request)
@@ -930,9 +931,9 @@ async def add_litellm_data_to_request( # noqa: PLR0915
data[_metadata_variable_name]["litellm_api_version"] = version
if general_settings is not None:
- data[_metadata_variable_name]["global_max_parallel_requests"] = (
- general_settings.get("global_max_parallel_requests", None)
- )
+ data[_metadata_variable_name][
+ "global_max_parallel_requests"
+ ] = general_settings.get("global_max_parallel_requests", None)
### KEY-LEVEL Controls
key_metadata = user_api_key_dict.metadata
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index d1a78534dae..a3fd78d576d 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -961,6 +961,7 @@ class ProxyLogging:
Updated data dictionary if guardrail passes, None if guardrail should be skipped
"""
from litellm.types.guardrails import GuardrailEventHooks
+ from litellm.integrations.prometheus import PrometheusLogger
# Determine the event type based on call type
event_type = GuardrailEventHooks.pre_call
@@ -973,30 +974,62 @@ class ProxyLogging:
guardrail_name = callback.guardrail_name
- # Check if load balancing should be used
- if guardrail_name and self._should_use_guardrail_load_balancing(guardrail_name):
- response = await self._execute_guardrail_with_load_balancing(
- guardrail_name=guardrail_name,
- hook_type="pre_call",
- data=data,
- user_api_key_dict=user_api_key_dict,
- call_type=call_type,
- )
- else:
- # Single guardrail - execute directly
- response = await self._execute_guardrail_hook(
- callback=callback,
- hook_type="pre_call",
- data=data,
- user_api_key_dict=user_api_key_dict,
- call_type=call_type,
- )
+ # Track timing and errors for prometheus metrics
+ # Use time.perf_counter() for more accurate duration measurements
+ guardrail_start_time = time.perf_counter()
+ status = "success"
+ error_type = None
- # Process the response if one was returned
- if response is not None:
- data = await self.process_pre_call_hook_response(
- response=response, data=data, call_type=call_type
- )
+ try:
+ # Check if load balancing should be used
+ if guardrail_name and self._should_use_guardrail_load_balancing(guardrail_name):
+ response = await self._execute_guardrail_with_load_balancing(
+ guardrail_name=guardrail_name,
+ hook_type="pre_call",
+ data=data,
+ user_api_key_dict=user_api_key_dict,
+ call_type=call_type,
+ )
+ else:
+ # Single guardrail - execute directly
+ response = await self._execute_guardrail_hook(
+ callback=callback,
+ hook_type="pre_call",
+ data=data,
+ user_api_key_dict=user_api_key_dict,
+ call_type=call_type,
+ )
+
+ # Process the response if one was returned
+ if response is not None:
+ data = await self.process_pre_call_hook_response(
+ response=response, data=data, call_type=call_type
+ )
+
+ except Exception as e:
+ status = "error"
+ error_type = type(e).__name__
+ # Re-raise the exception to maintain existing behavior
+ raise
+ finally:
+ # Record prometheus metrics
+ guardrail_end_time = time.perf_counter()
+ latency_seconds = guardrail_end_time - guardrail_start_time
+
+ # Get guardrail name for metrics (fallback if not set)
+ metrics_guardrail_name = guardrail_name or getattr(callback, "guardrail_name", callback.__class__.__name__) or "unknown"
+
+ # Find PrometheusLogger in callbacks and record metrics
+ for prom_callback in litellm.callbacks:
+ if isinstance(prom_callback, PrometheusLogger):
+ prom_callback._record_guardrail_metrics(
+ guardrail_name=metrics_guardrail_name,
+ latency_seconds=latency_seconds,
+ status=status,
+ error_type=error_type,
+ hook_type="pre_call",
+ )
+ break
return data
diff --git a/litellm/types/integrations/prometheus.py b/litellm/types/integrations/prometheus.py
index 6a254fc8252..6a98c8a6105 100644
--- a/litellm/types/integrations/prometheus.py
+++ b/litellm/types/integrations/prometheus.py
@@ -1,7 +1,7 @@
import re
from dataclasses import dataclass
from enum import Enum
-from typing import Dict, List, Literal, Optional, Tuple, Union
+from typing import Dict, List, Literal, Optional, Tuple
from pydantic import BaseModel, Field
from typing_extensions import Annotated
@@ -185,6 +185,10 @@ DEFINED_PROMETHEUS_METRICS = Literal[
"litellm_redis_daily_spend_update_queue_size",
"litellm_in_memory_spend_update_queue_size",
"litellm_redis_spend_update_queue_size",
+ "litellm_request_queue_time_seconds",
+ "litellm_guardrail_latency_seconds",
+ "litellm_guardrail_errors_total",
+ "litellm_guardrail_requests_total",
]
@@ -219,6 +223,23 @@ class PrometheusMetricLabels:
UserAPIKeyLabelNames.v1_LITELLM_MODEL_NAME.value,
]
+ litellm_request_queue_time_seconds = [
+ UserAPIKeyLabelNames.END_USER.value,
+ UserAPIKeyLabelNames.API_KEY_HASH.value,
+ UserAPIKeyLabelNames.API_KEY_ALIAS.value,
+ UserAPIKeyLabelNames.REQUESTED_MODEL.value,
+ UserAPIKeyLabelNames.TEAM.value,
+ UserAPIKeyLabelNames.TEAM_ALIAS.value,
+ UserAPIKeyLabelNames.USER.value,
+ UserAPIKeyLabelNames.v1_LITELLM_MODEL_NAME.value,
+ ]
+
+ # Guardrail metrics - these use custom labels (guardrail_name, status, error_type, hook_type)
+ # which are not part of UserAPIKeyLabelNames
+ litellm_guardrail_latency_seconds: List[str] = []
+ litellm_guardrail_errors_total: List[str] = []
+ litellm_guardrail_requests_total: List[str] = []
+
litellm_proxy_total_requests_metric = [
UserAPIKeyLabelNames.END_USER.value,
UserAPIKeyLabelNames.API_KEY_HASH.value,
@@ -460,11 +481,6 @@ class PrometheusMetricLabels:
return default_labels + custom_labels
-from typing import List, Optional
-
-from pydantic import BaseModel, Field
-
-
class UserAPIKeyLabelValues(BaseModel):
end_user: Annotated[
Optional[str], Field(..., alias=UserAPIKeyLabelNames.END_USER.value)
diff --git a/tests/test_litellm/integrations/test_prometheus_queue_guardrail_metrics.py b/tests/test_litellm/integrations/test_prometheus_queue_guardrail_metrics.py
new file mode 100644
index 00000000000..0743a9c7ba2
--- /dev/null
+++ b/tests/test_litellm/integrations/test_prometheus_queue_guardrail_metrics.py
@@ -0,0 +1,424 @@
+"""
+Unit tests for prometheus queue time and guardrail metrics
+"""
+from datetime import datetime
+from unittest.mock import MagicMock
+
+import pytest
+from prometheus_client import REGISTRY
+
+from litellm.integrations.prometheus import PrometheusLogger
+from litellm.types.integrations.prometheus import UserAPIKeyLabelValues
+
+
[email protected](autouse=True)
+def cleanup_prometheus_registry():
+ """Clean up prometheus registry between tests"""
+ # Clear the registry before each test
+ collectors = list(REGISTRY._collector_to_names.keys())
+ for collector in collectors:
+ REGISTRY.unregister(collector)
+ yield
+ # Clean up after test
+ collectors = list(REGISTRY._collector_to_names.keys())
+ for collector in collectors:
+ REGISTRY.unregister(collector)
+
+
+class TestPrometheusQueueTimeMetric:
+ """Test request queue time metric recording"""
+
+ def test_queue_time_metric_recorded_in_set_latency_metrics(self):
+ """Test that queue time metric is recorded when queue_time_seconds is present in metadata"""
+ # Arrange
+ prometheus_logger = PrometheusLogger()
+
+ # Mock the metric
+ mock_metric = MagicMock()
+ mock_labeled_metric = MagicMock()
+ mock_metric.labels.return_value = mock_labeled_metric
+ prometheus_logger.litellm_request_queue_time_metric = mock_metric
+
+ # Create mock kwargs with queue_time_seconds in metadata
+ queue_time_seconds = 0.5
+
+ kwargs = {
+ "litellm_params": {"metadata": {"queue_time_seconds": queue_time_seconds}},
+ "model": "gpt-3.5-turbo",
+ "start_time": datetime.now(),
+ "end_time": datetime.now(),
+ }
+
+ enum_values = UserAPIKeyLabelValues(
+ end_user=None,
+ hashed_api_key="test-key",
+ api_key_alias="test-alias",
+ requested_model="gpt-3.5-turbo",
+ model_group="gpt-3.5-turbo",
+ team=None,
+ team_alias=None,
+ user=None,
+ user_email=None,
+ status_code="200",
+ model="gpt-3.5-turbo",
+ litellm_model_name="gpt-3.5-turbo",
+ tags=[],
+ model_id="gpt-3.5-turbo",
+ api_base="https://api.openai.com",
+ api_provider="openai",
+ exception_status=None,
+ exception_class=None,
+ custom_metadata_labels={},
+ route=None,
+ )
+
+ # Act
+ prometheus_logger._set_latency_metrics(
+ kwargs=kwargs,
+ model="gpt-3.5-turbo",
+ user_api_key="test-key",
+ user_api_key_alias="test-alias",
+ user_api_team=None,
+ user_api_team_alias=None,
+ enum_values=enum_values,
+ )
+
+ # Assert - queue time metric should be called
+ mock_metric.labels.assert_called()
+ # Check that observe was called on the queue time metric
+ assert mock_labeled_metric.observe.called
+ # Verify the observed value
+ observed_value = None
+ for call in mock_labeled_metric.observe.call_args_list:
+ if len(call[0]) > 0:
+ observed_value = call[0][0]
+ if observed_value == queue_time_seconds:
+ break
+ assert observed_value == queue_time_seconds
+ assert observed_value >= 0
+
+ def test_queue_time_metric_not_recorded_when_missing(self):
+ """Test that queue time metric is not recorded when queue_time_seconds is missing"""
+ # Arrange
+ prometheus_logger = PrometheusLogger()
+
+ # Mock the metric
+ mock_metric = MagicMock()
+ mock_labeled_metric = MagicMock()
+ mock_metric.labels.return_value = mock_labeled_metric
+ prometheus_logger.litellm_request_queue_time_metric = mock_metric
+
+ # Create mock kwargs without queue_time_seconds
+ kwargs = {
+ "litellm_params": {"metadata": {}},
+ "model": "gpt-3.5-turbo",
+ "start_time": datetime.now(),
+ "end_time": datetime.now(),
+ }
+
+ enum_values = UserAPIKeyLabelValues(
+ end_user=None,
+ hashed_api_key="test-key",
+ api_key_alias="test-alias",
+ requested_model="gpt-3.5-turbo",
+ model_group="gpt-3.5-turbo",
+ team=None,
+ team_alias=None,
+ user=None,
+ user_email=None,
+ status_code="200",
+ model="gpt-3.5-turbo",
+ litellm_model_name="gpt-3.5-turbo",
+ tags=[],
+ model_id="gpt-3.5-turbo",
+ api_base="https://api.openai.com",
+ api_provider="openai",
+ exception_status=None,
+ exception_class=None,
+ custom_metadata_labels={},
+ route=None,
+ )
+
+ # Act
+ prometheus_logger._set_latency_metrics(
+ kwargs=kwargs,
+ model="gpt-3.5-turbo",
+ user_api_key="test-key",
+ user_api_key_alias="test-alias",
+ user_api_team=None,
+ user_api_team_alias=None,
+ enum_values=enum_values,
+ )
+
+ # Assert - queue time metric should not be called (queue_time_seconds is None)
+ # We check that observe was not called with queue_time_seconds
+ queue_time_called = False
+ for call in mock_labeled_metric.observe.call_args_list:
+ if len(call[0]) > 0 and call[0][0] == 0.5: # Our test queue time value
+ queue_time_called = True
+ break
+ assert (
+ not queue_time_called
+ ), "Queue time metric should not be recorded when queue_time_seconds is missing"
+
+ def test_queue_time_metric_not_recorded_when_negative(self):
+ """Test that queue time metric is not recorded when queue_time_seconds is negative"""
+ # Arrange
+ prometheus_logger = PrometheusLogger()
+
+ # Mock the metric
+ mock_metric = MagicMock()
+ mock_labeled_metric = MagicMock()
+ mock_metric.labels.return_value = mock_labeled_metric
+ prometheus_logger.litellm_request_queue_time_metric = mock_metric
+
+ # Create mock kwargs with negative queue_time_seconds
+ kwargs = {
+ "litellm_params": {
+ "metadata": {"queue_time_seconds": -0.1} # Negative value
+ },
+ "model": "gpt-3.5-turbo",
+ "start_time": datetime.now(),
+ "end_time": datetime.now(),
+ }
+
+ enum_values = UserAPIKeyLabelValues(
+ end_user=None,
+ hashed_api_key="test-key",
+ api_key_alias="test-alias",
+ requested_model="gpt-3.5-turbo",
+ model_group="gpt-3.5-turbo",
+ team=None,
+ team_alias=None,
+ user=None,
+ user_email=None,
+ status_code="200",
+ model="gpt-3.5-turbo",
+ litellm_model_name="gpt-3.5-turbo",
+ tags=[],
+ model_id="gpt-3.5-turbo",
+ api_base="https://api.openai.com",
+ api_provider="openai",
+ exception_status=None,
+ exception_class=None,
+ custom_metadata_labels={},
+ route=None,
+ )
+
+ # Act
+ prometheus_logger._set_latency_metrics(
+ kwargs=kwargs,
+ model="gpt-3.5-turbo",
+ user_api_key="test-key",
+ user_api_key_alias="test-alias",
+ user_api_team=None,
+ user_api_team_alias=None,
+ enum_values=enum_values,
+ )
+
+ # Assert - queue time metric should not be called for negative values
+ # We check that observe was not called with the negative value
+ negative_value_called = False
+ for call in mock_labeled_metric.observe.call_args_list:
+ if len(call[0]) > 0 and call[0][0] == -0.1:
+ negative_value_called = True
+ break
+ assert (
+ not negative_value_called
+ ), "Queue time metric should not be recorded for negative values"
+
+
+class TestPrometheusGuardrailMetrics:
+ """Test guardrail metrics recording"""
+
+ def test_record_guardrail_metrics_success(self):
+ """Test recording guardrail metrics for successful execution"""
+ # Arrange
+ prometheus_logger = PrometheusLogger()
+
+ # Mock metrics
+ mock_latency_metric = MagicMock()
+ mock_requests_metric = MagicMock()
+ mock_errors_metric = MagicMock()
+
+ prometheus_logger.litellm_guardrail_latency_metric = mock_latency_metric
+ prometheus_logger.litellm_guardrail_requests_total = mock_requests_metric
+ prometheus_logger.litellm_guardrail_errors_total = mock_errors_metric
+
+ guardrail_name = "test_guardrail"
+ latency_seconds = 0.15
+ status = "success"
+ error_type = None
+ hook_type = "pre_call"
+
+ # Act
+ prometheus_logger._record_guardrail_metrics(
+ guardrail_name=guardrail_name,
+ latency_seconds=latency_seconds,
+ status=status,
+ error_type=error_type,
+ hook_type=hook_type,
+ )
+
+ # Assert - latency metric should be recorded
+ mock_latency_metric.labels.assert_called_once_with(
+ guardrail_name=guardrail_name,
+ status=status,
+ error_type="none",
+ hook_type=hook_type,
+ )
+ mock_latency_metric.labels.return_value.observe.assert_called_once_with(
+ latency_seconds
+ )
+
+ # Assert - requests metric should be incremented
+ mock_requests_metric.labels.assert_called_once_with(
+ guardrail_name=guardrail_name,
+ status=status,
+ hook_type=hook_type,
+ )
+ mock_requests_metric.labels.return_value.inc.assert_called_once()
+
+ # Assert - errors metric should NOT be called for success
+ mock_errors_metric.labels.assert_not_called()
+
+ def test_record_guardrail_metrics_error(self):
+ """Test recording guardrail metrics for failed execution"""
+ # Arrange
+ prometheus_logger = PrometheusLogger()
+
+ # Mock metrics
+ mock_latency_metric = MagicMock()
+ mock_requests_metric = MagicMock()
+ mock_errors_metric = MagicMock()
+
+ prometheus_logger.litellm_guardrail_latency_metric = mock_latency_metric
+ prometheus_logger.litellm_guardrail_requests_total = mock_requests_metric
+ prometheus_logger.litellm_guardrail_errors_total = mock_errors_metric
+
+ guardrail_name = "test_guardrail"
+ latency_seconds = 0.2
+ status = "error"
+ error_type = "ValueError"
+ hook_type = "pre_call"
+
+ # Act
+ prometheus_logger._record_guardrail_metrics(
+ guardrail_name=guardrail_name,
+ latency_seconds=latency_seconds,
+ status=status,
+ error_type=error_type,
+ hook_type=hook_type,
+ )
+
+ # Assert - latency metric should be recorded
+ mock_latency_metric.labels.assert_called_once_with(
+ guardrail_name=guardrail_name,
+ status=status,
+ error_type=error_type,
+ hook_type=hook_type,
+ )
+ mock_latency_metric.labels.return_value.observe.assert_called_once_with(
+ latency_seconds
+ )
+
+ # Assert - requests metric should be incremented
+ mock_requests_metric.labels.assert_called_once_with(
+ guardrail_name=guardrail_name,
+ status=status,
+ hook_type=hook_type,
+ )
+ mock_requests_metric.labels.return_value.inc.assert_called_once()
+
+ # Assert - errors metric should be incremented
+ mock_errors_metric.labels.assert_called_once_with(
+ guardrail_name=guardrail_name,
+ error_type=error_type,
+ hook_type=hook_type,
+ )
+ mock_errors_metric.labels.return_value.inc.assert_called_once()
+
+ def test_record_guardrail_metrics_during_call_hook(self):
+ """Test recording guardrail metrics for during_call hook"""
+ # Arrange
+ prometheus_logger = PrometheusLogger()
+
+ # Mock metrics
+ mock_latency_metric = MagicMock()
+ mock_requests_metric = MagicMock()
+
+ prometheus_logger.litellm_guardrail_latency_metric = mock_latency_metric
+ prometheus_logger.litellm_guardrail_requests_total = mock_requests_metric
+
+ guardrail_name = "moderation_guardrail"
+ latency_seconds = 0.1
+ status = "success"
+ hook_type = "during_call"
+
+ # Act
+ prometheus_logger._record_guardrail_metrics(
+ guardrail_name=guardrail_name,
+ latency_seconds=latency_seconds,
+ status=status,
+ error_type=None,
+ hook_type=hook_type,
+ )
+
+ # Assert - hook_type should be "during_call"
+ mock_latency_metric.labels.assert_called_once()
+ call_kwargs = mock_latency_metric.labels.call_args[1]
+ assert call_kwargs["hook_type"] == "during_call"
+
+ def test_record_guardrail_metrics_handles_exception(self):
+ """Test that _record_guardrail_metrics handles exceptions gracefully"""
+ # Arrange
+ prometheus_logger = PrometheusLogger()
+
+ # Mock metric to raise exception
+ mock_metric = MagicMock()
+ mock_metric.labels.side_effect = Exception("Test error")
+ prometheus_logger.litellm_guardrail_latency_metric = mock_metric
+ prometheus_logger.litellm_guardrail_requests_total = MagicMock()
+
+ # Act & Assert - should not raise exception
+ try:
+ prometheus_logger._record_guardrail_metrics(
+ guardrail_name="test",
+ latency_seconds=0.1,
+ status="success",
+ error_type=None,
+ hook_type="pre_call",
+ )
+ except Exception:
+ pytest.fail("_record_guardrail_metrics should handle exceptions gracefully")
+
+ def test_record_guardrail_metrics_with_guardrail_name_attribute(self):
+ """Test that guardrail name is extracted from guardrail_name attribute if available"""
+ # Arrange
+ prometheus_logger = PrometheusLogger()
+
+ # Mock metrics
+ mock_latency_metric = MagicMock()
+ mock_requests_metric = MagicMock()
+
+ prometheus_logger.litellm_guardrail_latency_metric = mock_latency_metric
+ prometheus_logger.litellm_guardrail_requests_total = mock_requests_metric
+
+ guardrail_name = "custom_guardrail_name"
+ latency_seconds = 0.1
+ status = "success"
+ hook_type = "pre_call"
+
+ # Act
+ prometheus_logger._record_guardrail_metrics(
+ guardrail_name=guardrail_name,
+ latency_seconds=latency_seconds,
+ status=status,
+ error_type=None,
+ hook_type=hook_type,
+ )
+
+ # Assert - guardrail_name should be used
+ mock_latency_metric.labels.assert_called_once()
+ call_kwargs = mock_latency_metric.labels.call_args[1]
+ assert call_kwargs["guardrail_name"] == guardrail_name