From 571a2a18b0f607dc9f2b4578251f008a162bee16 Mon Sep 17 00:00:00 2001 From: lewis Date: Sat, 3 Oct 2026 20:33:54 -0400 Subject: [PATCH] fix(exceptions): map OpenAI-compatible 401 invalid_request_error to AuthenticationError The invalid_request_error branch only exempted OpenAI's exact "Incorrect API key provided" wording, so a provider that returns 401 with a differently worded invalid_request_error body was raised as BadRequestError. Exempt every 401 so it reaches the status-code mapping. --- .../litellm_core_utils/exception_mapping_utils.py | 6 +++++- .../test_exception_mapping_utils.py | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/litellm/litellm_core_utils/exception_mapping_utils.py b/litellm/litellm_core_utils/exception_mapping_utils.py index 0fdfb301291..a5651f9da73 100644 --- a/litellm/litellm_core_utils/exception_mapping_utils.py +++ b/litellm/litellm_core_utils/exception_mapping_utils.py @@ -370,7 +370,11 @@ def _map_openai_exception( litellm_debug_info=extra_information, body=getattr(original_exception, "body", None), ) - elif "invalid_request_error" in error_str and "Incorrect API key provided" not in error_str: + elif ( + "invalid_request_error" in error_str + and "Incorrect API key provided" not in error_str + and getattr(original_exception, "status_code", None) != 401 + ): raise BadRequestError( message=f"{exception_provider} - {message}", llm_provider=custom_llm_provider, diff --git a/tests/unit/litellm_core_utils/test_exception_mapping_utils.py b/tests/unit/litellm_core_utils/test_exception_mapping_utils.py index 9de768ea47b..3dd979b6cc6 100644 --- a/tests/unit/litellm_core_utils/test_exception_mapping_utils.py +++ b/tests/unit/litellm_core_utils/test_exception_mapping_utils.py @@ -360,6 +360,21 @@ def test_openai_compatible_429_still_maps_to_rate_limit(): assert excinfo.value.status_code == 429 +@pytest.mark.parametrize("provider", ["deepinfra", "openai", "together_ai"]) +def test_openai_compatible_401_typed_invalid_request_maps_to_authentication(provider: str) -> None: + original_exception = OpenAIError( + status_code=401, + message='{"error":{"message":"Invalid API-key provided.","type":"invalid_request_error","code":"invalid_api_key"}}', + headers={}, + ) + + with pytest.raises(litellm.AuthenticationError) as excinfo: + exception_type(model="test-model", original_exception=original_exception, custom_llm_provider=provider) + + assert excinfo.value.status_code == 401 + assert excinfo.value.llm_provider == provider + + @pytest.mark.parametrize( "error_message", [