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 testing for prometheus failure metrics (#5823)

Ishaan Jaff711932294c69
diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.py
index d5b6bc2b47f..792251559b1 100644
--- a/litellm/integrations/prometheus.py
+++ b/litellm/integrations/prometheus.py
@@ -17,6 +17,11 @@ from litellm._logging import print_verbose, verbose_logger
from litellm.integrations.custom_logger import CustomLogger
from litellm.proxy._types import UserAPIKeyAuth
+REQUESTED_MODEL = "requested_model"
+EXCEPTION_STATUS = "exception_status"
+EXCEPTION_CLASS = "exception_class"
+EXCEPTION_LABELS = [EXCEPTION_STATUS, EXCEPTION_CLASS]
+
class PrometheusLogger(CustomLogger):
# Class variables or attributes
@@ -39,8 +44,6 @@ class PrometheusLogger(CustomLogger):
)
return
- REQUESTED_MODEL = "requested_model"
-
self.litellm_proxy_failed_requests_metric = Counter(
name="litellm_proxy_failed_requests_metric",
documentation="Total number of failed responses from proxy - the client did not get a success response from litellm proxy",
@@ -52,7 +55,8 @@ class PrometheusLogger(CustomLogger):
"team",
"team_alias",
"user",
- ],
+ ]
+ + EXCEPTION_LABELS,
)
self.litellm_proxy_total_requests_metric = Counter(
@@ -147,13 +151,6 @@ class PrometheusLogger(CustomLogger):
labelnames=["hashed_api_key", "api_key_alias", "model"],
)
- # New metric for tracking error codes and models
- self.litellm_error_code_metric = Counter(
- "litellm_error_code_metric",
- "Total number of errors by error code and model",
- labelnames=["error_code", "model"],
- )
-
########################################
# LLM API Deployment Metrics / analytics
########################################
@@ -198,7 +195,7 @@ class PrometheusLogger(CustomLogger):
self.litellm_deployment_cooled_down = Counter(
"litellm_deployment_cooled_down",
"LLM Deployment Analytics - Number of times a deployment has been cooled down by LiteLLM load balancing logic. exception_status is the status of the exception that caused the deployment to be cooled down",
- labelnames=_logged_llm_labels + ["exception_status"],
+ labelnames=_logged_llm_labels + [EXCEPTION_STATUS],
)
self.litellm_deployment_success_responses = Counter(
@@ -209,7 +206,7 @@ class PrometheusLogger(CustomLogger):
self.litellm_deployment_failure_responses = Counter(
name="litellm_deployment_failure_responses",
documentation="LLM Deployment Analytics - Total number of failed LLM API calls for a specific LLM deploymeny. exception_status is the status of the exception from the llm api",
- labelnames=[REQUESTED_MODEL, "exception_status"] + _logged_llm_labels,
+ labelnames=[REQUESTED_MODEL] + _logged_llm_labels + EXCEPTION_LABELS,
)
self.litellm_deployment_total_requests = Counter(
name="litellm_deployment_total_requests",
@@ -454,16 +451,6 @@ class PrometheusLogger(CustomLogger):
user_id,
).inc()
self.set_llm_deployment_failure_metrics(kwargs)
-
- _exception = kwargs.get("exception", None)
- error_code = "unknown"
- if _exception is not None and hasattr(_exception, "status_code"):
- error_code = _exception.status_code
-
- # Increment the new error code metric
- self.litellm_error_code_metric.labels(
- error_code=error_code, model=model
- ).inc()
except Exception as e:
verbose_logger.exception(
"prometheus Layer Error(): Exception occured - {}".format(str(e))
@@ -486,21 +473,22 @@ class PrometheusLogger(CustomLogger):
"end_user",
"hashed_api_key",
"api_key_alias",
- "model",
+ REQUESTED_MODEL,
"team",
"team_alias",
- "user",
- ],
+ ] + EXCEPTION_LABELS,
"""
try:
self.litellm_proxy_failed_requests_metric.labels(
- user_api_key_dict.end_user_id,
- user_api_key_dict.api_key,
- user_api_key_dict.key_alias,
- request_data.get("model", ""),
- user_api_key_dict.team_id,
- user_api_key_dict.team_alias,
- user_api_key_dict.user_id,
+ end_user=user_api_key_dict.end_user_id,
+ hashed_api_key=user_api_key_dict.api_key,
+ api_key_alias=user_api_key_dict.key_alias,
+ requested_model=request_data.get("model", ""),
+ team=user_api_key_dict.team_id,
+ team_alias=user_api_key_dict.team_alias,
+ user=user_api_key_dict.user_id,
+ exception_status=getattr(original_exception, "status_code", None),
+ exception_class=str(original_exception.__class__.__name__),
).inc()
self.litellm_proxy_total_requests_metric.labels(
@@ -511,7 +499,7 @@ class PrometheusLogger(CustomLogger):
user_api_key_dict.team_id,
user_api_key_dict.team_alias,
user_api_key_dict.user_id,
- )
+ ).inc()
pass
except Exception as e:
verbose_logger.exception(
@@ -555,8 +543,7 @@ class PrometheusLogger(CustomLogger):
llm_provider = _litellm_params.get("custom_llm_provider", None)
_model_info = _metadata.get("model_info") or {}
model_id = _model_info.get("id", None)
- exception = request_kwargs.get("exception", None)
- exception_status_code: str = str(getattr(exception, "status_code", None))
+ exception: Exception = request_kwargs.get("exception", None)
"""
log these labels
@@ -568,13 +555,13 @@ class PrometheusLogger(CustomLogger):
api_base=api_base,
api_provider=llm_provider,
)
-
self.litellm_deployment_failure_responses.labels(
litellm_model_name=litellm_model_name,
model_id=model_id,
api_base=api_base,
api_provider=llm_provider,
- exception_status=exception_status_code,
+ exception_status=str(getattr(exception, "status_code", None)),
+ exception_class=exception.__class__.__name__,
requested_model=model_group,
).inc()
diff --git a/litellm/proxy/example_config_yaml/otel_test_config.yaml b/litellm/proxy/example_config_yaml/otel_test_config.yaml
index e040cfd68c5..fae3ee3daec 100644
--- a/litellm/proxy/example_config_yaml/otel_test_config.yaml
+++ b/litellm/proxy/example_config_yaml/otel_test_config.yaml
@@ -19,6 +19,11 @@ model_list:
litellm_params:
model: cohere/rerank-english-v3.0
api_key: os.environ/COHERE_API_KEY
+ - model_name: fake-azure-endpoint
+ litellm_params:
+ model: openai/429
+ api_key: fake-key
+ api_base: https://exampleopenaiendpoint-production.up.railway.app
- model_name: llava-hf
litellm_params:
model: openai/llava-hf/llava-v1.6-vicuna-7b-hf
@@ -28,9 +33,10 @@ model_list:
supports_vision: True
+
litellm_settings:
cache: true
- callbacks: ["otel"]
+ callbacks: ["otel", "prometheus"]
guardrails:
- guardrail_name: "aporia-pre-guard"
diff --git a/litellm/proxy/otel_config.yaml b/litellm/proxy/otel_config.yaml
deleted file mode 100644
index 5b75697b7bd..00000000000
--- a/litellm/proxy/otel_config.yaml
+++ /dev/null
@@ -1,30 +0,0 @@
-receivers:
- otlp:
- protocols:
- grpc:
- endpoint: 0.0.0.0:4317
-
-processors:
- batch:
- timeout: 1s
- send_batch_size: 1024
-
-exporters:
- logging:
- loglevel: debug
- otlphttp/elastic:
- endpoint: "https://3f51c0abae7743e2800df44a8a5f0997.apm.us-central1.gcp.cloud.es.io:443"
- headers:
- Authorization: "Bearer <elastic api key>"
-
-service:
- pipelines:
- metrics:
- receivers: [otlp]
- exporters: [logging, otlphttp/elastic]
- traces:
- receivers: [otlp]
- exporters: [logging, otlphttp/elastic]
- logs:
- receivers: [otlp]
- exporters: [logging,otlphttp/elastic]
\ No newline at end of file
diff --git a/tests/otel_tests/test_prometheus.py b/tests/otel_tests/test_prometheus.py
new file mode 100644
index 00000000000..84333f7c84a
--- /dev/null
+++ b/tests/otel_tests/test_prometheus.py
@@ -0,0 +1,61 @@
+"""
+Unit tests for prometheus metrics
+"""
+
+import pytest
+import aiohttp
+import asyncio
+
+
+async def make_bad_chat_completion_request(session, key):
+ url = "http://0.0.0.0:4000/chat/completions"
+ headers = {
+ "Authorization": f"Bearer {key}",
+ "Content-Type": "application/json",
+ }
+ data = {
+ "model": "fake-azure-endpoint",
+ "messages": [{"role": "user", "content": "Hello"}],
+ }
+ async with session.post(url, headers=headers, json=data) as response:
+ status = response.status
+ response_text = await response.text()
+ return status, response_text
+
+
+async def test_proxy_failure_metrics():
+ """
+ - Make 1 bad chat completion call to "fake-azure-endpoint"
+ - GET /metrics
+ - assert the failure metric for the requested model is incremented by 1
+ - Assert the Exception class and status code are correct
+ """
+ async with aiohttp.ClientSession() as session:
+ # Make a bad chat completion call
+ status, response_text = await make_bad_chat_completion_request(
+ session, "sk-1234"
+ )
+
+ # Check if the request failed as expected
+ assert status == 429, f"Expected status 429, but got {status}"
+
+ # Get metrics
+ async with session.get("http://0.0.0.0:4000/metrics") as response:
+ metrics = await response.text()
+
+ print("/metrics", metrics)
+
+ # Check if the failure metric is present and correct
+ expected_metric = 'litellm_proxy_failed_requests_metric_total{api_key_alias="None",end_user="None",exception_class="RateLimitError",exception_status="429",hashed_api_key="88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b",requested_model="fake-azure-endpoint",team="None",team_alias="None",user="default_user_id"} 1.0'
+
+ assert (
+ expected_metric in metrics
+ ), "Expected failure metric not found in /metrics"
+ expected_llm_deployment_failure = 'litellm_deployment_failure_responses_total{api_base="https://exampleopenaiendpoint-production.up.railway.app",api_provider="openai",exception_class="RateLimitError",exception_status="429",litellm_model_name="429",model_id="7499d31f98cd518cf54486d5a00deda6894239ce16d13543398dc8abf870b15f",requested_model="fake-azure-endpoint"} 1.0'
+ assert expected_llm_deployment_failure
+
+ assert (
+ 'litellm_proxy_total_requests_metric_total{api_key_alias="None",end_user="None",hashed_api_key="88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b",requested_model="fake-azure-endpoint",team="None",team_alias="None",user="default_user_id"} 1.0'
+ in metrics
+ )