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
Guardrails AI - support `llmOutput` based guardrails as pre-call hooks (#12674)
Krish Dholakia5004b915d1e3
diff --git a/litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/__init__.pyindex 885a88334df..454e06fdbc5 100644--- a/litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/__init__.py+++ b/litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/__init__.py@@ -23,6 +23,9 @@ def initialize_guardrail(litellm_params: "LitellmParams", guardrail: "Guardrail"event_hook=litellm_params.mode,default_on=litellm_params.default_on,guard_name=litellm_params.guard_name,+ guardrails_ai_api_input_format=getattr(+ litellm_params, "guardrails_ai_api_input_format", "llmOutput"+ ),)litellm.logging_callback_manager.add_litellm_callback(_guardrails_ai_callback)diff --git a/litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/guardrails_ai.py b/litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/guardrails_ai.pyindex 0e3b4b670f6..050617790df 100644--- a/litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/guardrails_ai.py+++ b/litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/guardrails_ai.py@@ -62,6 +62,7 @@ class GuardrailsAI(CustomGuardrail):self,guard_name: str,api_base: Optional[str] = None,+ guardrails_ai_api_input_format: Literal["inputs", "llmOutput"] = "llmOutput",**kwargs,):if guard_name is None:@@ -74,6 +75,7 @@ class GuardrailsAI(CustomGuardrail):)self.guardrails_ai_guard_name = guard_nameself.optional_params = kwargs+ self.guardrails_ai_api_input_format = guardrails_ai_api_input_formatsupported_event_hooks = [GuardrailEventHooks.post_call,GuardrailEventHooks.pre_call,@@ -81,7 +83,9 @@ class GuardrailsAI(CustomGuardrail):]super().__init__(supported_event_hooks=supported_event_hooks, **kwargs)- async def make_guardrails_ai_api_request(self, llm_output: str, request_data: dict):+ async def make_guardrails_ai_api_request(+ self, llm_output: str, request_data: dict+ ) -> GuardrailsAIResponse:from httpx import URLdata = {@@ -166,9 +170,17 @@ class GuardrailsAI(CustomGuardrail):text = get_last_user_message(data["messages"])if text is None:return data- updated_text = await self.make_guardrails_ai_api_request_pre_call_request(- text_input=text, request_data=data- )+ if self.guardrails_ai_api_input_format == "inputs":+ updated_text = (+ await self.make_guardrails_ai_api_request_pre_call_request(+ text_input=text, request_data=data+ )+ )+ else:+ _result = await self.make_guardrails_ai_api_request(+ llm_output=text, request_data=data+ )+ updated_text = _result.get("rawLlmOutput") or textdata["messages"] = set_last_user_message(data["messages"], updated_text)return datadiff --git a/litellm/types/proxy/guardrails/guardrail_hooks/guardrails_ai.py b/litellm/types/proxy/guardrails/guardrail_hooks/guardrails_ai.pyindex cb5e85661e4..a0298dbe955 100644--- a/litellm/types/proxy/guardrails/guardrail_hooks/guardrails_ai.py+++ b/litellm/types/proxy/guardrails/guardrail_hooks/guardrails_ai.py@@ -1,4 +1,4 @@-from typing import Optional+from typing import Literal, Optionalfrom pydantic import Field@@ -16,6 +16,11 @@ class GuardrailsAIGuardrailConfigModel(GuardrailConfigModel):description="The name of the Guardrails AI guardrail. Required for the Guardrails AI guardrail.",)+ guardrails_ai_api_input_format: Optional[Literal["inputs", "llmOutput"]] = Field(+ default="llmOutput",+ description="The format of the input to the Guardrails AI API. Defaults to 'llmOutput'.",+ )+@staticmethoddef ui_friendly_name() -> str:return "Guardrails AI"diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/test_guardrails_ai.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/test_guardrails_ai.pyindex a3e1b0cd4c8..ba0db9fc538 100644--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/test_guardrails_ai.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/guardrails_ai/test_guardrails_ai.py@@ -15,6 +15,9 @@ from litellm.types.utils import Choices, Message, ModelResponse@pytest.mark.asyncioasync def test_guardrails_ai_process_input():"""Test the process_input method of GuardrailsAI with various scenarios"""+ from litellm.proxy.guardrails.guardrail_hooks.guardrails_ai.guardrails_ai import (+ GuardrailsAIResponse,+ )# Initialize the GuardrailsAI instanceguardrails_ai_guardrail = GuardrailsAI(@@ -26,8 +29,10 @@ async def test_guardrails_ai_process_input():# Test case 1: Valid completion call with messageswith patch.object(guardrails_ai_guardrail,- "make_guardrails_ai_api_request_pre_call_request",- return_value="processed text",+ "make_guardrails_ai_api_request",+ return_value=GuardrailsAIResponse(+ rawLlmOutput="processed text",+ ),) as mock_api_request:data = {@@ -41,7 +46,7 @@ async def test_guardrails_ai_process_input():# Verify the API was called with the user messagemock_api_request.assert_called_once_with(- text_input="Hello, how are you?", request_data=data+ llm_output="Hello, how are you?", request_data=data)# Verify the message was updated@@ -52,8 +57,10 @@ async def test_guardrails_ai_process_input():# Test case 2: Valid acompletion call with messageswith patch.object(guardrails_ai_guardrail,- "make_guardrails_ai_api_request_pre_call_request",- return_value="async processed text",+ "make_guardrails_ai_api_request",+ return_value=GuardrailsAIResponse(+ rawLlmOutput="async processed text",+ ),) as mock_api_request:data = {"messages": [{"role": "user", "content": "What is the weather?"}]}@@ -61,7 +68,7 @@ async def test_guardrails_ai_process_input():result = await guardrails_ai_guardrail.process_input(data, "acompletion")mock_api_request.assert_called_once_with(- text_input="What is the weather?", request_data=data+ llm_output="What is the weather?", request_data=data)assert result["messages"][0]["content"] == "async processed text"@@ -99,8 +106,10 @@ async def test_guardrails_ai_process_input():# Test case 6: Complex conversation with multiple messageswith patch.object(guardrails_ai_guardrail,- "make_guardrails_ai_api_request_pre_call_request",- return_value="sanitized message",+ "make_guardrails_ai_api_request",+ return_value=GuardrailsAIResponse(+ rawLlmOutput="sanitized message",+ ),) as mock_api_request:data = {@@ -116,7 +125,7 @@ async def test_guardrails_ai_process_input():# Should process the last user messagemock_api_request.assert_called_once_with(- text_input="Second question", request_data=data+ llm_output="Second question", request_data=data)# Only the last user message should be updated