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(proxy): gate streaming pipelines on a route-resolved guardrail translation

mateo-berri9cb5d9b76c0c
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index c38eb900a05..37d077d607c 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -192,6 +192,7 @@ if TYPE_CHECKING:
from prisma.types import HttpConfig
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+ from litellm.llms.base_llm.guardrail_translation.base_translation import BaseTranslation
from litellm.models.team import LiteLLM_TeamTableCachedObj
from litellm.proxy.db.autorouter_session_rollup import AutoRouterTurnTransaction
from litellm.proxy.db.spend_log_tool_index import ToolUsageTransaction
@@ -559,7 +560,7 @@ def _pipeline_is_streamable(policy_name: str, pipeline: "GuardrailPipeline") ->
def _route_supports_streaming_pipelines(user_api_key_dict: UserAPIKeyAuth) -> bool:
- return not user_api_key_dict.request_route or resolve_endpoint_translation(user_api_key_dict, None) is not None
+ return resolve_endpoint_translation(user_api_key_dict, None) is not None
def _stream_gated_guardrail_names(
@@ -3435,12 +3436,16 @@ class ProxyLogging:
),
)
- if post_call_pipelines:
+ pipeline_translation: Final = (
+ resolve_endpoint_translation(user_api_key_dict, None) if post_call_pipelines else None
+ )
+ if pipeline_translation is not None:
current_response = self._pipeline_gated_stream(
response=current_response,
user_api_key_dict=user_api_key_dict,
request_data=request_data,
pipelines=post_call_pipelines,
+ translation=pipeline_translation,
)
try:
@@ -3464,6 +3469,7 @@ class ProxyLogging:
user_api_key_dict: UserAPIKeyAuth,
request_data: dict, # mutable-ok: same request-payload shape the hooks mutate
pipelines: "tuple[tuple[str, GuardrailPipeline], ...]",
+ translation: "tuple[str, BaseTranslation]",
) -> "AsyncGenerator[Any, None]":
"""
Execute post_call policy pipelines against a streamed response.
@@ -3478,9 +3484,8 @@ class ProxyLogging:
rewritten chunks, so rewrites chain). A rewrite the translation cannot
deliver yet (one on a route without write-back, or a shape the route
refuses) is discarded by the executor and the original chunks are
- released, as is a buffered shape no translation resolves; a block or
- modify_response terminates with the translation's block chunks or the
- raised error.
+ released; a block or modify_response terminates with the translation's
+ block chunks or the raised error.
"""
buffered: Final[list[object]] = [] # mutable-ok: accumulates the stream before the pipeline verdict
async for item in response:
@@ -3488,17 +3493,7 @@ class ProxyLogging:
if not buffered:
return
- resolved: Final = resolve_endpoint_translation(user_api_key_dict, buffered[0])
- if resolved is None:
- verbose_proxy_logger.warning(
- "Policies with post_call guardrail pipelines cannot scan this streaming response shape yet; "
- "the stream is released ungoverned by them: %s",
- ", ".join(policy_name for policy_name, _pipeline in pipelines),
- )
- for buffered_item in buffered:
- yield buffered_item
- return
- call_type, endpoint_translation = resolved
+ call_type, endpoint_translation = translation
for policy_name, pipeline in pipelines:
result: PipelineExecutionResult = await PipelineExecutor.execute_steps(
diff --git a/tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py b/tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py
index bf71780ad7b..3b59bbac3fd 100644
--- a/tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py
+++ b/tests/test_litellm/proxy/utils/proxy_logging/test_guardrail_pipeline.py
@@ -1969,28 +1969,61 @@ async def test_streaming_iterator_hook_pipeline_releases_stream_echoed_in_anothe
@pytest.mark.asyncio
-async def test_streaming_iterator_hook_pipeline_releases_originals_on_unresolvable_response_shape(
+async def test_streaming_iterator_hook_skips_pipeline_and_warns_without_request_route(
proxy_logging, make_user_api_key_auth, monkeypatch, caplog
):
seen: Dict[str, Any] = {}
monkeypatch.setattr(litellm, "callbacks", [_unified_stream_guardrail(seen)])
monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None, raising=False)
data = _post_call_pipeline_data(stream=True)
- chunks = [object(), object()]
- delivered: List[Any] = []
+ chunks = _stream_chunks()
with caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"):
- async for item in proxy_logging.async_post_call_streaming_iterator_hook(
- user_api_key_dict=make_user_api_key_auth(),
- response=_async_chunk_iter(chunks),
- request_data=data,
- ):
- delivered.append(item)
+ delivered = [
+ item
+ async for item in proxy_logging.async_post_call_streaming_iterator_hook(
+ user_api_key_dict=make_user_api_key_auth(),
+ response=_async_chunk_iter(chunks),
+ request_data=data,
+ )
+ ]
assert [item is chunk for item, chunk in zip(delivered, chunks)] == [True, True]
assert len(delivered) == 2
assert seen.get("count") is None
- assert any("response-governance" in message and "shape" in message for message in _warnings(caplog))
+ assert any("response-governance" in message and "route None" in message for message in _warnings(caplog))
+
+
+async def test_per_chunk_streaming_hook_runs_pipeline_managed_guardrail_without_request_route(
+ proxy_logging, make_user_api_key_auth, monkeypatch
+):
+ seen: Dict[str, Any] = {}
+
+ class UnifiedRecordingGuardrail(CustomGuardrail):
+ async def async_post_call_streaming_hook(self, user_api_key_dict, response):
+ seen[self.guardrail_name] = seen.get(self.guardrail_name, 0) + 1
+ return None
+
+ async def apply_guardrail(self, inputs, request_data, input_type, logging_obj=None):
+ return inputs
+
+ monkeypatch.setattr(
+ litellm,
+ "callbacks",
+ [UnifiedRecordingGuardrail(guardrail_name="gr-post", event_hook=GuardrailEventHooks.post_call, default_on=True)],
+ )
+ monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", None, raising=False)
+ data = _post_call_pipeline_data(stream=True)
+
+ result = await proxy_logging.async_post_call_streaming_hook(
+ data=data,
+ response=_stream_chunks()[0],
+ user_api_key_dict=make_user_api_key_auth(),
+ )
+
+ assert result is not None
+ assert seen["gr-post"] == 1
def _anthropic_sse_chunks() -> List[bytes]: