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): stop expected 4xx responses from saturating worker CPU on failure logging (#38102)
devin-ai-integration[bot]e25ce85dbc0d
diff --git a/litellm/__init__.py b/litellm/__init__.pyindex ee2c551481c..f42b8280761 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -199,6 +199,7 @@ standard_logging_payload_excluded_fields: Optional[List[str]] = (None # Fields to exclude from StandardLoggingPayload before callbacks receive it)log_raw_request_response: bool = False+log_client_error_tracebacks: bool = Falserequest_correlation_in_logs: bool = Falseredact_messages_in_exceptions: Optional[bool] = Falseredact_user_api_key_info: Optional[bool] = Falsediff --git a/litellm/litellm_core_utils/core_helpers.py b/litellm/litellm_core_utils/core_helpers.pyindex de1092bc02f..b71ef4c8e06 100644--- a/litellm/litellm_core_utils/core_helpers.py+++ b/litellm/litellm_core_utils/core_helpers.py@@ -58,6 +58,26 @@ def safe_divide(return numerator / denominator+def is_expected_client_error(exception: BaseException | None) -> bool:+ """+ True when the exception maps to an HTTP 4xx status.++ ProxyException stores the status on .code (as a str), HTTPException and+ litellm exceptions on .status_code.+ """+ if exception is None:+ return False+ code: Final[object] = getattr(exception, "code", None)+ status_code: Final[object] = code if code is not None else getattr(exception, "status_code", None)+ if status_code is None or isinstance(status_code, bool):+ return False+ try:+ status: Final = int(str(status_code))+ except ValueError:+ return False+ return 400 <= status < 500++def coerce_token_limit(value: object) -> int | None:"""Coerce a max_input_tokens / max_output_tokens value to an int, treating adiff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex 960ed266e75..626af7530a4 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -62,7 +62,7 @@ from litellm.integrations.custom_logger import CustomLoggerfrom litellm.integrations.deepeval.deepeval import DeepEvalLoggerfrom litellm.integrations.mlflow import MlflowLoggerfrom litellm.integrations.sqs import SQSLogger-from litellm.litellm_core_utils.core_helpers import reconstruct_model_name+from litellm.litellm_core_utils.core_helpers import is_expected_client_error, reconstruct_model_namefrom litellm.litellm_core_utils.get_litellm_params import get_litellm_paramsfrom litellm.litellm_core_utils.llm_cost_calc.guardrail_cost import (cost_breakdown_with_guardrail,@@ -3124,6 +3124,13 @@ class Logging(LiteLLMLoggingBaseClass):if not hasattr(self, "model_call_details"):self.model_call_details = {}+ if (+ self.model_call_details.get("log_event_type") == "failed_api_call"+ and self.model_call_details.get("exception") is exception+ and self.model_call_details.get("standard_logging_object") is not None+ ):+ return start_time, self.model_call_details["end_time"]+self.model_call_details["log_event_type"] = "failed_api_call"self.model_call_details["exception"] = exceptionself.model_call_details["traceback_exception"] = (@@ -5455,9 +5462,10 @@ class StandardLoggingPayloadSetup:error_class: Final[str] = str(original_exception.__class__.__name__) if original_exception else ""_llm_provider_in_exception: Final = getattr(original_exception, "llm_provider", "")- # Get traceback information (first 100 lines)traceback_info = traceback_str or ""- if original_exception:+ if original_exception and (+ litellm.log_client_error_tracebacks or not is_expected_client_error(original_exception)+ ):tb: Final[TracebackType | None] = getattr(original_exception, "__traceback__", None)if tb:tb_lines: Final = traceback.format_tb(tb)diff --git a/litellm/proxy/auth/auth_exception_handler.py b/litellm/proxy/auth/auth_exception_handler.pyindex 233679126f8..a42187b3a44 100644--- a/litellm/proxy/auth/auth_exception_handler.py+++ b/litellm/proxy/auth/auth_exception_handler.py@@ -11,6 +11,7 @@ import litellmfrom litellm._logging import verbose_proxy_loggerfrom litellm.constants import EMPTY_MAPPINGfrom litellm.integrations.otel.runtime import seed_request_identity+from litellm.litellm_core_utils.core_helpers import is_expected_client_errorfrom litellm.proxy._types import (LitellmUserRoles,ProxyErrorTypes,@@ -109,7 +110,12 @@ class UserAPIKeyAuthExceptionHandler:request=request,use_x_forwarded_for=general_settings.get("use_x_forwarded_for") is True,)- verbose_proxy_logger.exception(+ log_fn: Final = (+ verbose_proxy_logger.error+ if is_expected_client_error(e) and not litellm.log_client_error_tracebacks+ else verbose_proxy_logger.exception+ )+ log_fn("litellm.proxy.proxy_server.user_api_key_auth(): Exception occured - %s\nRequester IP Address:%s",e,requester_ip,diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex 413fead9bd4..6fd743deb44 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -33,7 +33,7 @@ from litellm.constants import (UNSAFE_PROXY_RESPONSE_HEADERS,)from litellm.integrations.custom_guardrail import CustomGuardrail-from litellm.litellm_core_utils.core_helpers import get_or_create_metadata_bucket+from litellm.litellm_core_utils.core_helpers import get_or_create_metadata_bucket, is_expected_client_errorfrom litellm.litellm_core_utils.dd_tracing import NullTracer, tracerfrom litellm.litellm_core_utils.get_supported_openai_params import (get_supported_openai_params,@@ -1380,7 +1380,12 @@ def _log_llm_api_exception(e: Exception) -> None:"litellm.proxy.proxy_server._handle_llm_api_exception(): client disconnected, upstream LLM request cancelled")return- verbose_proxy_logger.exception("litellm.proxy.proxy_server._handle_llm_api_exception(): Exception occured - %s", e)+ log_fn: Final = (+ verbose_proxy_logger.error+ if is_expected_client_error(e) and not litellm.log_client_error_tracebacks+ else verbose_proxy_logger.exception+ )+ log_fn("litellm.proxy.proxy_server._handle_llm_api_exception(): Exception occured - %s", e)async def _cancel_llm_call_on_client_disconnect(diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.pyindex 86d954c0913..2bbdad9c487 100644--- a/litellm/proxy/utils.py+++ b/litellm/proxy/utils.py@@ -91,7 +91,7 @@ from litellm.integrations.custom_logger import CustomLoggerfrom litellm.integrations.prometheus import PrometheusLoggerfrom litellm.integrations.SlackAlerting.slack_alerting import SlackAlertingfrom litellm.integrations.SlackAlerting.utils import _add_langfuse_trace_id_to_alert-from litellm.litellm_core_utils.core_helpers import coerce_token_limit+from litellm.litellm_core_utils.core_helpers import coerce_token_limit, is_expected_client_errorfrom litellm.litellm_core_utils.litellm_logging import Loggingfrom litellm.litellm_core_utils.safe_json_dumps import safe_dumpsfrom litellm.litellm_core_utils.safe_json_loads import safe_json_loads@@ -2575,20 +2575,36 @@ class ProxyLogging:api_key="",)- # log the custom exception- await litellm_logging_obj.async_failure_handler(- exception=original_exception,- traceback_exception=traceback.format_exc(),+ await self._dispatch_proxy_only_failure_handlers(+ litellm_logging_obj=litellm_logging_obj,+ original_exception=original_exception,)- threading.Thread(- target=litellm_logging_obj.failure_handler,- args=(- original_exception,- traceback.format_exc(),- ),- daemon=True,- ).start()+ @staticmethod+ async def _dispatch_proxy_only_failure_handlers(+ litellm_logging_obj: Logging,+ original_exception: Exception | None,+ ) -> None:+ """Runs the async failure handler plus the threaded sync handler. Expected+ client (4xx) errors skip traceback formatting unless+ litellm.log_client_error_tracebacks is set."""+ include_traceback: Final = litellm.log_client_error_tracebacks or not is_expected_client_error(+ original_exception+ )+ traceback_str: Final = traceback.format_exc() if include_traceback else ""+ await litellm_logging_obj.async_failure_handler(+ exception=original_exception,+ traceback_exception=traceback_str,+ )++ threading.Thread(+ target=litellm_logging_obj.failure_handler,+ args=(+ original_exception,+ traceback_str,+ ),+ daemon=True,+ ).start()async def post_call_success_hook(self,diff --git a/tests/test_litellm/litellm_core_utils/test_core_helpers.py b/tests/test_litellm/litellm_core_utils/test_core_helpers.pyindex aa7f2990c13..33a33711698 100644--- a/tests/test_litellm/litellm_core_utils/test_core_helpers.py+++ b/tests/test_litellm/litellm_core_utils/test_core_helpers.py@@ -255,3 +255,26 @@ class TestRedactNestedMatchAndRegexKeys:def test_passes_through_none_and_str(self):assert redact_nested_match_and_regex_keys(None) is Noneassert redact_nested_match_and_regex_keys("plain") == "plain"+++class TestIsExpectedClientError:+ def test_status_ranges(self):+ from litellm.litellm_core_utils.core_helpers import is_expected_client_error++ class WithStatusCode(Exception):+ def __init__(self, status_code):+ self.status_code = status_code++ class WithCode(Exception):+ def __init__(self, code):+ self.code = code++ assert is_expected_client_error(WithStatusCode(400)) is True+ assert is_expected_client_error(WithStatusCode(429)) is True+ assert is_expected_client_error(WithStatusCode(499)) is True+ assert is_expected_client_error(WithStatusCode(500)) is False+ assert is_expected_client_error(WithStatusCode(399)) is False+ assert is_expected_client_error(WithCode("403")) is True+ assert is_expected_client_error(WithCode("invalid_request_error")) is False+ assert is_expected_client_error(Exception("no status")) is False+ assert is_expected_client_error(None) is Falsediff --git a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py b/tests/test_litellm/litellm_core_utils/test_litellm_logging.pyindex cc738d68016..f93daa61570 100644--- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py+++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py@@ -5678,3 +5678,62 @@ def test_get_custom_logger_compatible_class_finds_v2_newrelic(monkeypatch):logging_module._in_memory_loggers.clear()monkeypatch.delenv("LITELLM_OTEL_V2", raising=False)is_otel_v2_enabled.cache_clear()+++class _ClientError(Exception):+ def __init__(self, status_code, message):+ self.status_code = status_code+ self.message = message+ super().__init__(message)+++def _raise_and_catch(exc):+ try:+ raise exc+ except Exception as caught:+ return caught+++def test_get_error_information_skips_traceback_for_expected_4xx(monkeypatch):+ """Regression for LIT-6043: expected client (4xx) errors must not pay for+ traceback.format_tb on every rejected request unless+ litellm.log_client_error_tracebacks is enabled."""+ from litellm.litellm_core_utils.litellm_logging import StandardLoggingPayloadSetup++ client_exc = _raise_and_catch(_ClientError(status_code=403, message="team does not allow model"))+ assert client_exc.__traceback__ is not None+ result = StandardLoggingPayloadSetup.get_error_information(client_exc)+ assert result["traceback"] == ""++ server_exc = _raise_and_catch(_ClientError(status_code=500, message="boom"))+ result = StandardLoggingPayloadSetup.get_error_information(server_exc)+ assert "test_litellm_logging" in result["traceback"]++ monkeypatch.setattr(litellm, "log_client_error_tracebacks", True)+ result = StandardLoggingPayloadSetup.get_error_information(client_exc)+ assert "test_litellm_logging" in result["traceback"]+++def test_failure_handler_helper_fn_builds_payload_once_per_exception():+ """Regression for LIT-6043: async and sync failure handlers both call+ _failure_handler_helper_fn for the same failed request; the standardized+ payload must be built once, not once per handler."""+ obj = LitellmLogging(+ model="gpt-4o",+ messages=[{"role": "user", "content": "Hey"}],+ stream=False,+ call_type="acompletion",+ start_time=time.time(),+ litellm_call_id="lit-6043-1",+ function_id="f",+ )+ exc = _raise_and_catch(_ClientError(status_code=400, message="invalid model"))+ obj._failure_handler_helper_fn(exception=exc, traceback_exception="")+ first_payload = obj.model_call_details["standard_logging_object"]+ assert first_payload is not None+ obj._failure_handler_helper_fn(exception=exc, traceback_exception="")+ assert obj.model_call_details["standard_logging_object"] is first_payload++ other_exc = _raise_and_catch(_ClientError(status_code=429, message="rate limited"))+ obj._failure_handler_helper_fn(exception=other_exc, traceback_exception="")+ assert obj.model_call_details["standard_logging_object"] is not first_payloaddiff --git a/tests/test_litellm/proxy/auth/test_auth_exception_handler.py b/tests/test_litellm/proxy/auth/test_auth_exception_handler.pyindex b0094b81112..90b3b29d919 100644--- a/tests/test_litellm/proxy/auth/test_auth_exception_handler.py+++ b/tests/test_litellm/proxy/auth/test_auth_exception_handler.py@@ -701,3 +701,58 @@ async def test_auth_failure_ip_stamp_does_not_mutate_callers_request_data():)assert request_data == {"model": "gpt-4o"}+++ "auth_error,expect_traceback",+ [+ pytest.param(+ ProxyException(+ message="Authentication Error", type=ProxyErrorTypes.auth_error, param=None, code=401+ ),+ False,+ id="expected_401_no_traceback",+ ),+ pytest.param(ValueError("unexpected internal error"), True, id="unexpected_error_keeps_traceback"),+ ],+)+async def test_handle_authentication_error_traceback_only_for_unexpected_errors(auth_error, expect_traceback, caplog):+ """Regression for LIT-6043: expected 4xx auth rejections must not format a+ traceback via logger.exception; unexpected errors must keep it."""+ handler = UserAPIKeyAuthExceptionHandler()++ with (+ patch( # test-quality-ok: handler reads proxy_server globals at call time+ "litellm.proxy.proxy_server.proxy_logging_obj.post_call_failure_hook",+ new_callable=AsyncMock,+ return_value=None,+ ),+ patch( # test-quality-ok: handler reads proxy_server globals at call time+ "litellm.proxy.auth.auth_exception_handler.seed_request_identity",+ ),+ patch( # test-quality-ok: handler reads proxy_server globals at call time+ "litellm.proxy.proxy_server.general_settings",+ {"allow_requests_on_db_unavailable": False},+ ),+ ):+ verbose_proxy_logger.propagate = True+ try:+ try:+ raise auth_error+ except (ProxyException, ValueError) as caught:+ with caplog.at_level("ERROR", logger="LiteLLM Proxy"), pytest.raises(ProxyException):+ await handler._handle_authentication_error(+ caught,+ MagicMock(),+ {},+ "/v1/chat/completions",+ None,+ "sk-bad-key",+ )+ finally:+ verbose_proxy_logger.propagate = False++ records = [r for r in caplog.records if "user_api_key_auth(): Exception occured" in r.getMessage()]+ assert len(records) == 1+ assert (records[0].exc_info is not None) is expect_tracebackdiff --git a/tests/test_litellm/proxy/test_common_request_processing.py b/tests/test_litellm/proxy/test_common_request_processing.pyindex c9b3e5faf8b..b595c44d2ce 100644--- a/tests/test_litellm/proxy/test_common_request_processing.py+++ b/tests/test_litellm/proxy/test_common_request_processing.py@@ -7343,3 +7343,31 @@ class TestRouterModelNameOnNonStreamingResponse:)assert response[ROUTER_MODEL_NAME_RESPONSE_FIELD] == "deep-model"+++ "exc,expect_traceback",+ [+ pytest.param(HTTPException(status_code=400, detail="Invalid model name passed in"), False, id="expected_400"),+ pytest.param(ValueError("unexpected internal error"), True, id="unexpected_error"),+ ],+)+def test_log_llm_api_exception_traceback_only_for_unexpected_errors(exc, expect_traceback, caplog):+ """Regression for LIT-6043: expected 4xx errors log without formatting a+ traceback; unexpected errors keep logger.exception behavior."""+ from litellm._logging import verbose_proxy_logger+ from litellm.proxy.common_request_processing import _log_llm_api_exception++ verbose_proxy_logger.propagate = True+ try:+ with caplog.at_level("ERROR", logger="LiteLLM Proxy"):+ try:+ raise exc+ except Exception as raised:+ _log_llm_api_exception(raised)+ finally:+ verbose_proxy_logger.propagate = False++ records = [r for r in caplog.records if "_handle_llm_api_exception(): Exception occured" in r.getMessage()]+ assert len(records) == 1+ assert (records[0].exc_info is not None) is expect_tracebackdiff --git a/tests/test_litellm/proxy/test_proxy_utils.py b/tests/test_litellm/proxy/test_proxy_utils.pyindex fb01216982f..6920cc0dae3 100644--- a/tests/test_litellm/proxy/test_proxy_utils.py+++ b/tests/test_litellm/proxy/test_proxy_utils.py@@ -11,7 +11,6 @@ from litellm.proxy.utils import ProxyLoggingfrom litellm.types.guardrails import GuardrailEventHooks-from unittest.mock import MagicMock, patchfrom litellm.proxy.utils import get_custom_url, join_paths@@ -82,9 +81,7 @@ async def test_proxy_only_error_log_marks_no_upstream_llm_call():captured = {}def fake_pre_call(self, *args, **kwargs):- captured["flag"] = self.model_call_details.get(- LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL- )+ captured["flag"] = self.model_call_details.get(LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL)from litellm.litellm_core_utils.litellm_logging import Logging@@ -102,9 +99,7 @@ async def test_proxy_only_error_log_marks_no_upstream_llm_call():"model": "gpt-4o","messages": [{"role": "user", "content": "hi"}],},- user_api_key_dict=UserAPIKeyAuth(- api_key="sk-bad", request_route="/v1/chat/completions"- ),+ user_api_key_dict=UserAPIKeyAuth(api_key="sk-bad", request_route="/v1/chat/completions"),route="/v1/chat/completions",original_exception=Exception("bad key"),)@@ -148,13 +143,9 @@ async def test_proxy_only_error_log_keeps_litellm_metadata_in_litellm_params():request_data={"model": "gpt-4o","input": "blocked prompt",- "litellm_metadata": {- "standard_logging_guardrail_information": guardrail_info- },+ "litellm_metadata": {"standard_logging_guardrail_information": guardrail_info},},- user_api_key_dict=UserAPIKeyAuth(- api_key="sk-1234", request_route="/v1/responses"- ),+ user_api_key_dict=UserAPIKeyAuth(api_key="sk-1234", request_route="/v1/responses"),route="/v1/responses",original_exception=HTTPException(status_code=400, detail="blocked"),)@@ -163,12 +154,7 @@ async def test_proxy_only_error_log_keeps_litellm_metadata_in_litellm_params():Logging.pre_call = orig_pre_callLogging.async_failure_handler = orig_async_failure- assert (- captured["litellm_params"]["litellm_metadata"][- "standard_logging_guardrail_information"- ]- == guardrail_info- )+ assert captured["litellm_params"]["litellm_metadata"]["standard_logging_guardrail_information"] == guardrail_infoassert "litellm_metadata" not in captured["optional_params"]@@ -206,9 +192,7 @@ def test_get_model_group_info_order():def test_join_paths_no_duplication():"""Test that join_paths doesn't duplicate route when base_path already ends with it"""- result = join_paths(- base_path="http://0.0.0.0:4000/my-custom-path/", route="/my-custom-path"- )+ result = join_paths(base_path="http://0.0.0.0:4000/my-custom-path/", route="/my-custom-path")assert result == "http://0.0.0.0:4000/my-custom-path"@@ -814,9 +798,9 @@ class TestPostCallFailureHookEstimatesDispatchedInputTokens:estimated = request_data["combined_usage_object"]assert isinstance(estimated, Usage)- expected = litellm_module.token_counter(model="gpt-3.5-turbo", messages=messages) + litellm_module.token_counter(- model="gpt-3.5-turbo", text=system_prompt- )+ expected = litellm_module.token_counter(+ model="gpt-3.5-turbo", messages=messages+ ) + litellm_module.token_counter(model="gpt-3.5-turbo", text=system_prompt)assert estimated.prompt_tokens == expected@pytest.mark.asyncio@@ -834,7 +818,9 @@ class TestPostCallFailureHookEstimatesDispatchedInputTokens:estimated = request_data["combined_usage_object"]assert isinstance(estimated, Usage)- expected = litellm_module.token_counter(model="gpt-3.5-turbo", messages=messages) + litellm_module.token_counter(+ expected = litellm_module.token_counter(+ model="gpt-3.5-turbo", messages=messages+ ) + litellm_module.token_counter(model="gpt-3.5-turbo", text="part one of the system prompt. part two of the system prompt.")assert estimated.prompt_tokens == expected@@ -870,9 +856,9 @@ class TestPostCallFailureHookEstimatesDispatchedInputTokens:estimated = request_data["combined_usage_object"]assert isinstance(estimated, Usage)- expected = litellm_module.token_counter(model="gpt-3.5-turbo", messages=messages) + litellm_module.token_counter(- model="gpt-3.5-turbo", text=system_prompt- )+ expected = litellm_module.token_counter(+ model="gpt-3.5-turbo", messages=messages+ ) + litellm_module.token_counter(model="gpt-3.5-turbo", text=system_prompt)assert estimated.prompt_tokens == expected@pytest.mark.asyncio@@ -890,9 +876,9 @@ class TestPostCallFailureHookEstimatesDispatchedInputTokens:estimated = request_data["combined_usage_object"]assert isinstance(estimated, Usage)- expected = litellm_module.token_counter(model="gpt-3.5-turbo", messages=messages) + litellm_module.token_counter(- model="gpt-3.5-turbo", text=dispatched_system- )+ expected = litellm_module.token_counter(+ model="gpt-3.5-turbo", messages=messages+ ) + litellm_module.token_counter(model="gpt-3.5-turbo", text=dispatched_system)assert estimated.prompt_tokens == expected@@ -916,9 +902,7 @@ def test_create_model_info_response_includes_max_tokens_from_lookup():model_id="some-model",provider="openai",llm_router=None,- get_model_info=lambda _model: _fake_model_info(- max_input_tokens=128000, max_output_tokens=16384- ),+ get_model_info=lambda _model: _fake_model_info(max_input_tokens=128000, max_output_tokens=16384),)assert response["id"] == "some-model"@@ -935,9 +919,7 @@ def test_create_model_info_response_does_not_call_router_group_info():model_id="some-model",provider="openai",llm_router=router,- get_model_info=lambda _model: _fake_model_info(- max_input_tokens=128000, max_output_tokens=16384- ),+ get_model_info=lambda _model: _fake_model_info(max_input_tokens=128000, max_output_tokens=16384),)router.get_model_group_info.assert_not_called()@@ -968,9 +950,7 @@ def test_create_model_info_response_deployment_limits_override_cost_map():model_id="gpt-4o",provider="openai",llm_router=router,- get_model_info=lambda _model: _fake_model_info(- max_input_tokens=128000, max_output_tokens=16384- ),+ get_model_info=lambda _model: _fake_model_info(max_input_tokens=128000, max_output_tokens=16384),)assert response["max_input_tokens"] == 200000@@ -1008,9 +988,7 @@ def test_create_model_info_response_survives_malformed_cost_map_limits(bad_valuemodel_id="some-model",provider="openai",llm_router=None,- get_model_info=lambda _model: _fake_model_info(- max_input_tokens=bad_value, max_output_tokens=bad_value- ),+ get_model_info=lambda _model: _fake_model_info(max_input_tokens=bad_value, max_output_tokens=bad_value),)assert response["id"] == "some-model"@@ -1023,9 +1001,7 @@ def test_create_model_info_response_keeps_valid_cost_map_limit_beside_malformed_model_id="some-model",provider="openai",llm_router=None,- get_model_info=lambda _model: _fake_model_info(- max_input_tokens="128,000", max_output_tokens=16384- ),+ get_model_info=lambda _model: _fake_model_info(max_input_tokens="128,000", max_output_tokens=16384),)assert "max_input_tokens" not in response@@ -1068,9 +1044,7 @@ def test_create_model_info_response_emits_integer_token_counts():model_id="some-model",provider="openai",llm_router=None,- get_model_info=lambda _model: _fake_model_info(- max_input_tokens=128000, max_output_tokens=16384- ),+ get_model_info=lambda _model: _fake_model_info(max_input_tokens=128000, max_output_tokens=16384),)assert isinstance(response["max_input_tokens"], int)@@ -1119,9 +1093,7 @@ def test_create_model_info_response_no_router_keeps_base_fields():def test_create_model_info_response_reads_real_cost_map():- response = create_model_info_response(- model_id="gpt-4o", provider="openai", llm_router=None- )+ response = create_model_info_response(model_id="gpt-4o", provider="openai", llm_router=None)assert isinstance(response["max_input_tokens"], int)assert response["max_input_tokens"] > 0@@ -1205,10 +1177,7 @@ class TestPostCallFailureHookLLMExceptionAlerting:@pytest.mark.asyncioasync def test_http_exception_does_not_alert(self):- assert (- await self._alerted(HTTPException(status_code=400, detail="blocked"))- is False- )+ assert await self._alerted(HTTPException(status_code=400, detail="blocked")) is False@pytest.mark.asyncioasync def test_genuine_llm_api_error_still_alerts(self):@@ -1241,9 +1210,7 @@ class TestPostCallFailureHookProxyExceptionLogging:await proxy_logging_obj.post_call_failure_hook(request_data={},original_exception=exc,- user_api_key_dict=UserAPIKeyAuth(- api_key="sk-test", request_route=request_route- ),+ user_api_key_dict=UserAPIKeyAuth(api_key="sk-test", request_route=request_route),)return handle_mock.await_count > 0@@ -1260,20 +1227,12 @@ class TestPostCallFailureHookProxyExceptionLogging:@pytest.mark.asyncioasync def test_proxy_exception_on_llm_route_is_logged(self):- assert (- await self._logged(self._block(), request_route="/v1/chat/completions")- is True- )+ assert await self._logged(self._block(), request_route="/v1/chat/completions") is True@pytest.mark.asyncioasync def test_generic_exception_on_llm_route_is_not_logged(self):# A raw provider/unknown exception is logged by the LLM call path, not here.- assert (- await self._logged(- Exception("upstream 503"), request_route="/v1/chat/completions"- )- is False- )+ assert await self._logged(Exception("upstream 503"), request_route="/v1/chat/completions") is Falseclass TestShouldUseSmtpSsl:@@ -1307,9 +1266,7 @@ class TestCreateSmtpConnection:patch("smtplib.SMTP_SSL") as mock_smtp_ssl,patch("smtplib.SMTP") as mock_smtp,):- result = _create_smtp_connection(- smtp_host="mail.example.com", smtp_port=465- )+ result = _create_smtp_connection(smtp_host="mail.example.com", smtp_port=465)mock_smtp.assert_not_called()assert result is mock_smtp_ssl.return_value@@ -1329,9 +1286,7 @@ class TestCreateSmtpConnection:patch("smtplib.SMTP_SSL") as mock_smtp_ssl,patch("smtplib.SMTP") as mock_smtp,):- result = _create_smtp_connection(- smtp_host="mail.example.com", smtp_port=587- )+ result = _create_smtp_connection(smtp_host="mail.example.com", smtp_port=587)mock_smtp_ssl.assert_not_called()assert result is mock_smtp.return_value@@ -1352,9 +1307,7 @@ class TestSendEmailStartTls:monkeypatch.delenv("SMTP_USE_SSL", raising=False)mock_server = MagicMock(spec=smtplib.SMTP)- with patch(- "litellm.proxy.utils._create_smtp_connection"- ) as mock_create_connection:+ with patch("litellm.proxy.utils._create_smtp_connection") as mock_create_connection:mock_create_connection.return_value.__enter__.return_value = mock_serverawait send_email(receiver_email="[email protected]",@@ -1690,9 +1643,7 @@ def test_a_failed_dispatch_is_estimated_as_input_only():usage = _estimate_dispatched_failure_usage(FAILURE_USAGE_MODEL, ONE_USER_MESSAGE, None)assert usage is not None- assert usage.prompt_tokens == _count_request_input_tokens(- FAILURE_USAGE_MODEL, ONE_USER_MESSAGE, None- )+ assert usage.prompt_tokens == _count_request_input_tokens(FAILURE_USAGE_MODEL, ONE_USER_MESSAGE, None)assert usage.completion_tokens == 0assert usage.total_tokens == usage.prompt_tokens@@ -1759,9 +1710,7 @@ def test_a_request_that_reached_a_provider_bills_its_input_at_no_cost():def test_a_failure_that_cost_the_provider_nothing_lifts_nothing(model_call_details, dispatched):from litellm.proxy.utils import _failure_usage_to_lift- assert _failure_usage_to_lift(- model_call_details=model_call_details, request_body={}, dispatched=dispatched- ) is None+ assert _failure_usage_to_lift(model_call_details=model_call_details, request_body={}, dispatched=dispatched) is Nonedef test_the_no_upstream_call_key_the_module_uses_is_the_one_asserted_above():@@ -1829,3 +1778,102 @@ def test_a_dispatched_failure_lifts_the_four_fields_the_spend_log_needs():assert lifted["response_cost"] == 0.0assert lifted["combined_usage_object"].prompt_tokens > 0assert lifted["standard_logging_object"] == {"id": "log-1"}+++async def test_proxy_only_error_expected_4xx_skips_traceback_for_both_handlers(monkeypatch):+ """Regression for LIT-6043: an expected 4xx must not format a traceback for+ either the async or the threaded sync failure handler."""+ import asyncio++ import litellm+ from litellm.litellm_core_utils.litellm_logging import Logging+ from litellm.proxy._types import UserAPIKeyAuth++ monkeypatch.setattr(litellm, "failure_callback", [])+ proxy_logging_obj = ProxyLogging(user_api_key_cache=DualCache())+ captured = {}+ sync_ran = asyncio.Event()+ loop = asyncio.get_running_loop()++ async def fake_async_failure(self, exception, traceback_exception, *args, **kwargs):+ captured["async_traceback"] = traceback_exception++ def fake_sync_failure(self, exception, traceback_exception, *args, **kwargs):+ captured["sync_traceback"] = traceback_exception+ loop.call_soon_threadsafe(sync_ran.set)++ orig_async_failure = Logging.async_failure_handler+ orig_sync_failure = Logging.failure_handler+ Logging.async_failure_handler = fake_async_failure+ Logging.failure_handler = fake_sync_failure+ try:+ try:+ raise HTTPException(status_code=400, detail="Invalid model name passed in")+ except HTTPException as exc:+ await proxy_logging_obj._handle_logging_proxy_only_error(+ request_data={+ "model": "does-not-exist",+ "messages": [{"role": "user", "content": "hi"}],+ },+ user_api_key_dict=UserAPIKeyAuth(api_key="sk-1234", request_route="/v1/chat/completions"),+ route="/v1/chat/completions",+ original_exception=exc,+ )+ await asyncio.wait_for(sync_ran.wait(), timeout=5)+ finally:+ Logging.async_failure_handler = orig_async_failure+ Logging.failure_handler = orig_sync_failure++ assert captured["async_traceback"] == ""+ assert captured["sync_traceback"] == ""+++async def test_proxy_only_error_5xx_keeps_traceback_and_runs_sync_callbacks(monkeypatch):+ """Unexpected (5xx) errors keep the full traceback, and a configured+ sync-only failure callback still gets its threaded handler."""+ import asyncio++ import litellm+ from litellm.litellm_core_utils.litellm_logging import Logging+ from litellm.proxy._types import UserAPIKeyAuth++ def _custom_sync_callback(kwargs, completion_response, start_time, end_time):+ pass++ monkeypatch.setattr(litellm, "failure_callback", [_custom_sync_callback])+ proxy_logging_obj = ProxyLogging(user_api_key_cache=DualCache())+ captured = {}+ sync_ran = asyncio.Event()+ loop = asyncio.get_running_loop()++ async def fake_async_failure(self, exception, traceback_exception, *args, **kwargs):+ captured["async_traceback"] = traceback_exception++ def fake_sync_failure(self, *args, **kwargs):+ loop.call_soon_threadsafe(sync_ran.set)++ orig_async_failure = Logging.async_failure_handler+ orig_sync_failure = Logging.failure_handler+ Logging.async_failure_handler = fake_async_failure+ Logging.failure_handler = fake_sync_failure+ try:+ try:+ raise HTTPException(status_code=500, detail="internal error")+ except HTTPException as exc:+ await proxy_logging_obj._handle_logging_proxy_only_error(+ request_data={+ "model": "gpt-4o",+ "messages": [{"role": "user", "content": "hi"}],+ },+ user_api_key_dict=UserAPIKeyAuth(api_key="sk-1234", request_route="/v1/chat/completions"),+ route="/v1/chat/completions",+ original_exception=exc,+ )+ await asyncio.wait_for(sync_ran.wait(), timeout=5)+ finally:+ Logging.async_failure_handler = orig_async_failure+ Logging.failure_handler = orig_sync_failure++ assert "test_proxy_utils" in captured["async_traceback"]