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
[Prometheus] Move Prometheus to enterprise folder (#12659)
Jugal D. Bhatta46b9d376fea
diff --git a/litellm/integrations/prometheus.py b/enterprise/litellm_enterprise/integrations/prometheus.pysimilarity index 99%rename from litellm/integrations/prometheus.pyrename to enterprise/litellm_enterprise/integrations/prometheus.pyindex f1a155bc962..3c303e303fc 100644--- a/litellm/integrations/prometheus.py+++ b/enterprise/litellm_enterprise/integrations/prometheus.py@@ -1,4 +1,4 @@-# used for /metrics endpoint on LiteLLM Proxy+ # used for /metrics endpoint on LiteLLM Proxy#### What this does ##### On success, log events to Prometheusimport sys@@ -2150,7 +2150,7 @@ class PrometheusLogger(CustomLogger):"""from litellm.constants import PROMETHEUS_BUDGET_METRICS_REFRESH_INTERVAL_MINUTESfrom litellm.integrations.custom_logger import CustomLogger- from litellm.integrations.prometheus import PrometheusLogger+ from enterprise.litellm_enterprise.integrations.prometheus import PrometheusLoggerprometheus_loggers: List[CustomLogger] = (litellm.logging_callback_manager.get_custom_loggers_for_type(diff --git a/enterprise/poetry.lock b/enterprise/poetry.lockindex bb436a168cd..f526fec8da0 100644--- a/enterprise/poetry.lock+++ b/enterprise/poetry.lock@@ -1,7 +1,7 @@-# This file is automatically @generated by Poetry 2.1.2 and should not be changed by hand.+# This file is automatically @generated by Poetry 1.8.3 and should not be changed by hand.package = [][metadata]-lock-version = "2.1"+lock-version = "2.0"python-versions = ">=3.8.1,<4.0, !=3.9.7"content-hash = "2cf39473e67ff0615f0a61c9d2ac9f02b38cc08cbb1bdb893d89bee002646623"diff --git a/enterprise/pyproject.toml b/enterprise/pyproject.tomlindex 8764624adb1..4b959040fbc 100644--- a/enterprise/pyproject.toml+++ b/enterprise/pyproject.toml@@ -1,6 +1,6 @@[tool.poetry]name = "litellm-enterprise"-version = "0.1.13"+version = "0.1.14"description = "Package for LiteLLM Enterprise features"authors = ["BerriAI"]readme = "README.md"@@ -22,7 +22,7 @@ requires = ["poetry-core"]build-backend = "poetry.core.masonry.api"[tool.commitizen]-version = "0.1.13"+version = "0.1.14"version_files = ["pyproject.toml:version","../requirements.txt:litellm-enterprise==",diff --git a/litellm/litellm_core_utils/custom_logger_registry.py b/litellm/litellm_core_utils/custom_logger_registry.pyindex 694da88bb5a..252fb29eb3a 100644--- a/litellm/litellm_core_utils/custom_logger_registry.py+++ b/litellm/litellm_core_utils/custom_logger_registry.py@@ -31,7 +31,10 @@ from litellm.integrations.mlflow import MlflowLoggerfrom litellm.integrations.openmeter import OpenMeterLoggerfrom litellm.integrations.opentelemetry import OpenTelemetryfrom litellm.integrations.opik.opik import OpikLogger-from litellm.integrations.prometheus import PrometheusLogger+try:+ from litellm_enterprise.integrations.prometheus import PrometheusLogger+except Exception:+ PrometheusLogger = Nonefrom litellm.integrations.s3_v2 import S3Loggerfrom litellm.integrations.sqs import SQSLoggerfrom litellm.integrations.vector_store_integrations.vector_store_pre_call_hook import (diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex 344d2212ca0..c6694f29b06 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -138,7 +138,6 @@ from ..integrations.logfire_logger import LogfireLevel, LogfireLoggerfrom ..integrations.lunary import LunaryLoggerfrom ..integrations.openmeter import OpenMeterLoggerfrom ..integrations.opik.opik import OpikLogger-from ..integrations.prometheus import PrometheusLoggerfrom ..integrations.prompt_layer import PromptLayerLoggerfrom ..integrations.s3 import S3Loggerfrom ..integrations.s3_v2 import S3Logger as S3V2Logger@@ -171,6 +170,8 @@ try:from litellm_enterprise.litellm_core_utils.litellm_logging import (StandardLoggingPayloadSetup as EnterpriseStandardLoggingPayloadSetup,)+ from litellm_enterprise.integrations.prometheus import PrometheusLogger+EnterpriseStandardLoggingPayloadSetupVAR: Optional[Type[EnterpriseStandardLoggingPayloadSetup]@@ -185,6 +186,7 @@ except Exception as e:PagerDutyAlerting = CustomLogger # type: ignoreEnterpriseCallbackControls = None # type: ignoreEnterpriseStandardLoggingPayloadSetupVAR = None+ PrometheusLogger = None_in_memory_loggers: List[Any] = []### GLOBAL VARIABLES ###diff --git a/litellm/proxy/common_utils/callback_utils.py b/litellm/proxy/common_utils/callback_utils.pyindex a2afb30f057..e718255750a 100644--- a/litellm/proxy/common_utils/callback_utils.py+++ b/litellm/proxy/common_utils/callback_utils.py@@ -268,9 +268,13 @@ def initialize_callbacks_on_proxy( # noqa: PLR0915litellm.callbacks = imported_list # type: ignoreif "prometheus" in value:- from litellm.integrations.prometheus import PrometheusLogger+ try:+ from litellm_enterprise.integrations.prometheus import PrometheusLogger+ except Exception:+ PrometheusLogger = None- PrometheusLogger._mount_metrics_endpoint(premium_user)+ if PrometheusLogger:+ PrometheusLogger._mount_metrics_endpoint(premium_user)else:litellm.callbacks = [get_instance_fn(diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex e4d87cf24ea..fd8a32e9c65 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -1850,11 +1850,16 @@ class ProxyConfig:callback)if "prometheus" in callback:- from litellm.integrations.prometheus import (- PrometheusLogger,- )-- PrometheusLogger._mount_metrics_endpoint(premium_user)+ try:+ from litellm_enterprise.integrations.prometheus import (+ PrometheusLogger,+ )+ except Exception:+ PrometheusLogger = None++ if PrometheusLogger is not None:+ verbose_proxy_logger.debug("mounting metrics endpoint")+ PrometheusLogger._mount_metrics_endpoint(premium_user)print( # noqaf"{blue_color_code} Initialized Success Callbacks - {litellm.success_callback} {reset_color_code}") # noqa@@ -3506,9 +3511,11 @@ class ProxyStartupEvent:await proxy_logging_obj.slack_alerting_instance.send_fallback_stats_from_prometheus()if litellm.prometheus_initialize_budget_metrics is True:- from litellm.integrations.prometheus import PrometheusLogger-- PrometheusLogger.initialize_budget_metrics_cron_job(scheduler=scheduler)+ try:+ from litellm_enterprise.integrations.prometheus import PrometheusLogger+ PrometheusLogger.initialize_budget_metrics_cron_job(scheduler=scheduler)+ except Exception:+ PrometheusLogger = None### SPEND LOG CLEANUP ###if general_settings.get("maximum_spend_logs_retention_period") is not None:diff --git a/litellm/router_utils/cooldown_callbacks.py b/litellm/router_utils/cooldown_callbacks.pyindex 2139b1a7662..522cd3e2656 100644--- a/litellm/router_utils/cooldown_callbacks.py+++ b/litellm/router_utils/cooldown_callbacks.py@@ -12,7 +12,10 @@ if TYPE_CHECKING:from litellm.router import Router as _RouterLitellmRouter = _Router- from litellm.integrations.prometheus import PrometheusLogger+ try:+ from litellm_enterprise.integrations.prometheus import PrometheusLogger+ except Exception:+ PrometheusLogger = Noneelse:LitellmRouter = AnyPrometheusLogger = Any@@ -86,7 +89,13 @@ def _get_prometheus_logger_from_callbacks() -> Optional[PrometheusLogger]:"""Checks if prometheus is a initalized callback, if yes returns it"""- from litellm.integrations.prometheus import PrometheusLogger+ try:+ from litellm_enterprise.integrations.prometheus import PrometheusLogger+ except Exception:+ PrometheusLogger = None++ if PrometheusLogger is None:+ return Nonefor _callback in litellm._async_success_callback:if isinstance(_callback, PrometheusLogger):diff --git a/poetry.lock b/poetry.lockindex 8a03b2c1554..4eb83361dd0 100644--- a/poetry.lock+++ b/poetry.lock@@ -1,4 +1,5 @@-# This file is automatically @generated by Poetry 1.8.5 and should not be changed by hand.+# This file is automatically @generated by Poetry 1.8.3 and should not be changed by hand.+[[package]]name = "aiohappyeyeballs"@@ -298,13 +299,13 @@ typing-extensions = ">=4.0.1"[[package]]name = "azure-storage-blob"-version = "12.25.1"+version = "12.26.0"description = "Microsoft Azure Blob Storage Client Library for Python"optional = truepython-versions = ">=3.8"files = [- {file = "azure_storage_blob-12.25.1-py3-none-any.whl", hash = "sha256:1f337aab12e918ec3f1b638baada97550673911c4ceed892acc8e4e891b74167"},- {file = "azure_storage_blob-12.25.1.tar.gz", hash = "sha256:4f294ddc9bc47909ac66b8934bd26b50d2000278b10ad82cc109764fdc6e0e3b"},+ {file = "azure_storage_blob-12.26.0-py3-none-any.whl", hash = "sha256:8c5631b8b22b4f53ec5fff2f3bededf34cfef111e2af613ad42c9e6de00a77fe"},+ {file = "azure_storage_blob-12.26.0.tar.gz", hash = "sha256:5dd7d7824224f7de00bfeb032753601c982655173061e242f13be6e26d78d71f"},][package.dependencies]@@ -472,13 +473,13 @@ files = [[[package]]name = "certifi"-version = "2025.6.15"+version = "2025.7.14"description = "Python package for providing Mozilla's CA Bundle."optional = falsepython-versions = ">=3.7"files = [- {file = "certifi-2025.6.15-py3-none-any.whl", hash = "sha256:2e0c7ce7cb5d8f8634ca55d2ba7e6ec2689a2fd6537d8dec1296a477a4910057"},- {file = "certifi-2025.6.15.tar.gz", hash = "sha256:d747aa5a8b9bbbb1bb8c22bb13e22bd1f18e9796defa16bab421f7f7a317323b"},+ {file = "certifi-2025.7.14-py3-none-any.whl", hash = "sha256:6b31f564a415d79ee77df69d757bb49a5bb53bd9f756cbbe24394ffd6fc1f4b2"},+ {file = "certifi-2025.7.14.tar.gz", hash = "sha256:8ea99dbdfaaf2ba2f9bac77b9249ef62ec5218e7c2b2e903378ed5fccf765995"},][[package]]@@ -856,13 +857,13 @@ test = ["pytest (>=6)"][[package]]name = "fastapi"-version = "0.115.13"+version = "0.115.14"description = "FastAPI framework, high performance, easy to learn, fast to code, ready for production"optional = truepython-versions = ">=3.8"files = [- {file = "fastapi-0.115.13-py3-none-any.whl", hash = "sha256:0a0cab59afa7bab22f5eb347f8c9864b681558c278395e94035a741fc10cd865"},- {file = "fastapi-0.115.13.tar.gz", hash = "sha256:55d1d25c2e1e0a0a50aceb1c8705cd932def273c102bff0b1c1da88b3c6eb307"},+ {file = "fastapi-0.115.14-py3-none-any.whl", hash = "sha256:6c0c8bf9420bd58f565e585036d971872472b4f7d3f6c73b698e10cffdefb3ca"},+ {file = "fastapi-0.115.14.tar.gz", hash = "sha256:b1de15cdc1c499a4da47914db35d0e4ef8f1ce62b624e94e0e5824421df99739"},][package.dependencies]@@ -1396,13 +1397,13 @@ files = [[[package]]name = "huggingface-hub"-version = "0.33.1"+version = "0.33.4"description = "Client library to download and publish models, datasets and other repos on the huggingface.co hub"optional = falsepython-versions = ">=3.8.0"files = [- {file = "huggingface_hub-0.33.1-py3-none-any.whl", hash = "sha256:ec8d7444628210c0ba27e968e3c4c973032d44dcea59ca0d78ef3f612196f095"},- {file = "huggingface_hub-0.33.1.tar.gz", hash = "sha256:589b634f979da3ea4b8bdb3d79f97f547840dc83715918daf0b64209c0844c7b"},+ {file = "huggingface_hub-0.33.4-py3-none-any.whl", hash = "sha256:09f9f4e7ca62547c70f8b82767eefadd2667f4e116acba2e3e62a5a81815a7bb"},+ {file = "huggingface_hub-0.33.4.tar.gz", hash = "sha256:6af13478deae120e765bfd92adad0ae1aec1ad8c439b46f23058ad5956cbca0a"},][package.dependencies]@@ -1748,12 +1749,13 @@ openai = ["openai (>=0.27.8)"][[package]]name = "litellm-enterprise"-version = "0.1.13"+version = "0.1.14"description = "Package for LiteLLM Enterprise features"optional = truepython-versions = "!=2.7.*,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,!=3.7.*,>=3.8"files = [- {file = "litellm_enterprise-0.1.13.tar.gz", hash = "sha256:42c1c690b62251d7b50b049aac3e485ecf303bdc55bd1e2f8e2924e82bb44ac8"},+ {file = "litellm_enterprise-0.1.14-py3-none-any.whl", hash = "sha256:acaf48bb0cd29eac2910f855f36dada3b481cd2d1b7dad47761af88542035ec8"},+ {file = "litellm_enterprise-0.1.14.tar.gz", hash = "sha256:b45a2ab3301cf4f9442642e704eb9c86bd6024b9df75b24659923f0757e4cc1a"},][[package]]@@ -2311,13 +2313,13 @@ signedtoken = ["cryptography (>=3.0.0)", "pyjwt (>=2.0.0,<3)"][[package]]name = "openai"-version = "1.91.0"+version = "1.97.0"description = "The official Python library for the openai API"optional = falsepython-versions = ">=3.8"files = [- {file = "openai-1.91.0-py3-none-any.whl", hash = "sha256:207f87aa3bc49365e014fac2f7e291b99929f4fe126c4654143440e0ad446a5f"},- {file = "openai-1.91.0.tar.gz", hash = "sha256:d6b07730d2f7c6745d0991997c16f85cddfc90ddcde8d569c862c30716b9fc90"},+ {file = "openai-1.97.0-py3-none-any.whl", hash = "sha256:a1c24d96f4609f3f7f51c9e1c2606d97cc6e334833438659cfd687e9c972c610"},+ {file = "openai-1.97.0.tar.gz", hash = "sha256:0be349569ccaa4fb54f97bb808423fd29ccaeb1246ee1be762e0c81a47bae0aa"},][package.dependencies]@@ -2331,7 +2333,7 @@ tqdm = ">4"typing-extensions = ">=4.11,<5"[package.extras]-aiohttp = ["aiohttp", "httpx-aiohttp (>=0.1.6)"]+aiohttp = ["aiohttp", "httpx-aiohttp (>=0.1.8)"]datalib = ["numpy (>=1)", "pandas (>=1.2.3)", "pandas-stubs (>=1.1.0.11)"]realtime = ["websockets (>=13,<16)"]voice-helpers = ["numpy (>=2.0.2)", "sounddevice (>=0.5.1)"]@@ -4734,4 +4736,5 @@ utils = ["numpydoc"][metadata]lock-version = "2.0"python-versions = ">=3.8.1,<4.0, !=3.9.7"-content-hash = "cc4ec4c836f59c99cd19ed1cae7bf496ced535dea41d6c05e1d34eba42f71a1b"+content-hash = "39827a54e964e0d54d87fa2fa096ada5859835d490e3c17d089124010012c938"+diff --git a/pyproject.toml b/pyproject.tomlindex ea657598892..9e332dacfda 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -58,8 +58,8 @@ boto3 = {version = "1.34.34", optional = true}redisvl = {version = "^0.4.1", optional = true, markers = "python_version >= '3.9' and python_version < '3.14'"}mcp = {version = "1.10.0", optional = true, python = ">=3.10"}litellm-proxy-extras = {version = "0.2.10", optional = true}-rich = {version = ">=13.7.1", optional = true}-litellm-enterprise = {version = "0.1.13", optional = true}+rich = {version = "13.7.1", optional = true}+litellm-enterprise = {version = "0.1.14", optional = true}diskcache = {version = "^5.6.1", optional = true}[tool.poetry.extras]diff --git a/requirements.txt b/requirements.txtindex 2eca8df558c..befca89eb85 100644--- a/requirements.txt+++ b/requirements.txt@@ -57,4 +57,4 @@ websockets==13.1.0 # for realtime API######################### LITELLM ENTERPRISE DEPENDENCIES########################-litellm-enterprise==0.1.13+litellm-enterprise==0.1.14diff --git a/tests/logging_callback_tests/test_prometheus_unit_tests.py b/tests/enterprise/litellm_enterprise/enterprise_callbacks/test_prometheus_logging_callbacks.pysimilarity index 98%rename from tests/logging_callback_tests/test_prometheus_unit_tests.pyrename to tests/enterprise/litellm_enterprise/enterprise_callbacks/test_prometheus_logging_callbacks.pyindex 6451f30e416..31c849fea52 100644--- a/tests/logging_callback_tests/test_prometheus_unit_tests.py+++ b/tests/enterprise/litellm_enterprise/enterprise_callbacks/test_prometheus_logging_callbacks.py@@ -14,11 +14,6 @@ from prometheus_client import REGISTRY, CollectorRegistryimport litellmfrom litellm import completionfrom litellm._logging import verbose_logger-from litellm.integrations.prometheus import (- PrometheusLogger,- UserAPIKeyLabelValues,- get_custom_labels_from_metadata,-)from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandlerfrom litellm.types.utils import (StandardLoggingPayload,@@ -29,7 +24,10 @@ from litellm.types.utils import (import pytestfrom unittest.mock import MagicMock, patch, callfrom datetime import datetime, timedelta, timezone-from litellm.integrations.prometheus import PrometheusLogger+try:+ from litellm_enterprise.integrations.prometheus import PrometheusLogger, UserAPIKeyLabelValues, get_custom_labels_from_metadata+except Exception:+ PrometheusLogger = Nonefrom litellm.proxy._types import UserAPIKeyAuthverbose_logger.setLevel(logging.DEBUG)@@ -1055,7 +1053,7 @@ def test_increment_deployment_cooled_down(prometheus_logger):@pytest.mark.parametrize("enable_end_user_cost_tracking_prometheus_only", [True, False])def test_prometheus_factory(monkeypatch, enable_end_user_cost_tracking_prometheus_only):- from litellm.integrations.prometheus import prometheus_label_factory+ from litellm_enterprise.integrations.prometheus import prometheus_label_factoryfrom litellm.types.integrations.prometheus import UserAPIKeyLabelValuesmonkeypatch.setattr(@@ -1097,7 +1095,7 @@ def test_get_custom_labels_from_metadata_tags(monkeypatch):def test_get_custom_labels_from_tags(monkeypatch):- from litellm.integrations.prometheus import get_custom_labels_from_tags+ from litellm_enterprise.integrations.prometheus import get_custom_labels_from_tagsmonkeypatch.setattr("litellm.custom_prometheus_tags", ["prod", "test-env", "batch.job"]@@ -1112,7 +1110,7 @@ def test_get_custom_labels_from_tags(monkeypatch):def test_get_custom_labels_from_tags_empty_config(monkeypatch):- from litellm.integrations.prometheus import get_custom_labels_from_tags+ from litellm_enterprise.integrations.prometheus import get_custom_labels_from_tagsmonkeypatch.setattr("litellm.custom_prometheus_tags", [])tags = ["prod", "debug"]@@ -1121,7 +1119,7 @@ def test_get_custom_labels_from_tags_empty_config(monkeypatch):def test_get_custom_labels_from_tags_no_tags(monkeypatch):- from litellm.integrations.prometheus import get_custom_labels_from_tags+ from litellm_enterprise.integrations.prometheus import get_custom_labels_from_tagsmonkeypatch.setattr("litellm.custom_prometheus_tags", ["prod", "test"])tags = []@@ -1534,7 +1532,7 @@ 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_enterprise.integrations.prometheus import get_custom_labels_from_tags, prometheus_label_factoryfrom litellm.types.integrations.prometheus import UserAPIKeyLabelValues# Set custom tags configuration@@ -1569,7 +1567,7 @@ 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_enterprise.integrations.prometheus import get_custom_labels_from_tags, prometheus_label_factoryfrom litellm.types.integrations.prometheus import UserAPIKeyLabelValues# Set empty custom tags configurationdiff --git a/tests/test_litellm/integrations/test_prometheus.py b/tests/enterprise/litellm_enterprise/integrations/test_prometheus.pysimilarity index 99%rename from tests/test_litellm/integrations/test_prometheus.pyrename to tests/enterprise/litellm_enterprise/integrations/test_prometheus.pyindex dc8593758d6..82f4c4bd298 100644--- a/tests/test_litellm/integrations/test_prometheus.py+++ b/tests/enterprise/litellm_enterprise/integrations/test_prometheus.py@@ -23,7 +23,11 @@ from prometheus_client import REGISTRYimport litellmfrom litellm.constants import PROMETHEUS_BUDGET_METRICS_REFRESH_INTERVAL_MINUTES-from litellm.integrations.prometheus import PrometheusLogger, prometheus_label_factory+try:+ from enterprise.litellm_enterprise.integrations.prometheus import PrometheusLogger, prometheus_label_factory+except Exception:+ PrometheusLogger = None+ prometheus_label_factory = Nonefrom litellm.types.integrations.prometheus import (PrometheusMetricLabels,PrometheusMetricsConfig,diff --git a/tests/enterprise/litellm_enterprise/integrations/test_prometheus_unit_tests.py b/tests/enterprise/litellm_enterprise/integrations/test_prometheus_unit_tests.pynew file mode 100644index 00000000000..8a3238a675e--- /dev/null+++ b/tests/enterprise/litellm_enterprise/integrations/test_prometheus_unit_tests.py@@ -0,0 +1,321 @@+from unittest.mock import patch+import pytest_asyncio++from prometheus_client import REGISTRY++try:+ from litellm_enterprise.integrations.prometheus import PrometheusLogger+except Exception:+ PrometheusLogger = None++import sys, asyncio+from dotenv import load_dotenv++load_dotenv()+import os++sys.path.insert(+ 0, os.path.abspath("../..")+) # Adds the parent directory to the system-path+import pytest+from litellm import Router+from litellm.router_strategy.budget_limiter import RouterBudgetLimiting++from litellm.types.utils import GenericBudgetConfigType, BudgetConfig+from litellm.caching.caching import DualCache+import litellm+from unittest.mock import MagicMock, patch+from litellm.router_utils.cooldown_callbacks import router_cooldown_event_callback+from litellm.types.router import ModelInfo++++++def compare_metrics(func):+ def get_metrics():+ metrics = {}+ for metric in REGISTRY.collect():+ for sample in metric.samples:+ metrics[sample.name] = sample.value+ return metrics++ async def wrapper(*args, **kwargs):+ initial_metrics = get_metrics()+ await func(*args, **kwargs)+ await asyncio.sleep(2)+ updated_metrics = get_metrics()++ return {+ metric: updated_metrics.get(metric, 0) - initial_metrics.get(metric, 0)+ for metric in set(initial_metrics) | set(updated_metrics)+ }++ return wrapper+++@pytest_asyncio.fixture(scope="function")+async def prometheus_logger():+ collectors = list(REGISTRY._collector_to_names.keys())+ for collector in collectors:+ REGISTRY.unregister(collector)++ with patch("litellm.proxy.proxy_server.premium_user", True):+ yield PrometheusLogger()+++async def test_async_prometheus_success_logging_with_callbacks(prometheus_logger):+ litellm.callbacks = [prometheus_logger]++ @compare_metrics+ async def op():+ await litellm.acompletion(+ model="claude-3-haiku-20240307",+ messages=[{"role": "user", "content": "what llm are u"}],+ max_tokens=10,+ mock_response="hi",+ temperature=0.2,+ )++ diff = await op()+ assert diff["litellm_requests_metric_total"] == 1.0+++async def test_async_prometheus_budget_logging_with_callbacks(prometheus_logger):+ litellm.callbacks = [prometheus_logger]++ @compare_metrics+ async def op():+ provider_budget_config: GenericBudgetConfigType = {+ "openai": BudgetConfig(time_period="1d", budget_limit=50),+ }++ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo",+ "litellm_params": {+ "model": "openai/gpt-3.5-turbo",+ "api_key": "mock-key",+ },+ }+ ],+ provider_budget_config=provider_budget_config,+ )++ await router.acompletion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "llm?"}],+ mock_response="openai",+ metadata={+ "user_api_key_team_id": "team-1",+ "user_api_key_team_alias": "test-team",+ "user_api_key": "test-key",+ "user_api_key_alias": "test-key-alias",+ },+ )++ diff = await op()++ # TODO: Should implement `litellm_provider_remaining_budget_metric` in prometheus.py+ assert diff.get("litellm_provider_remaining_budget_metric", 50.0) == 50.0+++async def test_prometheus_metric_tracking():+ """+ Test that the Prometheus metric for provider budget is tracked correctly+ """+ try:+ from litellm_enterprise.integrations.prometheus import PrometheusLogger+ from unittest.mock import MagicMock+ except Exception:+ PrometheusLogger = None+ if PrometheusLogger is None:+ pytest.skip("PrometheusLogger is not installed")++ # Create a mock PrometheusLogger+ mock_prometheus = MagicMock(spec=PrometheusLogger)++ # Setup provider budget limiting+ provider_budget = RouterBudgetLimiting(+ dual_cache=DualCache(),+ provider_budget_config={+ "openai": BudgetConfig(budget_duration="1d", max_budget=100)+ },+ )++ litellm._async_success_callback = [mock_prometheus]++ provider_budget_config: GenericBudgetConfigType = {+ "openai": BudgetConfig(budget_duration="1d", max_budget=0.000000000001),+ "azure": BudgetConfig(budget_duration="1d", max_budget=100),+ }++ router = Router(+ model_list=[+ {+ "model_name": "gpt-3.5-turbo", # openai model name+ "litellm_params": { # params for litellm completion/embedding call+ "model": "azure/chatgpt-v-3",+ "api_key": os.getenv("AZURE_API_KEY"),+ "api_version": os.getenv("AZURE_API_VERSION"),+ "api_base": os.getenv("AZURE_API_BASE"),+ },+ "model_info": {"id": "azure-model-id"},+ },+ {+ "model_name": "gpt-3.5-turbo", # openai model name+ "litellm_params": {+ "model": "openai/gpt-4o-mini",+ },+ "model_info": {"id": "openai-model-id"},+ },+ ],+ provider_budget_config=provider_budget_config,+ redis_host=os.getenv("REDIS_HOST"),+ redis_port=int(os.getenv("REDIS_PORT", 6379)),+ redis_password=os.getenv("REDIS_PASSWORD"),+ )++ try:+ response = await router.acompletion(+ messages=[{"role": "user", "content": "Hello, how are you?"}],+ model="openai/gpt-4o-mini",+ mock_response="hi",+ )+ print(response)+ except Exception as e:+ print("error", e)++ await asyncio.sleep(2.5)++ # Verify the mock was called correctly+ mock_prometheus.track_provider_remaining_budget.assert_called()++++class CustomPrometheusLogger(PrometheusLogger):+ def __init__(self):+ super().__init__()+ self.deployment_complete_outages = []+ self.deployment_cooled_downs = []++ def set_deployment_complete_outage(+ self,+ litellm_model_name: str,+ model_id: str,+ api_base: str,+ api_provider: str,+ ):+ self.deployment_complete_outages.append(+ [litellm_model_name, model_id, api_base, api_provider]+ )++ def increment_deployment_cooled_down(+ self,+ litellm_model_name: str,+ model_id: str,+ api_base: str,+ api_provider: str,+ exception_status: str,+ ):+ self.deployment_cooled_downs.append(+ [litellm_model_name, model_id, api_base, api_provider, exception_status]+ )+++async def test_router_cooldown_event_callback():+ # Clear Prometheus registry to avoid duplicate metric registration+ from prometheus_client import REGISTRY+ collectors = list(REGISTRY._collector_to_names.keys())+ for collector in collectors:+ REGISTRY.unregister(collector)++ """+ Test the router_cooldown_event_callback function++ Ensures that the router_cooldown_event_callback function correctly logs the cooldown event to the PrometheusLogger+ """+ # Mock Router instance+ mock_router = MagicMock()+ mock_deployment = {+ "litellm_params": {"model": "gpt-3.5-turbo"},+ "model_name": "gpt-3.5-turbo",+ "model_info": ModelInfo(id="test-model-id"),+ }+ mock_router.get_deployment.return_value = mock_deployment++ # Create a real PrometheusLogger instance+ prometheus_logger = CustomPrometheusLogger()+ litellm.callbacks = [prometheus_logger]++ await router_cooldown_event_callback(+ litellm_router_instance=mock_router,+ deployment_id="test-deployment",+ exception_status="429",+ cooldown_time=60.0,+ )++ await asyncio.sleep(0.5)++ # Assert that the router's get_deployment method was called+ mock_router.get_deployment.assert_called_once_with(model_id="test-deployment")++ print(+ "prometheus_logger.deployment_complete_outages",+ prometheus_logger.deployment_complete_outages,+ )+ print(+ "prometheus_logger.deployment_cooled_downs",+ prometheus_logger.deployment_cooled_downs,+ )++ # Assert that PrometheusLogger methods were called+ assert len(prometheus_logger.deployment_complete_outages) == 1+ assert len(prometheus_logger.deployment_cooled_downs) == 1++ assert prometheus_logger.deployment_complete_outages[0] == [+ "gpt-3.5-turbo",+ "test-model-id",+ "https://api.openai.com",+ "openai",+ ]+ assert prometheus_logger.deployment_cooled_downs[0] == [+ "gpt-3.5-turbo",+ "test-model-id",+ "https://api.openai.com",+ "openai",+ "429",+ ]+++async def test_router_cooldown_event_callback_no_prometheus():+ """+ Test the router_cooldown_event_callback function++ Ensures that the router_cooldown_event_callback function does not raise an error when no PrometheusLogger is found+ """+ # Mock Router instance+ mock_router = MagicMock()+ mock_deployment = {+ "litellm_params": {"model": "gpt-3.5-turbo"},+ "model_name": "gpt-3.5-turbo",+ "model_info": ModelInfo(id="test-model-id"),+ }+ mock_router.get_deployment.return_value = mock_deployment++ await router_cooldown_event_callback(+ litellm_router_instance=mock_router,+ deployment_id="test-deployment",+ exception_status="429",+ cooldown_time=60.0,+ )++ # Assert that the router's get_deployment method was called+ mock_router.get_deployment.assert_called_once_with(model_id="test-deployment")+diff --git a/tests/local_testing/test_prometheus.py b/tests/local_testing/test_prometheus.pydeleted file mode 100644index 8a4d03e630d..00000000000--- a/tests/local_testing/test_prometheus.py+++ /dev/null@@ -1,102 +0,0 @@-import asyncio--import pytest-from unittest.mock import patch-import pytest_asyncio--from prometheus_client import REGISTRY--import litellm-from litellm.integrations.prometheus import PrometheusLogger-from litellm.types.utils import BudgetConfig, GenericBudgetConfigType---def compare_metrics(func):- def get_metrics():- metrics = {}- for metric in REGISTRY.collect():- for sample in metric.samples:- metrics[sample.name] = sample.value- return metrics-- async def wrapper(*args, **kwargs):- initial_metrics = get_metrics()- await func(*args, **kwargs)- await asyncio.sleep(2)- updated_metrics = get_metrics()-- return {- metric: updated_metrics.get(metric, 0) - initial_metrics.get(metric, 0)- for metric in set(initial_metrics) | set(updated_metrics)- }-- return wrapper---@pytest_asyncio.fixture(scope="function")-async def prometheus_logger():- collectors = list(REGISTRY._collector_to_names.keys())- for collector in collectors:- REGISTRY.unregister(collector)-- with patch("litellm.proxy.proxy_server.premium_user", True):- yield PrometheusLogger()---async def test_async_prometheus_success_logging_with_callbacks(prometheus_logger):- litellm.callbacks = [prometheus_logger]-- @compare_metrics- async def op():- await litellm.acompletion(- model="claude-3-haiku-20240307",- messages=[{"role": "user", "content": "what llm are u"}],- max_tokens=10,- mock_response="hi",- temperature=0.2,- )-- diff = await op()- assert diff["litellm_requests_metric_total"] == 1.0---async def test_async_prometheus_budget_logging_with_callbacks(prometheus_logger):- litellm.callbacks = [prometheus_logger]-- @compare_metrics- async def op():- provider_budget_config: GenericBudgetConfigType = {- "openai": BudgetConfig(time_period="1d", budget_limit=50),- }-- router = litellm.Router(- model_list=[- {- "model_name": "gpt-3.5-turbo",- "litellm_params": {- "model": "openai/gpt-3.5-turbo",- "api_key": "mock-key",- },- }- ],- provider_budget_config=provider_budget_config,- )-- await router.acompletion(- model="gpt-3.5-turbo",- messages=[{"role": "user", "content": "llm?"}],- mock_response="openai",- metadata={- "user_api_key_team_id": "team-1",- "user_api_key_team_alias": "test-team",- "user_api_key": "test-key",- "user_api_key_alias": "test-key-alias",- },- )-- diff = await op()-- # TODO: Should implement `litellm_provider_remaining_budget_metric` in prometheus.py- assert diff.get("litellm_provider_remaining_budget_metric", 50.0) == 50.0diff --git a/tests/local_testing/test_router_budget_limiter.py b/tests/local_testing/test_router_budget_limiter.pyindex 27fef41ef46..7ff940c8e4b 100644--- a/tests/local_testing/test_router_budget_limiter.py+++ b/tests/local_testing/test_router_budget_limiter.py@@ -236,75 +236,6 @@ async def test_get_budget_config_for_provider():assert provider_budget._get_budget_config_for_provider("unknown") is None-async def test_prometheus_metric_tracking():- """- Test that the Prometheus metric for provider budget is tracked correctly- """- cleanup_redis()- from unittest.mock import MagicMock- from litellm.integrations.prometheus import PrometheusLogger-- # Create a mock PrometheusLogger- mock_prometheus = MagicMock(spec=PrometheusLogger)-- # Setup provider budget limiting- provider_budget = RouterBudgetLimiting(- dual_cache=DualCache(),- provider_budget_config={- "openai": BudgetConfig(budget_duration="1d", max_budget=100)- },- )-- litellm._async_success_callback = [mock_prometheus]-- provider_budget_config: GenericBudgetConfigType = {- "openai": BudgetConfig(budget_duration="1d", max_budget=0.000000000001),- "azure": BudgetConfig(budget_duration="1d", max_budget=100),- }-- router = Router(- model_list=[- {- "model_name": "gpt-3.5-turbo", # openai model name- "litellm_params": { # params for litellm completion/embedding call- "model": "azure/chatgpt-v-3",- "api_key": os.getenv("AZURE_API_KEY"),- "api_version": os.getenv("AZURE_API_VERSION"),- "api_base": os.getenv("AZURE_API_BASE"),- },- "model_info": {"id": "azure-model-id"},- },- {- "model_name": "gpt-3.5-turbo", # openai model name- "litellm_params": {- "model": "openai/gpt-4o-mini",- },- "model_info": {"id": "openai-model-id"},- },- ],- provider_budget_config=provider_budget_config,- redis_host=os.getenv("REDIS_HOST"),- redis_port=int(os.getenv("REDIS_PORT")),- redis_password=os.getenv("REDIS_PASSWORD"),- )-- try:- response = await router.acompletion(- messages=[{"role": "user", "content": "Hello, how are you?"}],- model="openai/gpt-4o-mini",- mock_response="hi",- )- print(response)- except Exception as e:- print("error", e)-- await asyncio.sleep(2.5)-- # Verify the mock was called correctly- mock_prometheus.track_provider_remaining_budget.assert_called()--@pytest.mark.asyncioasync def test_handle_new_budget_window():"""diff --git a/tests/router_unit_tests/test_router_cooldown_utils.py b/tests/router_unit_tests/test_router_cooldown_utils.pyindex 4ac703419ae..19299aa698e 100644--- a/tests/router_unit_tests/test_router_cooldown_utils.py+++ b/tests/router_unit_tests/test_router_cooldown_utils.py@@ -13,7 +13,6 @@ from concurrent.futures import ThreadPoolExecutorfrom collections import defaultdictfrom dotenv import load_dotenvfrom unittest.mock import AsyncMock, MagicMock, patch-from litellm.integrations.prometheus import PrometheusLoggerfrom litellm.router_utils.cooldown_callbacks import router_cooldown_event_callbackfrom litellm.router_utils.cooldown_handlers import (_should_run_cooldown_logic,@@ -32,124 +31,6 @@ from litellm.router_utils.cooldown_handlers import _should_cooldown_deploymentload_dotenv()--class CustomPrometheusLogger(PrometheusLogger):- def __init__(self):- super().__init__()- self.deployment_complete_outages = []- self.deployment_cooled_downs = []-- def set_deployment_complete_outage(- self,- litellm_model_name: str,- model_id: str,- api_base: str,- api_provider: str,- ):- self.deployment_complete_outages.append(- [litellm_model_name, model_id, api_base, api_provider]- )-- def increment_deployment_cooled_down(- self,- litellm_model_name: str,- model_id: str,- api_base: str,- api_provider: str,- exception_status: str,- ):- self.deployment_cooled_downs.append(- [litellm_model_name, model_id, api_base, api_provider, exception_status]- )---async def test_router_cooldown_event_callback():- """- Test the router_cooldown_event_callback function-- Ensures that the router_cooldown_event_callback function correctly logs the cooldown event to the PrometheusLogger- """- # Mock Router instance- mock_router = MagicMock()- mock_deployment = {- "litellm_params": {"model": "gpt-3.5-turbo"},- "model_name": "gpt-3.5-turbo",- "model_info": ModelInfo(id="test-model-id"),- }- mock_router.get_deployment.return_value = mock_deployment-- # Create a real PrometheusLogger instance- prometheus_logger = CustomPrometheusLogger()- litellm.callbacks = [prometheus_logger]-- await router_cooldown_event_callback(- litellm_router_instance=mock_router,- deployment_id="test-deployment",- exception_status="429",- cooldown_time=60.0,- )-- await asyncio.sleep(0.5)-- # Assert that the router's get_deployment method was called- mock_router.get_deployment.assert_called_once_with(model_id="test-deployment")-- print(- "prometheus_logger.deployment_complete_outages",- prometheus_logger.deployment_complete_outages,- )- print(- "prometheus_logger.deployment_cooled_downs",- prometheus_logger.deployment_cooled_downs,- )-- # Assert that PrometheusLogger methods were called- assert len(prometheus_logger.deployment_complete_outages) == 1- assert len(prometheus_logger.deployment_cooled_downs) == 1-- assert prometheus_logger.deployment_complete_outages[0] == [- "gpt-3.5-turbo",- "test-model-id",- "https://api.openai.com",- "openai",- ]- assert prometheus_logger.deployment_cooled_downs[0] == [- "gpt-3.5-turbo",- "test-model-id",- "https://api.openai.com",- "openai",- "429",- ]---async def test_router_cooldown_event_callback_no_prometheus():- """- Test the router_cooldown_event_callback function-- Ensures that the router_cooldown_event_callback function does not raise an error when no PrometheusLogger is found- """- # Mock Router instance- mock_router = MagicMock()- mock_deployment = {- "litellm_params": {"model": "gpt-3.5-turbo"},- "model_name": "gpt-3.5-turbo",- "model_info": ModelInfo(id="test-model-id"),- }- mock_router.get_deployment.return_value = mock_deployment-- await router_cooldown_event_callback(- litellm_router_instance=mock_router,- deployment_id="test-deployment",- exception_status="429",- cooldown_time=60.0,- )-- # Assert that the router's get_deployment method was called- mock_router.get_deployment.assert_called_once_with(model_id="test-deployment")--@pytest.mark.asyncioasync def test_router_cooldown_event_callback_no_deployment():"""