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] - Track cost + add tags for health checks done by LiteLLM Proxy (#12880)

Ishaan Jaffb41ce5c92f3c
diff --git a/litellm/constants.py b/litellm/constants.py
index 970b16617fe..b25e2ff0fb9 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -799,6 +799,7 @@ BATCH_STATUS_POLL_MAX_ATTEMPTS = int(
HEALTH_CHECK_TIMEOUT_SECONDS = int(
os.getenv("HEALTH_CHECK_TIMEOUT_SECONDS", 60)
) # 60 seconds
+LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME = "litellm-internal-health-check"
UI_SESSION_TOKEN_TEAM_ID = "litellm-dashboard"
LITELLM_PROXY_ADMIN_NAME = "default_user_id"
diff --git a/litellm/litellm_core_utils/health_check_helpers.py b/litellm/litellm_core_utils/health_check_helpers.py
new file mode 100644
index 00000000000..7a2c005e8f6
--- /dev/null
+++ b/litellm/litellm_core_utils/health_check_helpers.py
@@ -0,0 +1,78 @@
+
+"""
+Helper functions for health check calls.
+"""
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from litellm.litellm_core_utils.litellm_logging import Logging
+
+class HealthCheckHelpers:
+
+ @staticmethod
+ async def ahealth_check_wildcard_models(
+ model: str,
+ custom_llm_provider: str,
+ model_params: dict,
+ litellm_logging_obj: "Logging",
+ ) -> dict:
+ from litellm import acompletion
+ from litellm.litellm_core_utils.llm_request_utils import (
+ pick_cheapest_chat_models_from_llm_provider,
+ )
+
+ # this is a wildcard model, we need to pick a random model from the provider
+ cheapest_models = pick_cheapest_chat_models_from_llm_provider(
+ custom_llm_provider=custom_llm_provider, n=3
+ )
+ if len(cheapest_models) == 0:
+ raise Exception(
+ f"Unable to health check wildcard model for provider {custom_llm_provider}. Add a model on your config.yaml or contribute here - https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json"
+ )
+ if len(cheapest_models) > 1:
+ fallback_models = cheapest_models[
+ 1:
+ ] # Pick the last 2 models from the shuffled list
+ else:
+ fallback_models = None
+ model_params["model"] = cheapest_models[0]
+ model_params["litellm_logging_obj"] = litellm_logging_obj
+ model_params["fallbacks"] = fallback_models
+ model_params["max_tokens"] = 1
+ await acompletion(**model_params)
+ return {}
+
+
+ @staticmethod
+ def _update_model_params_with_health_check_tracking_information(
+ model_params: dict,
+ ) -> dict:
+ """
+ Updates the health check model params with tracking information.
+
+ The following is added at this stage:
+ 1. `tags`: This helps identify health check calls in the DB.
+ 2. `user_api_key_auth`: This helps identify health check calls in the DB.
+ We need this since the DB requires an API Key to track a log in the SpendLogs Table
+ """
+ from litellm.proxy._types import UserAPIKeyAuth
+ from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetup
+ _metadata_variable_name = "litellm_metadata"
+ litellm_metadata = HealthCheckHelpers._get_metadata_for_health_check_call()
+ model_params[_metadata_variable_name] = litellm_metadata
+ model_params = LiteLLMProxyRequestSetup.add_user_api_key_auth_to_request_metadata(
+ data=model_params,
+ user_api_key_dict=UserAPIKeyAuth.get_litellm_internal_health_check_user_api_key_auth(),
+ _metadata_variable_name=_metadata_variable_name,
+ )
+ return model_params
+
+ @staticmethod
+ def _get_metadata_for_health_check_call():
+ """
+ Returns the metadata for the health check call.
+ """
+ from litellm.constants import LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME
+ return {
+ "tags": [LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME],
+ }
\ No newline at end of file
diff --git a/litellm/main.py b/litellm/main.py
index e0b76d57a6a..accd93ed8d5 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -66,9 +66,6 @@ from litellm.litellm_core_utils.health_check_utils import (
_filter_model_params,
)
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
-from litellm.litellm_core_utils.llm_request_utils import (
- pick_cheapest_chat_models_from_llm_provider,
-)
from litellm.litellm_core_utils.mock_functions import (
mock_embedding,
mock_image_generation,
@@ -5433,35 +5430,6 @@ def speech( # noqa: PLR0915
##### Health Endpoints #######################
-
-async def ahealth_check_wildcard_models(
- model: str,
- custom_llm_provider: str,
- model_params: dict,
- litellm_logging_obj: Logging,
-) -> dict:
- # this is a wildcard model, we need to pick a random model from the provider
- cheapest_models = pick_cheapest_chat_models_from_llm_provider(
- custom_llm_provider=custom_llm_provider, n=3
- )
- if len(cheapest_models) == 0:
- raise Exception(
- f"Unable to health check wildcard model for provider {custom_llm_provider}. Add a model on your config.yaml or contribute here - https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json"
- )
- if len(cheapest_models) > 1:
- fallback_models = cheapest_models[
- 1:
- ] # Pick the last 2 models from the shuffled list
- else:
- fallback_models = None
- model_params["model"] = cheapest_models[0]
- model_params["litellm_logging_obj"] = litellm_logging_obj
- model_params["fallbacks"] = fallback_models
- model_params["max_tokens"] = 1
- await acompletion(**model_params)
- return {}
-
-
async def ahealth_check(
model_params: dict,
mode: Optional[
@@ -5490,7 +5458,12 @@ async def ahealth_check(
"x-ms-region": str,
}
"""
+ from litellm.litellm_core_utils.health_check_helpers import HealthCheckHelpers
+
# Map modes to their corresponding health check calls
+ #########################################################
+ # Init request with tracking information
+ #########################################################
litellm_logging_obj = Logging(
model="",
messages=[],
@@ -5501,6 +5474,9 @@ async def ahealth_check(
function_id="1234",
log_raw_request_response=True,
)
+ model_params["litellm_logging_obj"] = litellm_logging_obj
+ model_params = HealthCheckHelpers._update_model_params_with_health_check_tracking_information(model_params=model_params)
+ #########################################################
try:
model: Optional[str] = model_params.get("model", None)
if model is None:
@@ -5518,13 +5494,12 @@ async def ahealth_check(
} # don't used cached responses for making health check calls
mode = mode or "chat"
if "*" in model:
- return await ahealth_check_wildcard_models(
+ return await HealthCheckHelpers.ahealth_check_wildcard_models(
model=model,
custom_llm_provider=custom_llm_provider,
model_params=model_params,
litellm_logging_obj=litellm_logging_obj,
)
- model_params["litellm_logging_obj"] = litellm_logging_obj
mode_handlers = {
"chat": lambda: litellm.acompletion(
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 466a4d3f2db..b5c63026f65 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -1766,6 +1766,22 @@ class UserAPIKeyAuth(
if JWTHandler.is_jwt(token=api_key):
return f"hashed-jwt-{hash_token(token=api_key)}"
return api_key
+
+
+ @classmethod
+ def get_litellm_internal_health_check_user_api_key_auth(cls) -> "UserAPIKeyAuth":
+ """
+ Returns a `UserAPIKeyAuth` object for the litellm internal health check service account.
+
+ This is used to track number of requests/spend for health check calls.
+ """
+ from litellm.constants import LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME
+ return cls(
+ api_key=LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,
+ team_id=LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,
+ key_alias=LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,
+ team_alias=LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,
+ )
class UserInfoResponse(LiteLLMPydanticObjectBase):
diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.py
index d0dd025309f..256b51efd15 100644
--- a/litellm/proxy/litellm_pre_call_utils.py
+++ b/litellm/proxy/litellm_pre_call_utils.py
@@ -425,6 +425,32 @@ class LiteLLMProxyRequestSetup:
user_api_key_request_route=user_api_key_dict.request_route,
)
return user_api_key_logged_metadata
+
+ @staticmethod
+ def add_user_api_key_auth_to_request_metadata(
+ data: dict,
+ user_api_key_dict: UserAPIKeyAuth,
+ _metadata_variable_name: str,
+ ) -> dict:
+ """
+ Adds the `UserAPIKeyAuth` object to the request metadata.
+ """
+ user_api_key_logged_metadata = (
+ LiteLLMProxyRequestSetup.get_sanitized_user_information_from_key(
+ user_api_key_dict=user_api_key_dict
+ )
+ )
+ data[_metadata_variable_name].update(user_api_key_logged_metadata)
+ data[_metadata_variable_name][
+ "user_api_key"
+ ] = (
+ user_api_key_dict.api_key
+ ) # this is just the hashed token
+
+ data[_metadata_variable_name]["user_api_end_user_max_budget"] = getattr(
+ user_api_key_dict, "end_user_max_budget", None
+ )
+ return data
@staticmethod
def add_key_level_controls(
@@ -646,22 +672,11 @@ async def add_litellm_data_to_request( # noqa: PLR0915
data["metadata"]
)
- user_api_key_logged_metadata = (
- LiteLLMProxyRequestSetup.get_sanitized_user_information_from_key(
- user_api_key_dict=user_api_key_dict
- )
- )
- data[_metadata_variable_name].update(user_api_key_logged_metadata)
- data[_metadata_variable_name][
- "user_api_key"
- ] = (
- user_api_key_dict.api_key
- ) # this is just the hashed token. [TODO]: replace variable name in repo.
-
- data[_metadata_variable_name]["user_api_end_user_max_budget"] = getattr(
- user_api_key_dict, "end_user_max_budget", None
+ data = LiteLLMProxyRequestSetup.add_user_api_key_auth_to_request_metadata(
+ data=data,
+ user_api_key_dict=user_api_key_dict,
+ _metadata_variable_name=_metadata_variable_name,
)
-
data[_metadata_variable_name]["litellm_api_version"] = version
if general_settings is not None:
diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yaml
index 9effb01e1e0..02364eb22ab 100644
--- a/litellm/proxy/proxy_config.yaml
+++ b/litellm/proxy/proxy_config.yaml
@@ -16,6 +16,8 @@ guardrails:
guardrailVersion: "DRAFT"
default_on: true
+
+
litellm_settings:
callbacks: ["datadog_llm_observability"]
cache: true
diff --git a/tests/test_litellm/litellm_core_utils/test_health_check_helpers.py b/tests/test_litellm/litellm_core_utils/test_health_check_helpers.py
new file mode 100644
index 00000000000..49be7f39a18
--- /dev/null
+++ b/tests/test_litellm/litellm_core_utils/test_health_check_helpers.py
@@ -0,0 +1,81 @@
+"""Test health check helper functions"""
+import os
+import sys
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+sys.path.insert(
+ 0, os.path.abspath("../../..")
+) # Adds the parent directory to the system path
+
+from litellm.constants import LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME
+from litellm.litellm_core_utils.health_check_helpers import HealthCheckHelpers
+from litellm.proxy._types import UserAPIKeyAuth
+
+
+def test_update_model_params_with_health_check_tracking_information():
+ """Test _update_model_params_with_health_check_tracking_information adds required tracking info."""
+ initial_model_params = {
+ "model": "gpt-3.5-turbo",
+ "api_key": "test_key"
+ }
+
+ with patch(
+ "litellm.proxy._types.UserAPIKeyAuth.get_litellm_internal_health_check_user_api_key_auth"
+ ) as mock_get_auth:
+ mock_auth = MagicMock()
+ mock_get_auth.return_value = mock_auth
+
+ with patch(
+ "litellm.proxy.litellm_pre_call_utils.LiteLLMProxyRequestSetup.add_user_api_key_auth_to_request_metadata"
+ ) as mock_add_auth:
+ mock_add_auth.return_value = {
+ **initial_model_params,
+ "litellm_metadata": {
+ "tags": [LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME],
+ "user_api_key_auth": mock_auth
+ }
+ }
+
+ result = HealthCheckHelpers._update_model_params_with_health_check_tracking_information(
+ initial_model_params
+ )
+
+ # Verify that litellm_metadata was added
+ assert "litellm_metadata" in result
+ assert result["litellm_metadata"]["tags"] == [LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME]
+
+ # Verify the auth setup was called
+ mock_add_auth.assert_called_once()
+ call_args = mock_add_auth.call_args
+ assert call_args[1]["user_api_key_dict"] == mock_auth
+ assert call_args[1]["_metadata_variable_name"] == "litellm_metadata"
+
+
+def test_get_metadata_for_health_check_call():
+ """Test _get_metadata_for_health_check_call returns correct metadata structure."""
+ result = HealthCheckHelpers._get_metadata_for_health_check_call()
+
+ expected_metadata = {
+ "tags": [LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME],
+ }
+
+ assert result == expected_metadata
+ assert isinstance(result["tags"], list)
+ assert len(result["tags"]) == 1
+ assert result["tags"][0] == LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME
+
+
+def test_get_litellm_internal_health_check_user_api_key_auth():
+ """Test get_litellm_internal_health_check_user_api_key_auth returns properly configured UserAPIKeyAuth object."""
+ result = UserAPIKeyAuth.get_litellm_internal_health_check_user_api_key_auth()
+
+ # Verify the returned object is of correct type
+ assert isinstance(result, UserAPIKeyAuth)
+
+ # Verify all fields are set to the expected constant value
+ assert result.api_key == LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME
+ assert result.team_id == LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME
+ assert result.key_alias == LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME
+ assert result.team_alias == LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME
\ No newline at end of file
diff --git a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py b/tests/test_litellm/proxy/test_litellm_pre_call_utils.py
index 33322150407..e68767204f2 100644
--- a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py
+++ b/tests/test_litellm/proxy/test_litellm_pre_call_utils.py
@@ -611,3 +611,61 @@ def test_get_dynamic_logging_metadata_with_arize_team_logging():
assert result.callback_vars is not None
assert result.callback_vars["arize_api_key"] == "test_arize_api_key"
assert result.callback_vars["arize_space_id"] == "test_arize_space_id"
+
+
+def test_add_user_api_key_auth_to_request_metadata():
+ """
+ Test that add_user_api_key_auth_to_request_metadata properly adds user API key authentication data to request metadata
+ """
+ # Setup test data
+ data = {
+ "model": "gpt-3.5-turbo",
+ "messages": [{"role": "user", "content": "Hello"}],
+ "litellm_metadata": {} # This will be the metadata variable name
+ }
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key="hashed-test-key-123",
+ user_id="test-user-123",
+ org_id="test-org-456",
+ team_id="test-team-789",
+ key_alias="test-key-alias",
+ user_email="[email protected]",
+ team_alias="test-team-alias",
+ end_user_id="test-end-user-123",
+ request_route="/chat/completions",
+ end_user_max_budget=500.0
+ )
+
+ metadata_variable_name = "litellm_metadata"
+
+ # Call the function
+ result = LiteLLMProxyRequestSetup.add_user_api_key_auth_to_request_metadata(
+ data=data,
+ user_api_key_dict=user_api_key_dict,
+ _metadata_variable_name=metadata_variable_name
+ )
+
+ # Verify the metadata was properly added
+ metadata = result[metadata_variable_name]
+
+ # Check that user API key information was added
+ assert metadata["user_api_key_hash"] == "hashed-test-key-123"
+ assert metadata["user_api_key_alias"] == "test-key-alias"
+ assert metadata["user_api_key_team_id"] == "test-team-789"
+ assert metadata["user_api_key_user_id"] == "test-user-123"
+ assert metadata["user_api_key_org_id"] == "test-org-456"
+ assert metadata["user_api_key_team_alias"] == "test-team-alias"
+ assert metadata["user_api_key_end_user_id"] == "test-end-user-123"
+ assert metadata["user_api_key_user_email"] == "[email protected]"
+ assert metadata["user_api_key_request_route"] == "/chat/completions"
+
+ # Check that the hashed API key was added
+ assert metadata["user_api_key"] == "hashed-test-key-123"
+
+ # Check that end user max budget was added
+ assert metadata["user_api_end_user_max_budget"] == 500.0
+
+ # Verify original data is preserved
+ assert result["model"] == "gpt-3.5-turbo"
+ assert result["messages"] == [{"role": "user", "content": "Hello"}]