From 852848149078d27ed133bf5474bafcf0ae0cf4d1 Mon Sep 17 00:00:00 2001 From: Steve Date: Tue, 16 Dec 2025 20:18:45 -0500 Subject: [PATCH 1/8] Add post-call hook for Lakera guardrail and mask PII in responses --- .../guardrail_hooks/lakera_ai_v2.py | 60 ++++ tests/guardrails_tests/test_lakera_v2.py | 258 ++++++++++++++++++ 2 files changed, 318 insertions(+) diff --git a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py index c9d88badde84..285233c73ed5 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py +++ b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py @@ -300,6 +300,66 @@ async def async_moderation_hook( return data + async def async_post_call_success_hook( + self, + data: dict, + user_api_key_dict: UserAPIKeyAuth, + response, + ): + """ + Post-call hook for Lakera guardrail. + """ + from litellm.proxy.common_utils.callback_utils import ( + add_guardrail_to_applied_guardrails_header, + ) + + event_type: GuardrailEventHooks = GuardrailEventHooks.post_call + if self.should_run_guardrail(data=data, event_type=event_type) is not True: + return response + + original_messages: Optional[List[AllMessageValues]] = data.get("messages", []) + if original_messages is None: + original_messages = [] + + # Extract assistant messages from the response + response_messages: List[AllMessageValues] = [] + response_dict = ( + response.model_dump() if hasattr(response, "model_dump") else {} + ) + for choice in response_dict.get("choices", []): + msg = choice.get("message") + if msg: + response_messages.append(msg) + + post_call_messages = original_messages + response_messages + + # Call Lakera guardrail + lakera_guardrail_response, _ = await self.call_v2_guard( + messages=post_call_messages, + request_data=data, + ) + + # Handle flagged content + if lakera_guardrail_response.get("flagged") is True: + action = getattr(self, "on_flagged", "block") + if action == "monitor": + verbose_proxy_logger.warning( + "Lakera Guardrail: Post-call violation detected in monitor mode" + ) + # Allow response to proceed + else: + # Default/block behavior + raise self._get_http_exception_for_blocked_guardrail( + lakera_guardrail_response + ) + + # Record applied guardrail + add_guardrail_to_applied_guardrails_header( + request_data=data, guardrail_name=self.guardrail_name + ) + + return response + def _is_only_pii_violation( self, lakera_response: Optional[LakeraAIResponse] ) -> bool: diff --git a/tests/guardrails_tests/test_lakera_v2.py b/tests/guardrails_tests/test_lakera_v2.py index f3b2795a2755..8aa6b6b960c9 100644 --- a/tests/guardrails_tests/test_lakera_v2.py +++ b/tests/guardrails_tests/test_lakera_v2.py @@ -231,3 +231,261 @@ async def test_lakera_blocks_flagged_content_with_user_scenario(): assert lakera_response["metadata"]["request_uuid"] == "b7cd4c8a-28aa-4285-a245-2befee514dbf" assert len(lakera_response["breakdown"]) == 16 # All the breakdown items from the user's scenario +<<<<<<< HEAD +======= + +@pytest.mark.asyncio +async def test_lakera_monitor_mode_allows_flagged_content(): + """Test that monitor mode logs violations but allows requests to proceed.""" + + lakera_guardrail = LakeraAIGuardrail( + api_key="test_key", + on_flagged="monitor", # Monitor mode + ) + + # Mock response with violations + mock_response = { + 'payload': [], + 'flagged': True, + 'breakdown': [ + {'detector_type': 'moderated_content/violence', 'detected': True, 'message_id': 0}, + {'detector_type': 'prompt_attack', 'detected': True, 'message_id': 0}, + ] + } + + with patch.object(lakera_guardrail, 'call_v2_guard', new_callable=AsyncMock) as mock_call: + mock_call.return_value = (mock_response, {}) + + data = { + "messages": [ + {"role": "user", "content": "Some harmful content"} + ], + "model": "gpt-3.5-turbo", + "metadata": {} + } + + user_api_key_dict = UserAPIKeyAuth(api_key="test_key") + cache = DualCache() + + # Should NOT raise an exception in monitor mode + result = await lakera_guardrail.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="completion" + ) + + # Verify request was allowed through + assert result is not None + assert "messages" in result + + +@pytest.mark.asyncio +async def test_lakera_block_mode_raises_exception(): + """Test that block mode (default) raises HTTPException for violations.""" + + lakera_guardrail = LakeraAIGuardrail( + api_key="test_key", + on_flagged="block", # Block mode (default) + ) + + mock_response = { + 'payload': [], + 'flagged': True, + 'breakdown': [ + {'detector_type': 'moderated_content/violence', 'detected': True, 'message_id': 0}, + ] + } + + with patch.object(lakera_guardrail, 'call_v2_guard', new_callable=AsyncMock) as mock_call: + mock_call.return_value = (mock_response, {}) + + data = { + "messages": [ + {"role": "user", "content": "Harmful content"} + ], + "model": "gpt-3.5-turbo", + "metadata": {} + } + + user_api_key_dict = UserAPIKeyAuth(api_key="test_key") + cache = DualCache() + + # Should raise HTTPException in block mode + with pytest.raises(HTTPException) as exc_info: + await lakera_guardrail.async_pre_call_hook( + user_api_key_dict=user_api_key_dict, + cache=cache, + data=data, + call_type="completion" + ) + + assert exc_info.value.status_code == 400 + + +@pytest.mark.asyncio +async def test_lakera_monitor_mode_during_call(): + """Test monitor mode works with during_call (moderation_hook).""" + + lakera_guardrail = LakeraAIGuardrail( + api_key="test_key", + on_flagged="monitor", + ) + + mock_response = { + 'payload': [], + 'flagged': True, + 'breakdown': [ + {'detector_type': 'prompt_attack', 'detected': True, 'message_id': 0}, + ] + } + + with patch.object(lakera_guardrail, 'call_v2_guard', new_callable=AsyncMock) as mock_call: + mock_call.return_value = (mock_response, {}) + + data = { + "messages": [ + {"role": "user", "content": "Test content"} + ], + "model": "gpt-3.5-turbo", + "metadata": {} + } + + user_api_key_dict = UserAPIKeyAuth(api_key="test_key") + + # Should NOT raise exception in monitor mode + result = await lakera_guardrail.async_moderation_hook( + data=data, + user_api_key_dict=user_api_key_dict, + call_type="completion" + ) + + assert result is not None + + +@pytest.mark.asyncio +async def test_lakera_post_call_blocks_flagged_content(): + """Post-call hook should block when violations are flagged.""" + + lakera_guardrail = LakeraAIGuardrail(api_key="test_key") + + mock_response = { + "payload": [], + "flagged": True, + "breakdown": [ + {"detector_type": "moderated_content/violence", "detected": True, "message_id": 0}, + ], + } + + # Mock LLM response object + llm_response = MagicMock() + llm_response.model_dump.return_value = { + "choices": [ + {"message": {"role": "assistant", "content": "some response"}} + ] + } + + with patch.object(lakera_guardrail, "call_v2_guard", new_callable=AsyncMock) as mock_call: + mock_call.return_value = (mock_response, {}) + + data = { + "messages": [{"role": "user", "content": "Harmful content"}], + "model": "gpt-3.5-turbo", + "metadata": {}, + } + + user_api_key_dict = UserAPIKeyAuth(api_key="test_key") + + with pytest.raises(HTTPException) as exc_info: + await lakera_guardrail.async_post_call_success_hook( + data=data, + user_api_key_dict=user_api_key_dict, + response=llm_response, + ) + + assert exc_info.value.status_code == 400 + + +@pytest.mark.asyncio +async def test_lakera_post_call_allows_clean_content(): + """Post-call hook should allow when not flagged.""" + + lakera_guardrail = LakeraAIGuardrail(api_key="test_key") + + mock_response = { + "payload": [], + "flagged": False, + "breakdown": [], + } + + llm_response = MagicMock() + llm_response.model_dump.return_value = { + "choices": [ + {"message": {"role": "assistant", "content": "clean response"}} + ] + } + + with patch.object(lakera_guardrail, "call_v2_guard", new_callable=AsyncMock) as mock_call: + mock_call.return_value = (mock_response, {}) + + data = { + "messages": [{"role": "user", "content": "Hello"}], + "model": "gpt-3.5-turbo", + "metadata": {}, + } + + user_api_key_dict = UserAPIKeyAuth(api_key="test_key") + + result = await lakera_guardrail.async_post_call_success_hook( + data=data, + user_api_key_dict=user_api_key_dict, + response=llm_response, + ) + + assert result is llm_response + + +@pytest.mark.asyncio +async def test_lakera_post_call_masks_pii_and_allows(): + """Post-call hook should mask PII-only violations and allow response.""" + + lakera_guardrail = LakeraAIGuardrail(api_key="test_key") + + mock_response = { + "payload": [ + {"detector_type": "pii/email", "start": 11, "end": 26, "message_id": 1} + ], + "flagged": True, + "breakdown": [ + {"detector_type": "pii/email", "detected": True, "message_id": 1}, + ], + } + + llm_response = MagicMock() + llm_response.model_dump.return_value = { + "choices": [ + {"message": {"role": "assistant", "content": "Your email is test@example.com"}}, + ] + } + + with patch.object(lakera_guardrail, "call_v2_guard", new_callable=AsyncMock) as mock_call: + mock_call.return_value = (mock_response, {}) + + data = { + "messages": [{"role": "user", "content": "Hello"}], + "model": "gpt-3.5-turbo", + "metadata": {}, + } + + user_api_key_dict = UserAPIKeyAuth(api_key="test_key") + + result = await lakera_guardrail.async_post_call_success_hook( + data=data, + user_api_key_dict=user_api_key_dict, + response=llm_response, + ) + + assert result["choices"][0]["message"]["content"] != "Your email is test@example.com" + assert "[MASKED" in result["choices"][0]["message"]["content"] + +>>>>>>> bb602f149b (Add post-call hook for Lakera guardrail and mask PII in responses) From f1665c4d0bbb4643c9ff69ef1e6948c4fd6a810a Mon Sep 17 00:00:00 2001 From: Steve Date: Tue, 16 Dec 2025 21:11:50 -0500 Subject: [PATCH 2/8] Add post-call hook for Lakera and mask PII in responses --- .../guardrail_hooks/lakera_ai_v2.py | 55 +++++++++--- tests/guardrails_tests/test_lakera_v2.py | 89 ------------------- 2 files changed, 44 insertions(+), 100 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py index 285233c73ed5..61180eb0f0f9 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py +++ b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py @@ -228,10 +228,16 @@ async def async_pre_call_hook( "Lakera AI: Masked PII in messages instead of blocking request" ) else: - # If there are other violations or not set to mask PII, raise exception - raise self._get_http_exception_for_blocked_guardrail( - lakera_guardrail_response - ) + action = getattr(self, "on_flagged", "block") + if action == "monitor": + verbose_proxy_logger.warning( + "Lakera Guardrail: Monitoring mode - violation detected but allowing request" + ) + else: + # Default/block behavior + raise self._get_http_exception_for_blocked_guardrail( + lakera_guardrail_response + ) ######################################################### ########## 3. Add the guardrail to the applied guardrails header ########## @@ -286,10 +292,16 @@ async def async_moderation_hook( "Lakera AI: Masked PII in messages instead of blocking request" ) else: - # If there are other violations or not set to mask PII, raise exception - raise self._get_http_exception_for_blocked_guardrail( - lakera_guardrail_response - ) + action = getattr(self, "on_flagged", "block") + if action == "monitor": + verbose_proxy_logger.warning( + "Lakera Guardrail: Monitoring mode - violation detected but allowing request" + ) + else: + # Default/block behavior + raise self._get_http_exception_for_blocked_guardrail( + lakera_guardrail_response + ) ######################################################### ########## 3. Add the guardrail to the applied guardrails header ########## @@ -321,15 +333,19 @@ async def async_post_call_success_hook( if original_messages is None: original_messages = [] - # Extract assistant messages from the response + # Extract assistant messages from the response, keeping only role/content response_messages: List[AllMessageValues] = [] response_dict = ( response.model_dump() if hasattr(response, "model_dump") else {} ) for choice in response_dict.get("choices", []): msg = choice.get("message") - if msg: - response_messages.append(msg) + if not msg: + continue + role = msg.get("role") + content = msg.get("content") + if role and content: + response_messages.append({"role": role, "content": content}) post_call_messages = original_messages + response_messages @@ -341,6 +357,23 @@ async def async_post_call_success_hook( # Handle flagged content if lakera_guardrail_response.get("flagged") is True: + # If only PII violations exist, mask the PII in the response and allow + if self._is_only_pii_violation(lakera_guardrail_response): + masked_entity_count: Dict = {} + masked_messages = self._mask_pii_in_messages( + messages=post_call_messages, + lakera_response=lakera_guardrail_response, + masked_entity_count=masked_entity_count, + ) + assistant_messages = masked_messages[len(original_messages) :] + for idx, msg in enumerate(assistant_messages): + if idx < len(response_dict.get("choices", [])): + response_dict["choices"][idx]["message"] = { + "role": msg.get("role", "assistant"), + "content": msg.get("content", ""), + } + return response_dict + action = getattr(self, "on_flagged", "block") if action == "monitor": verbose_proxy_logger.warning( diff --git a/tests/guardrails_tests/test_lakera_v2.py b/tests/guardrails_tests/test_lakera_v2.py index 8aa6b6b960c9..4cf95a959653 100644 --- a/tests/guardrails_tests/test_lakera_v2.py +++ b/tests/guardrails_tests/test_lakera_v2.py @@ -231,54 +231,6 @@ async def test_lakera_blocks_flagged_content_with_user_scenario(): assert lakera_response["metadata"]["request_uuid"] == "b7cd4c8a-28aa-4285-a245-2befee514dbf" assert len(lakera_response["breakdown"]) == 16 # All the breakdown items from the user's scenario -<<<<<<< HEAD -======= - -@pytest.mark.asyncio -async def test_lakera_monitor_mode_allows_flagged_content(): - """Test that monitor mode logs violations but allows requests to proceed.""" - - lakera_guardrail = LakeraAIGuardrail( - api_key="test_key", - on_flagged="monitor", # Monitor mode - ) - - # Mock response with violations - mock_response = { - 'payload': [], - 'flagged': True, - 'breakdown': [ - {'detector_type': 'moderated_content/violence', 'detected': True, 'message_id': 0}, - {'detector_type': 'prompt_attack', 'detected': True, 'message_id': 0}, - ] - } - - with patch.object(lakera_guardrail, 'call_v2_guard', new_callable=AsyncMock) as mock_call: - mock_call.return_value = (mock_response, {}) - - data = { - "messages": [ - {"role": "user", "content": "Some harmful content"} - ], - "model": "gpt-3.5-turbo", - "metadata": {} - } - - user_api_key_dict = UserAPIKeyAuth(api_key="test_key") - cache = DualCache() - - # Should NOT raise an exception in monitor mode - result = await lakera_guardrail.async_pre_call_hook( - user_api_key_dict=user_api_key_dict, - cache=cache, - data=data, - call_type="completion" - ) - - # Verify request was allowed through - assert result is not None - assert "messages" in result - @pytest.mark.asyncio async def test_lakera_block_mode_raises_exception(): @@ -323,46 +275,6 @@ async def test_lakera_block_mode_raises_exception(): assert exc_info.value.status_code == 400 -@pytest.mark.asyncio -async def test_lakera_monitor_mode_during_call(): - """Test monitor mode works with during_call (moderation_hook).""" - - lakera_guardrail = LakeraAIGuardrail( - api_key="test_key", - on_flagged="monitor", - ) - - mock_response = { - 'payload': [], - 'flagged': True, - 'breakdown': [ - {'detector_type': 'prompt_attack', 'detected': True, 'message_id': 0}, - ] - } - - with patch.object(lakera_guardrail, 'call_v2_guard', new_callable=AsyncMock) as mock_call: - mock_call.return_value = (mock_response, {}) - - data = { - "messages": [ - {"role": "user", "content": "Test content"} - ], - "model": "gpt-3.5-turbo", - "metadata": {} - } - - user_api_key_dict = UserAPIKeyAuth(api_key="test_key") - - # Should NOT raise exception in monitor mode - result = await lakera_guardrail.async_moderation_hook( - data=data, - user_api_key_dict=user_api_key_dict, - call_type="completion" - ) - - assert result is not None - - @pytest.mark.asyncio async def test_lakera_post_call_blocks_flagged_content(): """Post-call hook should block when violations are flagged.""" @@ -488,4 +400,3 @@ async def test_lakera_post_call_masks_pii_and_allows(): assert result["choices"][0]["message"]["content"] != "Your email is test@example.com" assert "[MASKED" in result["choices"][0]["message"]["content"] ->>>>>>> bb602f149b (Add post-call hook for Lakera guardrail and mask PII in responses) From cb2a2eeaa291e5a67a37dc734f96e5b73426fa74 Mon Sep 17 00:00:00 2001 From: Steve Date: Sat, 21 Feb 2026 12:44:27 -0500 Subject: [PATCH 3/8] Fix post-call hook: pass event_type to call_v2_guard --- litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py | 1 + 1 file changed, 1 insertion(+) diff --git a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py index 12996ac0ff73..4433bd8d0c9a 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py +++ b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py @@ -362,6 +362,7 @@ async def async_post_call_success_hook( lakera_guardrail_response, _ = await self.call_v2_guard( messages=post_call_messages, request_data=data, + event_type=GuardrailEventHooks.post_call, ) # Handle flagged content From d77d480622195ab00888f6071ee45b7654a7fb64 Mon Sep 17 00:00:00 2001 From: Steve Date: Sat, 21 Feb 2026 13:39:33 -0500 Subject: [PATCH 4/8] Address Greptile review: return ModelResponse, fix mutation, add header, test location, mask order - PII masking path: return ModelResponse instead of dict so deployment hook accepts it - Avoid mutating request data: deep copy original_messages and messages in _mask_pii_in_messages - Add guardrail header in PII-only return path - Add test in tests/test_litellm/ (test_lakera_ai_v2.py) per PR checklist - Sort PII payload spans by (start,end) descending so multiple spans in one message mask correctly Co-authored-by: Cursor --- .../guardrail_hooks/lakera_ai_v2.py | 20 ++++-- tests/guardrails_tests/test_lakera_v2.py | 8 ++- .../guardrail_hooks/test_lakera_ai_v2.py | 66 +++++++++++++++++++ 3 files changed, 87 insertions(+), 7 deletions(-) create mode 100644 tests/test_litellm/proxy/guardrails/guardrail_hooks/test_lakera_ai_v2.py diff --git a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py index 4433bd8d0c9a..9fd1acc25e4d 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py +++ b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py @@ -20,7 +20,7 @@ LakeraAIRequest, LakeraAIResponse, ) -from litellm.types.utils import CallTypesLiteral, GuardrailStatus +from litellm.types.utils import CallTypesLiteral, GuardrailStatus, ModelResponse class LakeraAIGuardrail(CustomGuardrail): @@ -146,6 +146,7 @@ def _mask_pii_in_messages( if not payload: return messages + messages = copy.deepcopy(messages) # For each message, find its detections on the fly for idx, msg in enumerate(messages): content = msg.get("content", "") @@ -161,6 +162,13 @@ def _mask_pii_in_messages( if not detected_modifications: continue + # Apply masks from end to start so earlier indices remain valid after each replacement + detected_modifications = sorted( + detected_modifications, + key=lambda d: (d.get("start", 0), d.get("end", 0)), + reverse=True, + ) + for modification in detected_modifications: start, end = modification.get("start", 0), modification.get("end", 0) @@ -356,7 +364,8 @@ async def async_post_call_success_hook( if role and content: response_messages.append({"role": role, "content": content}) - post_call_messages = original_messages + response_messages + # Use a copy of original_messages so _mask_pii_in_messages does not mutate data["messages"] + post_call_messages = copy.deepcopy(original_messages) + response_messages # Call Lakera guardrail lakera_guardrail_response, _ = await self.call_v2_guard( @@ -369,7 +378,7 @@ async def async_post_call_success_hook( if lakera_guardrail_response.get("flagged") is True: # If only PII violations exist, mask the PII in the response and allow if self._is_only_pii_violation(lakera_guardrail_response): - masked_entity_count: Dict = {} + masked_entity_count = {} masked_messages = self._mask_pii_in_messages( messages=post_call_messages, lakera_response=lakera_guardrail_response, @@ -382,7 +391,10 @@ async def async_post_call_success_hook( "role": msg.get("role", "assistant"), "content": msg.get("content", ""), } - return response_dict + add_guardrail_to_applied_guardrails_header( + request_data=data, guardrail_name=self.guardrail_name + ) + return ModelResponse(**response_dict) action = getattr(self, "on_flagged", "block") if action == "monitor": diff --git a/tests/guardrails_tests/test_lakera_v2.py b/tests/guardrails_tests/test_lakera_v2.py index c3ca5470a278..aad9929809ca 100644 --- a/tests/guardrails_tests/test_lakera_v2.py +++ b/tests/guardrails_tests/test_lakera_v2.py @@ -13,7 +13,7 @@ from litellm.caching.caching import DualCache from litellm.exceptions import BlockedPiiEntityError, GuardrailRaisedException from fastapi import HTTPException -from litellm.types.utils import CallTypes as LitellmCallTypes +from litellm.types.utils import CallTypes as LitellmCallTypes, ModelResponse @pytest.mark.asyncio @@ -503,6 +503,8 @@ async def test_lakera_post_call_masks_pii_and_allows(): response=llm_response, ) - assert result["choices"][0]["message"]["content"] != "Your email is test@example.com" - assert "[MASKED" in result["choices"][0]["message"]["content"] + assert isinstance(result, ModelResponse), "PII masking path must return ModelResponse" + result_dict = result.model_dump() + assert result_dict["choices"][0]["message"]["content"] != "Your email is test@example.com" + assert "[MASKED" in result_dict["choices"][0]["message"]["content"] diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_lakera_ai_v2.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_lakera_ai_v2.py new file mode 100644 index 000000000000..f6e7b7841e26 --- /dev/null +++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_lakera_ai_v2.py @@ -0,0 +1,66 @@ +""" +Tests for Lakera AI v2 guardrail hook (post-call and shared behavior). + +PR checklist requires at least one test in tests/test_litellm/. +Additional tests live in tests/guardrails_tests/test_lakera_v2.py. +""" +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from litellm.proxy._types import UserAPIKeyAuth +from litellm.proxy.guardrails.guardrail_hooks.lakera_ai_v2 import LakeraAIGuardrail +from litellm.types.utils import ModelResponse + + +@pytest.mark.asyncio +async def test_lakera_post_call_success_hook_returns_model_response_when_pii_masked(): + """ + Post-call hook must return a ModelResponse (not a dict) when PII is masked, + so the parent async_post_call_success_deployment_hook accepts it via _is_valid_response_type. + """ + lakera_guardrail = LakeraAIGuardrail(api_key="test_key") + mock_response = { + "payload": [ + {"detector_type": "pii/email", "start": 11, "end": 26, "message_id": 1} + ], + "flagged": True, + "breakdown": [ + {"detector_type": "pii/email", "detected": True, "message_id": 1}, + ], + } + llm_response = MagicMock() + llm_response.model_dump.return_value = { + "choices": [ + { + "message": { + "role": "assistant", + "content": "Your email is test@example.com", + } + }, + ] + } + + with patch.object( + lakera_guardrail, "call_v2_guard", new_callable=AsyncMock + ) as mock_call: + mock_call.return_value = (mock_response, {}) + data = { + "messages": [{"role": "user", "content": "Hello"}], + "model": "gpt-3.5-turbo", + "metadata": {}, + } + user_api_key_dict = UserAPIKeyAuth(api_key="test_key") + + result = await lakera_guardrail.async_post_call_success_hook( + data=data, + user_api_key_dict=user_api_key_dict, + response=llm_response, + ) + + assert isinstance( + result, ModelResponse + ), "Must return ModelResponse so deployment hook does not discard masked response" + result_dict = result.model_dump() + assert "[MASKED" in result_dict["choices"][0]["message"]["content"] + assert "test@example.com" not in result_dict["choices"][0]["message"]["content"] From 275c05623f7bca88ae272c1633ed975fc40f5e17 Mon Sep 17 00:00:00 2001 From: Steve Date: Sat, 21 Feb 2026 15:07:38 -0500 Subject: [PATCH 5/8] Updated ponteital for index mismatch when choices have null content and inconsistent on_flagged access pattern --- .../guardrail_hooks/lakera_ai_v2.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py index 9fd1acc25e4d..775782adb278 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py +++ b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py @@ -350,12 +350,15 @@ async def async_post_call_success_hook( if original_messages is None: original_messages = [] - # Extract assistant messages from the response, keeping only role/content + # Extract assistant messages from the response, keeping only role/content. + # Track choice indices so we write masked content back to the correct choice + # when some choices have null content (e.g. tool-call-only). response_messages: List[AllMessageValues] = [] + choice_indices: List[int] = [] response_dict = ( response.model_dump() if hasattr(response, "model_dump") else {} ) - for choice in response_dict.get("choices", []): + for i, choice in enumerate(response_dict.get("choices", [])): msg = choice.get("message") if not msg: continue @@ -363,6 +366,7 @@ async def async_post_call_success_hook( content = msg.get("content") if role and content: response_messages.append({"role": role, "content": content}) + choice_indices.append(i) # Use a copy of original_messages so _mask_pii_in_messages does not mutate data["messages"] post_call_messages = copy.deepcopy(original_messages) + response_messages @@ -386,8 +390,9 @@ async def async_post_call_success_hook( ) assistant_messages = masked_messages[len(original_messages) :] for idx, msg in enumerate(assistant_messages): - if idx < len(response_dict.get("choices", [])): - response_dict["choices"][idx]["message"] = { + if idx < len(choice_indices): + choice_idx = choice_indices[idx] + response_dict["choices"][choice_idx]["message"] = { "role": msg.get("role", "assistant"), "content": msg.get("content", ""), } @@ -396,14 +401,12 @@ async def async_post_call_success_hook( ) return ModelResponse(**response_dict) - action = getattr(self, "on_flagged", "block") - if action == "monitor": + if self.on_flagged == "monitor": verbose_proxy_logger.warning( "Lakera Guardrail: Post-call violation detected in monitor mode" ) # Allow response to proceed - else: - # Default/block behavior + elif self.on_flagged == "block": raise self._get_http_exception_for_blocked_guardrail( lakera_guardrail_response ) From 33257c37d41d5f340fa21577fedae5f9de9cf709 Mon Sep 17 00:00:00 2001 From: Steve G <9045562+eurogig@users.noreply.github.com> Date: Sat, 21 Feb 2026 15:41:56 -0500 Subject: [PATCH 6/8] Update litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> --- litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py index 775782adb278..237629e920fd 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py +++ b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py @@ -392,10 +392,7 @@ async def async_post_call_success_hook( for idx, msg in enumerate(assistant_messages): if idx < len(choice_indices): choice_idx = choice_indices[idx] - response_dict["choices"][choice_idx]["message"] = { - "role": msg.get("role", "assistant"), - "content": msg.get("content", ""), - } + response_dict["choices"][choice_idx]["message"]["content"] = msg.get("content", "") add_guardrail_to_applied_guardrails_header( request_data=data, guardrail_name=self.guardrail_name ) From 610dc2b7bc53edc922b9e58aca7ecbc63df96c76 Mon Sep 17 00:00:00 2001 From: Steve Date: Sun, 22 Feb 2026 15:36:17 -0500 Subject: [PATCH 7/8] Update to explicitly state supported endpoints - chat completions --- docs/my-website/docs/proxy/guardrails/lakera_ai.md | 2 ++ litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py | 3 +++ 2 files changed, 5 insertions(+) diff --git a/docs/my-website/docs/proxy/guardrails/lakera_ai.md b/docs/my-website/docs/proxy/guardrails/lakera_ai.md index 7aacc3fa9246..cd27dd236180 100644 --- a/docs/my-website/docs/proxy/guardrails/lakera_ai.md +++ b/docs/my-website/docs/proxy/guardrails/lakera_ai.md @@ -4,6 +4,8 @@ import TabItem from '@theme/TabItem'; # Lakera AI +**Supported endpoints:** The Lakera v2 integration only supports the **chat completions** endpoint (`/v1/chat/completions`). It is not supported for the Responses API, `/v1/messages`, MCP, A2A, or other proxy endpoints. + ## Quick Start ### 1. Define Guardrails on your LiteLLM config.yaml diff --git a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py index 237629e920fd..b4850b99277b 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py +++ b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py @@ -39,6 +39,9 @@ def __init__( """ Initialize the LakeraAIGuardrail class. + This guardrail only supports the chat completions endpoint (/v1/chat/completions). + It is not supported for the Responses API, /v1/messages, MCP, A2A, or other endpoints. + This calls: https://api.lakera.ai/v2/guard Args: From d78869dda1ecd42baecf74c1059c65a7654ad0e9 Mon Sep 17 00:00:00 2001 From: Steve Date: Wed, 25 Feb 2026 14:53:51 -0500 Subject: [PATCH 8/8] Fix minor lint error on masked_entity_count --- litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py index b4850b99277b..dbda524ca044 100644 --- a/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py +++ b/litellm/proxy/guardrails/guardrail_hooks/lakera_ai_v2.py @@ -385,7 +385,7 @@ async def async_post_call_success_hook( if lakera_guardrail_response.get("flagged") is True: # If only PII violations exist, mask the PII in the response and allow if self._is_only_pii_violation(lakera_guardrail_response): - masked_entity_count = {} + masked_entity_count: Dict[str, int] = {} masked_messages = self._mask_pii_in_messages( messages=post_call_messages, lakera_response=lakera_guardrail_response,