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.
This commit is contained in:
lewis 2026-10-03 20:33:54 -04:00
parent 02f61c9c42
commit 571a2a18b0
2 changed files with 20 additions and 1 deletions

View file

@ -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,

View file

@ -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",
[