Skip to content

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]

Add `retry-after` header support for errors `502`, `503`, `504` (#16288)

Andrii Kislitsync497b6f239fb
diff --git a/litellm/__init__.py b/litellm/__init__.py
index 20fe4a2aeac..bf7d609d2a6 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -4,8 +4,10 @@ import warnings
warnings.filterwarnings("ignore", message=".*conflict with protected namespace.*")
# Suppress Pydantic 2.11+ deprecation warning about accessing model_fields on instances
# This warning can accumulate during streaming and cause memory leaks
-warnings.filterwarnings("ignore", message=".*Accessing the.*attribute on the instance is deprecated.*")
-### INIT VARIABLES #######################
+warnings.filterwarnings(
+ "ignore", message=".*Accessing the.*attribute on the instance is deprecated.*"
+)
+### INIT VARIABLES ######################
import threading
import os
from typing import (
@@ -179,22 +181,22 @@ prometheus_initialize_budget_metrics: Optional[bool] = False
require_auth_for_metrics_endpoint: Optional[bool] = False
argilla_batch_size: Optional[int] = None
datadog_use_v1: Optional[bool] = False # if you want to use v1 datadog logged payload.
-gcs_pub_sub_use_v1: Optional[bool] = (
- False # if you want to use v1 gcs pubsub logged payload
-)
-generic_api_use_v1: Optional[bool] = (
- False # if you want to use v1 generic api logged payload
-)
+gcs_pub_sub_use_v1: Optional[
+ bool
+] = False # if you want to use v1 gcs pubsub logged payload
+generic_api_use_v1: Optional[
+ bool
+] = False # if you want to use v1 generic api logged payload
argilla_transformation_object: Optional[Dict[str, Any]] = None
-_async_input_callback: List[Union[str, Callable, CustomLogger]] = (
- []
-) # internal variable - async custom callbacks are routed here.
-_async_success_callback: List[Union[str, Callable, CustomLogger]] = (
- []
-) # internal variable - async custom callbacks are routed here.
-_async_failure_callback: List[Union[str, Callable, CustomLogger]] = (
- []
-) # internal variable - async custom callbacks are routed here.
+_async_input_callback: List[
+ Union[str, Callable, CustomLogger]
+] = [] # internal variable - async custom callbacks are routed here.
+_async_success_callback: List[
+ Union[str, Callable, CustomLogger]
+] = [] # internal variable - async custom callbacks are routed here.
+_async_failure_callback: List[
+ Union[str, Callable, CustomLogger]
+] = [] # internal variable - async custom callbacks are routed here.
pre_call_rules: List[Callable] = []
post_call_rules: List[Callable] = []
turn_off_message_logging: Optional[bool] = False
@@ -202,18 +204,18 @@ log_raw_request_response: bool = False
redact_messages_in_exceptions: Optional[bool] = False
redact_user_api_key_info: Optional[bool] = False
filter_invalid_headers: Optional[bool] = False
-add_user_information_to_llm_headers: Optional[bool] = (
- None # adds user_id, team_id, token hash (params from StandardLoggingMetadata) to request headers
-)
+add_user_information_to_llm_headers: Optional[
+ bool
+] = None # adds user_id, team_id, token hash (params from StandardLoggingMetadata) to request headers
store_audit_logs = False # Enterprise feature, allow users to see audit logs
### end of callbacks #############
-email: Optional[str] = (
- None # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
-)
-token: Optional[str] = (
- None # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
-)
+email: Optional[
+ str
+] = None # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
+token: Optional[
+ str
+] = None # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
telemetry = True
max_tokens: int = DEFAULT_MAX_TOKENS # OpenAI Defaults
drop_params = bool(os.getenv("LITELLM_DROP_PARAMS", False))
@@ -269,9 +271,9 @@ use_client: bool = False
ssl_verify: Union[str, bool] = True
ssl_security_level: Optional[str] = None
ssl_certificate: Optional[str] = None
-ssl_ecdh_curve: Optional[str] = (
- None # Set to 'X25519' to disable PQC and improve performance
-)
+ssl_ecdh_curve: Optional[
+ str
+] = None # Set to 'X25519' to disable PQC and improve performance
disable_streaming_logging: bool = False
disable_token_counter: bool = False
disable_add_transform_inline_image_block: bool = False
@@ -317,24 +319,20 @@ enable_loadbalancing_on_batch_endpoints: Optional[bool] = None
enable_caching_on_provider_specific_optional_params: bool = (
False # feature-flag for caching on optional params - e.g. 'top_k'
)
-caching: bool = (
- False # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
-)
-caching_with_models: bool = (
- False # # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
-)
-cache: Optional[Cache] = (
- None # cache object <- use this - https://docs.litellm.ai/docs/caching
-)
+caching: bool = False # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
+caching_with_models: bool = False # # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648
+cache: Optional[
+ Cache
+] = None # cache object <- use this - https://docs.litellm.ai/docs/caching
default_in_memory_ttl: Optional[float] = None
default_redis_ttl: Optional[float] = None
default_redis_batch_cache_expiry: Optional[float] = None
model_alias_map: Dict[str, str] = {}
model_group_settings: Optional["ModelGroupSettings"] = None
max_budget: float = 0.0 # set the max budget across all providers
-budget_duration: Optional[str] = (
- None # proxy only - resets budget after fixed duration. You can set duration as seconds ("30s"), minutes ("30m"), hours ("30h"), days ("30d").
-)
+budget_duration: Optional[
+ str
+] = None # proxy only - resets budget after fixed duration. You can set duration as seconds ("30s"), minutes ("30m"), hours ("30h"), days ("30d").
default_soft_budget: float = (
DEFAULT_SOFT_BUDGET # by default all litellm proxy keys have a soft budget of 50.0
)
@@ -343,15 +341,11 @@ forward_traceparent_to_llm_provider: bool = False
_current_cost = 0.0 # private variable, used if max budget is set
error_logs: Dict = {}
-add_function_to_prompt: bool = (
- False # if function calling not supported by api, append function call details to system prompt
-)
+add_function_to_prompt: bool = False # if function calling not supported by api, append function call details to system prompt
client_session: Optional[httpx.Client] = None
aclient_session: Optional[httpx.AsyncClient] = None
model_fallbacks: Optional[List] = None # Deprecated for 'litellm.fallbacks'
-model_cost_map_url: str = (
- "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"
-)
+model_cost_map_url: str = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json"
suppress_debug_info = False
dynamodb_table_name: Optional[str] = None
s3_callback_params: Optional[Dict] = None
@@ -381,9 +375,7 @@ prometheus_metrics_config: Optional[List] = None
disable_add_prefix_to_prompt: bool = (
False # used by anthropic, to disable adding prefix to prompt
)
-disable_copilot_system_to_assistant: bool = (
- False # If false (default), converts all 'system' role messages to 'assistant' for GitHub Copilot compatibility. Set to true to disable this behavior.
-)
+disable_copilot_system_to_assistant: bool = False # If false (default), converts all 'system' role messages to 'assistant' for GitHub Copilot compatibility. Set to true to disable this behavior.
public_model_groups: Optional[List[str]] = None
public_model_groups_links: Dict[str, str] = {}
#### REQUEST PRIORITIZATION #######
@@ -394,17 +386,13 @@ priority_reservation_settings: "PriorityReservationSettings" = (
######## Networking Settings ########
-use_aiohttp_transport: bool = (
- True # Older variable, aiohttp is now the default. use disable_aiohttp_transport instead.
-)
+use_aiohttp_transport: bool = True # Older variable, aiohttp is now the default. use disable_aiohttp_transport instead.
aiohttp_trust_env: bool = False # set to true to use HTTP_ Proxy settings
disable_aiohttp_transport: bool = False # Set this to true to use httpx instead
disable_aiohttp_trust_env: bool = (
False # When False, aiohttp will respect HTTP(S)_PROXY env vars
)
-force_ipv4: bool = (
- False # when True, litellm will force ipv4 for all LLM requests. Some users have seen httpx ConnectionError when using ipv6.
-)
+force_ipv4: bool = False # when True, litellm will force ipv4 for all LLM requests. Some users have seen httpx ConnectionError when using ipv6.
module_level_aclient = AsyncHTTPHandler(
timeout=request_timeout, client_alias="module level aclient"
)
@@ -418,13 +406,13 @@ fallbacks: Optional[List] = None
context_window_fallbacks: Optional[List] = None
content_policy_fallbacks: Optional[List] = None
allowed_fails: int = 3
-num_retries_per_request: Optional[int] = (
- None # for the request overall (incl. fallbacks + model retries)
-)
+num_retries_per_request: Optional[
+ int
+] = None # for the request overall (incl. fallbacks + model retries)
####### SECRET MANAGERS #####################
-secret_manager_client: Optional[Any] = (
- None # list of instantiated key management clients - e.g. azure kv, infisical, etc.
-)
+secret_manager_client: Optional[
+ Any
+] = None # list of instantiated key management clients - e.g. azure kv, infisical, etc.
_google_kms_resource_name: Optional[str] = None
_key_management_system: Optional[KeyManagementSystem] = None
_key_management_settings: KeyManagementSettings = KeyManagementSettings()
@@ -434,9 +422,9 @@ output_parse_pii: bool = False
from litellm.litellm_core_utils.get_model_cost_map import get_model_cost_map
model_cost = get_model_cost_map(url=model_cost_map_url)
-cost_discount_config: Dict[str, float] = (
- {}
-) # Provider-specific cost discounts {"vertex_ai": 0.05} = 5% discount
+cost_discount_config: Dict[
+ str, float
+] = {} # Provider-specific cost discounts {"vertex_ai": 0.05} = 5% discount
custom_prompt_dict: Dict[str, dict] = {}
check_provider_endpoint = False
@@ -1345,6 +1333,7 @@ from .exceptions import (
NotFoundError,
RateLimitError,
ServiceUnavailableError,
+ BadGatewayError,
OpenAIError,
ContextWindowExceededError,
ContentPolicyViolationError,
@@ -1400,12 +1389,12 @@ from .types.llms.custom_llm import CustomLLMItem
from .types.utils import GenericStreamingChunk
custom_provider_map: List[CustomLLMItem] = []
-_custom_providers: List[str] = (
- []
-) # internal helper util, used to track names of custom providers
-disable_hf_tokenizer_download: Optional[bool] = (
- None # disable huggingface tokenizer download. Defaults to openai clk100
-)
+_custom_providers: List[
+ str
+] = [] # internal helper util, used to track names of custom providers
+disable_hf_tokenizer_download: Optional[
+ bool
+] = None # disable huggingface tokenizer download. Defaults to openai clk100
global_disable_no_log_param: bool = False
### CLI UTILITIES ###
diff --git a/litellm/exceptions.py b/litellm/exceptions.py
index ccb3ce90e9c..ae4b7c99a3e 100644
--- a/litellm/exceptions.py
+++ b/litellm/exceptions.py
@@ -501,8 +501,62 @@ class ServiceUnavailableError(openai.APIStatusError): # type: ignore
self.litellm_debug_info = litellm_debug_info
self.max_retries = max_retries
self.num_retries = num_retries
+ _response_headers = (
+ getattr(response, "headers", None) if response is not None else None
+ )
self.response = httpx.Response(
status_code=self.status_code,
+ headers=_response_headers,
+ request=httpx.Request(
+ method="POST",
+ url=" https://cloud.google.com/vertex-ai/",
+ ),
+ )
+ super().__init__(
+ self.message, response=self.response, body=None
+ ) # Call the base class constructor with the parameters it needs
+
+ def __str__(self):
+ _message = self.message
+ if self.num_retries:
+ _message += f" LiteLLM Retried: {self.num_retries} times"
+ if self.max_retries:
+ _message += f", LiteLLM Max Retries: {self.max_retries}"
+ return _message
+
+ def __repr__(self):
+ _message = self.message
+ if self.num_retries:
+ _message += f" LiteLLM Retried: {self.num_retries} times"
+ if self.max_retries:
+ _message += f", LiteLLM Max Retries: {self.max_retries}"
+ return _message
+
+
+class BadGatewayError(openai.APIStatusError): # type: ignore
+ def __init__(
+ self,
+ message,
+ llm_provider,
+ model,
+ response: Optional[httpx.Response] = None,
+ litellm_debug_info: Optional[str] = None,
+ max_retries: Optional[int] = None,
+ num_retries: Optional[int] = None,
+ ):
+ self.status_code = 502
+ self.message = "litellm.BadGatewayError: {}".format(message)
+ self.llm_provider = llm_provider
+ self.model = model
+ self.litellm_debug_info = litellm_debug_info
+ self.max_retries = max_retries
+ self.num_retries = num_retries
+ _response_headers = (
+ getattr(response, "headers", None) if response is not None else None
+ )
+ self.response = httpx.Response(
+ status_code=self.status_code,
+ headers=_response_headers,
request=httpx.Request(
method="POST",
url=" https://cloud.google.com/vertex-ai/",
@@ -547,8 +601,12 @@ class InternalServerError(openai.InternalServerError): # type: ignore
self.litellm_debug_info = litellm_debug_info
self.max_retries = max_retries
self.num_retries = num_retries
+ _response_headers = (
+ getattr(response, "headers", None) if response is not None else None
+ )
self.response = httpx.Response(
status_code=self.status_code,
+ headers=_response_headers,
request=httpx.Request(
method="POST",
url=" https://cloud.google.com/vertex-ai/",
@@ -754,6 +812,7 @@ LITELLM_EXCEPTION_TYPES = [
ContentPolicyViolationError,
InternalServerError,
ServiceUnavailableError,
+ BadGatewayError,
APIError,
APIConnectionError,
APIResponseValidationError,
diff --git a/litellm/litellm_core_utils/exception_mapping_utils.py b/litellm/litellm_core_utils/exception_mapping_utils.py
index 61551b04236..4bd9cb82f04 100644
--- a/litellm/litellm_core_utils/exception_mapping_utils.py
+++ b/litellm/litellm_core_utils/exception_mapping_utils.py
@@ -12,6 +12,7 @@ from ..exceptions import (
APIConnectionError,
APIError,
AuthenticationError,
+ BadGatewayError,
BadRequestError,
ContentPolicyViolationError,
ContextWindowExceededError,
@@ -43,16 +44,16 @@ class ExceptionCheckers:
"""
if not isinstance(error_str, str):
return False
-
+
if "429" in error_str or "rate limit" in error_str.lower():
return True
-
+
#######################################
# Mistral API returns this error string
#########################################
if "service tier capacity exceeded" in error_str.lower():
return True
-
+
return False
@staticmethod
@@ -507,6 +508,15 @@ def exception_type( # type: ignore # noqa: PLR0915
response=getattr(original_exception, "response", None),
litellm_debug_info=extra_information,
)
+ elif original_exception.status_code == 502:
+ exception_mapping_worked = True
+ raise BadGatewayError(
+ message=f"BadGatewayError: {exception_provider} - {message}",
+ model=model,
+ llm_provider=custom_llm_provider,
+ response=getattr(original_exception, "response", None),
+ litellm_debug_info=extra_information,
+ )
elif original_exception.status_code == 503:
exception_mapping_worked = True
raise ServiceUnavailableError(
@@ -637,6 +647,15 @@ def exception_type( # type: ignore # noqa: PLR0915
message=f"AnthropicException - {error_str}. Handle with `litellm.InternalServerError`.",
llm_provider="anthropic",
model=model,
+ response=getattr(original_exception, "response", None),
+ )
+ elif original_exception.status_code == 502:
+ exception_mapping_worked = True
+ raise BadGatewayError(
+ message=f"AnthropicException BadGatewayError - {error_str}",
+ llm_provider="anthropic",
+ model=model,
+ response=getattr(original_exception, "response", None),
)
elif original_exception.status_code == 503:
exception_mapping_worked = True
@@ -644,6 +663,15 @@ def exception_type( # type: ignore # noqa: PLR0915
message=f"AnthropicException - {error_str}. Handle with `litellm.ServiceUnavailableError`.",
llm_provider="anthropic",
model=model,
+ response=getattr(original_exception, "response", None),
+ )
+ elif original_exception.status_code == 504: # gateway timeout error
+ exception_mapping_worked = True
+ raise Timeout(
+ message=f"AnthropicException Timeout - {error_str}",
+ model=model,
+ llm_provider="anthropic",
+ exception_status_code=original_exception.status_code,
)
elif custom_llm_provider == "replicate":
if "Incorrect authentication token" in error_str:
@@ -2089,6 +2117,15 @@ def exception_type( # type: ignore # noqa: PLR0915
litellm_debug_info=extra_information,
response=getattr(original_exception, "response", None),
)
+ elif original_exception.status_code == 502:
+ exception_mapping_worked = True
+ raise BadGatewayError(
+ message=f"AzureException BadGatewayError - {message}",
+ model=model,
+ llm_provider="azure",
+ litellm_debug_info=extra_information,
+ response=getattr(original_exception, "response", None),
+ )
elif original_exception.status_code == 503:
exception_mapping_worked = True
raise ServiceUnavailableError(
diff --git a/tests/test_litellm/litellm_core_utils/test_retry_after_headers.py b/tests/test_litellm/litellm_core_utils/test_retry_after_headers.py
new file mode 100644
index 00000000000..5717eab5a06
--- /dev/null
+++ b/tests/test_litellm/litellm_core_utils/test_retry_after_headers.py
@@ -0,0 +1,147 @@
+"""
+Test that retry-after headers are properly preserved for status codes 502, 503, and 504.
+
+This test module verifies that:
+1. BadGatewayError exception exists and preserves retry-after headers
+2. ServiceUnavailableError preserves retry-after headers
+3. InternalServerError preserves retry-after headers
+4. All these exceptions are in LITELLM_EXCEPTION_TYPES
+"""
+
+import httpx
+
+import litellm
+
+
+def test_bad_gateway_error_preserves_retry_after_header():
+ """Test that BadGatewayError preserves retry-after headers."""
+ response = httpx.Response(
+ status_code=502,
+ headers=httpx.Headers({"retry-after": "30"}),
+ request=httpx.Request("POST", "http://test.com"),
+ )
+
+ error = litellm.BadGatewayError(
+ message="Test bad gateway error",
+ llm_provider="test",
+ model="test-model",
+ response=response,
+ )
+
+ assert error.status_code == 502
+ assert "BadGatewayError" in str(error)
+ assert error.response is not None
+ assert error.response.headers is not None
+ assert "retry-after" in error.response.headers
+ assert error.response.headers["retry-after"] == "30"
+
+
+def test_service_unavailable_error_preserves_retry_after_header():
+ """Test that ServiceUnavailableError preserves retry-after headers."""
+ response = httpx.Response(
+ status_code=503,
+ headers=httpx.Headers({"retry-after": "60"}),
+ request=httpx.Request("POST", "http://test.com"),
+ )
+
+ error = litellm.ServiceUnavailableError(
+ message="Service unavailable",
+ llm_provider="test",
+ model="test-model",
+ response=response,
+ )
+
+ assert error.status_code == 503
+ assert error.response.headers is not None
+ assert "retry-after" in error.response.headers
+ assert error.response.headers["retry-after"] == "60"
+
+
+def test_internal_server_error_preserves_retry_after_header():
+ """Test that InternalServerError preserves retry-after headers."""
+ response = httpx.Response(
+ status_code=500,
+ headers=httpx.Headers({"retry-after": "45"}),
+ request=httpx.Request("POST", "http://test.com"),
+ )
+
+ error = litellm.InternalServerError(
+ message="Internal server error",
+ llm_provider="test",
+ model="test-model",
+ response=response,
+ )
+
+ assert error.status_code == 500
+ assert error.response.headers is not None
+ assert "retry-after" in error.response.headers
+ assert error.response.headers["retry-after"] == "45"
+
+
+def test_bad_gateway_error_in_exception_types():
+ """Test that BadGatewayError is in LITELLM_EXCEPTION_TYPES."""
+ assert litellm.BadGatewayError in litellm.LITELLM_EXCEPTION_TYPES
+
+
+def test_bad_gateway_error_attributes():
+ """Test that BadGatewayError has expected attributes."""
+ response = httpx.Response(
+ status_code=502,
+ headers=httpx.Headers({"retry-after": "20"}),
+ request=httpx.Request("POST", "http://test.com"),
+ )
+
+ error = litellm.BadGatewayError(
+ message="Test error",
+ llm_provider="openai",
+ model="gpt-3.5-turbo",
+ response=response,
+ max_retries=3,
+ num_retries=1,
+ )
+
+ assert error.status_code == 502
+ assert error.llm_provider == "openai"
+ assert error.model == "gpt-3.5-turbo"
+ assert error.max_retries == 3
+ assert error.num_retries == 1
+ assert "LiteLLM Retried: 1 times" in str(error)
+ assert "LiteLLM Max Retries: 3" in str(error)
+
+
+def test_exception_without_response_headers():
+ """Test that exceptions work even without response headers."""
+ # Test with None response
+ error = litellm.BadGatewayError(
+ message="Test error",
+ llm_provider="test",
+ model="test-model",
+ response=None,
+ )
+
+ assert error.status_code == 502
+ assert error.response is not None # Should create a default response
+ assert (
+ error.response.headers is not None
+ ) # Should have headers object (may be empty)
+
+
+def test_exception_with_empty_headers():
+ """Test that exceptions work with empty headers."""
+ response = httpx.Response(
+ status_code=502,
+ headers=httpx.Headers({}), # Empty headers
+ request=httpx.Request("POST", "http://test.com"),
+ )
+
+ error = litellm.BadGatewayError(
+ message="Test error",
+ llm_provider="test",
+ model="test-model",
+ response=response,
+ )
+
+ assert error.status_code == 502
+ assert error.response.headers is not None
+ # Should not have retry-after since we didn't provide it
+ assert "retry-after" not in error.response.headers