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
Merge branch 'litellm_internal_staging' into litellm_fix_bedrock_buffered_responses_stream
mateo-berri24c5846c7586
diff --cc litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.pyindex 6f005f1569f,a6635ea0776..d320119344c--- a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py+++ b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py@@@ -2671,24 -2692,21 +2703,39 @@@ class BedrockGuardrail(CustomGuardrailCollect content from the stream and run the bedrock OUTPUT scan(post_call only validates the response)."""+ if self._streams_incrementally():+ from litellm.proxy.guardrails.guardrail_hooks.unified_guardrail.unified_guardrail import (+ UnifiedLLMGuardrails,+ )++ async for streamed_chunk in UnifiedLLMGuardrails().async_post_call_streaming_iterator_hook(+ user_api_key_dict=user_api_key_dict,+ response=response,+ request_data=request_data,+ guardrail_to_apply=self,+ buffer_until_moderated_default=False,+ ):+ yield streamed_chunk+ return++ # Responses-API events are neither chat-completions chunks nor raw+ # Anthropic SSE, so the assembly below cannot scan them; the unified+ # guardrail's translation layer can, with buffering semantics kept.+ if _is_responses_api_route(user_api_key_dict.request_route):+ from litellm.proxy.guardrails.guardrail_hooks.unified_guardrail.unified_guardrail import (+ UnifiedLLMGuardrails,+ )++ async for translated_chunk in UnifiedLLMGuardrails().async_post_call_streaming_iterator_hook(+ user_api_key_dict=user_api_key_dict,+ response=response,+ request_data=request_data,+ guardrail_to_apply=self,+ buffer_until_moderated_default=True,+ ):+ yield translated_chunk+ return+# Import here to avoid circular importsfrom litellm.llms.base_llm.base_model_iterator import MockResponseIteratorfrom litellm.main import stream_chunk_builderdiff --cc tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.pyindex ba710b4a0e9,235a5c0c09b..aaaa651f538--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py@@@ -5347,78 -5347,246 +5347,323 @@@ def test_initialize_bedrock_forwards_awlitellm.logging_callback_manager.remove_callback_from_list_by_object(litellm.callbacks, guardrail)+ def _chat_chunk(content: str, finish_reason: str | None) -> litellm.ModelResponseStream:+ return litellm.ModelResponseStream(+ id="tid",+ choices=[+ litellm.types.utils.StreamingChoices(+ delta=litellm.types.utils.Delta(content=content, role="assistant"),+ finish_reason=finish_reason,+ index=0,+ )+ ],+ created=1,+ model="gpt-4o-mini",+ object="chat.completion.chunk",+ )+++ def _streaming_litellm_params(**extras):+ from litellm.types.guardrails import LitellmParams++ return LitellmParams(+ guardrail="bedrock",+ mode="post_call",+ guardrailIdentifier="test-id",+ guardrailVersion="DRAFT",+ **extras,+ )+++ def test_initialize_bedrock_wires_streaming_flags():+ from litellm.proxy.guardrails.guardrail_initializers import initialize_bedrock++ configured = initialize_bedrock(+ _streaming_litellm_params(+ streaming_buffer_until_moderated=False,+ streaming_sampling_rate=3,+ streaming_end_of_stream_only=True,+ ),+ {"guardrail_name": "bedrock-streaming"},+ )+ defaulted = initialize_bedrock(+ _streaming_litellm_params(),+ {"guardrail_name": "bedrock-defaults"},+ )+ for registered in (configured, defaulted):+ litellm.logging_callback_manager.remove_callback_from_list_by_object(litellm.callbacks, registered)++ assert configured.streaming_buffer_until_moderated is False+ assert configured.streaming_sampling_rate == 3+ assert configured.streaming_end_of_stream_only is True+ assert defaulted.streaming_buffer_until_moderated is True+ assert defaulted.streaming_sampling_rate == 5+ assert defaulted.streaming_end_of_stream_only is False+++ def test_initialize_bedrock_rejects_non_positive_sampling_rate():+ from pydantic import ValidationError++ from litellm.proxy.guardrails.guardrail_initializers import initialize_bedrock++ with pytest.raises(ValidationError):+ initialize_bedrock(+ _streaming_litellm_params(streaming_sampling_rate=0),+ {"guardrail_name": "bedrock-bad-rate"},+ )+++ def test_update_in_memory_litellm_params_round_trips_streaming_flags():+ guardrail = BedrockGuardrail(+ guardrail_name="bedrock-update",+ guardrailIdentifier="test-id",+ guardrailVersion="DRAFT",+ )++ guardrail.update_in_memory_litellm_params(+ _streaming_litellm_params(+ streaming_buffer_until_moderated=False,+ streaming_sampling_rate=7,+ streaming_end_of_stream_only=True,+ )+ )+ assert guardrail.streaming_buffer_until_moderated is False+ assert guardrail.streaming_sampling_rate == 7+ assert guardrail.streaming_end_of_stream_only is True++ guardrail.update_in_memory_litellm_params(_streaming_litellm_params())+ assert guardrail.streaming_buffer_until_moderated is True+ assert guardrail.streaming_sampling_rate == 5+ assert guardrail.streaming_end_of_stream_only is False+++ async def _run_streaming_hook_recording_order(guardrail: BedrockGuardrail) -> list:+ events = []+ minimal = {"action": "NONE", "assessments": [], "outputs": []}++ async def record_scan(*args, **kwargs):+ events.append("scan")+ return minimal++ async def mock_stream():+ yield _chat_chunk("Hello", None)+ yield _chat_chunk(" world", None)+ yield _chat_chunk("", "stop")++ with patch.object(guardrail, "make_bedrock_api_request", AsyncMock(side_effect=record_scan)):+ async for chunk in guardrail.async_post_call_streaming_iterator_hook(+ user_api_key_dict=UserAPIKeyAuth(),+ response=mock_stream(),+ request_data={"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "hi"}]},+ ):+ content = chunk.choices[0].delta.content if chunk.choices else None+ events.append(("chunk", content))+ return events+++ @pytest.mark.asyncio+ async def test_unbuffered_end_of_stream_hook_yields_chunks_before_scan():+ guardrail = BedrockGuardrail(+ guardrail_name="bedrock-audit-mode",+ guardrailIdentifier="test-id",+ guardrailVersion="DRAFT",+ event_hook=GuardrailEventHooks.post_call,+ default_on=True,+ streaming_buffer_until_moderated=False,+ streaming_end_of_stream_only=True,+ )++ events = await _run_streaming_hook_recording_order(guardrail)++ scan_index = events.index("scan")+ chunk_events = [e for e in events if e != "scan"]+ assert events.count("scan") == 1+ assert [e for e in events[:scan_index] if e != "scan"] == chunk_events[: scan_index]+ assert ("chunk", "Hello") in events[:scan_index]+ assert ("chunk", " world") in events[:scan_index]+ assert len(chunk_events) == 3+++ @pytest.mark.asyncio+ async def test_buffered_default_hook_scans_before_any_chunk():+ guardrail = BedrockGuardrail(+ guardrail_name="bedrock-buffered-default",+ guardrailIdentifier="test-id",+ guardrailVersion="DRAFT",+ event_hook=GuardrailEventHooks.post_call,+ default_on=True,+ )++ events = await _run_streaming_hook_recording_order(guardrail)++ assert events[0] == "scan"+ assert all(e == "scan" or e[0] == "chunk" for e in events)+ assert len([e for e in events if e != "scan"]) >= 1+++ @pytest.mark.asyncio+ async def test_masking_keeps_buffered_path_even_when_unbuffered_configured():+ guardrail = BedrockGuardrail(+ guardrail_name="bedrock-mask-buffered",+ guardrailIdentifier="test-id",+ guardrailVersion="DRAFT",+ event_hook=GuardrailEventHooks.post_call,+ default_on=True,+ mask_response_content=True,+ streaming_buffer_until_moderated=False,+ streaming_end_of_stream_only=True,+ )++ assert guardrail._streams_incrementally() is False+ events = await _run_streaming_hook_recording_order(guardrail)+ assert events[0] == "scan"+++ @pytest.mark.asyncio+ async def test_streaming_end_of_stream_block_emits_error_frame_instead_of_truncating():+ """Regression for PR #38722: a topicPolicy DENY caught by the end-of-stream+ scan used to raise after SSE headers were flushed, so the client saw a+ silently truncated stream. The unified hook must emit the chat in-stream+ error frame instead."""+ from litellm.llms import load_guardrail_translation_mappings+ from litellm.proxy.guardrails.guardrail_hooks.unified_guardrail import (+ unified_guardrail as unified_module,+ )+ from litellm.proxy.guardrails.guardrail_hooks.unified_guardrail.unified_guardrail import (+ UnifiedLLMGuardrails,+ )+ from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices++ guardrail = BedrockGuardrail(+ guardrailIdentifier="test-guardrail",+ guardrailVersion="DRAFT",+ streaming_end_of_stream_only=True,+ streaming_buffer_until_moderated=False,+ guardrail_name="bedrock-eos",+ event_hook=GuardrailEventHooks.post_call,+ default_on=True,+ )+ blocked_response = {+ "action": "GUARDRAIL_INTERVENED",+ "actionReason": "Guardrail blocked.",+ "outputs": [{"text": "Sorry, the model cannot answer this question."}],+ "assessments": [+ {"topicPolicy": {"topics": [{"name": "Forbidden topic", "type": "DENY", "action": "BLOCKED"}]}}+ ],+ }++ def _chunk(content, finish_reason=None):+ return ModelResponseStream(+ choices=[+ StreamingChoices(+ index=0,+ delta={"content": content, "role": "assistant"},+ finish_reason=finish_reason,+ )+ ],+ )++ async def _mock_stream():+ yield _chunk("the forbidden ")+ yield _chunk("topic answer", finish_reason="stop")++ unified_module.endpoint_guardrail_translation_mappings = load_guardrail_translation_mappings()+ try:+ with patch.object(guardrail, "make_bedrock_api_request", new_callable=AsyncMock) as mock_api:+ mock_api.side_effect = guardrail._get_http_exception_for_blocked_guardrail(blocked_response)++ out = []+ async for item in UnifiedLLMGuardrails().async_post_call_streaming_iterator_hook(+ user_api_key_dict=UserAPIKeyAuth(api_key="test", request_route="/v1/chat/completions"),+ response=_mock_stream(),+ request_data={"guardrail_to_apply": guardrail, "model": "gpt-4"},+ ):+ out.append(item)+ finally:+ unified_module.endpoint_guardrail_translation_mappings = None++ assert len(out) == 3+ assert isinstance(out[0], ModelResponseStream)+ frame = out[-1]+ assert isinstance(frame, bytes)+ payload = json.loads(frame.decode()[len("data: ") :])+ assert payload["error"]["message"] == "Violated guardrail policy"+ assert payload["error"]["code"] == "400"+ assert payload["error"]["provider_specific_fields"]["guardrailIdentifier"] == "test-guardrail"+++++def _responses_stream_events() -> list:+ from litellm.types.llms.openai import (+ OutputTextDeltaEvent,+ ResponseCompletedEvent,+ ResponsesAPIResponse,+ ResponsesAPIStreamEvents,+ )++ deltas = [+ OutputTextDeltaEvent(+ type=ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA,+ item_id="msg_lit6457",+ output_index=0,+ content_index=0,+ delta=part,+ )+ for part in ("Hello", " world")+ ]+ completed = ResponseCompletedEvent(+ type=ResponsesAPIStreamEvents.RESPONSE_COMPLETED,+ response=ResponsesAPIResponse(+ id="resp_lit6457",+ created_at=1234567890,+ model="gpt-4o",+ object="response",+ status="completed",+ output=[+ {+ "type": "message",+ "id": "msg_lit6457",+ "status": "completed",+ "role": "assistant",+ "content": [{"type": "output_text", "text": "Hello world"}],+ }+ ],+ ),+ )+ return [*deltas, completed]+++async def test_responses_api_stream_scans_output_and_replays_buffered_events():+ """Streamed /v1/responses events must be scanned via the unified translation+ layer, not fed to stream_chunk_builder (which raises APIError on them)."""+ guardrail = BedrockGuardrail(+ guardrail_name="bedrock-responses-stream",+ guardrailIdentifier="test-id",+ guardrailVersion="DRAFT",+ event_hook=GuardrailEventHooks.post_call,+ default_on=True,+ )+ stream_events = _responses_stream_events()+ order = []+ yielded = []++ async def record_scan(*args, **kwargs):+ order.append("scan")+ return {"action": "NONE", "assessments": [], "outputs": []}++ async def mock_stream():+ for event in stream_events:+ yield event++ with patch.object(guardrail, "make_bedrock_api_request", AsyncMock(side_effect=record_scan)):+ async for chunk in guardrail.async_post_call_streaming_iterator_hook(+ user_api_key_dict=UserAPIKeyAuth(api_key="test-key", request_route="/v1/responses"),+ response=mock_stream(),+ request_data={"model": "gpt-4o", "input": "hi"},+ ):+ order.append("chunk")+ yielded.append(chunk)++ assert order == ["scan", "chunk", "chunk", "chunk"]+ assert len(yielded) == len(stream_events)+ assert all(emitted is original for emitted, original in zip(yielded, stream_events))