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
Add Azure Content Safety Guardrails to LiteLLM proxy (#12268)
Krish Dholakia42cd05dee884
diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.pyindex a82eed8eb8f..2cb80b3d698 100644--- a/litellm/integrations/custom_guardrail.py+++ b/litellm/integrations/custom_guardrail.py@@ -46,6 +46,7 @@ class CustomGuardrail(CustomLogger):self.mask_response_content: bool = mask_response_contentif supported_event_hooks:+## validate event_hook is in supported_event_hooksself._validate_event_hook(event_hook, supported_event_hooks)super().__init__(**kwargs)@@ -55,10 +56,15 @@ class CustomGuardrail(CustomLogger):event_hook: Optional[Union[GuardrailEventHooks, List[GuardrailEventHooks]]],supported_event_hooks: List[GuardrailEventHooks],) -> None:+if event_hook is None:return+ if isinstance(event_hook, str):+ event_hook = GuardrailEventHooks(event_hook)if isinstance(event_hook, list):for hook in event_hook:+ if isinstance(hook, str):+ hook = GuardrailEventHooks(hook)if hook not in supported_event_hooks:raise ValueError(f"Event hook {hook} is not in the supported event hooks {supported_event_hooks}"diff --git a/litellm/litellm_core_utils/exception_mapping_utils.py b/litellm/litellm_core_utils/exception_mapping_utils.pyindex ad5060c533b..5d1d5c71276 100644--- a/litellm/litellm_core_utils/exception_mapping_utils.py+++ b/litellm/litellm_core_utils/exception_mapping_utils.py@@ -28,23 +28,22 @@ class ExceptionCheckers:"""Helper class for checking various error conditions in exception strings."""-+@staticmethoddef is_error_str_rate_limit(error_str: str) -> bool:"""Check if an error string indicates a rate limit error.-+Args:error_str: The error string to check-+Returns:True if the error indicates a rate limit, False otherwise"""if not isinstance(error_str, str):return False-+return "429" in error_str or "rate limit" in error_str.lower()-@staticmethoddef is_error_str_context_window_exceeded(error_str: str) -> bool:@@ -289,6 +288,7 @@ def exception_type( # type: ignore # noqa: PLR0915or custom_llm_provider == "text-completion-openai"or custom_llm_provider == "custom_openai"or custom_llm_provider in litellm.openai_compatible_providers+ or custom_llm_provider == "mistral"):# custom_llm_provider is openai, make it OpenAImessage = get_error_message(error_obj=original_exception)diff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yamlindex 6ad4c778888..8be231a1fe5 100644--- a/litellm/proxy/_new_secret_config.yaml+++ b/litellm/proxy/_new_secret_config.yaml@@ -1,11 +1,8 @@model_list:- - model_name: "gpt-4o"+ - model_name: gpt-3.5-turbolitellm_params:- model: "gpt-4o"+ model: openai/gpt-3.5-turboapi_key: os.environ/OPENAI_API_KEY-<<<<<<< HEAD- - model_name: "gemini-2.0-flash"-=======guardrails:- guardrail_name: azure-prompt-shield@@ -13,10 +10,4 @@ guardrails:guardrail: azure/prompt_shieldmode: pre_call # "During_call" is also availableapi_key: os.environ/AZURE_GUARDRAIL_API_KEY- api_base: os.environ/AZURE_GUARDRAIL_API_BASE- - guardrail_name: azure-text-moderation->>>>>>> 6ebc8d473 (test: change mistral model)- litellm_params:- model: "gemini/gemini-2.0-flash"- api_key: os.environ/GEMINI_API_KEY- stream: True+ api_base: os.environ/AZURE_GUARDRAIL_API_BASE\ No newline at end of filediff --git a/litellm/proxy/guardrails/guardrail_hooks/azure/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/azure/__init__.pynew file mode 100644index 00000000000..39501ca470d--- /dev/null+++ b/litellm/proxy/guardrails/guardrail_hooks/azure/__init__.py@@ -0,0 +1,59 @@+from typing import TYPE_CHECKING, Union++from litellm.types.guardrails import SupportedGuardrailIntegrations++if TYPE_CHECKING:+ from litellm.types.guardrails import Guardrail, LitellmParams+++def initialize_guardrail(litellm_params: "LitellmParams", guardrail: "Guardrail"):+ import litellm++ from .prompt_shield import AzureContentSafetyPromptShieldGuardrail+ from .text_moderation import AzureContentSafetyTextModerationGuardrail++ if not litellm_params.api_key:+ raise ValueError("Azure Content Safety: api_key is required")+ if not litellm_params.api_base:+ raise ValueError("Azure Content Safety: api_base is required")++ azure_guardrail = litellm_params.guardrail.split("/")[1]++ guardrail_name = guardrail.get("guardrail_name")+ if not guardrail_name:+ raise ValueError("Azure Content Safety: guardrail_name is required")++ if azure_guardrail == "prompt_shield":+ azure_content_safety_guardrail: Union[+ AzureContentSafetyPromptShieldGuardrail,+ AzureContentSafetyTextModerationGuardrail,+ ] = AzureContentSafetyPromptShieldGuardrail(+ guardrail_name=guardrail_name,+ api_key=litellm_params.api_key,+ api_base=litellm_params.api_base,+ default_on=litellm_params.default_on,+ event_hook=litellm_params.mode,+ )+ elif azure_guardrail == "text_moderations":+ azure_content_safety_guardrail = AzureContentSafetyTextModerationGuardrail(+ guardrail_name=guardrail_name,+ api_key=litellm_params.api_key,+ api_base=litellm_params.api_base,+ default_on=litellm_params.default_on,+ event_hook=litellm_params.mode,+ )+ else:+ raise ValueError(+ f"Azure Content Safety: {azure_guardrail} is not a valid guardrail"+ )++ litellm.logging_callback_manager.add_litellm_callback(+ azure_content_safety_guardrail+ )+ return azure_content_safety_guardrail+++guardrail_initializer_registry = {+ SupportedGuardrailIntegrations.AZURE_PROMPT_SHIELD.value: initialize_guardrail,+ SupportedGuardrailIntegrations.AZURE_TEXT_MODERATIONS.value: initialize_guardrail,+}diff --git a/litellm/proxy/guardrails/guardrail_hooks/azure/base.py b/litellm/proxy/guardrails/guardrail_hooks/azure/base.pynew file mode 100644index 00000000000..7903cd8bc0d--- /dev/null+++ b/litellm/proxy/guardrails/guardrail_hooks/azure/base.py@@ -0,0 +1,52 @@+from typing import TYPE_CHECKING, List, Optional++if TYPE_CHECKING:+ from litellm.types.llms.openai import AllMessageValues+++class AzureGuardrailBase:+ """+ Base class for Azure guardrails.+ """++ def get_user_prompt(self, messages: List["AllMessageValues"]) -> Optional[str]:+ """+ Get the last consecutive block of messages from the user.++ Example:+ messages = [+ {"role": "user", "content": "Hello, how are you?"},+ {"role": "assistant", "content": "I'm good, thank you!"},+ {"role": "user", "content": "What is the weather in Tokyo?"},+ ]+ get_user_prompt(messages) -> "What is the weather in Tokyo?"+ """+ from litellm.litellm_core_utils.prompt_templates.common_utils import (+ convert_content_list_to_str,+ )++ if not messages:+ return None++ # Iterate from the end to find the last consecutive block of user messages+ user_messages = []+ for message in reversed(messages):+ if message.get("role") == "user":+ user_messages.append(message)+ else:+ # Stop when we hit a non-user message+ break++ if not user_messages:+ return None++ # Reverse to get the messages in chronological order+ user_messages.reverse()++ user_prompt = ""+ for message in user_messages:+ text_content = convert_content_list_to_str(message)+ user_prompt += text_content + "\n"++ result = user_prompt.strip()+ return result if result else Nonediff --git a/litellm/proxy/guardrails/guardrail_hooks/azure/prompt_shield.py b/litellm/proxy/guardrails/guardrail_hooks/azure/prompt_shield.pynew file mode 100644index 00000000000..7624a963b77--- /dev/null+++ b/litellm/proxy/guardrails/guardrail_hooks/azure/prompt_shield.py@@ -0,0 +1,185 @@+#!/usr/bin/env python3+"""+Azure Prompt Shield Native Guardrail Integrationfor LiteLLM+"""++from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, cast++from fastapi import HTTPException++from litellm._logging import verbose_proxy_logger+from litellm.integrations.custom_guardrail import (+ CustomGuardrail,+ log_guardrail_information,+)+from litellm.llms.custom_httpx.http_handler import (+ get_async_httpx_client,+ httpxSpecialProvider,+)++from .base import AzureGuardrailBase++if TYPE_CHECKING:+ from litellm.proxy._types import UserAPIKeyAuth+ from litellm.types.llms.openai import AllMessageValues+ from litellm.types.proxy.guardrails.guardrail_hooks.azure.azure_prompt_shield import (+ AzurePromptShieldGuardrailResponse,+ )+ from litellm.types.utils import ModelResponse+++class AzureContentSafetyPromptShieldGuardrail(AzureGuardrailBase, CustomGuardrail):+ """+ LiteLLM Built-in Guardrail for Azure Content Safety Guardrail (Prompt Shield).++ This guardrail scans prompts and responses using the Azure Prompt Shield API to detect+ malicious content, injection attempts, and policy violations.++ Configuration:+ guardrail_name: Name of the guardrail instance+ api_key: Azure Prompt Shield API key+ api_base: Azure Prompt Shield API endpoint+ default_on: Whether to enable by default+ """++ def __init__(+ self,+ guardrail_name: str,+ api_key: str,+ api_base: str,+ **kwargs,+ ):+ """Initialize Azure Prompt Shield guardrail handler."""+ from litellm.types.guardrails import GuardrailEventHooks++ # Initialize parent CustomGuardrail++ supported_event_hooks = [+ GuardrailEventHooks.pre_call,+ GuardrailEventHooks.during_call,+ ]+ super().__init__(+ guardrail_name=guardrail_name,+ supported_event_hooks=supported_event_hooks,+ **kwargs,+ )+ self.async_handler = get_async_httpx_client(+ llm_provider=httpxSpecialProvider.GuardrailCallback+ )++ # Store configuration+ self.api_key = api_key+ self.api_base = api_base+ self.api_version = kwargs.get("api_version") or "2024-09-01"++ verbose_proxy_logger.info(+ f"Initialized Azure Prompt Shield Guardrail: {guardrail_name}"+ )++ async def async_make_request(+ self, user_prompt: str+ ) -> "AzurePromptShieldGuardrailResponse":+ """+ Make a request to the Azure Prompt Shield API.+ """+ from litellm.types.proxy.guardrails.guardrail_hooks.azure.azure_prompt_shield import (+ AzurePromptShieldGuardrailRequestBody,+ AzurePromptShieldGuardrailResponse,+ )++ request_body = AzurePromptShieldGuardrailRequestBody(+ documents=[], userPrompt=user_prompt+ )+ verbose_proxy_logger.debug(+ "Azure Prompt Shield guard request: %s", request_body+ )+ response = await self.async_handler.post(+ url=f"{self.api_base}/contentsafety/text:shieldPrompt?api-version={self.api_version}",+ headers={+ "Ocp-Apim-Subscription-Key": self.api_key,+ "Content-Type": "application/json",+ },+ json=cast(dict, request_body),+ )++ verbose_proxy_logger.debug(+ "Azure Prompt Shield guard response: %s", response.json()+ )+ return AzurePromptShieldGuardrailResponse(**response.json()) # type: ignore++ @log_guardrail_information+ async def async_pre_call_hook(+ self,+ user_api_key_dict: "UserAPIKeyAuth",+ cache: Any,+ data: Dict[str, Any],+ call_type: Literal[+ "completion",+ "text_completion",+ "embeddings",+ "image_generation",+ "moderation",+ "audio_transcription",+ "pass_through_endpoint",+ "rerank",+ ],+ ) -> Optional[Dict[str, Any]]:+ """+ Pre-call hook to scan user prompts before sending to LLM.++ Raises HTTPException if content should be blocked.+ """+ verbose_proxy_logger.info(+ "Azure Prompt Shield: Running pre-call prompt scan, on call_type: %s",+ call_type,+ )+ if call_type == "acompletion":+ new_messages: Optional[List[AllMessageValues]] = data.get("messages")+ if new_messages is None:+ verbose_proxy_logger.warning(+ "Lakera AI: not running guardrail. No messages in data"+ )+ return data+ user_prompt = self.get_user_prompt(new_messages)++ if user_prompt:+ verbose_proxy_logger.info(+ f"Azure Prompt Shield: User prompt: {user_prompt}"+ )+ azure_prompt_shield_response = await self.async_make_request(+ user_prompt=user_prompt,+ )+ if azure_prompt_shield_response["userPromptAnalysis"].get(+ "attackDetected"+ ):+ verbose_proxy_logger.warning("Azure Prompt Shield: Attack detected")+ raise HTTPException(+ status_code=400,+ detail={+ "error": "Violated Azure Prompt Shield guardrail policy",+ "detection_message": f"Attack detected: {azure_prompt_shield_response['userPromptAnalysis']}",+ },+ )+ else:+ verbose_proxy_logger.warning(+ "Azure Prompt Shield: No user prompt found"+ )+ return None++ @log_guardrail_information+ async def async_post_call_hook(+ self,+ data: Dict[str, Any],+ user_api_key_dict: "UserAPIKeyAuth",+ response: "ModelResponse",+ ) -> "ModelResponse":+ """+ Post-call hook to scan LLM responses before returning to user.++ Raises HTTPException if response should be blocked.+ """+ verbose_proxy_logger.info(+ "Azure Prompt Shield: Running post-call response scan"+ )++ return responsediff --git a/litellm/proxy/guardrails/guardrail_hooks/azure/text_moderation.py b/litellm/proxy/guardrails/guardrail_hooks/azure/text_moderation.pynew file mode 100644index 00000000000..d1f154daead--- /dev/null+++ b/litellm/proxy/guardrails/guardrail_hooks/azure/text_moderation.py@@ -0,0 +1,273 @@+#!/usr/bin/env python3+"""+Azure Text Moderation Native Guardrail Integrationfor LiteLLM+"""++from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union, cast++from fastapi import HTTPException++from litellm._logging import verbose_proxy_logger+from litellm.integrations.custom_guardrail import (+ CustomGuardrail,+ log_guardrail_information,+)+from litellm.llms.custom_httpx.http_handler import (+ get_async_httpx_client,+ httpxSpecialProvider,+)+from litellm.proxy._types import UserAPIKeyAuth++from .base import AzureGuardrailBase++if TYPE_CHECKING:+ from litellm.proxy._types import UserAPIKeyAuth+ from litellm.types.llms.openai import AllMessageValues+ from litellm.types.proxy.guardrails.guardrail_hooks.azure.azure_text_moderation import (+ AzureTextModerationGuardrailResponse,+ )+ from litellm.types.utils import EmbeddingResponse, ImageResponse, ModelResponse+++class AzureContentSafetyTextModerationGuardrail(AzureGuardrailBase, CustomGuardrail):+ """+ LiteLLM Built-in Guardrail for Azure Content Safety Guardrail (Prompt Shield).++ This guardrail scans prompts and responses using the Azure Prompt Shield API to detect+ malicious content, injection attempts, and policy violations.++ Configuration:+ guardrail_name: Name of the guardrail instance+ api_key: Azure Prompt Shield API key+ api_base: Azure Prompt Shield API endpoint+ default_on: Whether to enable by default+ """++ default_severity_threshold: int = 2++ def __init__(+ self,+ guardrail_name: str,+ api_key: str,+ api_base: str,+ severity_threshold: Optional[int] = None,+ severity_threshold_by_category: Optional[Dict[str, int]] = None,+ **kwargs,+ ):+ """Initialize Azure Text Moderation guardrail handler."""+ # Initialize parent CustomGuardrail+ from litellm.types.proxy.guardrails.guardrail_hooks.azure.azure_text_moderation import (+ AzureTextModerationRequestBodyOptionalParams,+ )++ super().__init__(+ guardrail_name=guardrail_name,+ **kwargs,+ )+ self.async_handler = get_async_httpx_client(+ llm_provider=httpxSpecialProvider.GuardrailCallback+ )++ # Store configuration+ self.api_key = api_key+ self.api_base = api_base+ self.api_version = kwargs.get("api_version") or "2024-09-01"+ self.optional_params_request_body: (+ AzureTextModerationRequestBodyOptionalParams+ ) = {+ "categories": kwargs.get("categories")+ or [+ "Hate",+ "Sexual",+ "SelfHarm",+ "Violence",+ ],+ "blocklistNames": cast(+ Optional[List[str]], kwargs.get("blocklistNames") or None+ ),+ "haltOnBlocklistHit": kwargs.get("haltOnBlocklistHit") or False,+ "outputType": kwargs.get("outputType") or "FourSeverityLevels",+ }++ self.severity_threshold = severity_threshold+ self.severity_threshold_by_category = severity_threshold_by_category++ verbose_proxy_logger.info(+ f"Initialized Azure Prompt Shield Guardrail: {guardrail_name}"+ )++ async def async_make_request(+ self, text: str+ ) -> "AzureTextModerationGuardrailResponse":+ """+ Make a request to the Azure Prompt Shield API.+ """+ from litellm.types.proxy.guardrails.guardrail_hooks.azure.azure_text_moderation import (+ AzureTextModerationGuardrailRequestBody,+ AzureTextModerationGuardrailResponse,+ )++ request_body = AzureTextModerationGuardrailRequestBody(+ text=text,+ **self.optional_params_request_body,+ )+ verbose_proxy_logger.debug(+ "Azure Text Moderation guard request: %s", request_body+ )+ response = await self.async_handler.post(+ url=f"{self.api_base}/contentsafety/text:analyze?api-version={self.api_version}",+ headers={+ "Ocp-Apim-Subscription-Key": self.api_key,+ "Content-Type": "application/json",+ },+ json=cast(dict, request_body),+ )++ verbose_proxy_logger.debug(+ "Azure Text Moderation guard response: %s", response.json()+ )+ return AzureTextModerationGuardrailResponse(**response.json()) # type: ignore++ def check_severity_threshold(+ self, response: "AzureTextModerationGuardrailResponse"+ ) -> Literal[True]:+ """+ - Check if threshold set by category+ - Check if general severity threshold set+ - If both none, use default_severity_threshold+ """+ if self.severity_threshold_by_category:+ for category in response["categoriesAnalysis"]:+ severity_category_threshold_item = (+ self.severity_threshold_by_category.get(category["category"])+ )+ if (+ severity_category_threshold_item is not None+ and severity_category_threshold_item >= category["severity"]+ ):+ raise HTTPException(+ status_code=400,+ detail={+ "error": "Azure Content Safety Guardrail: {} crossed severity {}, Got severity: {}".format(+ category["category"],+ self.severity_threshold_by_category.get(+ category["category"]+ ),+ category["severity"],+ )+ },+ )+ if self.severity_threshold:+ for category in response["categoriesAnalysis"]:+ if category["severity"] >= self.severity_threshold:+ raise HTTPException(+ status_code=400,+ detail={+ "error": "Azure Content Safety Guardrail: {} crossed severity {}, Got severity: {}".format(+ category["category"],+ self.severity_threshold,+ category["severity"],+ )+ },+ )+ if (+ self.severity_threshold is None+ and self.severity_threshold_by_category is None+ ):+ for category in response["categoriesAnalysis"]:++ if category["severity"] >= self.default_severity_threshold:+ raise HTTPException(+ status_code=400,+ detail={+ "error": "Azure Content Safety Guardrail: {} crossed severity {}, Got severity: {}".format(+ category["category"],+ self.default_severity_threshold,+ category["severity"],+ )+ },+ )+ return True++ @log_guardrail_information+ async def async_pre_call_hook(+ self,+ user_api_key_dict: "UserAPIKeyAuth",+ cache: Any,+ data: Dict[str, Any],+ call_type: Literal[+ "completion",+ "text_completion",+ "embeddings",+ "image_generation",+ "moderation",+ "audio_transcription",+ "pass_through_endpoint",+ "rerank",+ ],+ ) -> Optional[Dict[str, Any]]:+ """+ Pre-call hook to scan user prompts before sending to LLM.++ Raises HTTPException if content should be blocked.+ """+ verbose_proxy_logger.info(+ "Azure Prompt Shield: Running pre-call prompt scan, on call_type: %s",+ call_type,+ )+ if call_type == "acompletion":+ new_messages: Optional[List[AllMessageValues]] = data.get("messages")+ if new_messages is None:+ verbose_proxy_logger.warning(+ "Lakera AI: not running guardrail. No messages in data"+ )+ return data+ user_prompt = self.get_user_prompt(new_messages)++ if user_prompt:+ verbose_proxy_logger.info(+ f"Azure Text Moderation: User prompt: {user_prompt}"+ )+ azure_text_moderation_response = await self.async_make_request(+ text=user_prompt,+ )+ self.check_severity_threshold(response=azure_text_moderation_response)+ else:+ verbose_proxy_logger.warning("Azure Text Moderation: No text found")+ return None++ async def async_post_call_success_hook(+ self,+ data: dict,+ user_api_key_dict: "UserAPIKeyAuth",+ response: Union[Any, "ModelResponse", "EmbeddingResponse", "ImageResponse"],+ ) -> Any:+ from litellm.types.utils import Choices, ModelResponse++ if (+ isinstance(response, ModelResponse)+ and response.choices+ and isinstance(response.choices[0], Choices)+ ):+ content = response.choices[0].message.content or ""+ azure_text_moderation_response = await self.async_make_request(+ text=content,+ )+ self.check_severity_threshold(response=azure_text_moderation_response)+ return response++ async def async_post_call_streaming_hook(+ self, user_api_key_dict: UserAPIKeyAuth, response: str+ ) -> Any:+ try:+ if response is not None and len(response) > 0:+ azure_text_moderation_response = await self.async_make_request(+ text=response,+ )+ self.check_severity_threshold(response=azure_text_moderation_response)+ return response+ except HTTPException as e:+ import json++ error_returned = json.dumps({"error": e.detail})+ return f"data: {error_returned}\n\n"diff --git a/litellm/proxy/guardrails/guardrail_registry.py b/litellm/proxy/guardrails/guardrail_registry.pyindex c7418116bc2..fb6810a1893 100644--- a/litellm/proxy/guardrails/guardrail_registry.py+++ b/litellm/proxy/guardrails/guardrail_registry.py@@ -30,8 +30,8 @@ from .guardrail_initializers import (initialize_lakera_v2,initialize_lasso,initialize_pangea,- initialize_presidio,initialize_panw_prisma_airs,+ initialize_presidio,)guardrail_initializer_registry = {@@ -49,6 +49,88 @@ guardrail_initializer_registry = {}+def get_guardrail_initializer_from_hooks():+ """+ Get guardrail initializers by discovering them from the guardrail_hooks directory structure.++ Scans the guardrail_hooks directory for subdirectories containing __init__.py files+ with either guardrail_initializer_registry or initialize_guardrail functions.++ Returns:+ Dict[str, Callable]: A dictionary mapping guardrail types to their initializer functions+ """+ discovered_initializers = {}++ try:+ # Get the path to the guardrail_hooks directory+ current_dir = os.path.dirname(__file__)+ hooks_dir = os.path.join(current_dir, "guardrail_hooks")++ if not os.path.exists(hooks_dir):+ verbose_proxy_logger.debug("guardrail_hooks directory not found")+ return discovered_initializers++ # Scan each subdirectory in guardrail_hooks+ for item in os.listdir(hooks_dir):+ item_path = os.path.join(hooks_dir, item)++ # Skip files and __pycache__ directories+ if not os.path.isdir(item_path) or item.startswith("__"):+ continue++ # Check if the directory has an __init__.py file+ init_file = os.path.join(item_path, "__init__.py")+ if not os.path.exists(init_file):+ continue++ module_path = f"litellm.proxy.guardrails.guardrail_hooks.{item}"+ try:+ # Import the module+ verbose_proxy_logger.debug(f"Discovering guardrails in: {module_path}")++ module = importlib.import_module(module_path)++ # Check for guardrail_initializer_registry dictionary+ if hasattr(module, "guardrail_initializer_registry"):+ registry = getattr(module, "guardrail_initializer_registry")+ if isinstance(registry, dict):+ discovered_initializers.update(registry)+ verbose_proxy_logger.debug(+ f"Found guardrail_initializer_registry in {module_path}: {list(registry.keys())}"+ )++ # Check for standalone initialize_guardrail function (fallback for directory-based guardrails)+ elif hasattr(module, "initialize_guardrail"):+ # For directories with just initialize_guardrail, use the directory name as the key+ initialize_fn = getattr(module, "initialize_guardrail")+ discovered_initializers[item] = initialize_fn+ verbose_proxy_logger.debug(+ f"Found initialize_guardrail function in {module_path}"+ )++ except ImportError as e:+ verbose_proxy_logger.debug(f"Could not import {module_path}: {e}")+ continue+ except Exception as e:+ verbose_proxy_logger.error(f"Error processing {module_path}: {e}")+ continue++ verbose_proxy_logger.debug(+ f"Discovered {len(discovered_initializers)} guardrail initializers: {list(discovered_initializers.keys())}"+ )++ except Exception as e:+ verbose_proxy_logger.error(f"Error discovering guardrail initializers: {e}")++ return discovered_initializers+++# Merge with dynamically discovered guardrail initializers+_discovered_initializers = get_guardrail_initializer_from_hooks()++guardrail_initializer_registry.update(_discovered_initializers)++class GuardrailRegistry:"""Registry for guardrailsdiff --git a/litellm/proxy/guardrails/init_guardrails.py b/litellm/proxy/guardrails/init_guardrails.pyindex 70c6fe65ad5..6009fce31ea 100644--- a/litellm/proxy/guardrails/init_guardrails.py+++ b/litellm/proxy/guardrails/init_guardrails.py@@ -89,4 +89,4 @@ def init_guardrails_v2(if initialized_guardrail:guardrail_list.append(initialized_guardrail)- verbose_proxy_logger.info(f"\nGuardrail List:{guardrail_list}\n")+ verbose_proxy_logger.debug(f"\nGuardrail List:{guardrail_list}\n")diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.pyindex 615fd15839f..742dcf82b5a 100644--- a/litellm/types/guardrails.py+++ b/litellm/types/guardrails.py@@ -31,6 +31,8 @@ class SupportedGuardrailIntegrations(Enum):PANGEA = "pangea"LASSO = "lasso"PANW_PRISMA_AIRS = "panw_prisma_airs"+ AZURE_PROMPT_SHIELD = "azure/prompt_shield"+ AZURE_TEXT_MODERATIONS = "azure/text_moderations"class Role(Enum):diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_prompt_shield.py b/litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_prompt_shield.pynew file mode 100644index 00000000000..6b7f1da7620--- /dev/null+++ b/litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_prompt_shield.py@@ -0,0 +1,19 @@+from typing import Any, Dict, List, TypedDict+++class AzurePromptShieldGuardrailRequestBody(TypedDict):+ """Configuration parameters for the Azure Prompt Shield guardrail"""++ userPrompt: str+ documents: List[str]+++class UserPromptAnalysis(TypedDict, total=False):+ attackDetected: bool+++class AzurePromptShieldGuardrailResponse(TypedDict):+ """Configuration parameters for the Azure Prompt Shield guardrail"""++ userPromptAnalysis: UserPromptAnalysis+ documentsAnalysis: List[Dict[str, Any]]diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_text_moderation.py b/litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_text_moderation.pynew file mode 100644index 00000000000..39fad0553b7--- /dev/null+++ b/litellm/types/proxy/guardrails/guardrail_hooks/azure/azure_text_moderation.py@@ -0,0 +1,32 @@+from typing import Any, Dict, List, Literal, Optional, Required, TypedDict+++class AzureTextModerationRequestBodyOptionalParams(TypedDict, total=False):+ """Optional parameters for the Azure Text Moderation guardrail"""++ categories: Optional[List[str]]+ blocklistNames: Optional[List[str]]+ haltOnBlocklistHit: Optional[bool]+ outputType: Literal["FourSeverityLevels", "EightSeverityLevels"]+++class AzureTextModerationGuardrailRequestBody(+ AzureTextModerationRequestBodyOptionalParams+):+ """Configuration parameters for the Azure Text Moderation guardrail"""++ text: Required[str]+++class AzureTextModerationGuardrailResponseCategoriesAnalysis(TypedDict):+ """Response from the Azure Text Moderation guardrail"""++ category: str+ severity: int+++class AzureTextModerationGuardrailResponse(TypedDict):+ """Response from the Azure Text Moderation guardrail"""++ blocklistsMatch: List[Dict[str, Any]]+ categoriesAnalysis: List[AzureTextModerationGuardrailResponseCategoriesAnalysis]diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/azure/test_azure_prompt_shield.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/azure/test_azure_prompt_shield.pynew file mode 100644index 00000000000..19c07d60e9d--- /dev/null+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/azure/test_azure_prompt_shield.py@@ -0,0 +1,48 @@+from unittest.mock import AsyncMock, patch++import httpx+import pytest+from fastapi import HTTPException++from litellm.proxy._types import UserAPIKeyAuth+from litellm.proxy.guardrails.guardrail_hooks.azure.prompt_shield import (+ AzureContentSafetyPromptShieldGuardrail,+)+from litellm.proxy.guardrails.init_guardrails import init_guardrails_v2+from litellm.types.utils import Choices, Message, ModelResponse+++async def test_azure_prompt_shield_guardrail_pre_call_hook():++ azure_prompt_shield_guardrail = AzureContentSafetyPromptShieldGuardrail(+ guardrail_name="azure_prompt_shield",+ api_key="azure_prompt_shield_api_key",+ api_base="azure_prompt_shield_api_base",+ )+ with patch.object(+ azure_prompt_shield_guardrail, "async_make_request"+ ) as mock_async_make_request:+ mock_async_make_request.return_value = {+ "userPromptAnalysis": {"attackDetected": False},+ "documentsAnalysis": [],+ }+ await azure_prompt_shield_guardrail.async_pre_call_hook(+ user_api_key_dict=UserAPIKeyAuth(api_key="azure_prompt_shield_api_key"),+ cache=None,+ data={+ "messages": [+ {+ "role": "user",+ "content": "Hello, how are you?",+ }+ ]+ },+ call_type="acompletion",+ )++ mock_async_make_request.assert_called_once()+ assert (+ mock_async_make_request.call_args.kwargs["user_prompt"]+ == "Hello, how are you?"+ )diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/azure/test_azure_text_moderation.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/azure/test_azure_text_moderation.pynew file mode 100644index 00000000000..6fc70560d47--- /dev/null+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/azure/test_azure_text_moderation.py@@ -0,0 +1,87 @@+from unittest.mock import AsyncMock, patch++import httpx+import pytest+from fastapi import HTTPException++from litellm.proxy._types import UserAPIKeyAuth+from litellm.proxy.guardrails.guardrail_hooks.azure.text_moderation import (+ AzureContentSafetyTextModerationGuardrail,+)+from litellm.proxy.guardrails.init_guardrails import init_guardrails_v2+from litellm.types.utils import Choices, Message, ModelResponse+++async def test_azure_text_moderation_guardrail_pre_call_hook():++ azure_text_moderation_guardrail = AzureContentSafetyTextModerationGuardrail(+ guardrail_name="azure_text_moderation",+ api_key="azure_text_moderation_api_key",+ api_base="azure_text_moderation_api_base",+ )+ with patch.object(+ azure_text_moderation_guardrail, "async_make_request"+ ) as mock_async_make_request:+ mock_async_make_request.return_value = {+ "blocklistsMatch": [],+ "categoriesAnalysis": [+ {"category": "Hate", "severity": 2},+ ],+ }+ with pytest.raises(HTTPException):+ await azure_text_moderation_guardrail.async_pre_call_hook(+ user_api_key_dict=UserAPIKeyAuth(+ api_key="azure_text_moderation_api_key"+ ),+ cache=None,+ data={+ "messages": [+ {+ "role": "user",+ "content": "I hate you!",+ }+ ]+ },+ call_type="acompletion",+ )++ mock_async_make_request.assert_called_once()+ assert mock_async_make_request.call_args.kwargs["text"] == "I hate you!"+++async def test_azure_text_moderation_guardrail_post_call_success_hook():++ azure_text_moderation_guardrail = AzureContentSafetyTextModerationGuardrail(+ guardrail_name="azure_text_moderation",+ api_key="azure_text_moderation_api_key",+ api_base="azure_text_moderation_api_base",+ )+ with patch.object(+ azure_text_moderation_guardrail, "async_make_request"+ ) as mock_async_make_request:+ mock_async_make_request.return_value = {+ "blocklistsMatch": [],+ "categoriesAnalysis": [+ {"category": "Hate", "severity": 2},+ ],+ }+ with pytest.raises(HTTPException):+ result = await azure_text_moderation_guardrail.async_post_call_success_hook(+ data={},+ user_api_key_dict=UserAPIKeyAuth(+ api_key="azure_text_moderation_api_key"+ ),+ response=ModelResponse(+ choices=[+ Choices(+ index=0,+ message=Message(content="I hate you!"),+ )+ ]+ ),+ )++ mock_async_make_request.assert_called_once()+ mock_async_make_request.call_args.kwargs["text"] == "I hate you!"