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
[Bug Fix] Bedrock Guardrail - Don't raise exception on intervene action (#11875)
Ishaan Jaffd677a6bda2c5
diff --git a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.pyindex fb8e9236f48..39b6fe9a25e 100644--- a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py+++ b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py@@ -79,9 +79,9 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):if messages:for message in messages:- message_text_content: Optional[- List[str]- ] = self.get_content_for_message(message=message)+ message_text_content: Optional[List[str]] = (+ self.get_content_for_message(message=message)+ )if message_text_content is None:continuefor text_content in message_text_content:@@ -241,7 +241,7 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):self, response: BedrockGuardrailResponse) -> bool:"""- By default always raise an exception when a guardrail intervention is detected.+ Only raise exception for "BLOCKED" actions, not for "ANONYMIZED" actions.If `self.mask_request_content` or `self.mask_response_content` is set to `True`, then use the output from the guardrail to mask the request or response content."""@@ -250,11 +250,68 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):if self.mask_request_content or self.mask_response_content:return False- # if intervention, return True- if response.get("action") == "GUARDRAIL_INTERVENED":- return True-# if no intervention, return False+ if response.get("action") != "GUARDRAIL_INTERVENED":+ return False++ # Check assessments to determine if any actions were BLOCKED (vs ANONYMIZED)+ assessments = response.get("assessments", [])+ if not assessments:+ return False++ for assessment in assessments:+ # Check topic policy+ topic_policy = assessment.get("topicPolicy")+ if topic_policy:+ topics = topic_policy.get("topics", [])+ for topic in topics:+ if topic.get("action") == "BLOCKED":+ return True++ # Check content policy+ content_policy = assessment.get("contentPolicy")+ if content_policy:+ filters = content_policy.get("filters", [])+ for filter_item in filters:+ if filter_item.get("action") == "BLOCKED":+ return True++ # Check word policy+ word_policy = assessment.get("wordPolicy")+ if word_policy:+ custom_words = word_policy.get("customWords", [])+ for custom_word in custom_words:+ if custom_word.get("action") == "BLOCKED":+ return True+ managed_words = word_policy.get("managedWordLists", [])+ for managed_word in managed_words:+ if managed_word.get("action") == "BLOCKED":+ return True++ # Check sensitive information policy+ sensitive_info_policy = assessment.get("sensitiveInformationPolicy")+ if sensitive_info_policy:+ pii_entities = sensitive_info_policy.get("piiEntities", [])+ if pii_entities:+ for pii_entity in pii_entities:+ if pii_entity.get("action") == "BLOCKED":+ return True+ regexes = sensitive_info_policy.get("regexes", [])+ if regexes:+ for regex in regexes:+ if regex.get("action") == "BLOCKED":+ return True++ # Check contextual grounding policy+ contextual_grounding_policy = assessment.get("contextualGroundingPolicy")+ if contextual_grounding_policy:+ grounding_filters = contextual_grounding_policy.get("filters", [])+ for filter_item in grounding_filters:+ if filter_item.get("action") == "BLOCKED":+ return True++ # If we got here, intervention occurred but no BLOCKED actions found+ # This means all actions were ANONYMIZED or NONE, so don't raise exceptionreturn False@log_guardrail_information@@ -300,11 +357,11 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):################################################################### 2. Update the messages with the guardrail response ###################################################################- data[- "messages"- ] = self._update_messages_with_updated_bedrock_guardrail_response(- messages=new_messages,- bedrock_guardrail_response=bedrock_guardrail_response,+ data["messages"] = (+ self._update_messages_with_updated_bedrock_guardrail_response(+ messages=new_messages,+ bedrock_guardrail_response=bedrock_guardrail_response,+ ))#########################################################@@ -354,11 +411,11 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):################################################################### 2. Update the messages with the guardrail response ###################################################################- data[- "messages"- ] = self._update_messages_with_updated_bedrock_guardrail_response(- messages=new_messages,- bedrock_guardrail_response=bedrock_guardrail_response,+ data["messages"] = (+ self._update_messages_with_updated_bedrock_guardrail_response(+ messages=new_messages,+ bedrock_guardrail_response=bedrock_guardrail_response,+ ))#########################################################@@ -408,11 +465,11 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):################################################################### 2. Update the messages with the guardrail response ###################################################################- data[- "messages"- ] = self._update_messages_with_updated_bedrock_guardrail_response(- messages=new_messages,- bedrock_guardrail_response=bedrock_guardrail_response,+ data["messages"] = (+ self._update_messages_with_updated_bedrock_guardrail_response(+ messages=new_messages,+ bedrock_guardrail_response=bedrock_guardrail_response,+ ))#########################################################@@ -440,21 +497,29 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):Returns:List of messages with content masked according to guardrail response"""- # Skip processing if masking is not enabled- if not (self.mask_request_content or self.mask_response_content):- return messages-# Get masked texts from guardrail responsemasked_texts = self._extract_masked_texts_from_response(bedrock_guardrail_response)- if not masked_texts:- return messages- # Apply masking to messages using index tracking- return self._apply_masking_to_messages(- messages=messages, masked_texts=masked_texts- )+ # If guardrail provided masked output, use it regardless of masking flags+ # because the guardrail has already determined this content needs anonymization+ if masked_texts:+ verbose_proxy_logger.debug(+ "Bedrock guardrail provided masked output, applying to messages"+ )+ return self._apply_masking_to_messages(+ messages=messages, masked_texts=masked_texts+ )++ # If masking is enabled but no masked texts available, still try to apply+ # (this maintains backward compatibility for edge cases)+ if self.mask_request_content or self.mask_response_content:+ verbose_proxy_logger.debug(+ "Masking enabled but no masked output from guardrail, returning original messages"+ )++ return messagesasync def async_post_call_streaming_iterator_hook(self,diff --git a/tests/guardrails_tests/test_bedrock_guardrails.py b/tests/guardrails_tests/test_bedrock_guardrails.pyindex 998c27a93db..246338fd1d3 100644--- a/tests/guardrails_tests/test_bedrock_guardrails.py+++ b/tests/guardrails_tests/test_bedrock_guardrails.py@@ -10,14 +10,13 @@ from litellm.caching import DualCachefrom unittest.mock import MagicMock, AsyncMock, patch@pytest.mark.asyncio-async def test_bedrock_guardrails():+async def test_bedrock_guardrails_pii_masking():# Create proper mock objectsmock_user_api_key_dict = UserAPIKeyAuth()guardrail = BedrockGuardrail(guardrailIdentifier="wf0hkdb5x07f",guardrailVersion="DRAFT",- mask_request_content=True,)request_data = {@@ -35,7 +34,7 @@ async def test_bedrock_guardrails():user_api_key_dict=mock_user_api_key_dict,call_type="completion")- print(response)+ print("response after moderation hook", response)if response: # Only assert if response is not Noneassert response["messages"][0]["content"] == "Hello, my phone number is {PHONE}"@@ -45,14 +44,13 @@ async def test_bedrock_guardrails():@pytest.mark.asyncio-async def test_bedrock_guardrails_content_list():+async def test_bedrock_guardrails_pii_masking_content_list():# Create proper mock objectsmock_user_api_key_dict = UserAPIKeyAuth()guardrail = BedrockGuardrail(guardrailIdentifier="wf0hkdb5x07f",guardrailVersion="DRAFT",- mask_request_content=True,)request_data = {@@ -105,7 +103,7 @@ async def test_bedrock_guardrails_with_streaming():)guardrail = BedrockGuardrail(- guardrailIdentifier="wf0hkdb5x07f",+ guardrailIdentifier="ff6ujrregl1q",guardrailVersion="DRAFT",supported_event_hooks=[GuardrailEventHooks.post_call],guardrail_name="bedrock-post-guard",@@ -118,7 +116,7 @@ async def test_bedrock_guardrails_with_streaming():"messages": [{"role": "user",- "content": "My name is [email protected]"+ "content": "Hi I like coffee"}],"stream": True,@@ -154,7 +152,7 @@ async def test_bedrock_guardrails_with_streaming_no_violation():)guardrail = BedrockGuardrail(- guardrailIdentifier="wf0hkdb5x07f",+ guardrailIdentifier="ff6ujrregl1q",guardrailVersion="DRAFT",supported_event_hooks=[GuardrailEventHooks.post_call],guardrail_name="bedrock-post-guard",@@ -334,4 +332,241 @@ async def test_bedrock_guardrail_aws_param_persistence():assert kwargs["aws_secret_access_key"] == "test-secret-key"assert kwargs["aws_region_name"] == "us-east-1"+async def test_bedrock_guardrail_blocked_vs_anonymized_actions():+ """Test that BLOCKED actions raise exceptions but ANONYMIZED actions do not"""+ from unittest.mock import MagicMock+ from litellm.proxy.guardrails.guardrail_hooks.bedrock_guardrails import BedrockGuardrail+ from litellm.types.proxy.guardrails.guardrail_hooks.bedrock_guardrails import BedrockGuardrailResponse++ guardrail = BedrockGuardrail(+ guardrailIdentifier="test-guardrail",+ guardrailVersion="DRAFT"+ )++ # Test 1: ANONYMIZED action should NOT raise exception+ anonymized_response: BedrockGuardrailResponse = {+ "action": "GUARDRAIL_INTERVENED",+ "outputs": [{+ "text": "Hello, my phone number is {PHONE}"+ }],+ "assessments": [{+ "sensitiveInformationPolicy": {+ "piiEntities": [{+ "type": "PHONE",+ "match": "+1 412 555 1212",+ "action": "ANONYMIZED"+ }]+ }+ }]+ }++ should_raise = guardrail._should_raise_guardrail_blocked_exception(anonymized_response)+ assert should_raise is False, "ANONYMIZED actions should not raise exceptions"++ # Test 2: BLOCKED action should raise exception+ blocked_response: BedrockGuardrailResponse = {+ "action": "GUARDRAIL_INTERVENED",+ "outputs": [{+ "text": "I can't provide that information."+ }],+ "assessments": [{+ "topicPolicy": {+ "topics": [{+ "name": "Sensitive Topic",+ "type": "DENY",+ "action": "BLOCKED"+ }]+ }+ }]+ }++ should_raise = guardrail._should_raise_guardrail_blocked_exception(blocked_response)+ assert should_raise is True, "BLOCKED actions should raise exceptions"++ # Test 3: Mixed actions - should raise if ANY action is BLOCKED+ mixed_response: BedrockGuardrailResponse = {+ "action": "GUARDRAIL_INTERVENED",+ "outputs": [{+ "text": "I can't provide that information."+ }],+ "assessments": [{+ "sensitiveInformationPolicy": {+ "piiEntities": [{+ "type": "PHONE",+ "match": "+1 412 555 1212",+ "action": "ANONYMIZED"+ }]+ },+ "topicPolicy": {+ "topics": [{+ "name": "Blocked Topic",+ "type": "DENY",+ "action": "BLOCKED"+ }]+ }+ }]+ }++ should_raise = guardrail._should_raise_guardrail_blocked_exception(mixed_response)+ assert should_raise is True, "Mixed actions with any BLOCKED should raise exceptions"++ # Test 4: NONE action should not raise exception+ none_response: BedrockGuardrailResponse = {+ "action": "NONE",+ "outputs": [],+ "assessments": []+ }++ should_raise = guardrail._should_raise_guardrail_blocked_exception(none_response)+ assert should_raise is False, "NONE actions should not raise exceptions"++ # Test 5: Test other policy types with BLOCKED actions+ content_blocked_response: BedrockGuardrailResponse = {+ "action": "GUARDRAIL_INTERVENED",+ "outputs": [{+ "text": "I can't provide that information."+ }],+ "assessments": [{+ "contentPolicy": {+ "filters": [{+ "type": "VIOLENCE",+ "confidence": "HIGH",+ "action": "BLOCKED"+ }]+ }+ }]+ }++ should_raise = guardrail._should_raise_guardrail_blocked_exception(content_blocked_response)+ assert should_raise is True, "Content policy BLOCKED actions should raise exceptions"+++async def test_bedrock_guardrail_masking_with_anonymized_response():+ """Test that masking works correctly when guardrail returns ANONYMIZED actions"""+ from unittest.mock import AsyncMock, MagicMock, patch+ from litellm.proxy._types import UserAPIKeyAuth+ from litellm.caching import DualCache++ # Create proper mock objects+ mock_user_api_key_dict = UserAPIKeyAuth()++ guardrail = BedrockGuardrail(+ guardrailIdentifier="test-guardrail",+ guardrailVersion="DRAFT",+ mask_request_content=True,+ )++ # Mock the Bedrock API response with ANONYMIZED action+ mock_bedrock_response = MagicMock()+ mock_bedrock_response.status_code = 200+ mock_bedrock_response.json.return_value = {+ "action": "GUARDRAIL_INTERVENED",+ "outputs": [{+ "text": "Hello, my phone number is {PHONE}"+ }],+ "assessments": [{+ "sensitiveInformationPolicy": {+ "piiEntities": [{+ "type": "PHONE",+ "match": "+1 412 555 1212",+ "action": "ANONYMIZED"+ }]+ }+ }]+ }++ request_data = {+ "model": "gpt-4o",+ "messages": [+ {"role": "user", "content": "Hello, my phone number is +1 412 555 1212"},+ ],+ }++ # Patch the async_handler.post method+ with patch.object(guardrail.async_handler, 'post', new_callable=AsyncMock) as mock_post:+ mock_post.return_value = mock_bedrock_response++ # This should NOT raise an exception since action is ANONYMIZED+ try:+ response = await guardrail.async_moderation_hook(+ data=request_data,+ user_api_key_dict=mock_user_api_key_dict,+ call_type="completion"+ )+ # Should succeed and return data with masked content+ assert response is not None+ assert response["messages"][0]["content"] == "Hello, my phone number is {PHONE}"+ except Exception as e:+ pytest.fail(f"Should not raise exception for ANONYMIZED actions, but got: {e}")+++async def test_bedrock_guardrail_uses_masked_output_without_masking_flags():+ """Test that masked output from guardrails is used even when masking flags are not enabled"""+ from unittest.mock import AsyncMock, MagicMock, patch+ from litellm.proxy._types import UserAPIKeyAuth++ # Create proper mock objects+ mock_user_api_key_dict = UserAPIKeyAuth()++ # Create guardrail WITHOUT masking flags enabled+ guardrail = BedrockGuardrail(+ guardrailIdentifier="test-guardrail",+ guardrailVersion="DRAFT",+ # Note: No mask_request_content=True or mask_response_content=True+ )++ # Mock the Bedrock API response with ANONYMIZED action and masked output+ mock_bedrock_response = MagicMock()+ mock_bedrock_response.status_code = 200+ mock_bedrock_response.json.return_value = {+ "action": "GUARDRAIL_INTERVENED",+ "outputs": [{+ "text": "Hello, my phone number is {PHONE} and email is {EMAIL}"+ }],+ "assessments": [{+ "sensitiveInformationPolicy": {+ "piiEntities": [+ {+ "type": "PHONE",+ "match": "+1 412 555 1212",+ "action": "ANONYMIZED"+ },+ {+ "type": "EMAIL",+ "match": "[email protected]",+ "action": "ANONYMIZED"+ }+ ]+ }+ }]+ }++ request_data = {+ "model": "gpt-4o",+ "messages": [+ {"role": "user", "content": "Hello, my phone number is +1 412 555 1212 and email is [email protected]"},+ ],+ }++ # Patch the async_handler.post method+ with patch.object(guardrail.async_handler, 'post', new_callable=AsyncMock) as mock_post:+ mock_post.return_value = mock_bedrock_response++ # This should use the masked output even without masking flags+ response = await guardrail.async_moderation_hook(+ data=request_data,+ user_api_key_dict=mock_user_api_key_dict,+ call_type="completion"+ )++ # Should use the masked content from guardrail output+ assert response is not None+ assert response["messages"][0]["content"] == "Hello, my phone number is {PHONE} and email is {EMAIL}"+ print("✅ Masked output was applied even without masking flags enabled")+++\ No newline at end of file