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]

Feat/support anonymize in aim guardrail (#10757)

Dror Baron93639df4c381
diff --git a/litellm/proxy/guardrails/guardrail_hooks/aim.py b/litellm/proxy/guardrails/guardrail_hooks/aim.py
index 86a9cf778a5..0409068afc4 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/aim.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/aim.py
@@ -56,6 +56,8 @@ class AimGuardrail(CustomGuardrail):
self.ws_api_base = self.api_base.replace("http://", "ws://").replace(
"https://", "wss://"
)
+ self.dlp_entities: list[dict] = []
+ self._max_dlp_entities = 100
super().__init__(**kwargs)
async def async_pre_call_hook(
@@ -76,10 +78,9 @@ class AimGuardrail(CustomGuardrail):
) -> Union[Exception, str, dict, None]:
verbose_proxy_logger.debug("Inside AIM Pre-Call Hook")
- await self.call_aim_guardrail(
+ return await self.call_aim_guardrail(
data, hook="pre_call", key_alias=user_api_key_dict.key_alias
)
- return data
async def async_moderation_hook(
self,
@@ -103,7 +104,7 @@ class AimGuardrail(CustomGuardrail):
async def call_aim_guardrail(
self, data: dict, hook: str, key_alias: Optional[str]
- ) -> None:
+ ) -> dict:
user_email = data.get("metadata", {}).get("headers", {}).get("x-aim-user-email")
call_id = data.get("litellm_call_id")
headers = self._build_aim_headers(
@@ -113,31 +114,73 @@ class AimGuardrail(CustomGuardrail):
litellm_call_id=call_id,
)
response = await self.async_handler.post(
- f"{self.api_base}/detect/openai",
+ f"{self.api_base}/detect/openai/v2",
headers=headers,
json={"messages": data.get("messages", [])},
)
response.raise_for_status()
res = response.json()
- detected = res["detected"]
+ required_action = res.get("required_action")
+ action_type = required_action and required_action.get("action_type", None)
+ if action_type is None:
+ verbose_proxy_logger.debug("Aim: No required action specified")
+ return data
+ match action_type:
+ case "monitor_action":
+ verbose_proxy_logger.info("Aim: monitor action")
+ case "block_action":
+ self._handle_block_action(res["analysis_result"], required_action)
+ case "anonymize_action":
+ return self._anonymize_request(
+ res["analysis_result"], required_action, data
+ )
+ case _:
+ verbose_proxy_logger.error(f"Aim: {action_type} action")
+ return data
+
+ def _handle_block_action(self, analysis_result: Any, required_action: Any) -> None:
+ detection_message = required_action.get("detection_message", None)
verbose_proxy_logger.info(
- "Aim: detected: {detected}, enabled policies: {policies}".format(
- detected=detected,
- policies=list(res["details"].keys()),
+ "Aim: Violation detected enabled policies: {policies}".format(
+ policies=list(analysis_result["policy_drill_down"].keys()),
),
)
- if detected:
- raise HTTPException(status_code=400, detail=res["detection_message"])
+ raise HTTPException(status_code=400, detail=detection_message)
+
+ def _anonymize_request(
+ self, analysis_result: Any, required_action: Any, data: dict
+ ) -> dict:
+ verbose_proxy_logger.info("Aim: anonymize action")
+ redaction_result = required_action and required_action.get(
+ "chat_redaction_result"
+ )
+ if not redaction_result:
+ return data
+ if analysis_result and analysis_result.get("session_entities"):
+ self._set_dlp_entities(analysis_result.get("session_entities"))
+ data["messages"] = [
+ {
+ "role": redaction_result["redacted_new_message"]["role"],
+ "content": redaction_result["redacted_new_message"]["content"],
+ }
+ ] + [
+ {
+ "role": message["role"],
+ "content": message["content"],
+ }
+ for message in redaction_result["all_redacted_messages"]
+ ]
+ return data
async def call_aim_guardrail_on_output(
self, request_data: dict, output: str, hook: str, key_alias: Optional[str]
- ) -> Optional[str]:
+ ) -> Optional[dict]:
user_email = (
request_data.get("metadata", {}).get("headers", {}).get("x-aim-user-email")
)
call_id = request_data.get("litellm_call_id")
response = await self.async_handler.post(
- f"{self.api_base}/detect/output",
+ f"{self.api_base}/detect/output/v2",
headers=self._build_aim_headers(
hook=hook,
key_alias=key_alias,
@@ -148,16 +191,34 @@ class AimGuardrail(CustomGuardrail):
)
response.raise_for_status()
res = response.json()
- detected = res["detected"]
+ required_action = res.get("required_action")
+ action_type = required_action and required_action.get("action_type", None)
+ if action_type and action_type == "block_action":
+ return self._handle_block_action_on_output(
+ res["analysis_result"], required_action
+ )
+ return self._deanonymize_output(output)
+
+ def _handle_block_action_on_output(
+ self, analysis_result: Any, required_action: Any
+ ) -> dict | None:
+ detection_message = required_action.get("detection_message", None)
verbose_proxy_logger.info(
"Aim: detected: {detected}, enabled policies: {policies}".format(
- detected=detected,
- policies=list(res["details"].keys()),
+ detected=True,
+ policies=list(analysis_result["policy_drill_down"].keys()),
),
)
- if detected:
- return res["detection_message"]
- return None
+ return {"detection_message": detection_message}
+
+ def _deanonymize_output(self, output: str) -> dict | None:
+ try:
+ for entity in self.dlp_entities:
+ output = output.replace(f"[{entity['name']}]", entity["content"])
+ return {"redacted_output": output}
+ except Exception as e:
+ verbose_proxy_logger.error(f"Aim: Error while redacting output: {e}")
+ return None
def _build_aim_headers(
self,
@@ -204,11 +265,23 @@ class AimGuardrail(CustomGuardrail):
and isinstance(response.choices[0], Choices)
):
content = response.choices[0].message.content or ""
- detection = await self.call_aim_guardrail_on_output(
+ aim_output_guardrail_result = await self.call_aim_guardrail_on_output(
data, content, hook="output", key_alias=user_api_key_dict.key_alias
)
- if detection:
- raise HTTPException(status_code=400, detail=detection)
+ if aim_output_guardrail_result and aim_output_guardrail_result.get(
+ "detection_message"
+ ):
+ raise HTTPException(
+ status_code=400,
+ detail=aim_output_guardrail_result.get("detection_message"),
+ )
+ if aim_output_guardrail_result and aim_output_guardrail_result.get(
+ "redacted_output"
+ ):
+ response.choices[0].message.content = aim_output_guardrail_result.get(
+ "redacted_output"
+ )
+ return response
async def async_post_call_streaming_iterator_hook(
self,
@@ -259,3 +332,6 @@ class AimGuardrail(CustomGuardrail):
chunk = json.dumps(chunk)
await websocket.send(chunk)
await websocket.send(json.dumps({"done": True}))
+
+ def _set_dlp_entities(self, entities: list[dict]) -> None:
+ self.dlp_entities = entities[: self._max_dlp_entities]
diff --git a/tests/local_testing/test_aim_guardrails.py b/tests/local_testing/test_aim_guardrails.py
index 4e33bcda7c3..95614094b17 100644
--- a/tests/local_testing/test_aim_guardrails.py
+++ b/tests/local_testing/test_aim_guardrails.py
@@ -10,11 +10,16 @@ from fastapi.exceptions import HTTPException
from httpx import Request, Response
from litellm import DualCache
-from litellm.proxy.guardrails.guardrail_hooks.aim import AimGuardrail, AimGuardrailMissingSecrets
+from litellm.proxy.guardrails.guardrail_hooks.aim import (
+ AimGuardrail,
+ AimGuardrailMissingSecrets,
+)
from litellm.proxy.proxy_server import StreamingCallbackError, UserAPIKeyAuth
-from litellm.types.utils import ModelResponseStream
+from litellm.types.utils import ModelResponseStream, ModelResponse
-sys.path.insert(0, os.path.abspath("../..")) # Adds the parent directory to the system path
+sys.path.insert(
+ 0, os.path.abspath("../..")
+) # Adds the parent directory to the system path
import litellm
from litellm.proxy.guardrails.init_guardrails import init_guardrails_v2
@@ -70,7 +75,7 @@ def test_aim_guard_config_no_api_key():
@pytest.mark.asyncio
@pytest.mark.parametrize("mode", ["pre_call", "during_call"])
-async def test_callback(mode: str):
+async def test_block_callback(mode: str):
init_guardrails_v2(
all_guardrails=[
{
@@ -84,7 +89,9 @@ async def test_callback(mode: str):
],
config_file_path="",
)
- aim_guardrails = [callback for callback in litellm.callbacks if isinstance(callback, AimGuardrail)]
+ aim_guardrails = [
+ callback for callback in litellm.callbacks if isinstance(callback, AimGuardrail)
+ ]
assert len(aim_guardrails) == 1
aim_guardrail = aim_guardrails[0]
@@ -98,7 +105,18 @@ async def test_callback(mode: str):
with patch(
"litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.post",
return_value=Response(
- json={"detected": True, "details": {}, "detection_message": "Jailbreak detected"},
+ json={
+ "analysis_result": {
+ "analysis_time_ms": 212,
+ "policy_drill_down": {},
+ "session_entities": [],
+ },
+ "required_action": {
+ "action_type": "block_action",
+ "detection_message": "Jailbreak detected",
+ "policy_name": "blocking policy",
+ },
+ },
status_code=200,
request=Request(method="POST", url="http://aim"),
),
@@ -118,6 +136,123 @@ async def test_callback(mode: str):
)
[email protected]("mode", ["pre_call", "during_call"])
+async def test_anonymize_callback__it_returns_redacted_content(mode: str):
+ init_guardrails_v2(
+ all_guardrails=[
+ {
+ "guardrail_name": "gibberish-guard",
+ "litellm_params": {
+ "guardrail": "aim",
+ "mode": mode,
+ "api_key": "hs-aim-key",
+ },
+ },
+ ],
+ config_file_path="",
+ )
+ aim_guardrails = [
+ callback for callback in litellm.callbacks if isinstance(callback, AimGuardrail)
+ ]
+ assert len(aim_guardrails) == 1
+ aim_guardrail = aim_guardrails[0]
+
+ data = {
+ "messages": [
+ {"role": "user", "content": "Hi my name id Brian"},
+ ],
+ }
+
+ with patch(
+ "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.post",
+ return_value=response_with_detections,
+ ):
+ if mode == "pre_call":
+ data = await aim_guardrail.async_pre_call_hook(
+ data=data,
+ cache=DualCache(),
+ user_api_key_dict=UserAPIKeyAuth(),
+ call_type="completion",
+ )
+ else:
+ data = await aim_guardrail.async_moderation_hook(
+ data=data,
+ user_api_key_dict=UserAPIKeyAuth(),
+ call_type="completion",
+ )
+ assert data["messages"][0]["content"] == "Hi my name is [NAME_1]"
+
+
+async def test_post_call__with_anonymized_entities__it_deanonymizes_output():
+ init_guardrails_v2(
+ all_guardrails=[
+ {
+ "guardrail_name": "gibberish-guard",
+ "litellm_params": {
+ "guardrail": "aim",
+ "mode": "pre_call",
+ "api_key": "hs-aim-key",
+ },
+ },
+ ],
+ config_file_path="",
+ )
+ aim_guardrails = [
+ callback for callback in litellm.callbacks if isinstance(callback, AimGuardrail)
+ ]
+ assert len(aim_guardrails) == 1
+ aim_guardrail = aim_guardrails[0]
+
+ data = {
+ "messages": [
+ {"role": "user", "content": "Hi my name id Brian"},
+ ],
+ }
+
+ with patch(
+ "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.post"
+ ) as mock_post:
+
+ def mock_post_detect_side_effect(url, *args, **kwargs):
+ if url.endswith("/detect/openai/v2"):
+ return response_with_detections
+ elif url.endswith("/detect/output/v2"):
+ return response_without_detections
+ else:
+ raise ValueError("Unexpected URL: {}".format(url))
+
+ mock_post.side_effect = mock_post_detect_side_effect
+
+ data = await aim_guardrail.async_pre_call_hook(
+ data=data,
+ cache=DualCache(),
+ user_api_key_dict=UserAPIKeyAuth(),
+ call_type="completion",
+ )
+ assert data["messages"][0]["content"] == "Hi my name is [NAME_1]"
+
+ def llm_response() -> ModelResponse:
+ return ModelResponse(
+ choices=[
+ {
+ "finish_reason": "stop",
+ "index": 0,
+ "message": {
+ "content": "Hello [NAME_1]! How are you?",
+ "role": "assistant",
+ },
+ }
+ ]
+ )
+
+ result = await aim_guardrail.async_post_call_success_hook(
+ data=data, response=llm_response(), user_api_key_dict=UserAPIKeyAuth()
+ )
+ assert result["choices"][0]["message"]["content"] == "Hello Brian! How are you?"
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("length", (0, 1, 2))
async def test_post_call_stream__all_chunks_are_valid(monkeypatch, length: int):
@@ -134,7 +269,9 @@ async def test_post_call_stream__all_chunks_are_valid(monkeypatch, length: int):
],
config_file_path="",
)
- aim_guardrails = [callback for callback in litellm.callbacks if isinstance(callback, AimGuardrail)]
+ aim_guardrails = [
+ callback for callback in litellm.callbacks if isinstance(callback, AimGuardrail)
+ ]
assert len(aim_guardrails) == 1
aim_guardrail = aim_guardrails[0]
@@ -150,7 +287,9 @@ async def test_post_call_stream__all_chunks_are_valid(monkeypatch, length: int):
websocket_mock = AsyncMock()
- messages_from_aim = [b'{"verified_chunk": {"choices": [{"delta": {"content": "A"}}]}}'] * length
+ messages_from_aim = [
+ b'{"verified_chunk": {"choices": [{"delta": {"content": "A"}}]}}'
+ ] * length
messages_from_aim.append(b'{"done": true}')
websocket_mock.recv = ReceiveMock(messages_from_aim, delay=0.2)
@@ -158,7 +297,9 @@ async def test_post_call_stream__all_chunks_are_valid(monkeypatch, length: int):
async def connect_mock(*args, **kwargs):
yield websocket_mock
- monkeypatch.setattr("litellm.proxy.guardrails.guardrail_hooks.aim.connect", connect_mock)
+ monkeypatch.setattr(
+ "litellm.proxy.guardrails.guardrail_hooks.aim.connect", connect_mock
+ )
results = []
async for result in aim_guardrail.async_post_call_streaming_iterator_hook(
@@ -188,7 +329,9 @@ async def test_post_call_stream__blocked_chunks(monkeypatch):
],
config_file_path="",
)
- aim_guardrails = [callback for callback in litellm.callbacks if isinstance(callback, AimGuardrail)]
+ aim_guardrails = [
+ callback for callback in litellm.callbacks if isinstance(callback, AimGuardrail)
+ ]
assert len(aim_guardrails) == 1
aim_guardrail = aim_guardrails[0]
@@ -213,7 +356,9 @@ async def test_post_call_stream__blocked_chunks(monkeypatch):
async def connect_mock(*args, **kwargs):
yield websocket_mock
- monkeypatch.setattr("litellm.proxy.guardrails.guardrail_hooks.aim.connect", connect_mock)
+ monkeypatch.setattr(
+ "litellm.proxy.guardrails.guardrail_hooks.aim.connect", connect_mock
+ )
results = []
with pytest.raises(StreamingCallbackError, match="Jailbreak detected"):
@@ -227,4 +372,88 @@ async def test_post_call_stream__blocked_chunks(monkeypatch):
# Chunks that were received before the blocking message should be returned as usual.
assert len(results) == 1
assert results[0].choices[0].delta.content == "A"
- assert websocket_mock.send.mock_calls == [call('{"choices": [{"delta": {"content": "A"}}]}'), call('{"done": true}')]
+ assert websocket_mock.send.mock_calls == [
+ call('{"choices": [{"delta": {"content": "A"}}]}'),
+ call('{"done": true}'),
+ ]
+
+
+response_with_detections = Response(
+ json={
+ "analysis_result": {
+ "analysis_time_ms": 10,
+ "policy_drill_down": {
+ "PII": {
+ "detections": [
+ {
+ "message": '"Brian" detected as name',
+ "entity": {
+ "type": "NAME",
+ "content": "Brian",
+ "start": 14,
+ "end": 19,
+ "score": 1.0,
+ "certainty": "HIGH",
+ "additional_content_index": None,
+ },
+ "detection_location": None,
+ }
+ ]
+ }
+ },
+ "last_message_entities": [
+ {
+ "type": "NAME",
+ "content": "Brian",
+ "name": "NAME_1",
+ "start": 14,
+ "end": 19,
+ "score": 1.0,
+ "certainty": "HIGH",
+ "additional_content_index": None,
+ }
+ ],
+ "session_entities": [
+ {"type": "NAME", "content": "Brian", "name": "NAME_1"}
+ ],
+ },
+ "required_action": {
+ "action_type": "anonymize_action",
+ "policy_name": "PII",
+ "chat_redaction_result": {
+ "all_redacted_messages": [
+ {
+ "content": "Hi my name is [NAME_1]",
+ "role": "user",
+ "additional_contents": [],
+ "received_message_id": "0",
+ "extra_fields": {},
+ }
+ ],
+ "redacted_new_message": {
+ "content": "Hi my name is [NAME_1]",
+ "role": "user",
+ "additional_contents": [],
+ "received_message_id": "0",
+ "extra_fields": {},
+ },
+ },
+ },
+ },
+ status_code=200,
+ request=Request(method="POST", url="http://aim"),
+)
+
+response_without_detections = Response(
+ json={
+ "analysis_result": {
+ "analysis_time_ms": 10,
+ "policy_drill_down": {},
+ "last_message_entities": [],
+ "session_entities": [],
+ },
+ "required_action": None,
+ },
+ status_code=200,
+ request=Request(method="POST", url="http://aim"),
+)