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(exceptions): map upstream status codes for providers with no exception_type branch
mateo-berri53037c34ed04
diff --git a/litellm/litellm_core_utils/exception_mapping_utils.py b/litellm/litellm_core_utils/exception_mapping_utils.pyindex 4ee726b67de..bfa86a3df6e 100644--- a/litellm/litellm_core_utils/exception_mapping_utils.py+++ b/litellm/litellm_core_utils/exception_mapping_utils.py@@ -755,12 +755,19 @@ def _map_openai_like_exception(llm_provider=custom_llm_provider,model=model,)- elif original_exception.status_code == 401 or original_exception.status_code == 403:+ elif original_exception.status_code == 401:raise AuthenticationError(message=f"{custom_llm_provider.capitalize()}Exception - {original_exception.message}",llm_provider=custom_llm_provider,model=model,)+ elif original_exception.status_code == 403:+ raise PermissionDeniedError(+ message=f"{custom_llm_provider.capitalize()}Exception - {original_exception.message}",+ llm_provider=custom_llm_provider,+ model=model,+ response=_response_or_stub(original_exception, status_code=403),+ )elif original_exception.status_code == 400:raise BadRequestError(message=f"{custom_llm_provider.capitalize()}Exception - {original_exception.message}",@@ -2187,6 +2194,120 @@ def _map_openrouter_exception()+def _response_or_stub(original_exception: _ProviderHTTPException, status_code: int) -> httpx.Response:+ response: Final = original_exception.response if hasattr(original_exception, "response") else None+ if response is not None:+ return response+ return httpx.Response(+ status_code=status_code, request=httpx.Request(method="POST", url="https://docs.litellm.ai/docs")+ )+++def _map_exception_by_status(+ *,+ model: str,+ original_exception: _ProviderHTTPException,+ custom_llm_provider: str,+ error_str: str,+ exception_provider: str,+ extra_information: str,+) -> None:+ status_code: Final = original_exception.status_code if hasattr(original_exception, "status_code") else None+ if not isinstance(status_code, int) or status_code < 400:+ return+ message: Final = f"{exception_provider} - {error_str}"+ response: Final = original_exception.response if hasattr(original_exception, "response") else None+ match status_code:+ case 401:+ raise AuthenticationError(+ message=message,+ llm_provider=custom_llm_provider,+ model=model,+ response=response,+ litellm_debug_info=extra_information,+ )+ case 403:+ raise PermissionDeniedError(+ message=message,+ llm_provider=custom_llm_provider,+ model=model,+ response=_response_or_stub(original_exception, status_code=status_code),+ litellm_debug_info=extra_information,+ )+ case 404:+ raise NotFoundError(+ message=message,+ model=model,+ llm_provider=custom_llm_provider,+ response=response,+ litellm_debug_info=extra_information,+ )+ case 408:+ raise Timeout(+ message=message,+ model=model,+ llm_provider=custom_llm_provider,+ litellm_debug_info=extra_information,+ )+ case 429:+ raise RateLimitError(+ message=message,+ model=model,+ llm_provider=custom_llm_provider,+ response=response,+ litellm_debug_info=extra_information,+ )+ case 500:+ raise InternalServerError(+ message=message,+ llm_provider=custom_llm_provider,+ model=model,+ response=response,+ litellm_debug_info=extra_information,+ )+ case 502:+ raise BadGatewayError(+ message=message,+ llm_provider=custom_llm_provider,+ model=model,+ response=response,+ litellm_debug_info=extra_information,+ )+ case 503:+ raise ServiceUnavailableError(+ message=message,+ llm_provider=custom_llm_provider,+ model=model,+ response=response,+ litellm_debug_info=extra_information,+ )+ case 504:+ raise Timeout(+ message=message,+ model=model,+ llm_provider=custom_llm_provider,+ litellm_debug_info=extra_information,+ exception_status_code=status_code,+ )+ case _ if status_code < 500:+ raise BadRequestError(+ message=message,+ model=model,+ llm_provider=custom_llm_provider,+ response=response,+ litellm_debug_info=extra_information,+ )+ case _:+ raise APIError(+ status_code=status_code,+ message=message,+ llm_provider=custom_llm_provider,+ model=model,+ request=original_exception.request if hasattr(original_exception, "request") else None,+ litellm_debug_info=extra_information,+ )++def exception_type(model,original_exception,@@ -2501,6 +2622,14 @@ def exception_type(For unmapped exceptions - raise the exception with traceback - https://github.com/BerriAI/litellm/issues/4201"""exception_mapping_worked = True+ _map_exception_by_status(+ model=model,+ original_exception=mappable_exception,+ custom_llm_provider=custom_llm_provider,+ error_str=error_str,+ exception_provider=exception_provider,+ extra_information=extra_information,+ )if hasattr(original_exception, "request"):raise APIConnectionError(message=f"{exception_provider} - {error_str}",diff --git a/tests/test_litellm/litellm_core_utils/test_exception_mapping_utils.py b/tests/test_litellm/litellm_core_utils/test_exception_mapping_utils.pyindex 6f7ea9da640..895044c8ad5 100644--- a/tests/test_litellm/litellm_core_utils/test_exception_mapping_utils.py+++ b/tests/test_litellm/litellm_core_utils/test_exception_mapping_utils.py@@ -13,6 +13,7 @@ from litellm.litellm_core_utils.exception_mapping_utils import (extract_and_raise_litellm_exception,)from litellm.llms.openai.common_utils import OpenAIError+from litellm.types.utils import LlmProviders# Test cases for is_error_str_context_window_exceeded# Tuple format: (error_message, expected_result)@@ -785,33 +786,24 @@ OPENAI_SHAPED = {503: (litellm.ServiceUnavailableError, 503),}-UPSTREAM_STATUS_DISCARDED = (litellm.APIConnectionError, 500)+PERMISSION_DENIED = (litellm.PermissionDeniedError, 403)-PROVIDERS_THAT_DISCARD_THE_UPSTREAM_STATUS = ("cloudflare", "ollama", "vllm")+STATUS_KEYED = {**OPENAI_SHAPED, 403: PERMISSION_DENIED}DEVIATIONS_FROM_THE_OPENAI_SHAPE = {- "anthropic": {403: UPSTREAM_STATUS_DISCARDED, 422: UPSTREAM_STATUS_DISCARDED},+ "anthropic": {403: PERMISSION_DENIED},"azure": {500: (litellm.APIError, 500)},"bedrock": {- 403: UPSTREAM_STATUS_DISCARDED,+ 403: PERMISSION_DENIED,500: (litellm.ServiceUnavailableError, 503),},- "cohere": {- 401: UPSTREAM_STATUS_DISCARDED,- 403: UPSTREAM_STATUS_DISCARDED,- 404: UPSTREAM_STATUS_DISCARDED,- 422: UPSTREAM_STATUS_DISCARDED,- 429: UPSTREAM_STATUS_DISCARDED,- 503: UPSTREAM_STATUS_DISCARDED,- },+ "cloudflare": {403: PERMISSION_DENIED},+ "cohere": {403: PERMISSION_DENIED},"databricks": {- 403: (litellm.AuthenticationError, 401),+ 403: PERMISSION_DENIED,422: (litellm.BadRequestError, 400),},- "gemini": {- 403: (litellm.PermissionDeniedError, 403),- 422: UPSTREAM_STATUS_DISCARDED,- },+ "gemini": {403: PERMISSION_DENIED},"huggingface": {404: (litellm.APIError, 404),422: (litellm.APIError, 422),@@ -824,6 +816,7 @@ DEVIATIONS_FROM_THE_OPENAI_SHAPE = {500: (litellm.APIError, 500),503: (litellm.APIError, 503),},+ "ollama": {403: PERMISSION_DENIED},"openrouter": {500: (litellm.APIError, 500)},"replicate": {403: (litellm.APIError, 500),@@ -833,17 +826,11 @@ DEVIATIONS_FROM_THE_OPENAI_SHAPE = {503: (litellm.APIError, 500),},"sagemaker": {- 403: UPSTREAM_STATUS_DISCARDED,+ 403: PERMISSION_DENIED,500: (litellm.ServiceUnavailableError, 503),},- "vertex_ai": {- 403: (litellm.PermissionDeniedError, 403),- 422: UPSTREAM_STATUS_DISCARDED,- },- **{- provider: dict.fromkeys(UPSTREAM_STATUS_CODES, UPSTREAM_STATUS_DISCARDED)- for provider in PROVIDERS_THAT_DISCARD_THE_UPSTREAM_STATUS- },+ "vertex_ai": {403: PERMISSION_DENIED},+ "vllm": {403: PERMISSION_DENIED},}PROVIDERS_WITH_A_HANDLER = (@@ -875,6 +862,38 @@ PROVIDERS_WITH_A_HANDLER = ("xai",)+PROVIDER_ALIASES_WITH_A_HANDLER = (+ "aleph_alpha",+ "anthropic_text",+ "azure_text",+ "bedrock_mantle",+ "cohere_chat",+ "custom_openai",+ "lemonade",+ "litellm_proxy",+ "ollama_chat",+ "predibase",+ "sagemaker_chat",+ "text-completion-openai",+ "vertex_ai_beta",+ "watsonx",+)++PROVIDERS_WITHOUT_A_HANDLER = tuple(+ sorted(+ frozenset(provider.value for provider in LlmProviders)+ - frozenset(PROVIDERS_WITH_A_HANDLER)+ - frozenset(PROVIDER_ALIASES_WITH_A_HANDLER)+ - frozenset(litellm.openai_compatible_providers)+ )+)++MINIMAX_401_BODY = (+ '{"type":"error","error":{"type":"authorized_error","message":"login fail: Please carry the API secret key '+ "in the 'Authorization' field of the request header (1004)\",\"http_code\":\"401\"},"+ '"request_id":"06ddc9ba97ee6340e38f10e09787f547"}'+)+def _expected_for(provider: str, status_code: int) -> tuple[type[Exception], int]:return DEVIATIONS_FROM_THE_OPENAI_SHAPE.get(provider, {}).get(@@ -938,6 +957,51 @@ def test_an_already_mapped_litellm_exception_passes_through_untouched(assert returned is already_mapped[email protected]("status_code", UPSTREAM_STATUS_CODES)[email protected]("provider", PROVIDERS_WITHOUT_A_HANDLER)+def test_a_provider_without_a_handler_maps_by_the_upstream_status(+ provider, status_code, quiet_exception_mapping+):+ expected_class, expected_status = STATUS_KEYED[status_code]++ with pytest.raises(openai.APIError) as raised:+ exception_type(+ model="test-model",+ original_exception=_UpstreamHTTPError(status_code=status_code),+ custom_llm_provider=provider,+ )++ assert type(raised.value) is expected_class+ assert raised.value.status_code == expected_status+ assert raised.value.llm_provider == provider+ assert raised.value.model == "test-model"+++def test_a_minimax_bad_key_is_an_authentication_error(quiet_exception_mapping):+ from litellm.llms.base_llm.chat.transformation import BaseLLMException++ with pytest.raises(litellm.AuthenticationError) as raised:+ exception_type(+ model="MiniMax-M2.5",+ original_exception=BaseLLMException(status_code=401, message=MINIMAX_401_BODY),+ custom_llm_provider="minimax",+ )++ assert raised.value.status_code == 401+ assert raised.value.llm_provider == "minimax"+ assert raised.value.message.startswith("litellm.AuthenticationError: MinimaxException - ")+ assert "login fail" in raised.value.message+++def test_an_exception_without_a_status_is_still_a_connection_error(quiet_exception_mapping):+ with pytest.raises(litellm.APIConnectionError):+ exception_type(+ model="MiniMax-M2.5",+ original_exception=RuntimeError("socket hung up"),+ custom_llm_provider="minimax",+ )++CONTEXT_WINDOW_MESSAGE = "This model's maximum context length is 4096 tokens."CONTENT_POLICY_MESSAGE = ('{"error": {"type": "invalid_request_error", "code": "content_policy_violation"}}'@@ -993,9 +1057,7 @@ class _UpstreamErrorWithMessage(_UpstreamHTTPError):def test_a_full_context_window_reaches_the_caller_as_the_router_needs_it(provider, quiet_exception_mapping):- if provider in PROVIDERS_THAT_DISCARD_THE_UPSTREAM_STATUS:- expected_class, expected_status = UPSTREAM_STATUS_DISCARDED- elif provider in PROVIDERS_THAT_RECOGNISE_A_FULL_CONTEXT_WINDOW:+ if provider in PROVIDERS_THAT_RECOGNISE_A_FULL_CONTEXT_WINDOW:expected_class, expected_status = litellm.ContextWindowExceededError, 400else:expected_class, expected_status = litellm.BadRequestError, 400@@ -1015,9 +1077,7 @@ def test_a_full_context_window_reaches_the_caller_as_the_router_needs_it(def test_a_content_policy_block_reaches_the_caller_as_the_router_needs_it(provider, quiet_exception_mapping):- if provider in PROVIDERS_THAT_DISCARD_THE_UPSTREAM_STATUS:- expected_class, expected_status = UPSTREAM_STATUS_DISCARDED- elif provider in PROVIDERS_THAT_RECOGNISE_A_CONTENT_POLICY_BLOCK:+ if provider in PROVIDERS_THAT_RECOGNISE_A_CONTENT_POLICY_BLOCK:expected_class, expected_status = litellm.ContentPolicyViolationError, 400else:expected_class, expected_status = litellm.BadRequestError, 400diff --git a/tests/test_litellm/llms/base_llm/search/test_base_search_transformation.py b/tests/test_litellm/llms/base_llm/search/test_base_search_transformation.pyindex e6aad7688d1..35a54332f66 100644--- a/tests/test_litellm/llms/base_llm/search/test_base_search_transformation.py+++ b/tests/test_litellm/llms/base_llm/search/test_base_search_transformation.py@@ -322,7 +322,7 @@ async def test_query_param_key_not_leaked_with_dummy_caller_key("litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.get",fake_get,):- with pytest.raises(litellm.APIConnectionError):+ with pytest.raises(litellm.InternalServerError):await litellm.asearch(query="secrets",search_provider=provider,diff --git a/tests/test_litellm/llms/compactifai/test_compactifai.py b/tests/test_litellm/llms/compactifai/test_compactifai.pyindex fef0baf2884..fd31049731a 100644--- a/tests/test_litellm/llms/compactifai/test_compactifai.py+++ b/tests/test_litellm/llms/compactifai/test_compactifai.py@@ -172,7 +172,7 @@ def test_compactifai_authentication_error(respx_mock):json=mock_error, status_code=401)- with pytest.raises(litellm.APIConnectionError) as exc_info:+ with pytest.raises(litellm.AuthenticationError) as exc_info:litellm.completion(model="compactifai/cai-llama-3-1-8b-slim",messages=[{"role": "user", "content": "test"}],diff --git a/tests/test_litellm/llms/langflow/chat/test_langflow_chat_transformation.py b/tests/test_litellm/llms/langflow/chat/test_langflow_chat_transformation.pyindex 0c241add77b..383a7afbe93 100644--- a/tests/test_litellm/llms/langflow/chat/test_langflow_chat_transformation.py+++ b/tests/test_litellm/llms/langflow/chat/test_langflow_chat_transformation.py@@ -233,7 +233,7 @@ def test_langflow_extra_body_cannot_inject_tweaks_into_run_payload():return respwith patch.object(HTTPHandler, "post", side_effect=fake_post):- with pytest.raises(litellm.APIConnectionError):+ with pytest.raises(litellm.BadRequestError):litellm.completion(model="langflow/my-flow",messages=[{"role": "user", "content": "hello"}],diff --git a/tests/test_litellm/llms/vertex_ai/vertex_gemma_models/test_vertex_gemma_transformation.py b/tests/test_litellm/llms/vertex_ai/vertex_gemma_models/test_vertex_gemma_transformation.pyindex 39af9f08540..5f74f0f602f 100644--- a/tests/test_litellm/llms/vertex_ai/vertex_gemma_models/test_vertex_gemma_transformation.py+++ b/tests/test_litellm/llms/vertex_ai/vertex_gemma_models/test_vertex_gemma_transformation.py@@ -238,7 +238,7 @@ class TestVertexGemmaCompletion:Expected: Proper error handling when 'predictions' field is missing"""- from litellm.exceptions import APIConnectionError+ from litellm.exceptions import BadRequestError# Invalid response without predictions fieldinvalid_response = {@@ -260,8 +260,8 @@ class TestVertexGemmaCompletion:mock_client.post = AsyncMock(return_value=mock_response)mock_get_client.return_value = mock_client- # Should raise exception (wrapped as APIConnectionError by LiteLLM)- with pytest.raises(APIConnectionError) as exc_info:+ # Should raise exception (wrapped as BadRequestError by LiteLLM)+ with pytest.raises(BadRequestError) as exc_info:await litellm.acompletion(model="vertex_ai/gemma/gemma-3-12b-it",messages=[{"role": "user", "content": "Test"}],