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]

fix(sdk): keep body and proxy headers on BadRequestError mapped from a litellm_proxy 400

mateo-berric0c0c9a9ebc7
diff --git a/litellm/constants.py b/litellm/constants.py
index 5751e6e46af..caf1aff6792 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -1964,7 +1964,11 @@ BROWSER_SECURITY_HEADERS: Final[frozenset[str]] = frozenset(
}
)
-UNSAFE_PROXY_RESPONSE_HEADERS: Final[frozenset[str]] = HTTP_FRAMING_HEADERS | BROWSER_SECURITY_HEADERS
+ORIGIN_SERVER_HEADERS: Final[frozenset[str]] = frozenset({"date", "server"})
+
+UNSAFE_PROXY_RESPONSE_HEADERS: Final[frozenset[str]] = (
+ HTTP_FRAMING_HEADERS | BROWSER_SECURITY_HEADERS | ORIGIN_SERVER_HEADERS
+)
# A retrieved response replays the usage of the call that created it, so pricing these
# read/management routes like inference bills the same tokens twice.
diff --git a/litellm/exceptions.py b/litellm/exceptions.py
index 3f22a4b2dcd..3d9e26e450b 100644
--- a/litellm/exceptions.py
+++ b/litellm/exceptions.py
@@ -10,7 +10,7 @@
## LiteLLM versions of the OpenAI Exception Types
import enum
-from collections.abc import Sequence
+from collections.abc import Mapping, Sequence
from typing import Any, Final
import httpx
@@ -226,6 +226,7 @@ class BadRequestError(openai.BadRequestError):
max_retries: int | None = None,
num_retries: int | None = None,
body: dict | None = None,
+ headers: Mapping[str, str] | None = None,
):
self.status_code = 400
self.message = f"litellm.BadRequestError: {message}"
@@ -234,6 +235,7 @@ class BadRequestError(openai.BadRequestError):
self.litellm_debug_info = litellm_debug_info
self.max_retries = max_retries
self.num_retries = num_retries
+ self.headers: dict[str, str] | None = {k: str(v) for k, v in headers.items()} if headers else None
# Use response if it's a valid httpx.Response with a request, otherwise use minimal error response
# Note: We check _request (not .request property) to avoid RuntimeError when _request is None
if (
diff --git a/litellm/litellm_core_utils/exception_mapping_utils.py b/litellm/litellm_core_utils/exception_mapping_utils.py
index 82708d412c9..fd1ba666887 100644
--- a/litellm/litellm_core_utils/exception_mapping_utils.py
+++ b/litellm/litellm_core_utils/exception_mapping_utils.py
@@ -1,6 +1,7 @@
import json
import re
import traceback
+from collections.abc import Mapping
from typing import Any, Final, Protocol, cast
import httpx
@@ -254,6 +255,15 @@ class _ProviderHTTPException(Protocol):
llm_provider: str
+def _litellm_proxy_response_headers(
+ original_exception: _ProviderHTTPException, custom_llm_provider: str
+) -> Mapping[str, str] | None:
+ if custom_llm_provider != "litellm_proxy":
+ return None
+ headers: Final = getattr(original_exception, "headers", None)
+ return headers if isinstance(headers, Mapping) else None
+
+
def _map_openai_exception(
*,
model: str,
@@ -264,6 +274,7 @@ def _map_openai_exception(
exception_provider: str,
extra_information: str,
) -> None:
+ upstream_headers: Final = _litellm_proxy_response_headers(original_exception, custom_llm_provider)
# custom_llm_provider is openai, make it OpenAI
message = get_error_message(error_obj=original_exception)
if message is None:
@@ -348,6 +359,7 @@ def _map_openai_exception(
response=getattr(original_exception, "response", None),
litellm_debug_info=extra_information,
body=getattr(original_exception, "body", None),
+ headers=upstream_headers,
)
elif "invalid_request_error" in error_str and "Incorrect API key provided" not in error_str:
raise BadRequestError(
@@ -357,6 +369,7 @@ def _map_openai_exception(
response=getattr(original_exception, "response", None),
litellm_debug_info=extra_information,
body=getattr(original_exception, "body", None),
+ headers=upstream_headers,
)
elif (
"Web server is returning an unknown error" in error_str
@@ -404,6 +417,8 @@ def _map_openai_exception(
model=model,
response=getattr(original_exception, "response", None),
litellm_debug_info=extra_information,
+ body=getattr(original_exception, "body", None),
+ headers=upstream_headers,
)
elif original_exception.status_code == 401:
raise AuthenticationError(
@@ -436,6 +451,7 @@ def _map_openai_exception(
response=getattr(original_exception, "response", None),
litellm_debug_info=extra_information,
body=getattr(original_exception, "body", None),
+ headers=upstream_headers,
)
elif original_exception.status_code == 429:
raise RateLimitError(
diff --git a/litellm/proxy/common_utils/openai_error_payload.py b/litellm/proxy/common_utils/openai_error_payload.py
index 89f735ee8b6..90b3c998247 100644
--- a/litellm/proxy/common_utils/openai_error_payload.py
+++ b/litellm/proxy/common_utils/openai_error_payload.py
@@ -8,6 +8,8 @@ from typing import Final
from fastapi import status
+_STRINGIFIED_NONE: Final = "None"
+
_OPENAI_ERROR_TYPE_BY_STATUS: Final[Mapping[int, str]] = MappingProxyType(
{
status.HTTP_401_UNAUTHORIZED: "authentication_error",
@@ -35,7 +37,7 @@ def openai_error_type(exc: object, status_code: int) -> str:
"""OpenAI types ``error.type`` as a required string, so an exception carrying none
falls back to the type its status code stands for."""
carried: Final = attribute_of(exc, "type")
- if isinstance(carried, str):
+ if isinstance(carried, str) and carried != _STRINGIFIED_NONE:
return carried
mapped: Final = _OPENAI_ERROR_TYPE_BY_STATUS.get(status_code)
if mapped is not None:
@@ -49,4 +51,4 @@ def openai_error_param(exc: object) -> str | None:
"""OpenAI types ``error.param`` as nullable, so an exception carrying none
serializes as JSON ``null``."""
carried: Final = attribute_of(exc, "param")
- return carried if isinstance(carried, str) else None
+ return carried if isinstance(carried, str) and carried != _STRINGIFIED_NONE else None
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.py
index 42d3df76902..ea6ac17ad45 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
@@ -1409,3 +1409,71 @@ def test_bedrock_timeout_mapping_keeps_retry_after_readable(status_code):
exception_headers = _get_response_headers(original_exception=exc_info.value)
assert exception_headers is not None
assert litellm.utils._get_retry_after_from_exception_header(response_headers=exception_headers) == 7
+
+
+_GUARDRAIL_BLOCK_ERROR = {
+ "message": "Content blocked: secret_project_codename pattern detected",
+ "param": "None",
+ "code": "400",
+ "provider_specific_fields": {
+ "error": "Content blocked: secret_project_codename pattern detected",
+ "pattern": "secret_project_codename",
+ "guardrail_name": "block-secret-project",
+ "guardrail_mode": "pre_call",
+ },
+}
+
+
+def _openai_handler_error(error_type: str, headers: dict[str, str]) -> OpenAIError:
+ """What litellm/llms/openai/openai.py raises after the openai SDK rejects a 400:
+ the SDK's str() carries the wire body, and the handler copies headers and body over."""
+ wire_error = {**_GUARDRAIL_BLOCK_ERROR, "type": error_type}
+ wire = httpx.Response(
+ status_code=400,
+ headers=headers,
+ json={"error": wire_error},
+ request=httpx.Request("POST", "http://localhost:4000/v1/chat/completions"),
+ )
+ return OpenAIError(
+ status_code=400,
+ message=f"Error code: 400 - {{'error': {wire_error}}}",
+ headers=wire.headers,
+ body=wire_error,
+ )
+
+
[email protected]("error_type", ["None", "invalid_request_error"])
+def test_litellm_proxy_guardrail_block_keeps_body_and_headers(error_type: str):
+ """An SDK caller behind a proxy tells a guardrail block from any other 400 by the body's
+ provider_specific_fields and the proxy's x-litellm-* headers, so the mapped BadRequestError
+ must carry both whichever error.type the proxy version on the other end emits."""
+ proxy_headers = {"x-litellm-call-id": "call-guardrail", "x-litellm-applied-guardrails": "block-secret-project"}
+
+ with pytest.raises(litellm.BadRequestError) as exc_info:
+ exception_type(
+ model="claude-haiku-4-5",
+ original_exception=_openai_handler_error(error_type, proxy_headers),
+ custom_llm_provider="litellm_proxy",
+ completion_kwargs={},
+ extra_kwargs={},
+ )
+
+ assert exc_info.value.body["provider_specific_fields"]["guardrail_name"] == "block-secret-project"
+ assert exc_info.value.body["type"] == error_type
+ assert proxy_headers.items() <= exc_info.value.headers.items()
+
+
+def test_openai_compatible_vendor_400_keeps_body_but_not_headers():
+ """A vendor's own response headers stay on e.response the way every other mapped provider
+ error keeps them; only a LiteLLM proxy upstream puts headers on e.headers."""
+ with pytest.raises(litellm.BadRequestError) as exc_info:
+ exception_type(
+ model="gpt-5.4-mini",
+ original_exception=_openai_handler_error("vendor_specific_error", {"openai-organization": "org-1"}),
+ custom_llm_provider="openai",
+ completion_kwargs={},
+ extra_kwargs={},
+ )
+
+ assert exc_info.value.body["type"] == "vendor_specific_error"
+ assert exc_info.value.headers is None
diff --git a/tests/test_litellm/proxy/common_utils/test_openai_error_payload.py b/tests/test_litellm/proxy/common_utils/test_openai_error_payload.py
index 8b653ddfb71..db9fe3a2253 100644
--- a/tests/test_litellm/proxy/common_utils/test_openai_error_payload.py
+++ b/tests/test_litellm/proxy/common_utils/test_openai_error_payload.py
@@ -143,3 +143,21 @@ def test_a_status_carried_by_an_exception_drives_the_type_it_reports():
exc = HTTPException(status_code=403, detail="blocked by policy")
assert openai_error_type(exc, error_status_code(exc, 400)) == "permission_error"
+
+
+def test_the_stringified_none_an_older_upstream_proxy_sent_is_treated_as_absent():
+ """A proxy fronting a proxy older than 1.102 receives {"type": "None", "param": "None"} on
+ the wire; the SDK now keeps that body on the mapped exception, and re-emitting the literal
+ is the exact bug this module exists to stop."""
+ from litellm.exceptions import BadRequestError
+
+ carried = BadRequestError(
+ message="Content blocked",
+ model="claude-haiku-4-5",
+ llm_provider="litellm_proxy",
+ body={"message": "Content blocked", "type": "None", "param": "None", "code": "400"},
+ )
+
+ assert carried.type == "None"
+ assert openai_error_type(carried, 400) == "invalid_request_error"
+ assert openai_error_param(carried) is None
diff --git a/tests/test_litellm/proxy/test_common_request_processing.py b/tests/test_litellm/proxy/test_common_request_processing.py
index 69e89d1c604..3cb58c44354 100644
--- a/tests/test_litellm/proxy/test_common_request_processing.py
+++ b/tests/test_litellm/proxy/test_common_request_processing.py
@@ -3985,6 +3985,21 @@ class TestHandleLLMApiExceptionFramingHeaders:
assert proxy_exc.headers["x-custom-safe"] == "1"
assert proxy_exc.headers["x-request-id"] == "abc-123"
+ async def test_strips_the_date_and_server_headers_of_an_upstream_litellm_proxy(self):
+ """A proxy fronting another LiteLLM proxy gets the upstream's date and server
+ on the mapped exception; forwarding them would duplicate the Date header
+ uvicorn adds to every response and leak the upstream server identity."""
+ exc = litellm.BadRequestError(
+ message="Content blocked",
+ llm_provider="litellm_proxy",
+ model="claude-haiku-4-5",
+ headers={"date": "Sun, 13 Sep 2026 08:43:51 GMT", "server": "uvicorn", "x-request-id": "abc-123"},
+ )
+ proxy_exc = await self._invoke(exc)
+ assert "date" not in proxy_exc.headers
+ assert "server" not in proxy_exc.headers
+ assert proxy_exc.headers["x-request-id"] == "abc-123"
+
class TestAsyncStreamingDataGeneratorFastPath:
"""Fast/slow path branching in async_streaming_data_generator."""
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index 7eadaa6c991..839aa52fa84 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -16781,7 +16781,6 @@ export interface paths {
* - permissions: Optional[dict] - [Not Implemented Yet] User-specific permissions, eg. turning off pii masking.
* - metadata: Optional[dict] - Metadata for user, store information for user. Example metadata = {"team": "core-infra", "app": "app2", "email": "[email protected]" }
* - max_parallel_requests: Optional[int] - Rate limit a user based on the number of parallel requests. Raises 429 error, if user's parallel requests > x.
- * - soft_budget: Optional[float] - Get alerts when user crosses given budget, doesn't block requests.
* - model_max_budget: Optional[dict] - Model-specific max budget for user. [Docs](https://docs.litellm.ai/docs/proxy/users#add-model-specific-budgets-to-keys)
* - budget_fallbacks: Optional[Dict[str, List[str]]] - Per-model fallback chain tried in order when that model's own `model_max_budget` is exceeded, e.g. {"gpt-4o": ["gpt-4o-mini"]}.
* - model_rpm_limit: Optional[float] - Model-specific rpm limit for user. [Docs](https://docs.litellm.ai/docs/proxy/users#add-model-specific-limits-to-keys)
@@ -16887,7 +16886,6 @@ export interface paths {
* - permissions: Optional[dict] - [Not Implemented Yet] User-specific permissions, eg. turning off pii masking.
* - metadata: Optional[dict] - Metadata for user, store information for user. Example metadata = {"team": "core-infra", "app": "app2", "email": "[email protected]" }
* - max_parallel_requests: Optional[int] - Rate limit a user based on the number of parallel requests. Raises 429 error, if user's parallel requests > x.
- * - soft_budget: Optional[float] - Get alerts when user crosses given budget, doesn't block requests.
* - model_max_budget: Optional[dict] - Model-specific max budget for user. [Docs](https://docs.litellm.ai/docs/proxy/users#add-model-specific-budgets-to-keys)
* - budget_fallbacks: Optional[Dict[str, List[str]]] - Per-model fallback chain tried in order when that model's own `model_max_budget` is exceeded, e.g. {"gpt-4o": ["gpt-4o-mini"]}.
* - model_rpm_limit: Optional[float] - Model-specific rpm limit for user. [Docs](https://docs.litellm.ai/docs/proxy/users#add-model-specific-limits-to-keys)