Skip to content
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
0f79f10
fix(router): eagerly fetch deferred stream to surface HTTP errors in …
Jul 1, 2026
ba98bd0
fix(router): undo success_calls on deferred-stream fetch failure; bro…
Jul 14, 2026
e891a7d
fix(router): extract header-strip helper to keep _acompletion under s…
Jul 15, 2026
6c1511c
test(router): add unit tests for _strip_http_framing_headers to satis…
Jul 15, 2026
a1c933d
test(router): add sync _completion_streaming_iterator re-raise test f…
Jul 15, 2026
c7edad8
fix(router): restore Fallbacks context in no-fallback log; document u…
Jul 22, 2026
c63123d
fix(router): preserve original traceback in deferred stream fetch err…
Jul 23, 2026
a1ada63
style(test): restore black-style formatting in test_router.py
Jul 25, 2026
c1f1269
fix(router): re-raise mid-stream fallback on any generated content, n…
Jul 25, 2026
74c24a0
test(router): add direct coverage for _stream_chunks_have_generated_c…
Jul 25, 2026
e9fc5e5
revert(ui): drop incidental schema.d.ts regeneration
Jul 25, 2026
f2d8006
fix(proxy): strip framing headers on the pre-existing ProxyException …
Jul 25, 2026
98955e0
chore: retrigger CI (no GitHub Actions check-suite was created for th…
Jul 25, 2026
caad18a
fix(router): detect thinking_blocks as generated content in mid-strea…
Jul 26, 2026
471c324
fix(proxy): strip browser-facing security headers from provider excep…
Jul 28, 2026
3c0f29d
refactor(router): address maintainer review mechanicals
Jul 29, 2026
a778d05
revert(router): pull mid-stream continuation-removal out of this PR
Jul 29, 2026
b7e0a8d
fix(proxy): re-filter unsafe headers after the response-headers hook …
Jul 29, 2026
e661229
Revert "revert(router): pull mid-stream continuation-removal out of t…
Jul 29, 2026
3f0f138
fix(router): detect reasoning_items as generated content in mid-strea…
Jul 29, 2026
ebc3845
fix(router): annotate _stream_chunks_have_generated_content with Sequ…
Aug 4, 2026
70e47f4
fix(router): surface original provider exception, not the internal wr…
Aug 4, 2026
2f251ac
chore: retrigger CI (frontend-lint cancelled, schema.d.ts flake)
Aug 4, 2026
9389358
Merge branch 'litellm_internal_staging' into litellm_vertex_stream_fa…
yassin-berriai Aug 4, 2026
2d7a28a
chore: align with current litellm_internal_staging conventions
yassin-berriai Aug 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions litellm/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -1676,3 +1676,40 @@
"want to verify your reasoning, or face a complex decision. "
"Describe your question or challenge clearly in the 'question' field."
)

# Headers that must be stripped from a provider exception before it's forwarded as
# the proxy's own HTTP response, or they conflict with the framing the proxy sets.
HTTP_FRAMING_HEADERS: frozenset[str] = frozenset(
{
"content-length",
"transfer-encoding",
"content-encoding",
"content-type",
"set-cookie",
"cookie",
"proxy-authenticate",
"proxy-authorization",
}
)

# Browser-facing security headers that a malicious or misconfigured upstream
# provider must not be able to set on the proxy's own response.
BROWSER_SECURITY_HEADERS: frozenset[str] = frozenset(
{
"access-control-allow-origin",
"access-control-allow-credentials",
"access-control-allow-methods",
"access-control-allow-headers",
"access-control-expose-headers",
"content-security-policy",
"content-security-policy-report-only",
"clear-site-data",
"strict-transport-security",
"x-frame-options",
"cross-origin-opener-policy",
"cross-origin-embedder-policy",
"cross-origin-resource-policy",
}
)

UNSAFE_PROXY_RESPONSE_HEADERS: frozenset[str] = HTTP_FRAMING_HEADERS | BROWSER_SECURITY_HEADERS
7 changes: 6 additions & 1 deletion litellm/proxy/common_request_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
MAX_PAYLOAD_SIZE_FOR_DEBUG_LOG,
RETURN_RAW_MODEL_NAME_METADATA_KEY,
STREAM_SSE_DATA_PREFIX,
UNSAFE_PROXY_RESPONSE_HEADERS,
)
from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.litellm_core_utils.dd_tracing import NullTracer, tracer
Expand Down Expand Up @@ -2693,6 +2694,7 @@ async def _handle_llm_api_exception(
_response_headers = getattr(_response, "headers", None)
if _response_headers:
headers = get_response_headers(dict(_response_headers))
headers = {k: v for k, v in headers.items() if k.lower() not in UNSAFE_PROXY_RESPONSE_HEADERS}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
headers.update(custom_headers)

# Call response headers hook for failure
Expand All @@ -2708,13 +2710,16 @@ async def _handle_llm_api_exception(
except Exception:
pass

headers = {k: v for k, v in headers.items() if k.lower() not in UNSAFE_PROXY_RESPONSE_HEADERS}

self._apply_router_cooldown_retry_after(headers, e)

if isinstance(e, ProxyException):
e.headers = {
merged_headers = {
**e.headers,
**{k: v if isinstance(v, str) else str(v) for k, v in headers.items()},
}
e.headers = {k: v for k, v in merged_headers.items() if k.lower() not in UNSAFE_PROXY_RESPONSE_HEADERS}
raise e

if isinstance(e, HTTPException):
Expand Down
97 changes: 55 additions & 42 deletions litellm/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import time
import traceback
from collections import defaultdict
from collections.abc import AsyncGenerator, Callable, Generator, Mapping
from collections.abc import AsyncGenerator, Callable, Generator, Mapping, Sequence
from functools import lru_cache
from typing import (
TYPE_CHECKING,
Expand Down Expand Up @@ -308,6 +308,26 @@ def model_info_is_active_for_environment(model_info: Mapping[str, object] | None
_PreRoutingStrategyT = TypeVar("_PreRoutingStrategyT")


def _stream_chunks_have_generated_content(chunks: Sequence[ModelResponseStream]) -> bool:
for chunk in chunks:
if not chunk.choices:
continue
delta = chunk.choices[0].delta
if (
delta.get("content")
or delta.get("tool_calls")
or delta.get("function_call")
or delta.get("reasoning_content")
or delta.get("thinking_blocks")
or delta.get("reasoning_items")
or delta.get("audio")
or delta.get("images")
or delta.get("annotations")
):
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
return True
return False
Comment thread
deepanshululla marked this conversation as resolved.
Resolved


class RoutingArgs(enum.Enum):
ttl = 60 # 1min (RPM/TPM expire key)

Expand Down Expand Up @@ -2095,6 +2115,13 @@ async def stream_with_fallbacks():
async for item in model_response:
yield item
except MidStreamFallbackError as e:
Comment thread
deepanshululla marked this conversation as resolved.
Resolved
if not e.is_pre_first_chunk and (
e.generated_content or _stream_chunks_have_generated_content(model_response.chunks)
):
if e.original_exception is not None:
raise e.original_exception from e
raise
Comment thread
deepanshululla marked this conversation as resolved.
Resolved

from litellm.main import stream_chunk_builder

complete_response_object = stream_chunk_builder(chunks=model_response.chunks)
Expand All @@ -2113,24 +2140,7 @@ async def stream_with_fallbacks():
"content_policy_fallbacks", self.content_policy_fallbacks
)
initial_kwargs["original_function"] = self._acompletion
if e.is_pre_first_chunk or not e.generated_content:
# No content was generated before the error (e.g. a
# rate-limit 429 on the very first chunk). Retry with
# the original messages — adding a continuation prompt
# would waste tokens and confuse the model.
initial_kwargs["messages"] = messages
else:
initial_kwargs["messages"] = messages + [
{
"role": "system",
"content": "You are a helpful assistant. You are given a message and you need to respond to it. You are also given a generated content. You need to respond to the message in continuation of the generated content. Do not repeat the same content. Your response should be in continuation of this text: ",
},
{
"role": "assistant",
"content": e.generated_content,
"prefix": True,
},
]
initial_kwargs["messages"] = messages
self._update_kwargs_before_fallbacks(model=model_group, kwargs=initial_kwargs)
fallback_response = await self.async_function_with_fallbacks_common_utils(
e=e,
Expand Down Expand Up @@ -2650,6 +2660,13 @@ def stream_with_fallbacks():
for item in model_response:
yield item
except MidStreamFallbackError as e:
if not e.is_pre_first_chunk and (
e.generated_content or _stream_chunks_have_generated_content(model_response.chunks)
):
if e.original_exception is not None:
raise e.original_exception from e
raise

from litellm.main import stream_chunk_builder

complete_response_object = stream_chunk_builder(chunks=model_response.chunks)
Expand All @@ -2669,20 +2686,7 @@ def stream_with_fallbacks():
router_self.content_policy_fallbacks,
)
initial_kwargs["original_function"] = router_self._completion
if e.is_pre_first_chunk or not e.generated_content:
initial_kwargs["messages"] = messages
else:
initial_kwargs["messages"] = messages + [
{
"role": "system",
"content": "You are a helpful assistant. You are given a message and you need to respond to it. You are also given a generated content. You need to respond to the message in continuation of the generated content. Do not repeat the same content. Your response should be in continuation of this text: ",
},
{
"role": "assistant",
"content": e.generated_content,
"prefix": True,
},
]
initial_kwargs["messages"] = messages
router_self._update_kwargs_before_fallbacks(model=model_group, kwargs=initial_kwargs)
fallback_response = router_self.function_with_fallbacks(
**initial_kwargs,
Expand Down Expand Up @@ -2880,6 +2884,13 @@ async def _acompletion(
llm_provider="",
)

if (
isinstance(response, CustomStreamWrapper)
and response.completion_stream is None
and response.make_call is not None
):
await response.fetch_stream()

self.success_calls[model_name] += 1
verbose_router_logger.info("litellm.acompletion(model=%s)\x1b[32m 200 OK\x1b[0m", model_name)
# debug how often this deployment picked
Expand Down Expand Up @@ -6117,7 +6128,7 @@ async def async_function_with_fallbacks_common_utils(
"""
Common utilities for async_function_with_fallbacks
"""
verbose_router_logger.debug("Traceback%s", traceback.format_exc())
verbose_router_logger.debug("Traceback", exc_info=True)
original_exception = e
fallback_model_group = None
original_model_group: str | None = kwargs.get("model") # type: ignore
Expand Down Expand Up @@ -6333,15 +6344,17 @@ async def async_function_with_fallbacks_common_utils(
except Exception as new_exception:
parent_otel_span = _get_parent_otel_span_from_kwargs(kwargs)
fallback_failure_exception_str = redact_string(str(new_exception))
cooldown_info = await _async_get_cooldown_deployments_with_debug_info(
litellm_router_instance=self,
parent_otel_span=parent_otel_span,
)
verbose_router_logger.error(
"litellm.router.py::async_function_with_fallbacks() - Error occurred while trying to do fallbacks - {}\n{}\n\nDebug Information:\nCooldown Deployments={}".format(
fallback_failure_exception_str,
redact_string(traceback.format_exc()),
await _async_get_cooldown_deployments_with_debug_info(
litellm_router_instance=self,
parent_otel_span=parent_otel_span,
),
)
"litellm.router.py::async_function_with_fallbacks() - "
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
"Error occurred while trying to do fallbacks - %s\n"
"Debug Information:\nCooldown Deployments=%s",
fallback_failure_exception_str,
cooldown_info,
exc_info=True,
Comment thread
veria-ai[bot] marked this conversation as resolved.
Resolved
)

if hasattr(original_exception, "message") and litellm.expose_router_debug_in_errors:
Expand Down
110 changes: 108 additions & 2 deletions tests/test_litellm/proxy/test_common_request_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2425,14 +2425,14 @@ class TestHandleLLMApiExceptionDictDetail:
through ProxyException instead of being str()-mangled into a Python repr.
"""

async def _invoke(self, exc: Exception):
async def _invoke(self, exc: Exception, callback_headers: Optional[dict] = None):
from litellm.proxy._types import ProxyException, UserAPIKeyAuth

processor = ProxyBaseLLMRequestProcessing(data={})
user_api_key_dict = UserAPIKeyAuth(api_key="sk-test")
proxy_logging_obj = MagicMock()
proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None)
proxy_logging_obj.post_call_response_headers_hook = AsyncMock(return_value={})
proxy_logging_obj.post_call_response_headers_hook = AsyncMock(return_value=callback_headers or {})

try:
await processor._handle_llm_api_exception(
Expand Down Expand Up @@ -2952,6 +2952,112 @@ async def test_handle_llm_api_exception_retry_after_survives_callback_headers(se
assert proxy_exc.headers["x-custom"] == "1"


class TestHandleLLMApiExceptionFramingHeaders:
"""HTTP-framing headers on the provider exception must be stripped before the
proxy builds its own response, or they conflict with the framing the proxy
itself sets. Non-framing headers must survive unchanged."""

async def _invoke(self, exc: Exception, callback_headers: Optional[dict] = None):
from litellm.proxy._types import ProxyException, UserAPIKeyAuth

processor = ProxyBaseLLMRequestProcessing(data={})
user_api_key_dict = UserAPIKeyAuth(api_key="sk-test")
proxy_logging_obj = MagicMock()
proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None)
proxy_logging_obj.post_call_response_headers_hook = AsyncMock(return_value=callback_headers or {})

try:
await processor._handle_llm_api_exception(
e=exc,
user_api_key_dict=user_api_key_dict,
proxy_logging_obj=proxy_logging_obj,
)
except ProxyException as raised:
return raised
raise AssertionError("ProxyException was not raised")

async def test_strips_framing_headers_preserves_others(self):
exc = litellm.RateLimitError(
message="Resource exhausted",
llm_provider="vertex_ai",
model="gemini-2.0-flash",
)
exc.headers = {
"content-length": "42",
"transfer-encoding": "chunked",
"content-encoding": "gzip",
"content-type": "application/json",
"x-request-id": "abc-123",
}
proxy_exc = await self._invoke(exc)
assert "content-length" not in proxy_exc.headers
assert "transfer-encoding" not in proxy_exc.headers
assert "content-encoding" not in proxy_exc.headers
assert "content-type" not in proxy_exc.headers
assert proxy_exc.headers["x-request-id"] == "abc-123"

async def test_strips_framing_headers_on_existing_proxy_exception(self):
from litellm.proxy._types import ProxyException

exc = ProxyException(
message="Resource exhausted",
type="rate_limit_error",
param=None,
code=429,
headers={
"content-length": "42",
"transfer-encoding": "chunked",
"x-request-id": "abc-123",
},
)
proxy_exc = await self._invoke(exc)
assert "content-length" not in proxy_exc.headers
assert "transfer-encoding" not in proxy_exc.headers
assert proxy_exc.headers["x-request-id"] == "abc-123"

async def test_strips_browser_security_headers(self):
exc = litellm.RateLimitError(
message="Resource exhausted",
llm_provider="vertex_ai",
model="gemini-2.0-flash",
)
exc.headers = {
"access-control-allow-origin": "https://evil.example.com",
"content-security-policy": "default-src https://evil.example.com",
"clear-site-data": '"cache", "cookies", "storage"',
"strict-transport-security": "max-age=0",
"x-frame-options": "ALLOWALL",
"x-request-id": "abc-123",
}
proxy_exc = await self._invoke(exc)
assert "access-control-allow-origin" not in proxy_exc.headers
assert "content-security-policy" not in proxy_exc.headers
assert "clear-site-data" not in proxy_exc.headers
assert "strict-transport-security" not in proxy_exc.headers
assert "x-frame-options" not in proxy_exc.headers
assert proxy_exc.headers["x-request-id"] == "abc-123"

async def test_strips_unsafe_headers_added_by_response_headers_hook(self):
exc = litellm.RateLimitError(
message="Resource exhausted",
llm_provider="vertex_ai",
model="gemini-2.0-flash",
)
exc.headers = {"x-request-id": "abc-123"}
proxy_exc = await self._invoke(
exc,
callback_headers={
"x-frame-options": "ALLOWALL",
"content-length": "42",
"x-custom-safe": "1",
},
)
assert "x-frame-options" not in proxy_exc.headers
assert "content-length" not in proxy_exc.headers
assert proxy_exc.headers["x-custom-safe"] == "1"
assert proxy_exc.headers["x-request-id"] == "abc-123"


class TestAsyncStreamingDataGeneratorFastPath:
"""Fast/slow path branching in async_streaming_data_generator."""

Expand Down
Loading
Loading