The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(proxy): accept every known logging callback on /health/services (#46297)
Yassin Kortam912ad6537678
diff --git a/litellm/proxy/health_endpoints/_health_endpoints.py b/litellm/proxy/health_endpoints/_health_endpoints.pyindex e16a391dc12..3c8dd7890fc 100644--- a/litellm/proxy/health_endpoints/_health_endpoints.py+++ b/litellm/proxy/health_endpoints/_health_endpoints.py@@ -6,7 +6,7 @@ import osimport secretsimport timeimport traceback-from collections.abc import Iterable, Mapping+from collections.abc import Iterable, Mapping, Sequencefrom datetime import datetime, timedelta, timezonefrom typing import Final, Literal, TypedDict@@ -265,6 +265,63 @@ services = ()+_SERVICES_WITH_DEDICATED_CHECK: Final = frozenset(+ (+ "slack_budget_alerts",+ "email",+ "langfuse",+ "slack",+ "ms_teams",+ "webhook",+ "datadog",+ "datadog_metrics",+ "arize",+ "galileo",+ "newrelic",+ "pointfive",+ "sqs",+ "aws_sqs",+ )+)+_SERVICES_TESTABLE_ONLY_VIA_SUCCESS_CALLBACK: Final = frozenset(("custom_callback_api",))+++def _testable_services() -> frozenset[str]:+ return (+ _SERVICES_WITH_DEDICATED_CHECK+ | _SERVICES_TESTABLE_ONLY_VIA_SUCCESS_CALLBACK+ | frozenset(+ litellm._known_custom_logger_compatible_callbacks # pyright: ignore[reportPrivateUsage] # no public alias for the callback Literal's args+ )+ )+++def _is_testable_service(service: str) -> bool:+ return service in _testable_services()+++def _callback_matches(service: str, cb: object) -> bool:+ callback_name: Final = getattr(cb, "callback_name", None)+ if service in (cb, callback_name, get_callback_identifier(cb)):+ return True+ return (+ not callback_name+ and service not in _SERVICES_WITH_DEDICATED_CHECK+ and service in _unnamed_callback_aliases(type(cb))+ )+++def _unnamed_callback_aliases(callback_type: type) -> frozenset[str]:+ """A logger built from a bare config string carries no name, so its class aliases and its package name stand in."""+ return frozenset(CustomLoggerRegistry.get_all_callback_strs_from_class_type(callback_type)) | frozenset(+ callback_type.__module__.split(".")+ )+++def _service_configured_in(service: str, callbacks: Sequence[object]) -> bool:+ return any(_callback_matches(service, cb) for cb in callbacks)++class _ServiceTestErrorDetail(TypedDict):error: ReadOnly[str]@@ -326,53 +383,24 @@ async def health_services_endpoint(if service is None:raise HTTPException(status_code=400, detail={"error": "Service must be specified."})- if service not in [- "slack_budget_alerts",- "email",- "langfuse",- "langfuse_otel",- "slack",- "ms_teams",- "openmeter",- "webhook",- "braintrust",- "otel",- "custom_callback_api",- "langsmith",- "datadog",- "datadog_metrics",- "datadog_llm_observability",- "generic_api",- "arize",- "galileo",- "newrelic",- "pointfive",- "signoz",- "sqs",- ]:+ if not _is_testable_service(service):raise HTTPException(status_code=400,- detail={"error": f"Service must be in list. Service={service} not in {services}"},+ detail={"error": f"Service must be in list. Service={service} not in {sorted(_testable_services())}"},)- service_in_success_callbacks = False- if service in litellm.success_callback:- service_in_success_callbacks = True- else:- for cb in litellm.success_callback:- if getattr(cb, "callback_name", None) == service:- service_in_success_callbacks = True- break- cb_id = get_callback_identifier(cb)- if cb_id == service:- service_in_success_callbacks = True- break+ service_in_success_callbacks: Final = _service_configured_in(service, litellm.success_callback)+ logger_without_dedicated_check_configured: Final = (+ service not in _SERVICES_WITH_DEDICATED_CHECK+ and _service_configured_in(service, litellm.logging_callback_manager.get_all_callbacks())+ )if (service == "openmeter"or service == "braintrust"or service == "generic_api"- or (service_in_success_callbacks and service not in ("langfuse", "pointfive"))+ or (service_in_success_callbacks and service not in ("langfuse", "pointfive", "sqs", "aws_sqs"))+ or logger_without_dedicated_check_configured):_ = await litellm.acompletion(model="openai/litellm-mock-response-model",@@ -506,7 +534,11 @@ async def health_services_endpoint(type="user_budget",user_info=user_info,)- elif service == "sqs":+ return {+ "status": "success",+ "message": "Mock Webhook Alert sent, verify Webhook Alert Received",+ }+ elif service in ("sqs", "aws_sqs"):from litellm.integrations.sqs import SQSLoggersqs_logger: Final = SQSLogger()@@ -629,6 +661,13 @@ async def health_services_endpoint("message": "Mock Email Alert sent, verify Email Alert Received",}+ raise HTTPException(+ status_code=400,+ detail={+ "error": f"Service={service} is not configured as a callback, add it to litellm_settings.callbacks."+ },+ )+except Exception as e:verbose_proxy_logger.error("litellm.proxy.proxy_server.health_services_endpoint(): Exception occured - %s", e)verbose_proxy_logger.debug(traceback.format_exc())diff --git a/tests/unit/proxy/health_endpoints/test_health_endpoints.py b/tests/unit/proxy/health_endpoints/test_health_endpoints.pyindex f215da5cf3e..5d71222c391 100644--- a/tests/unit/proxy/health_endpoints/test_health_endpoints.py+++ b/tests/unit/proxy/health_endpoints/test_health_endpoints.py@@ -1429,6 +1429,142 @@ async def test_health_services_endpoint_datadog_llm_observability():assert "datadog_llm_observability" in result["message"]+ "service", ["zerobus", "langsmith", "otel", "langfuse_otel", "datadog_llm_observability", "signoz"]+)+async def test_health_services_endpoint_tests_any_known_callback_configured_via_callbacks(service: str):+ """A logger without its own health check, wired through litellm_settings.callbacks, gets the mock request."""+ acompletion: Final = AsyncMock(return_value=MagicMock())+ with (+ patch("litellm.success_callback", []),+ patch("litellm.callbacks", [service]),+ patch("litellm.acompletion", acompletion),+ ):+ result = await health_services_endpoint(service=service)++ assert result == {"status": "success", "message": f"Mock LLM request made - check {service}."}+ acompletion.assert_awaited_once()+ assert acompletion.await_args.kwargs["user"] == "litellm:/health/services"+++async def test_health_services_endpoint_tests_logger_configured_only_via_failure_callback():+ """litellm_settings.failure_callback: [langsmith] is configured too, so Test sends the mock request."""+ acompletion: Final = AsyncMock(return_value=MagicMock())+ with (+ patch("litellm.success_callback", []),+ patch("litellm.callbacks", []),+ patch("litellm.failure_callback", ["langsmith"]),+ patch("litellm.acompletion", acompletion),+ ):+ result = await health_services_endpoint(service="langsmith")++ assert result == {"status": "success", "message": "Mock LLM request made - check langsmith."}+ acompletion.assert_awaited_once()+++async def test_health_services_endpoint_matches_otel_instance_loaded_from_callbacks():+ """The proxy swaps the "otel" string for an OpenTelemetry instance without a callback_name, it still counts."""+ from litellm.integrations.opentelemetry import OpenTelemetry, OpenTelemetryConfig++ acompletion: Final = AsyncMock(return_value=MagicMock())+ otel_logger: Final = OpenTelemetry(config=OpenTelemetryConfig(exporter="console", skip_set_global=True))+ with (+ patch("litellm.success_callback", []),+ patch("litellm.callbacks", [otel_logger]),+ patch("litellm.acompletion", acompletion),+ ):+ result = await health_services_endpoint(service="otel")++ assert result == {"status": "success", "message": "Mock LLM request made - check otel."}+ acompletion.assert_awaited_once()+++async def test_health_services_endpoint_matches_unregistered_nameless_instance_by_package():+ """compression_interception is swapped for a logger outside CustomLoggerRegistry at startup, it still counts."""+ from litellm.integrations.compression_interception.handler import CompressionInterceptionLogger++ acompletion: Final = AsyncMock(return_value=MagicMock())+ with (+ patch("litellm.success_callback", []),+ patch("litellm.callbacks", [CompressionInterceptionLogger()]),+ patch("litellm.acompletion", acompletion),+ ):+ result = await health_services_endpoint(service="compression_interception")++ assert result == {"status": "success", "message": "Mock LLM request made - check compression_interception."}+ acompletion.assert_awaited_once()+++async def test_health_services_endpoint_otel_instance_does_not_claim_arize_dedicated_check():+ """A nameless OpenTelemetry logger shares arize's class, Test on arize must still run the Arize check."""+ from litellm.integrations.opentelemetry import OpenTelemetry, OpenTelemetryConfig++ acompletion: Final = AsyncMock(return_value=MagicMock())+ otel_logger: Final = OpenTelemetry(config=OpenTelemetryConfig(exporter="console", skip_set_global=True))+ with (+ patch("litellm.success_callback", [otel_logger]),+ patch("litellm.callbacks", [otel_logger]),+ patch("litellm.acompletion", acompletion),+ patch("litellm.integrations.arize.arize.ArizeLogger") as MockArizeLogger,+ ):+ mock_instance = MagicMock()+ mock_instance.async_health_check = AsyncMock(return_value={"status": "healthy", "error_message": ""})+ MockArizeLogger.return_value = mock_instance+ result = await health_services_endpoint(service="arize")++ assert result == {"status": "healthy", "message": "Arize is healthy"}+ acompletion.assert_not_awaited()+ mock_instance.async_health_check.assert_awaited_once()++[email protected]("service", ["sqs", "aws_sqs"])+async def test_health_services_endpoint_keeps_dedicated_check_for_logger_configured_via_callbacks(service: str):+ """callbacks: [aws_sqs] becomes a nameless SQSLogger at startup, Test on sqs or aws_sqs still runs its check."""+ from litellm.integrations.sqs import SQSLogger++ acompletion: Final = AsyncMock(return_value=MagicMock())+ configured_logger: Final = SQSLogger()+ with (+ patch("litellm.success_callback", [configured_logger]),+ patch("litellm.callbacks", [configured_logger]),+ patch("litellm.acompletion", acompletion),+ patch("litellm.integrations.sqs.SQSLogger") as MockSQSLogger,+ ):+ mock_instance = MagicMock()+ mock_instance.async_health_check = AsyncMock(return_value={"status": "healthy", "error_message": ""})+ MockSQSLogger.return_value = mock_instance+ result = await health_services_endpoint(service=service)++ assert result == {"status": "healthy", "message": ""}+ acompletion.assert_not_awaited()+ mock_instance.async_health_check.assert_awaited_once()+++async def test_health_services_endpoint_rejects_known_but_unconfigured_callback():+ """zerobus is a known logger, but with nothing configured the test is a 400, not an empty 200."""+ from litellm.proxy._types import ProxyException++ with (+ patch("litellm.success_callback", []),+ patch("litellm.failure_callback", []),+ patch("litellm.callbacks", []),+ patch("litellm._async_success_callback", []),+ patch("litellm._async_failure_callback", []),+ pytest.raises(ProxyException) as exc,+ ):+ await health_services_endpoint(service="zerobus")++ assert exc.value.code == "400"+ assert "not configured as a callback" in str(exc.value.message)++@pytest.mark.asyncioasync def test_health_services_endpoint_rejects_unknown_service():"""