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] Add EnkryptAI Guardrails on LiteLLM (#15390)

Ishaan Jaff6cf57d85c311
diff --git a/docs/my-website/docs/proxy/guardrails/enkryptai.md b/docs/my-website/docs/proxy/guardrails/enkryptai.md
new file mode 100644
index 00000000000..00a13be8949
--- /dev/null
+++ b/docs/my-website/docs/proxy/guardrails/enkryptai.md
@@ -0,0 +1,272 @@
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+# EnkryptAI Guardrails
+
+LiteLLM supports EnkryptAI guardrails for content moderation and safety checks on LLM inputs and outputs.
+
+## Quick Start
+
+### 1. Define Guardrails on your LiteLLM config.yaml
+
+Define your guardrails under the `guardrails` section:
+
+```yaml
+model_list:
+ - model_name: gpt-3.5-turbo
+ litellm_params:
+ model: openai/gpt-3.5-turbo
+ api_key: os.environ/OPENAI_API_KEY
+
+guardrails:
+ - guardrail_name: "enkryptai-guard"
+ litellm_params:
+ guardrail: enkryptai
+ mode: "pre_call"
+ api_key: os.environ/ENKRYPTAI_API_KEY
+ detectors:
+ toxicity:
+ enabled: true
+ nsfw:
+ enabled: true
+ pii:
+ enabled: true
+ entities: ["email", "phone", "secrets"]
+ injection_attack:
+ enabled: true
+```
+
+#### Supported values for `mode`
+
+- `pre_call` - Run **before** LLM call, on **input**
+- `post_call` - Run **after** LLM call, on **output**
+- `during_call` - Run **during** LLM call, on **input**. Same as `pre_call` but runs in parallel as LLM call
+
+#### Available Detectors
+
+EnkryptAI supports multiple content detection types:
+
+- **toxicity** - Detect toxic language
+- **nsfw** - Detect NSFW (Not Safe For Work) content
+- **pii** - Detect personally identifiable information
+ - Configure entities: `["pii", "email", "phone", "secrets", "ip_address", "url"]`
+- **injection_attack** - Detect prompt injection attempts
+- **keyword_detector** - Detect custom keywords/phrases
+- **policy_violation** - Detect policy violations
+- **bias** - Detect biased content
+- **sponge_attack** - Detect sponge attacks
+
+### 2. Set Environment Variables
+
+```bash
+export ENKRYPTAI_API_KEY="your-api-key"
+```
+
+### 3. Start LiteLLM Gateway
+
+```shell
+litellm --config config.yaml --detailed_debug
+```
+
+### 4. Test Request
+
+**[Langchain, OpenAI SDK Usage Examples](../proxy/user_keys#request-format)**
+
+<Tabs>
+<TabItem label="Successful Call" value="allowed">
+
+```shell
+curl -i http://localhost:4000/v1/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer sk-1234" \
+ -d '{
+ "model": "gpt-3.5-turbo",
+ "messages": [
+ {"role": "user", "content": "Hello, how can you help me today?"}
+ ],
+ "guardrails": ["enkryptai-guard"]
+ }'
+```
+
+**Response: HTTP 200 Success**
+
+Content passes all detector checks and is allowed through.
+
+</TabItem>
+
+<TabItem label="Unsuccessful Call" value="not-allowed">
+
+Expect this to fail if content violates detector policies:
+
+```shell
+curl -i http://localhost:4000/v1/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer sk-1234" \
+ -d '{
+ "model": "gpt-3.5-turbo",
+ "messages": [
+ {"role": "user", "content": "My email is [email protected] and my SSN is 123-45-6789"}
+ ],
+ "guardrails": ["enkryptai-guard"]
+ }'
+```
+
+**Expected Response on Failure: HTTP 400 Error**
+
+```json
+{
+ "error": {
+ "message": {
+ "error": "Content blocked by EnkryptAI guardrail",
+ "detected": true,
+ "violations": ["pii"],
+ "response": {
+ "summary": {
+ "pii": 1
+ },
+ "details": {
+ "pii": {
+ "detected": ["email", "ssn"]
+ }
+ }
+ }
+ },
+ "type": "None",
+ "param": "None",
+ "code": "400"
+ }
+}
+```
+
+</TabItem>
+</Tabs>
+
+## Advanced Configuration
+
+### Using Custom Policies
+
+You can specify a custom EnkryptAI policy:
+
+```yaml
+guardrails:
+ - guardrail_name: "enkryptai-custom"
+ litellm_params:
+ guardrail: enkryptai
+ mode: "pre_call"
+ api_key: os.environ/ENKRYPTAI_API_KEY
+ policy_name: "my-custom-policy" # Sent via x-enkrypt-policy header
+ detectors:
+ toxicity:
+ enabled: true
+```
+
+### Using Deployments
+
+Specify an EnkryptAI deployment:
+
+```yaml
+guardrails:
+ - guardrail_name: "enkryptai-deployment"
+ litellm_params:
+ guardrail: enkryptai
+ mode: "pre_call"
+ api_key: os.environ/ENKRYPTAI_API_KEY
+ deployment_name: "production" # Sent via X-Enkrypt-Deployment header
+ detectors:
+ toxicity:
+ enabled: true
+```
+
+### Monitor Mode (Logging Without Blocking)
+
+Set `block_on_violation: false` to log violations without blocking requests:
+
+```yaml
+guardrails:
+ - guardrail_name: "enkryptai-monitor"
+ litellm_params:
+ guardrail: enkryptai
+ mode: "pre_call"
+ api_key: os.environ/ENKRYPTAI_API_KEY
+ block_on_violation: false # Log violations but don't block
+ detectors:
+ toxicity:
+ enabled: true
+ nsfw:
+ enabled: true
+```
+
+In monitor mode, all violations are logged but requests are never blocked.
+
+### Input and Output Guardrails
+
+Configure separate guardrails for input and output:
+
+```yaml
+guardrails:
+ # Input guardrail
+ - guardrail_name: "enkryptai-input"
+ litellm_params:
+ guardrail: enkryptai
+ mode: "pre_call"
+ api_key: os.environ/ENKRYPTAI_API_KEY
+ detectors:
+ pii:
+ enabled: true
+ entities: ["email", "phone", "ssn"]
+ injection_attack:
+ enabled: true
+
+ # Output guardrail
+ - guardrail_name: "enkryptai-output"
+ litellm_params:
+ guardrail: enkryptai
+ mode: "post_call"
+ api_key: os.environ/ENKRYPTAI_API_KEY
+ detectors:
+ toxicity:
+ enabled: true
+ nsfw:
+ enabled: true
+```
+
+## Configuration Options
+
+| Parameter | Type | Description | Default |
+|-----------|------|-------------|---------|
+| `api_key` | string | EnkryptAI API key | `ENKRYPTAI_API_KEY` env var |
+| `api_base` | string | EnkryptAI API base URL | `https://api.enkryptai.com` |
+| `policy_name` | string | Custom policy name (sent via `x-enkrypt-policy` header) | None |
+| `deployment_name` | string | Deployment name (sent via `X-Enkrypt-Deployment` header) | None |
+| `detectors` | object | Detector configuration | `{}` |
+| `block_on_violation` | boolean | Block requests on violations | `true` |
+| `mode` | string | When to run: `pre_call`, `post_call`, or `during_call` | Required |
+
+## Observability
+
+EnkryptAI guardrail logs include:
+
+- **guardrail_status**: `success`, `guardrail_intervened`, or `guardrail_failed_to_respond`
+- **guardrail_provider**: `enkryptai`
+- **guardrail_json_response**: Full API response with detection details
+- **duration**: Time taken for guardrail check
+- **start_time** and **end_time**: Timestamps
+
+These logs are available through your configured LiteLLM logging callbacks.
+
+## Error Handling
+
+The guardrail handles errors gracefully:
+
+- **API Failures**: Logs error and raises exception
+- **Rate Limits (429)**: Logs error and raises exception
+- **Invalid Configuration**: Raises `ValueError` on initialization
+
+Set `block_on_violation: false` to continue processing even when violations are detected (monitor mode).
+
+## Support
+
+For more information about EnkryptAI:
+- Documentation: [https://docs.enkryptai.com](https://docs.enkryptai.com)
+- Website: [https://enkryptai.com](https://enkryptai.com)
+
diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.js
index a5c348a96ec..480232e326f 100644
--- a/docs/my-website/sidebars.js
+++ b/docs/my-website/sidebars.js
@@ -36,6 +36,7 @@ const sidebars = {
"proxy/guardrails/aporia_api",
"proxy/guardrails/azure_content_guardrail",
"proxy/guardrails/bedrock",
+ "proxy/guardrails/enkryptai",
"proxy/guardrails/lasso_security",
"proxy/guardrails/guardrails_ai",
"proxy/guardrails/lakera_ai",
diff --git a/litellm/proxy/guardrails/guardrail_hooks/enkryptai/__init__.py b/litellm/proxy/guardrails/guardrail_hooks/enkryptai/__init__.py
new file mode 100644
index 00000000000..9289693c2ca
--- /dev/null
+++ b/litellm/proxy/guardrails/guardrail_hooks/enkryptai/__init__.py
@@ -0,0 +1,43 @@
+from .enkryptai import EnkryptAIGuardrails
+
+__all__ = ["EnkryptAIGuardrails"]
+
+
+from typing import TYPE_CHECKING
+
+from litellm.types.guardrails import SupportedGuardrailIntegrations
+
+from .enkryptai import EnkryptAIGuardrails
+
+if TYPE_CHECKING:
+ from litellm.types.guardrails import Guardrail, LitellmParams
+
+
+def initialize_guardrail(litellm_params: "LitellmParams", guardrail: "Guardrail"):
+ import litellm
+
+ _enkryptai_callback = EnkryptAIGuardrails(
+ guardrail_name=guardrail.get("guardrail_name", ""),
+ api_key=litellm_params.api_key,
+ api_base=litellm_params.api_base,
+ policy_name=litellm_params.policy_name,
+ deployment_name=litellm_params.deployment_name,
+ detectors=litellm_params.detectors,
+ block_on_violation=litellm_params.block_on_violation,
+ event_hook=litellm_params.mode,
+ default_on=litellm_params.default_on,
+ )
+ litellm.logging_callback_manager.add_litellm_callback(_enkryptai_callback)
+
+ return _enkryptai_callback
+
+
+guardrail_initializer_registry = {
+ SupportedGuardrailIntegrations.ENKRYPTAI.value: initialize_guardrail,
+}
+
+
+guardrail_class_registry = {
+ SupportedGuardrailIntegrations.ENKRYPTAI.value: EnkryptAIGuardrails,
+}
+
diff --git a/litellm/proxy/guardrails/guardrail_hooks/enkryptai/enkryptai.py b/litellm/proxy/guardrails/guardrail_hooks/enkryptai/enkryptai.py
new file mode 100644
index 00000000000..39e658355e8
--- /dev/null
+++ b/litellm/proxy/guardrails/guardrail_hooks/enkryptai/enkryptai.py
@@ -0,0 +1,489 @@
+# +-------------------------------------------------------------+
+#
+# Use EnkryptAI Guardrails for your LLM calls
+# https://enkryptai.com
+#
+# +-------------------------------------------------------------+
+
+import os
+from datetime import datetime
+from typing import (
+ Any,
+ AsyncGenerator,
+ Dict,
+ List,
+ Literal,
+ Optional,
+ Union,
+)
+
+import httpx
+
+import litellm
+from litellm._logging import verbose_proxy_logger
+from litellm.caching.caching import DualCache
+from litellm.integrations.custom_guardrail import CustomGuardrail
+from litellm.llms.custom_httpx.http_handler import (
+ get_async_httpx_client,
+ httpxSpecialProvider,
+)
+from litellm.proxy._types import UserAPIKeyAuth
+from litellm.types.guardrails import GuardrailEventHooks
+from litellm.types.proxy.guardrails.guardrail_hooks.enkryptai import (
+ EnkryptAIProcessedResult,
+ EnkryptAIResponse,
+)
+from litellm.types.utils import GuardrailStatus, ModelResponseStream
+
+GUARDRAIL_NAME = "enkryptai"
+
+
+class EnkryptAIGuardrails(CustomGuardrail):
+ def __init__(
+ self,
+ guardrail_name: str = "litellm_test",
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ policy_name: Optional[str] = None,
+ **kwargs,
+ ):
+ self.async_handler = get_async_httpx_client(
+ llm_provider=httpxSpecialProvider.GuardrailCallback
+ )
+
+ # Set API configuration
+ self.api_key = api_key or os.getenv("ENKRYPTAI_API_KEY")
+ if not self.api_key:
+ raise ValueError(
+ "EnkryptAI API key is required. Set ENKRYPTAI_API_KEY environment variable or pass api_key parameter."
+ )
+
+ self.api_base = api_base or os.getenv(
+ "ENKRYPTAI_API_BASE", "https://api.enkryptai.com"
+ )
+ self.api_url = f"{self.api_base}/guardrails/policy/detect"
+
+ # Policy name can be passed as parameter or use guardrail_name
+ self.policy_name = policy_name
+ self.guardrail_name = guardrail_name
+ self.guardrail_provider = "enkryptai"
+
+ # store kwargs as optional_params
+ self.optional_params = kwargs
+
+ # Set supported event hooks
+ if "supported_event_hooks" not in kwargs:
+ kwargs["supported_event_hooks"] = [
+ GuardrailEventHooks.pre_call,
+ GuardrailEventHooks.post_call,
+ GuardrailEventHooks.during_call,
+ ]
+
+ super().__init__(guardrail_name=guardrail_name, **kwargs)
+
+ verbose_proxy_logger.debug(
+ "EnkryptAI Guardrail initialized with guardrail_name: %s, policy_name: %s",
+ self.guardrail_name,
+ self.policy_name,
+ )
+
+ async def _call_enkryptai_guardrails(
+ self,
+ prompt: str,
+ request_data: Optional[dict] = None,
+ ) -> EnkryptAIResponse:
+ """
+ Call Enkrypt AI Guardrails API to detect potential issues in the given prompt.
+
+ Args:
+ prompt (str): The text to analyze for potential violations
+ request_data (dict): Optional request data for logging purposes
+
+ Returns:
+ EnkryptAIResponse: Response from the Enkrypt AI Guardrails API
+ """
+ start_time = datetime.now()
+
+ payload = {
+ "text": prompt
+ }
+
+ headers = {
+ "Content-Type": "application/json",
+ "apikey": self.api_key
+ }
+
+ # Add policy header if policy_name is set
+ if self.policy_name:
+ headers["x-enkrypt-policy"] = self.policy_name
+
+ verbose_proxy_logger.debug(
+ "EnkryptAI request to %s with payload: %s",
+ self.api_url,
+ payload,
+ )
+
+ try:
+ response = await self.async_handler.post(
+ url=self.api_url,
+ json=payload,
+ headers=headers,
+ )
+ response.raise_for_status()
+ response_json = response.json()
+
+ end_time = datetime.now()
+ duration = (end_time - start_time).total_seconds()
+
+ # Add guardrail information to request trace
+ if request_data:
+ guardrail_status = self._determine_guardrail_status(response_json)
+ self.add_standard_logging_guardrail_information_to_request_data(
+ guardrail_provider=self.guardrail_provider,
+ guardrail_json_response=response_json,
+ request_data=request_data,
+ guardrail_status=guardrail_status,
+ start_time=start_time.timestamp(),
+ end_time=end_time.timestamp(),
+ duration=duration,
+ )
+
+ return response_json
+
+ except httpx.HTTPError as e:
+ end_time = datetime.now()
+ duration = (end_time - start_time).total_seconds()
+
+ verbose_proxy_logger.error(
+ "EnkryptAI API request failed: %s", str(e)
+ )
+
+ # Add guardrail information with failure status
+ if request_data:
+ self.add_standard_logging_guardrail_information_to_request_data(
+ guardrail_provider=self.guardrail_provider,
+ guardrail_json_response={"error": str(e)},
+ request_data=request_data,
+ guardrail_status="guardrail_failed_to_respond",
+ start_time=start_time.timestamp(),
+ end_time=end_time.timestamp(),
+ duration=duration,
+ )
+
+ raise
+
+ def _process_enkryptai_guardrails_response(
+ self, response: EnkryptAIResponse
+ ) -> EnkryptAIProcessedResult:
+ """
+ Process the response from the Enkrypt AI Guardrails API
+
+ Args:
+ response: The response from the API with 'summary' and 'details' keys
+
+ Returns:
+ EnkryptAIProcessedResult: Processed response with detected attacks and their details
+ """
+ summary = response.get("summary", {})
+ details = response.get("details", {})
+
+ detected_attacks: List[str] = []
+ attack_details: Dict[str, Any] = {}
+
+ for key, value in summary.items():
+ # Check if attack is detected
+ # For toxicity, it's a list (non-empty list means detected)
+ # For others, it's 1 for detected, 0 for not detected
+ if key == "toxicity":
+ if isinstance(value, list) and len(value) > 0:
+ detected_attacks.append(key)
+ attack_details[key] = details.get(key, {})
+ else:
+ if value == 1:
+ detected_attacks.append(key)
+ attack_details[key] = details.get(key, {})
+
+ return {
+ "attacks_detected": detected_attacks,
+ "attack_details": attack_details
+ }
+
+ def _determine_guardrail_status(
+ self, response_json: EnkryptAIResponse
+ ) -> GuardrailStatus:
+ """
+ Determine the guardrail status based on EnkryptAI API response.
+
+ Returns:
+ "success": Content allowed through with no violations
+ "guardrail_intervened": Content blocked due to policy violations
+ "guardrail_failed_to_respond": Technical error or API failure
+ """
+ try:
+ if not isinstance(response_json, dict):
+ return "guardrail_failed_to_respond"
+
+ # Process the response to check for violations
+ processed_result = self._process_enkryptai_guardrails_response(response_json)
+ attacks_detected = processed_result["attacks_detected"]
+
+ if attacks_detected:
+ return "guardrail_intervened"
+
+ return "success"
+
+ except Exception as e:
+ verbose_proxy_logger.error(
+ "Error determining EnkryptAI guardrail status: %s", str(e)
+ )
+ return "guardrail_failed_to_respond"
+
+ def _create_error_message(self, processed_result: EnkryptAIProcessedResult) -> str:
+ """
+ Create a detailed error message from processed guardrail results.
+
+ Args:
+ processed_result: Processed response with detected attacks and their details
+
+ Returns:
+ Formatted error message string
+ """
+ attacks_detected = processed_result["attacks_detected"]
+ attack_details = processed_result["attack_details"]
+
+ error_message = f"Guardrail failed: {len(attacks_detected)} violation(s) detected\n\n"
+
+ for attack_type in attacks_detected:
+ error_message += f"- {attack_type.upper()}:\n"
+ details = attack_details.get(attack_type, {})
+
+ # Format details based on attack type
+ if attack_type == "policy_violation":
+ error_message += f" Policy: {details.get('violating_policy', 'N/A')}\n"
+ error_message += f" Explanation: {details.get('explanation', 'N/A')}\n"
+ elif attack_type == "pii":
+ error_message += f" PII Detected: {details.get('pii', {})}\n"
+ elif attack_type == "toxicity":
+ toxic_types = [k for k, v in details.items() if isinstance(v, (int, float)) and v > 0.5]
+ error_message += f" Types: {', '.join(toxic_types)}\n"
+ elif attack_type == "keyword_detected":
+ error_message += f" Keywords: {details.get('detected_keywords', [])}\n"
+ elif attack_type == "bias":
+ error_message += f" Bias Detected: {details.get('bias_detected', False)}\n"
+ else:
+ error_message += f" Details: {details}\n"
+ error_message += "\n"
+
+ return error_message.strip()
+
+ async def async_pre_call_hook(
+ self,
+ user_api_key_dict: UserAPIKeyAuth,
+ cache: DualCache,
+ data: dict,
+ call_type: Literal[
+ "completion",
+ "text_completion",
+ "embeddings",
+ "image_generation",
+ "moderation",
+ "audio_transcription",
+ "pass_through_endpoint",
+ "rerank",
+ "mcp_call",
+ ],
+ ) -> Union[Exception, str, dict, None]:
+ """
+ Runs before the LLM API call
+ Runs on only Input
+ Use this if you want to MODIFY the input
+ """
+ verbose_proxy_logger.debug("Running EnkryptAI pre-call hook")
+
+ from litellm.proxy.common_utils.callback_utils import (
+ add_guardrail_to_applied_guardrails_header,
+ )
+
+ event_type: GuardrailEventHooks = GuardrailEventHooks.pre_call
+ if self.should_run_guardrail(data=data, event_type=event_type) is not True:
+ return data
+
+ _messages = data.get("messages")
+ if _messages:
+ for message in _messages:
+ _content = message.get("content")
+ if isinstance(_content, str):
+ result = await self._call_enkryptai_guardrails(
+ prompt=_content,
+ request_data=data,
+ )
+
+ verbose_proxy_logger.debug("Guardrails async_pre_call_hook result: %s", result)
+
+ # Process the guardrails response
+ processed_result = self._process_enkryptai_guardrails_response(result)
+ attacks_detected = processed_result["attacks_detected"]
+
+ # If any attacks are detected, raise an error
+ if attacks_detected:
+ error_message = self._create_error_message(processed_result)
+ raise ValueError(error_message)
+
+ # Add guardrail to applied guardrails header
+ add_guardrail_to_applied_guardrails_header(
+ request_data=data, guardrail_name=self.guardrail_name
+ )
+
+ return data
+
+ async def async_moderation_hook(
+ self,
+ data: dict,
+ user_api_key_dict: UserAPIKeyAuth,
+ call_type: Literal[
+ "completion",
+ "embeddings",
+ "image_generation",
+ "moderation",
+ "audio_transcription",
+ "responses",
+ "mcp_call",
+ ],
+ ):
+ """
+ Runs in parallel to LLM API call
+ Runs on only Input
+
+ This can NOT modify the input, only used to reject or accept a call before going to LLM API
+ """
+ from litellm.proxy.common_utils.callback_utils import (
+ add_guardrail_to_applied_guardrails_header,
+ )
+
+ event_type: GuardrailEventHooks = GuardrailEventHooks.during_call
+ if self.should_run_guardrail(data=data, event_type=event_type) is not True:
+ return
+
+ _messages = data.get("messages")
+ if _messages:
+ for message in _messages:
+ _content = message.get("content")
+ if isinstance(_content, str):
+ result = await self._call_enkryptai_guardrails(
+ prompt=_content,
+ request_data=data,
+ )
+
+ verbose_proxy_logger.debug("Guardrails async_moderation_hook result: %s", result)
+
+ # Process the guardrails response
+ processed_result = self._process_enkryptai_guardrails_response(result)
+ attacks_detected = processed_result["attacks_detected"]
+
+ # If any attacks are detected, raise an error
+ if attacks_detected:
+ error_message = self._create_error_message(processed_result)
+ raise ValueError(error_message)
+
+ # Add guardrail to applied guardrails header
+ add_guardrail_to_applied_guardrails_header(
+ request_data=data, guardrail_name=self.guardrail_name
+ )
+
+ return data
+
+ async def async_post_call_success_hook(
+ self,
+ data: dict,
+ user_api_key_dict: UserAPIKeyAuth,
+ response,
+ ):
+ """
+ Runs on response from LLM API call
+
+ It can be used to reject a response
+
+ Uses Enkrypt AI guardrails to check the response for policy violations, PII, and injection attacks
+ """
+ from litellm.proxy.common_utils.callback_utils import (
+ add_guardrail_to_applied_guardrails_header,
+ )
+ from litellm.types.guardrails import GuardrailEventHooks
+
+ if (
+ self.should_run_guardrail(
+ data=data, event_type=GuardrailEventHooks.post_call
+ )
+ is not True
+ ):
+ return
+
+ verbose_proxy_logger.debug("async_post_call_success_hook response: %s", response)
+
+ # Check if the ModelResponse has text content in its choices
+ # to avoid sending empty content to EnkryptAI (e.g., during tool calls)
+ if isinstance(response, litellm.ModelResponse):
+ has_text_content = False
+ for choice in response.choices:
+ if isinstance(choice, litellm.Choices):
+ if choice.message.content and isinstance(choice.message.content, str):
+ has_text_content = True
+ break
+
+ if not has_text_content:
+ verbose_proxy_logger.warning(
+ "EnkryptAI: not running guardrail. No output text in response"
+ )
+ return
+
+ for choice in response.choices:
+ if isinstance(choice, litellm.Choices):
+ verbose_proxy_logger.debug("async_post_call_success_hook choice: %s", choice)
+ if choice.message.content and isinstance(choice.message.content, str):
+ result = await self._call_enkryptai_guardrails(
+ prompt=choice.message.content,
+ request_data=data,
+ )
+
+ verbose_proxy_logger.debug("Guardrails async_post_call_success_hook result: %s", result)
+
+ # Process the guardrails response
+ processed_result = self._process_enkryptai_guardrails_response(result)
+ attacks_detected = processed_result["attacks_detected"]
+
+ # If any attacks are detected, raise an error
+ if attacks_detected:
+ error_message = self._create_error_message(processed_result)
+ raise ValueError(error_message)
+
+ # Add guardrail to applied guardrails header
+ add_guardrail_to_applied_guardrails_header(
+ request_data=data, guardrail_name=self.guardrail_name
+ )
+
+ async def async_post_call_streaming_iterator_hook(
+ self,
+ user_api_key_dict: UserAPIKeyAuth,
+ response: Any,
+ request_data: dict,
+ ) -> AsyncGenerator[ModelResponseStream, None]:
+ """
+ Passes the entire stream to the guardrail
+
+ This is useful for guardrails that need to see the entire response, such as PII masking.
+
+ See Aim guardrail implementation for an example - https://github.com/BerriAI/litellm/blob/d0e022cfacb8e9ebc5409bb652059b6fd97b45c0/litellm/proxy/guardrails/guardrail_hooks/aim.py#L168
+
+ Triggered by mode: 'post_call'
+ """
+ async for item in response:
+ yield item
+
+ @staticmethod
+ def get_config_model():
+ from litellm.types.proxy.guardrails.guardrail_hooks.enkryptai import (
+ EnkryptAIGuardrailConfigModel,
+ )
+
+ return EnkryptAIGuardrailConfigModel
+
diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.py
index 03347cd1cdd..e75f969892e 100644
--- a/litellm/types/guardrails.py
+++ b/litellm/types/guardrails.py
@@ -5,6 +5,10 @@ from typing import Any, Dict, List, Literal, Optional, Union
from pydantic import BaseModel, ConfigDict, Field
from typing_extensions import Required, TypedDict
+from litellm.types.proxy.guardrails.guardrail_hooks.enkryptai import (
+ EnkryptAIGuardrailConfigs,
+)
+
"""
Pydantic object defining how to set guardrails on litellm proxy
@@ -39,7 +43,7 @@ class SupportedGuardrailIntegrations(Enum):
NOMA = "noma"
TOOL_PERMISSION = "tool_permission"
JAVELIN = "javelin"
-
+ ENKRYPTAI = "enkryptai"
class Role(Enum):
SYSTEM = "system"
@@ -502,6 +506,7 @@ class LitellmParams(
ToolPermissionGuardrailConfigModel,
JavelinGuardrailConfigModel,
BaseLitellmParams,
+ EnkryptAIGuardrailConfigs,
):
guardrail: str = Field(description="The type of guardrail integration to use")
mode: Union[str, List[str], Mode] = Field(
diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/enkryptai.py b/litellm/types/proxy/guardrails/guardrail_hooks/enkryptai.py
new file mode 100644
index 00000000000..4ab49d52763
--- /dev/null
+++ b/litellm/types/proxy/guardrails/guardrail_hooks/enkryptai.py
@@ -0,0 +1,136 @@
+from typing import Any, Dict, List, Optional, Union
+
+from pydantic import BaseModel, Field
+from typing_extensions import TypedDict
+
+from .base import GuardrailConfigModel
+
+# TypedDicts for EnkryptAI API Response Structure
+
+
+class EnkryptAIPolicyViolationDetail(TypedDict, total=False):
+ """Details for policy violation detection."""
+
+ violating_policy: str
+ explanation: str
+
+
+class EnkryptAIPIIDetail(TypedDict, total=False):
+ """Details for PII detection."""
+
+ pii: Dict[str, Any]
+
+
+class EnkryptAIToxicityDetail(TypedDict, total=False):
+ """Details for toxicity detection.
+
+ Contains scores for different types of toxicity:
+ - toxic
+ - severe_toxic
+ - obscene
+ - threat
+ - insult
+ - identity_hate
+ """
+
+ toxic: Optional[float]
+ severe_toxic: Optional[float]
+ obscene: Optional[float]
+ threat: Optional[float]
+ insult: Optional[float]
+ identity_hate: Optional[float]
+
+
+class EnkryptAIKeywordDetail(TypedDict, total=False):
+ """Details for keyword detection."""
+
+ detected_keywords: List[str]
+
+
+class EnkryptAIBiasDetail(TypedDict, total=False):
+ """Details for bias detection."""
+
+ bias_detected: bool
+
+
+class EnkryptAIResponseSummary(TypedDict, total=False):
+ """Summary of detected violations in EnkryptAI response.
+
+ Each key represents a type of violation:
+ - toxicity: List (non-empty if detected)
+ - policy_violation: 0 or 1
+ - pii: 0 or 1
+ - keyword_detected: 0 or 1
+ - bias: 0 or 1
+ - prompt_injection: 0 or 1
+ - jailbreak: 0 or 1
+ """
+
+ toxicity: Optional[List[str]]
+ policy_violation: Optional[int]
+ pii: Optional[int]
+ keyword_detected: Optional[int]
+ bias: Optional[int]
+ prompt_injection: Optional[int]
+ jailbreak: Optional[int]
+
+
+class EnkryptAIResponseDetails(TypedDict, total=False):
+ """Detailed information about detected violations."""
+
+ policy_violation: Optional[EnkryptAIPolicyViolationDetail]
+ pii: Optional[EnkryptAIPIIDetail]
+ toxicity: Optional[EnkryptAIToxicityDetail]
+ keyword_detected: Optional[EnkryptAIKeywordDetail]
+ bias: Optional[EnkryptAIBiasDetail]
+ prompt_injection: Optional[Dict[str, Any]]
+ jailbreak: Optional[Dict[str, Any]]
+
+
+class EnkryptAIResponse(TypedDict, total=False):
+ """Complete response from EnkryptAI Guardrails API."""
+
+ summary: EnkryptAIResponseSummary
+ details: EnkryptAIResponseDetails
+
+
+class EnkryptAIProcessedResult(TypedDict):
+ """Processed result from EnkryptAI guardrail response."""
+
+ attacks_detected: List[str]
+ attack_details: Dict[str, Union[EnkryptAIPolicyViolationDetail, EnkryptAIPIIDetail, EnkryptAIToxicityDetail, EnkryptAIKeywordDetail, EnkryptAIBiasDetail, Dict[str, Any]]]
+
+
+# Pydantic Config Model
+class EnkryptAIGuardrailConfigs(BaseModel):
+ """Configuration parameters for the EnkryptAI guardrail"""
+ api_key: Optional[str] = Field(
+ default=None,
+ description="The EnkryptAI API key. Reads from ENKRYPTAI_API_KEY env var if None.",
+ )
+ api_base: Optional[str] = Field(
+ default=None,
+ description="The EnkryptAI API base URL. Defaults to https://api.enkryptai.com. Also checks if the ENKRYPTAI_API_KEY env var is set.",
+ )
+ policy_name: Optional[str] = Field(
+ default=None,
+ description="The EnkryptAI policy name to use. Sent via x-enkrypt-policy header.",
+ )
+ deployment_name: Optional[str] = Field(
+ default=None,
+ description="The EnkryptAI deployment name to use. Sent via X-Enkrypt-Deployment header.",
+ )
+ detectors: Optional[dict] = Field(
+ default=None,
+ description="Dictionary of detector configurations (e.g., {'nsfw': {'enabled': True}, 'toxicity': {'enabled': True}}).",
+ )
+ block_on_violation: Optional[bool] = Field(
+ default=True,
+ description="Whether to block requests when violations are detected. Defaults to True.",
+ )
+
+class EnkryptAIGuardrailConfigModel(GuardrailConfigModel, EnkryptAIGuardrailConfigs):
+ @staticmethod
+ def ui_friendly_name() -> str:
+ return "EnkryptAI"
+
diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_enkryptai.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_enkryptai.py
new file mode 100644
index 00000000000..625db837129
--- /dev/null
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_enkryptai.py
@@ -0,0 +1,440 @@
+"""
+Tests for EnkryptAI guardrail integration
+
+This test file tests the EnkryptAI guardrail implementation.
+"""
+import os
+from unittest.mock import MagicMock, patch
+
+import httpx
+import pytest
+
+import litellm
+from litellm import ModelResponse
+from litellm.proxy._types import UserAPIKeyAuth
+from litellm.proxy.guardrails.guardrail_hooks.enkryptai import EnkryptAIGuardrails
+from litellm.types.utils import Choices, Message
+
+
+def enkryptai_guardrail():
+ """Create an EnkryptAIGuardrail instance for testing"""
+ return EnkryptAIGuardrails(
+ api_key="test-api-key",
+ api_base="https://api.test.enkryptai.com",
+ guardrail_name="test-enkryptai-guardrail",
+ event_hook="pre_call",
+ default_on=True,
+ detectors={
+ "nsfw": {"enabled": True},
+ "toxicity": {"enabled": True},
+ }
+ )
+
+
+def mock_user_api_key_dict():
+ """Create a mock UserAPIKeyAuth object"""
+ return UserAPIKeyAuth(
+ user_id="test-user-id",
+ user_email="[email protected]",
+ key_name="test-key",
+ key_alias=None,
+ team_id=None,
+ team_alias=None,
+ user_role=None,
+ api_key="test-api-key",
+ permissions={},
+ models=[],
+ spend=0.0,
+ max_budget=None,
+ soft_budget=None,
+ tpm_limit=None,
+ rpm_limit=None,
+ metadata={},
+ max_parallel_requests=None,
+ allowed_cache_controls=[],
+ model_spend={},
+ model_max_budget={},
+ )
+
+
+def mock_request_data():
+ """Create mock request data"""
+ return {
+ "messages": [
+ {"role": "system", "content": "You are a helpful assistant"},
+ {"role": "user", "content": "Hello, how are you?"},
+ ],
+ "litellm_call_id": "test-call-id",
+ "metadata": {"requester_ip_address": "192.168.1.1"},
+ }
+
+
+class TestEnkryptAIGuardrailConfiguration:
+ """Test configuration and initialization of EnkryptAI guardrail"""
+
+ def test_init_with_config(self):
+ """Test initializing EnkryptAI guardrail with configuration"""
+ guardrail = EnkryptAIGuardrails(
+ api_key="test-key",
+ api_base="https://api.test.enkryptai.com",
+ policy_name="test-policy",
+ detectors={"toxicity": {"enabled": True}}
+ )
+ assert guardrail.api_key == "test-key"
+ assert guardrail.api_base == "https://api.test.enkryptai.com"
+ assert guardrail.policy_name == "test-policy"
+ assert guardrail.optional_params.get("detectors") == {"toxicity": {"enabled": True}}
+
+ def test_init_with_env_vars(self):
+ """Test initialization with environment variables"""
+ with patch.dict(
+ os.environ,
+ {
+ "ENKRYPTAI_API_KEY": "env-api-key",
+ "ENKRYPTAI_API_BASE": "https://env.api.enkryptai.com",
+ },
+ ):
+ guardrail = EnkryptAIGuardrails()
+ assert guardrail.api_key == "env-api-key"
+ assert guardrail.api_base == "https://env.api.enkryptai.com"
+
+ def test_init_with_params_override_env(self):
+ """Test that constructor params override environment variables"""
+ with patch.dict(
+ os.environ,
+ {
+ "ENKRYPTAI_API_KEY": "env-api-key",
+ },
+ ):
+ guardrail = EnkryptAIGuardrails(
+ api_key="param-api-key",
+ )
+ assert guardrail.api_key == "param-api-key"
+
+ def test_init_without_api_key_raises_error(self):
+ """Test that initialization without API key raises ValueError"""
+ with patch.dict(os.environ, {}, clear=True):
+ with pytest.raises(ValueError, match="EnkryptAI API key is required"):
+ EnkryptAIGuardrails()
+
+
+class TestEnkryptAIGuardrailHooks:
+ """Test the guardrail hook methods"""
+
+ @pytest.mark.asyncio
+ async def test_pre_call_hook_allowed(
+ self, enkryptai_guardrail, mock_user_api_key_dict, mock_request_data
+ ):
+ """Test pre-call hook when content is allowed"""
+ mock_response = MagicMock()
+ mock_response.json.return_value = {
+ "summary": {"nsfw": 0, "toxicity": []},
+ "violations": [],
+ "detected": False,
+ }
+ mock_response.raise_for_status = MagicMock()
+ mock_response.status_code = 200
+
+ with patch.object(
+ enkryptai_guardrail.async_handler, "post", return_value=mock_response
+ ) as mock_post:
+ result = await enkryptai_guardrail.async_pre_call_hook(
+ user_api_key_dict=mock_user_api_key_dict,
+ cache=MagicMock(),
+ data=mock_request_data,
+ call_type="completion",
+ )
+
+ assert result == mock_request_data
+ mock_post.assert_called_once()
+
+ # Verify API call details
+ call_args = mock_post.call_args
+ assert call_args[1]["url"].endswith("/guardrails/detect")
+ assert call_args[1]["headers"]["apikey"] == "test-api-key"
+ assert call_args[1]["json"]["text"] == "Hello, how are you?"
+
+ @pytest.mark.asyncio
+ async def test_pre_call_hook_blocked(
+ self, enkryptai_guardrail, mock_user_api_key_dict, mock_request_data
+ ):
+ """Test pre-call hook when content is blocked"""
+ mock_response = MagicMock()
+ mock_response.json.return_value = {
+ "summary": {"toxicity": ["high"]},
+ "violations": ["toxicity"],
+ "detected": True,
+ }
+ mock_response.raise_for_status = MagicMock()
+ mock_response.status_code = 200
+
+ with patch.object(
+ enkryptai_guardrail.async_handler, "post", return_value=mock_response
+ ):
+ with pytest.raises(Exception) as exc_info:
+ await enkryptai_guardrail.async_pre_call_hook(
+ user_api_key_dict=mock_user_api_key_dict,
+ cache=MagicMock(),
+ data=mock_request_data,
+ call_type="completion",
+ )
+
+ assert exc_info.value.status_code == 400
+
+ @pytest.mark.asyncio
+ async def test_pre_call_hook_with_policy_header(
+ self, mock_user_api_key_dict, mock_request_data
+ ):
+ """Test pre-call hook with policy header"""
+ guardrail = EnkryptAIGuardrails(
+ api_key="test-key",
+ policy_name="my-policy",
+ guardrail_name="test-guardrail",
+ event_hook="pre_call",
+ default_on=True,
+ )
+
+ mock_response = MagicMock()
+ mock_response.json.return_value = {
+ "violations": [],
+ "detected": False,
+ }
+ mock_response.raise_for_status = MagicMock()
+
+ with patch.object(
+ guardrail.async_handler, "post", return_value=mock_response
+ ) as mock_post:
+ await guardrail.async_pre_call_hook(
+ user_api_key_dict=mock_user_api_key_dict,
+ cache=MagicMock(),
+ data=mock_request_data,
+ call_type="completion",
+ )
+
+ # Verify policy header was sent
+ call_args = mock_post.call_args
+ assert call_args[1]["headers"]["x-enkrypt-policy"] == "my-policy"
+
+ @pytest.mark.asyncio
+ async def test_post_call_success_hook(
+ self, enkryptai_guardrail, mock_user_api_key_dict, mock_request_data
+ ):
+ """Test post-call success hook"""
+ # Create a mock ModelResponse
+ response = ModelResponse(
+ id="test-response-id",
+ choices=[
+ Choices(
+ finish_reason="stop",
+ index=0,
+ message=Message(
+ content="I'm doing well, thank you!", role="assistant"
+ ),
+ )
+ ],
+ created=1234567890,
+ model="gpt-3.5-turbo",
+ object="chat.completion",
+ system_fingerprint=None,
+ usage={"prompt_tokens": 10, "completion_tokens": 20, "total_tokens": 30},
+ )
+
+ mock_api_response = MagicMock()
+ mock_api_response.json.return_value = {
+ "violations": [],
+ "detected": False,
+ }
+ mock_api_response.raise_for_status = MagicMock()
+
+ # Update guardrail to use post_call event hook
+ enkryptai_guardrail.event_hook = "post_call"
+
+ with patch.object(
+ enkryptai_guardrail.async_handler, "post", return_value=mock_api_response
+ ) as mock_post:
+ result = await enkryptai_guardrail.async_post_call_success_hook(
+ data=mock_request_data,
+ user_api_key_dict=mock_user_api_key_dict,
+ response=response,
+ )
+
+ assert result == response
+ mock_post.assert_called_once()
+
+ # Verify API call details
+ call_args = mock_post.call_args
+ assert call_args[1]["json"]["text"] == "I'm doing well, thank you!"
+
+ @pytest.mark.asyncio
+ async def test_moderation_hook(
+ self, enkryptai_guardrail, mock_user_api_key_dict, mock_request_data
+ ):
+ """Test moderation hook (during_call)"""
+ # Update guardrail to use during_call event hook
+ enkryptai_guardrail.event_hook = "during_call"
+
+ mock_response = MagicMock()
+ mock_response.json.return_value = {
+ "violations": [],
+ "detected": False,
+ }
+ mock_response.raise_for_status = MagicMock()
+
+ with patch.object(
+ enkryptai_guardrail.async_handler, "post", return_value=mock_response
+ ):
+ result = await enkryptai_guardrail.async_moderation_hook(
+ data=mock_request_data,
+ user_api_key_dict=mock_user_api_key_dict,
+ call_type="completion",
+ )
+
+ assert result == mock_request_data
+
+ @pytest.mark.asyncio
+ async def test_api_failure_handling(
+ self, enkryptai_guardrail, mock_user_api_key_dict, mock_request_data
+ ):
+ """Test API failure handling"""
+ with patch.object(
+ enkryptai_guardrail.async_handler,
+ "post",
+ side_effect=httpx.HTTPStatusError(
+ "API Error", request=MagicMock(), response=MagicMock(status_code=500)
+ ),
+ ):
+ with pytest.raises(httpx.HTTPStatusError):
+ await enkryptai_guardrail.async_pre_call_hook(
+ user_api_key_dict=mock_user_api_key_dict,
+ cache=MagicMock(),
+ data=mock_request_data,
+ call_type="completion",
+ )
+
+ @pytest.mark.asyncio
+ async def test_monitor_mode(
+ self, mock_user_api_key_dict, mock_request_data
+ ):
+ """Test monitor mode (block_on_violation=False)"""
+ guardrail = EnkryptAIGuardrails(
+ api_key="test-key",
+ block_on_violation=False,
+ guardrail_name="test-guardrail",
+ event_hook="pre_call",
+ default_on=True,
+ )
+
+ mock_response = MagicMock()
+ mock_response.json.return_value = {
+ "violations": ["toxicity"],
+ "detected": True,
+ }
+ mock_response.raise_for_status = MagicMock()
+
+ with patch.object(
+ guardrail.async_handler, "post", return_value=mock_response
+ ):
+ # Should not raise exception in monitor mode
+ result = await guardrail.async_pre_call_hook(
+ user_api_key_dict=mock_user_api_key_dict,
+ cache=MagicMock(),
+ data=mock_request_data,
+ call_type="completion",
+ )
+
+ assert result == mock_request_data
+
+ def test_extract_user_message(self, enkryptai_guardrail):
+ """Test _extract_user_message helper method"""
+ data = {
+ "messages": [
+ {"role": "system", "content": "System prompt"},
+ {"role": "user", "content": "First user message"},
+ {"role": "assistant", "content": "Assistant response"},
+ {"role": "user", "content": "Second user message"},
+ ]
+ }
+
+ message = enkryptai_guardrail._extract_user_message(data)
+ assert message == "Second user message"
+
+ data = {"messages": [{"role": "system", "content": "System prompt"}]}
+ message = enkryptai_guardrail._extract_user_message(data)
+ assert message is None
+
+ data = {"messages": []}
+ message = enkryptai_guardrail._extract_user_message(data)
+ assert message is None
+
+ data = {}
+ message = enkryptai_guardrail._extract_user_message(data)
+ assert message is None
+
+ def test_determine_guardrail_status(self, enkryptai_guardrail):
+ """Test _determine_guardrail_status helper method"""
+ # Test success status
+ response_json = {"violations": [], "detected": False}
+ status = enkryptai_guardrail._determine_guardrail_status(response_json)
+ assert status == "success"
+
+ # Test intervened status
+ response_json = {"violations": ["toxicity"], "detected": True}
+ status = enkryptai_guardrail._determine_guardrail_status(response_json)
+ assert status == "guardrail_intervened"
+
+ # Test failed status
+ response_json = "invalid"
+ status = enkryptai_guardrail._determine_guardrail_status(response_json)
+ assert status == "guardrail_failed_to_respond"
+
+
+class TestEnkryptAIExtraction:
+ """Test content extraction methods"""
+
+ def test_extract_user_message_multipart(self):
+ """Test extracting user message with multipart content"""
+ guardrail = EnkryptAIGuardrails(api_key="test-key")
+
+ data = {
+ "messages": [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Hello"},
+ {"type": "text", "text": "world"},
+ ],
+ }
+ ]
+ }
+
+ message = guardrail._extract_user_message(data)
+ assert message == "Hello world"
+
+ def test_extract_response_content(self):
+ """Test extracting content from ModelResponse"""
+ guardrail = EnkryptAIGuardrails(api_key="test-key")
+
+ response = ModelResponse(
+ id="test-id",
+ choices=[
+ Choices(
+ finish_reason="stop",
+ index=0,
+ message=Message(content="Test response", role="assistant"),
+ )
+ ],
+ created=1234567890,
+ model="gpt-3.5-turbo",
+ object="chat.completion",
+ )
+
+ content = guardrail._extract_response_content(response)
+ assert content == "Test response"
+
+ # Test with non-ModelResponse
+ content = guardrail._extract_response_content("invalid")
+ assert content is None
+