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 remote-tracking branch 'origin/litellm_internal_staging' into litellm_fix_bedrock_buffered_responses_stream
Mateo Wangdeb67ce6e212
diff --cc litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.pyindex d320119344c,0237d82a0d9..30526d30dc5--- a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py+++ b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py@@@ -31,8 -31,10 +31,11 @@@ from litellm.caching import DualCachfrom litellm.constants import BEDROCK_APPLY_GUARDRAIL_CHUNK_BUDGET_CHARSfrom litellm.exceptions import ModifyResponseExceptionfrom litellm.integrations.custom_guardrail import CustomGuardrail+from litellm.litellm_core_utils.api_route_to_call_types import get_call_types_for_routefrom litellm.litellm_core_utils.core_helpers import redact_nested_match_and_regex_keys+ from litellm.litellm_core_utils.litellm_logging import (+ _get_masked_values, # pyright: ignore[reportPrivateUsage] # the shared header-masking helper has no public name+ )from litellm.litellm_core_utils.llm_cost_calc.guardrail_cost import bedrock_guardrail_costfrom litellm.llms.anthropic.chat.guardrail_translation.handler import AnthropicMessagesHandlerfrom litellm.llms.base_llm.guardrail_translation.utils import (diff --cc tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.pyindex ef263dfe268,bcda1b8b61d..8bc367b6b59--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py@@@ -5592,151 -5592,50 +5592,200 @@@ async def test_streaming_end_of_stream_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))+++def _responses_failed_stream_events() -> list:+ from litellm.types.llms.openai import (+ OutputTextDeltaEvent,+ ResponseFailedEvent,+ ResponsesAPIResponse,+ ResponsesAPIStreamEvents,+ )++ deltas = [+ OutputTextDeltaEvent(+ type=ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA,+ item_id="msg_lit6457_failed",+ output_index=0,+ content_index=0,+ delta=part,+ )+ for part in ("Hello", " world")+ ]+ failed = ResponseFailedEvent(+ type=ResponsesAPIStreamEvents.RESPONSE_FAILED,+ response=ResponsesAPIResponse(+ id="resp_lit6457_failed",+ created_at=1234567890,+ model="gpt-4o",+ object="response",+ status="failed",+ output=[],+ ),+ )+ return [*deltas, failed]+++async def test_responses_api_failed_stream_scans_delta_text_before_replay():+ """A responses stream that dies mid-generation carries its text only in delta+ events; the end-of-stream scan must still see that text instead of skipping+ on an empty assembled string and replaying the buffer unmoderated."""+ guardrail = BedrockGuardrail(+ guardrail_name="bedrock-responses-failed-stream",+ guardrailIdentifier="test-id",+ guardrailVersion="DRAFT",+ event_hook=GuardrailEventHooks.post_call,+ default_on=True,+ )+ stream_events = _responses_failed_stream_events()+ order = []+ scan_payloads = []+ yielded = []++ async def record_scan(*args, **kwargs):+ order.append("scan")+ scan_payloads.append(str(args) + str(kwargs))+ 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 "Hello world" in scan_payloads[0]+ assert len(yielded) == len(stream_events)+ assert all(emitted is original for emitted, original in zip(yielded, stream_events))+++++ @pytest.mark.asyncio+ async def test_apply_guardrail_debug_log_masks_signed_request_headers():+ import logging++ from litellm._logging import verbose_proxy_logger++ session_token = "FakeSessionTokenValueThatMustNeverAppearInLogs1234567890"+ guardrail = BedrockGuardrail(+ guardrailIdentifier="test-guardrail",+ guardrailVersion="DRAFT",+ aws_access_key_id="ASIAFAKEACCESSKEYID1",+ aws_secret_access_key="fakeSecretAccessKeyForSigning",+ aws_session_token=session_token,+ aws_region_name="us-east-1",+ )++ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.json.return_value = {"action": "NONE", "outputs": []}++ captured_records: list[logging.LogRecord] = []++ class _RecordingHandler(logging.Handler):+ def emit(self, record: logging.LogRecord) -> None:+ captured_records.append(record)++ handler = _RecordingHandler(level=logging.DEBUG)+ previous_level = verbose_proxy_logger.level+ verbose_proxy_logger.addHandler(handler)+ verbose_proxy_logger.setLevel(logging.DEBUG)+ try:+ with patch.object(guardrail.async_handler, "post", new_callable=AsyncMock) as mock_post:+ mock_post.return_value = mock_response+ await guardrail.make_bedrock_api_request(+ source="INPUT",+ messages=[{"role": "user", "content": "hello"}],+ request_data={},+ )+ finally:+ verbose_proxy_logger.removeHandler(handler)+ verbose_proxy_logger.setLevel(previous_level)++ rendered_messages = [record.getMessage() for record in captured_records]+ header_lines = [message for message in rendered_messages if "headers:" in message]+ assert header_lines, "expected the signed-request debug line to be logged"+ assert any("X-Amz-Security-Token" in message for message in header_lines)+ assert all(session_token not in message for message in rendered_messages)