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] Allow specifying PII Entities Config when using Presidio Guardrails (#10810)

Ishaan Jaff8142c20c9843
diff --git a/.circleci/config.yml b/.circleci/config.yml
index 7eab78cd766..beee6a80ea5 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -805,6 +805,51 @@ jobs:
paths:
- mcp_coverage.xml
- mcp_coverage
+ guardrails_testing:
+ docker:
+ - image: cimg/python:3.11
+ auth:
+ username: ${DOCKERHUB_USERNAME}
+ password: ${DOCKERHUB_PASSWORD}
+ working_directory: ~/project
+
+ steps:
+ - checkout
+ - setup_google_dns
+ - run:
+ name: Install Dependencies
+ command: |
+ python -m pip install --upgrade pip
+ python -m pip install -r requirements.txt
+ pip install "pytest==7.3.1"
+ pip install "pytest-retry==1.6.3"
+ pip install "pytest-cov==5.0.0"
+ pip install "pytest-asyncio==0.21.1"
+ pip install "respx==0.21.1"
+ pip install "pydantic==2.10.2"
+ pip install "boto3==1.34.34"
+ # Run pytest and generate JUnit XML report
+ - run:
+ name: Run tests
+ command: |
+ pwd
+ ls
+ python -m pytest -vv tests/guardrails_tests --cov=litellm --cov-report=xml -x -s -v --junitxml=test-results/junit.xml --durations=5
+ no_output_timeout: 120m
+ - run:
+ name: Rename the coverage files
+ command: |
+ mv coverage.xml guardrails_coverage.xml
+ mv .coverage guardrails_coverage
+
+ # Store test results
+ - store_test_results:
+ path: test-results
+ - persist_to_workspace:
+ root: .
+ paths:
+ - guardrails_coverage.xml
+ - guardrails_coverage
llm_responses_api_testing:
docker:
- image: cimg/python:3.11
@@ -1499,7 +1544,7 @@ jobs:
command: |
pwd
ls
- python -m pytest -s -vv tests/*.py -x --junitxml=test-results/junit.xml --durations=5 --ignore=tests/otel_tests --ignore=tests/spend_tracking_tests --ignore=tests/pass_through_tests --ignore=tests/proxy_admin_ui_tests --ignore=tests/load_tests --ignore=tests/llm_translation --ignore=tests/llm_responses_api_testing --ignore=tests/mcp_tests --ignore=tests/image_gen_tests --ignore=tests/pass_through_unit_tests
+ python -m pytest -s -vv tests/*.py -x --junitxml=test-results/junit.xml --durations=5 --ignore=tests/otel_tests --ignore=tests/spend_tracking_tests --ignore=tests/pass_through_tests --ignore=tests/proxy_admin_ui_tests --ignore=tests/load_tests --ignore=tests/llm_translation --ignore=tests/llm_responses_api_testing --ignore=tests/mcp_tests --ignore=tests/guardrails_tests --ignore=tests/image_gen_tests --ignore=tests/pass_through_unit_tests
no_output_timeout: 120m
# Store test results
@@ -2358,7 +2403,7 @@ jobs:
python -m venv venv
. venv/bin/activate
pip install coverage
- coverage combine llm_translation_coverage llm_responses_api_coverage mcp_coverage logging_coverage litellm_router_coverage local_testing_coverage litellm_assistants_api_coverage auth_ui_unit_tests_coverage langfuse_coverage caching_coverage litellm_proxy_unit_tests_coverage image_gen_coverage pass_through_unit_tests_coverage batches_coverage litellm_proxy_security_tests_coverage
+ coverage combine llm_translation_coverage llm_responses_api_coverage mcp_coverage logging_coverage litellm_router_coverage local_testing_coverage litellm_assistants_api_coverage auth_ui_unit_tests_coverage langfuse_coverage caching_coverage litellm_proxy_unit_tests_coverage image_gen_coverage pass_through_unit_tests_coverage batches_coverage litellm_proxy_security_tests_coverage guardrails_coverage
coverage xml
- codecov/upload:
file: ./coverage.xml
@@ -2848,6 +2893,12 @@ workflows:
only:
- main
- /litellm_.*/
+ - guardrails_testing:
+ filters:
+ branches:
+ only:
+ - main
+ - /litellm_.*/
- llm_responses_api_testing:
filters:
branches:
@@ -2894,6 +2945,7 @@ workflows:
requires:
- llm_translation_testing
- mcp_testing
+ - guardrails_testing
- llm_responses_api_testing
- litellm_mapped_tests
- batches_testing
@@ -2985,4 +3037,5 @@ workflows:
- proxy_pass_through_endpoint_tests
- check_code_and_doc_quality
- publish_proxy_extras
+ - guardrails_testing
diff --git a/docs/my-website/docs/proxy/guardrails/pii_masking_v2.md b/docs/my-website/docs/proxy/guardrails/pii_masking_v2.md
index 59690666ee4..1d1efd4e468 100644
--- a/docs/my-website/docs/proxy/guardrails/pii_masking_v2.md
+++ b/docs/my-website/docs/proxy/guardrails/pii_masking_v2.md
@@ -11,7 +11,7 @@ LiteLLM supports [Microsoft Presidio](https://github.com/microsoft/presidio/) fo
### 1. Define Guardrails on your LiteLLM config.yaml
Define your guardrails under the `guardrails` section
-```yaml
+```yaml title="config.yaml" showLineNumbers
model_list:
- model_name: gpt-3.5-turbo
litellm_params:
@@ -27,7 +27,7 @@ guardrails:
Set the following env vars
-```bash
+```bash title="Setup Environment Variables" showLineNumbers
export PRESIDIO_ANALYZER_API_BASE="http://localhost:5002"
export PRESIDIO_ANONYMIZER_API_BASE="http://localhost:5001"
```
@@ -42,7 +42,7 @@ export PRESIDIO_ANONYMIZER_API_BASE="http://localhost:5001"
### 2. Start LiteLLM Gateway
-```shell
+```shell title="Start Gateway" showLineNumbers
litellm --config config.yaml --detailed_debug
```
@@ -55,7 +55,7 @@ litellm --config config.yaml --detailed_debug
Expect this to mask `Jane Doe` since it's PII
-```shell
+```shell title="Masked PII Request" showLineNumbers
curl http://localhost:4000/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-1234" \
@@ -70,7 +70,7 @@ curl http://localhost:4000/chat/completions \
Expected response on failure
-```shell
+```shell title="Response with Masked PII" showLineNumbers
{
"id": "chatcmpl-A3qSC39K7imjGbZ8xCDacGJZBoTJQ",
"choices": [
@@ -102,7 +102,7 @@ Expected response on failure
<TabItem label="No PII Call " value = "allowed">
-```shell
+```shell title="No PII Request" showLineNumbers
curl http://localhost:4000/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-1234" \
@@ -120,6 +120,122 @@ curl http://localhost:4000/chat/completions \
</Tabs>
+## Entity Type Configuration
+
+You can configure specific entity types for PII detection and decide how to handle each entity type (mask or block).
+
+### Configure Entity Types in config.yaml
+
+Define your guardrails with specific entity type configuration:
+
+```yaml title="config.yaml with Entity Types" showLineNumbers
+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: "presidio-mask-guard"
+ litellm_params:
+ guardrail: presidio
+ mode: "pre_call"
+ pii_entities_config:
+ CREDIT_CARD: "MASK" # Will mask credit card numbers
+ EMAIL_ADDRESS: "MASK" # Will mask email addresses
+
+ - guardrail_name: "presidio-block-guard"
+ litellm_params:
+ guardrail: presidio
+ mode: "pre_call"
+ pii_entities_config:
+ CREDIT_CARD: "BLOCK" # Will block requests containing credit card numbers
+```
+
+### Supported Entity Types
+
+LiteLLM Supports all Presidio entity types. See the complete list of presidio entity types [here](https://microsoft.github.io/presidio/supported_entities/).
+
+### Supported Actions
+
+For each entity type, you can specify one of the following actions:
+
+- `MASK`: Replace the entity with a placeholder (e.g., `<PERSON>`)
+- `BLOCK`: Block the request entirely if this entity type is detected
+
+### Test request with Entity Type Configuration
+
+<Tabs>
+<TabItem label="Masking PII entities" value="masked-entities">
+
+When using the masking configuration, entities will be replaced with placeholders:
+
+```shell title="Masking PII Request" showLineNumbers
+curl http://localhost:4000/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer sk-1234" \
+ -d '{
+ "model": "gpt-3.5-turbo",
+ "messages": [
+ {"role": "user", "content": "My credit card is 4111-1111-1111-1111 and my email is [email protected]"}
+ ],
+ "guardrails": ["presidio-mask-guard"]
+ }'
+```
+
+Example response with masked entities:
+
+```json
+{
+ "id": "chatcmpl-123abc",
+ "choices": [
+ {
+ "message": {
+ "content": "I can see you provided a <CREDIT_CARD> and an <EMAIL_ADDRESS>. For security reasons, I recommend not sharing this sensitive information.",
+ "role": "assistant"
+ },
+ "index": 0,
+ "finish_reason": "stop"
+ }
+ ],
+ // ... other response fields
+}
+```
+
+</TabItem>
+
+<TabItem label="Blocking PII entities" value="blocked-entity">
+
+When using the blocking configuration, requests containing the configured entity types will be blocked completely with an exception:
+
+```shell title="Blocking PII Request" showLineNumbers
+curl http://localhost:4000/chat/completions \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer sk-1234" \
+ -d '{
+ "model": "gpt-3.5-turbo",
+ "messages": [
+ {"role": "user", "content": "My credit card is 4111-1111-1111-1111"}
+ ],
+ "guardrails": ["presidio-block-guard"]
+ }'
+```
+
+When running this request, the proxy will raise a `BlockedPiiEntityError` exception.
+
+```json
+{
+ "error": {
+ "message": "Blocked PII entity detected: CREDIT_CARD by Guardrail: presidio-block-guard."
+ }
+}
+```
+
+The exception includes the entity type that was blocked (`CREDIT_CARD` in this case) and the guardrail name that caused the blocking.
+
+</TabItem>
+</Tabs>
+
## Advanced
### Set `language` per request
@@ -129,7 +245,7 @@ The Presidio API [supports passing the `language` param](https://microsoft.githu
<Tabs>
<TabItem label="curl" value = "curl">
-```shell
+```shell title="Language Parameter - curl" showLineNumbers
curl http://localhost:4000/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-1234" \
@@ -148,8 +264,7 @@ curl http://localhost:4000/chat/completions \
<TabItem label="OpenAI Python SDK" value = "python">
-```python
-
+```python title="Language Parameter - Python" showLineNumbers
import openai
client = openai.OpenAI(
api_key="anything",
@@ -179,7 +294,6 @@ print(response)
</Tabs>
-
### Output parsing
@@ -188,7 +302,7 @@ LLM responses can sometimes contain the masked tokens.
For presidio 'replace' operations, LiteLLM can check the LLM response and replace the masked token with the user-submitted values.
Define your guardrails under the `guardrails` section
-```yaml
+```yaml title="Output Parsing Config" showLineNumbers
model_list:
- model_name: gpt-3.5-turbo
litellm_params:
@@ -223,7 +337,7 @@ Send ad-hoc recognizers to presidio `/analyze` by passing a json file to the pro
#### Define ad-hoc recognizer on your LiteLLM config.yaml
Define your guardrails under the `guardrails` section
-```yaml
+```yaml title="Ad Hoc Recognizers Config" showLineNumbers
model_list:
- model_name: gpt-3.5-turbo
litellm_params:
@@ -240,7 +354,7 @@ guardrails:
Set the following env vars
-```bash
+```bash title="Ad Hoc Recognizers Environment Variables" showLineNumbers
export PRESIDIO_ANALYZER_API_BASE="http://localhost:5002"
export PRESIDIO_ANONYMIZER_API_BASE="http://localhost:5001"
```
@@ -248,13 +362,13 @@ export PRESIDIO_ANONYMIZER_API_BASE="http://localhost:5001"
You can see this working, when you run the proxy:
-```bash
+```bash title="Run Proxy with Debug" showLineNumbers
litellm --config /path/to/config.yaml --debug
```
Make a chat completions request, example:
-```
+```json title="Custom PII Request" showLineNumbers
{
"model": "azure-gpt-3.5",
"messages": [{"role": "user", "content": "John Smith AHV number is 756.3026.0705.92. Zip code: 1334023"}]
@@ -262,7 +376,7 @@ Make a chat completions request, example:
```
And search for any log starting with `Presidio PII Masking`, example:
-```
+```text title="PII Masking Log" showLineNumbers
Presidio PII Masking: Redacted pii message: <PERSON> AHV number is <AHV_NUMBER>. Zip code: <US_DRIVER_LICENSE>
```
@@ -283,7 +397,7 @@ This is currently only applied for
1. Define mode: `logging_only` on your LiteLLM config.yaml
Define your guardrails under the `guardrails` section
-```yaml
+```yaml title="Logging Only Config" showLineNumbers
model_list:
- model_name: gpt-3.5-turbo
litellm_params:
@@ -299,7 +413,7 @@ guardrails:
Set the following env vars
-```bash
+```bash title="Logging Only Environment Variables" showLineNumbers
export PRESIDIO_ANALYZER_API_BASE="http://localhost:5002"
export PRESIDIO_ANONYMIZER_API_BASE="http://localhost:5001"
```
@@ -307,13 +421,13 @@ export PRESIDIO_ANONYMIZER_API_BASE="http://localhost:5001"
2. Start proxy
-```bash
+```bash title="Start Proxy" showLineNumbers
litellm --config /path/to/config.yaml
```
3. Test it!
-```bash
+```bash title="Test Logging Only" showLineNumbers
curl -X POST 'http://0.0.0.0:4000/chat/completions' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-1234' \
@@ -331,7 +445,7 @@ curl -X POST 'http://0.0.0.0:4000/chat/completions' \
**Expected Logged Response**
-```
+```text title="Logged Response with Masked PII" showLineNumbers
Hi, my name is <PERSON>!
```
diff --git a/litellm/exceptions.py b/litellm/exceptions.py
index 3cdc70b08aa..5beb2041c32 100644
--- a/litellm/exceptions.py
+++ b/litellm/exceptions.py
@@ -807,3 +807,18 @@ class LiteLLMUnknownProvider(BadRequestError):
def __str__(self):
return self.message
+
+
+class BlockedPiiEntityError(Exception):
+ def __init__(
+ self,
+ entity_type: str,
+ guardrail_name: Optional[str] = None,
+ ):
+ """
+ Raised when a blocked entity is detected by a guardrail.
+ """
+ self.entity_type = entity_type
+ self.guardrail_name = guardrail_name
+ self.message = f"Blocked entity detected: {entity_type} by Guardrail: {guardrail_name}. This entity is not allowed to be used in this request."
+ super().__init__(self.message)
diff --git a/litellm/proxy/guardrails/guardrail_hooks/presidio.py b/litellm/proxy/guardrails/guardrail_hooks/presidio.py
index 89beaea412d..222b506301d 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/presidio.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/presidio.py
@@ -11,7 +11,7 @@
import asyncio
import json
import uuid
-from typing import Any, List, Optional, Tuple, Union
+from typing import Any, Dict, List, Optional, Tuple, Union, cast
import aiohttp
from pydantic import BaseModel
@@ -20,12 +20,17 @@ import litellm # noqa: E401
from litellm import get_secret
from litellm._logging import verbose_proxy_logger
from litellm.caching.caching import DualCache
+from litellm.exceptions import BlockedPiiEntityError
from litellm.integrations.custom_guardrail import (
CustomGuardrail,
log_guardrail_information,
)
from litellm.proxy._types import UserAPIKeyAuth
-from litellm.types.guardrails import GuardrailEventHooks
+from litellm.types.guardrails import GuardrailEventHooks, PiiAction, PiiEntityType
+from litellm.types.proxy.guardrails.guardrail_hooks.presidio import (
+ PresidioAnalyzeRequest,
+ PresidioAnalyzeResponseItem,
+)
from litellm.utils import (
EmbeddingResponse,
ImageResponse,
@@ -40,6 +45,7 @@ class PresidioPerRequestConfig(BaseModel):
"""
language: Optional[str] = None
+ entities: Optional[List[PiiEntityType]] = None
class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
@@ -56,6 +62,7 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
output_parse_pii: Optional[bool] = False,
presidio_ad_hoc_recognizers: Optional[str] = None,
logging_only: Optional[bool] = None,
+ pii_entities_config: Optional[Dict[PiiEntityType, PiiAction]] = None,
**kwargs,
):
if logging_only is True:
@@ -67,6 +74,9 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
) # mapping of PII token to original text - only used with Presidio `replace` operation
self.mock_redacted_text = mock_redacted_text
self.output_parse_pii = output_parse_pii or False
+ self.pii_entities_config: Dict[PiiEntityType, PiiAction] = (
+ pii_entities_config or {}
+ )
if mock_testing is True: # for testing purposes only
return
@@ -132,58 +142,105 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
"http://" + self.presidio_anonymizer_api_base
)
- async def check_pii(
+ def _get_presidio_analyze_request_payload(
self,
text: str,
- output_parse_pii: bool,
presidio_config: Optional[PresidioPerRequestConfig],
request_data: dict,
- ) -> str:
+ ) -> PresidioAnalyzeRequest:
+ """
+ Construct the payload for the Presidio analyze request
+
+ API Ref: https://microsoft.github.io/presidio/api-docs/api-docs.html#tag/Analyzer/paths/~1analyze/post
+ """
+ analyze_payload: PresidioAnalyzeRequest = PresidioAnalyzeRequest(
+ text=text,
+ language="en",
+ )
+ ##################################################################
+ ###### Check if user has configured any params for this guardrail
+ ################################################################
+ if self.ad_hoc_recognizers is not None:
+ analyze_payload["ad_hoc_recognizers"] = self.ad_hoc_recognizers
+
+ if self.pii_entities_config:
+ analyze_payload["entities"] = list(self.pii_entities_config.keys())
+
+ ##################################################################
+ ######### End of adding config params
+ ##################################################################
+
+ # Check if client side request passed any dynamic params
+ if presidio_config and presidio_config.language:
+ analyze_payload["language"] = presidio_config.language
+
+ casted_analyze_payload: dict = cast(dict, analyze_payload)
+ casted_analyze_payload.update(
+ self.get_guardrail_dynamic_request_body_params(request_data=request_data)
+ )
+ return cast(PresidioAnalyzeRequest, casted_analyze_payload)
+
+ async def analyze_text(
+ self,
+ text: str,
+ presidio_config: Optional[PresidioPerRequestConfig],
+ request_data: dict,
+ ) -> Union[List[PresidioAnalyzeResponseItem], Dict]:
"""
- [TODO] make this more performant for high-throughput scenario
+ Send text to the Presidio analyzer endpoint and get analysis results
"""
try:
async with aiohttp.ClientSession() as session:
if self.mock_redacted_text is not None:
- redacted_text = self.mock_redacted_text
- else:
- # Make the first request to /analyze
- # Construct Request 1
- analyze_url = f"{self.presidio_analyzer_api_base}analyze"
- analyze_payload = {"text": text, "language": "en"}
- if presidio_config and presidio_config.language:
- analyze_payload["language"] = presidio_config.language
- if self.ad_hoc_recognizers is not None:
- analyze_payload["ad_hoc_recognizers"] = self.ad_hoc_recognizers
- # End of constructing Request 1
- analyze_payload.update(
- self.get_guardrail_dynamic_request_body_params(
- request_data=request_data
- )
- )
- redacted_text = None
- verbose_proxy_logger.debug(
- "Making request to: %s with payload: %s",
- analyze_url,
- analyze_payload,
+ return self.mock_redacted_text
+
+ # Make the request to /analyze
+ analyze_url = f"{self.presidio_analyzer_api_base}analyze"
+
+ analyze_payload: PresidioAnalyzeRequest = (
+ self._get_presidio_analyze_request_payload(
+ text=text,
+ presidio_config=presidio_config,
+ request_data=request_data,
)
- async with session.post(
- analyze_url, json=analyze_payload
- ) as response:
- analyze_results = await response.json()
-
- # Make the second request to /anonymize
- anonymize_url = f"{self.presidio_anonymizer_api_base}anonymize"
- verbose_proxy_logger.debug("Making request to: %s", anonymize_url)
- anonymize_payload = {
- "text": text,
- "analyzer_results": analyze_results,
- }
-
- async with session.post(
- anonymize_url, json=anonymize_payload
- ) as response:
- redacted_text = await response.json()
+ )
+
+ verbose_proxy_logger.debug(
+ "Making request to: %s with payload: %s",
+ analyze_url,
+ analyze_payload,
+ )
+
+ async with session.post(analyze_url, json=analyze_payload) as response:
+ analyze_results = await response.json()
+ verbose_proxy_logger.debug("analyze_results: %s", analyze_results)
+ final_results = []
+ for item in analyze_results:
+ final_results.append(PresidioAnalyzeResponseItem(**item))
+ return final_results
+ except Exception as e:
+ raise e
+
+ async def anonymize_text(
+ self, text: str, analyze_results: Any, output_parse_pii: bool
+ ) -> str:
+ """
+ Send analysis results to the Presidio anonymizer endpoint to get redacted text
+ """
+ try:
+ async with aiohttp.ClientSession() as session:
+ # Make the request to /anonymize
+ anonymize_url = f"{self.presidio_anonymizer_api_base}anonymize"
+ verbose_proxy_logger.debug("Making request to: %s", anonymize_url)
+ anonymize_payload = {
+ "text": text,
+ "analyzer_results": analyze_results,
+ }
+
+ async with session.post(
+ anonymize_url, json=anonymize_payload
+ ) as response:
+ redacted_text = await response.json()
new_text = text
if redacted_text is not None:
@@ -209,6 +266,74 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
except Exception as e:
raise e
+ def raise_exception_if_blocked_entities_detected(
+ self, analyze_results: Union[List[PresidioAnalyzeResponseItem], Dict]
+ ):
+ """
+ Raise an exception if blocked entities are detected
+ """
+ if self.pii_entities_config is None:
+ return
+
+ if isinstance(analyze_results, Dict):
+ # if mock testing is enabled, analyze_results is a dict
+ # we don't need to raise an exception in this case
+ return
+
+ for result in analyze_results:
+ entity_type = result.get("entity_type")
+
+ if entity_type:
+ casted_entity_type: PiiEntityType = cast(PiiEntityType, entity_type)
+ if (
+ casted_entity_type in self.pii_entities_config
+ and self.pii_entities_config[casted_entity_type] == PiiAction.BLOCK
+ ):
+ raise BlockedPiiEntityError(
+ entity_type=entity_type,
+ guardrail_name=self.guardrail_name,
+ )
+
+ async def check_pii(
+ self,
+ text: str,
+ output_parse_pii: bool,
+ presidio_config: Optional[PresidioPerRequestConfig],
+ request_data: dict,
+ ) -> str:
+ """
+ Calls Presidio Analyze + Anonymize endpoints for PII Analysis + Masking
+ """
+ try:
+ if self.mock_redacted_text is not None:
+ redacted_text = self.mock_redacted_text
+ else:
+ # First get analysis results
+ analyze_results = await self.analyze_text(
+ text=text,
+ presidio_config=presidio_config,
+ request_data=request_data,
+ )
+ verbose_proxy_logger.debug("analyze_results: %s", analyze_results)
+
+ ####################################################
+ # Blocked Entities check
+ ####################################################
+ self.raise_exception_if_blocked_entities_detected(
+ analyze_results=analyze_results
+ )
+
+ # Then anonymize the text using the analysis results
+ return await self.anonymize_text(
+ text=text,
+ analyze_results=analyze_results,
+ output_parse_pii=output_parse_pii,
+ )
+
+ return redacted_text["text"]
+ except Exception as e:
+ raise e
+
@log_guardrail_information
async def async_pre_call_hook(
self,
diff --git a/litellm/proxy/guardrails/guardrail_initializers.py b/litellm/proxy/guardrails/guardrail_initializers.py
index a5b0447fc53..7d3e2d8d5f0 100644
--- a/litellm/proxy/guardrails/guardrail_initializers.py
+++ b/litellm/proxy/guardrails/guardrail_initializers.py
@@ -72,6 +72,7 @@ def initialize_presidio(litellm_params, guardrail):
presidio_ad_hoc_recognizers=litellm_params["presidio_ad_hoc_recognizers"],
mock_redacted_text=litellm_params.get("mock_redacted_text") or None,
default_on=litellm_params["default_on"],
+ pii_entities_config=litellm_params.get("pii_entities_config"),
)
litellm.logging_callback_manager.add_litellm_callback(_presidio_callback)
diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.py
index b4ae6606034..1925c6371d8 100644
--- a/litellm/types/guardrails.py
+++ b/litellm/types/guardrails.py
@@ -80,6 +80,63 @@ class LakeraCategoryThresholds(TypedDict, total=False):
jailbreak: float
+class PiiAction(str, Enum):
+ BLOCK = "BLOCK"
+ MASK = "MASK"
+
+
+class PiiEntityType(str, Enum):
+ # General
+ CREDIT_CARD = "CREDIT_CARD"
+ CRYPTO = "CRYPTO"
+ DATE_TIME = "DATE_TIME"
+ EMAIL_ADDRESS = "EMAIL_ADDRESS"
+ IBAN_CODE = "IBAN_CODE"
+ IP_ADDRESS = "IP_ADDRESS"
+ NRP = "NRP"
+ LOCATION = "LOCATION"
+ PERSON = "PERSON"
+ PHONE_NUMBER = "PHONE_NUMBER"
+ MEDICAL_LICENSE = "MEDICAL_LICENSE"
+ URL = "URL"
+ # USA
+ US_BANK_NUMBER = "US_BANK_NUMBER"
+ US_DRIVER_LICENSE = "US_DRIVER_LICENSE"
+ US_ITIN = "US_ITIN"
+ US_PASSPORT = "US_PASSPORT"
+ US_SSN = "US_SSN"
+ # UK
+ UK_NHS = "UK_NHS"
+ UK_NINO = "UK_NINO"
+ # Spain
+ ES_NIF = "ES_NIF"
+ ES_NIE = "ES_NIE"
+ # Italy
+ IT_FISCAL_CODE = "IT_FISCAL_CODE"
+ IT_DRIVER_LICENSE = "IT_DRIVER_LICENSE"
+ IT_VAT_CODE = "IT_VAT_CODE"
+ IT_PASSPORT = "IT_PASSPORT"
+ IT_IDENTITY_CARD = "IT_IDENTITY_CARD"
+ # Poland
+ PL_PESEL = "PL_PESEL"
+ # Singapore
+ SG_NRIC_FIN = "SG_NRIC_FIN"
+ SG_UEN = "SG_UEN"
+ # Australia
+ AU_ABN = "AU_ABN"
+ AU_ACN = "AU_ACN"
+ AU_TFN = "AU_TFN"
+ AU_MEDICARE = "AU_MEDICARE"
+ # India
+ IN_PAN = "IN_PAN"
+ IN_AADHAAR = "IN_AADHAAR"
+ IN_VEHICLE_REGISTRATION = "IN_VEHICLE_REGISTRATION"
+ IN_VOTER = "IN_VOTER"
+ IN_PASSPORT = "IN_PASSPORT"
+ # Finland
+ FI_PERSONAL_IDENTITY_CODE = "FI_PERSONAL_IDENTITY_CODE"
+
+
class LitellmParams(TypedDict):
guardrail: str
mode: str
@@ -97,6 +154,8 @@ class LitellmParams(TypedDict):
output_parse_pii: Optional[bool]
presidio_ad_hoc_recognizers: Optional[str]
mock_redacted_text: Optional[dict]
+ # PII control params
+ pii_entities_config: Optional[Dict[PiiEntityType, PiiAction]]
# hide secrets params
detect_secrets_config: Optional[dict]
@@ -105,7 +164,8 @@ class LitellmParams(TypedDict):
guard_name: Optional[str]
default_on: Optional[bool]
- # PII control params
+ ################## PII control params #################
+ ########################################################
mask_request_content: Optional[
bool
] # will mask request content if guardrail makes any changes
diff --git a/litellm/types/proxy/guardrails/guardrail_hooks/presidio.py b/litellm/types/proxy/guardrails/guardrail_hooks/presidio.py
new file mode 100644
index 00000000000..2be568eed8f
--- /dev/null
+++ b/litellm/types/proxy/guardrails/guardrail_hooks/presidio.py
@@ -0,0 +1,19 @@
+from typing import Any, Dict, List, Optional, TypedDict, Union
+
+from litellm.types.guardrails import PiiEntityType
+
+
+class PresidioAnalyzeRequest(TypedDict, total=False):
+ text: str
+ language: Optional[str]
+ ad_hoc_recognizers: Optional[List[str]]
+ entities: Optional[List[PiiEntityType]]
+
+
+class PresidioAnalyzeResponseItem(TypedDict, total=False):
+ entity_type: Optional[Union[PiiEntityType, str]]
+ start: Optional[int]
+ end: Optional[int]
+ score: Optional[float]
+ analysis_explanation: Optional[Dict[str, Any]]
+ recognition_metadata: Optional[Dict[str, Any]]
diff --git a/tests/local_testing/test_presidio_masking.py b/tests/guardrails_tests/test_presidio_pii.py
similarity index 50%
rename from tests/local_testing/test_presidio_masking.py
rename to tests/guardrails_tests/test_presidio_pii.py
index c9d1adc9b2e..7a3977758ee 100644
--- a/tests/local_testing/test_presidio_masking.py
+++ b/tests/guardrails_tests/test_presidio_pii.py
@@ -1,32 +1,205 @@
-# What is this?
-## Unit test for presidio pii masking
-import asyncio
-import os
-import random
import sys
+import os
+import io, asyncio
+import pytest
import time
-import traceback
-from datetime import datetime
+from litellm import mock_completion
+from unittest.mock import MagicMock, AsyncMock, patch
+sys.path.insert(0, os.path.abspath("../.."))
+import litellm
+from litellm.proxy.guardrails.guardrail_hooks.presidio import _OPTIONAL_PresidioPIIMasking, PresidioPerRequestConfig
+from litellm.types.guardrails import PiiEntityType, PiiAction
+from litellm.proxy._types import UserAPIKeyAuth
+from litellm.caching.caching import DualCache
+from litellm.exceptions import BlockedPiiEntityError
-from dotenv import load_dotenv
-load_dotenv()
-import os
-sys.path.insert(
- 0, os.path.abspath("../..")
-) # Adds the parent directory to the system path
-from unittest.mock import AsyncMock, MagicMock, patch
-import pytest
-import litellm
-from litellm import Router, mock_completion
-from litellm.caching.caching import DualCache
-from litellm.proxy._types import UserAPIKeyAuth
-from litellm.proxy.guardrails.guardrail_hooks.presidio import (
- _OPTIONAL_PresidioPIIMasking,
-)
-from litellm.proxy.utils import ProxyLogging
+async def test_presidio_with_entities_config():
+ """Test for Presidio guardrail with entities config - requires actual Presidio API"""
+ # Setup the guardrail with specific entities config
+ litellm._turn_on_debug()
+ pii_entities_config = {
+ PiiEntityType.CREDIT_CARD: PiiAction.MASK,
+ PiiEntityType.EMAIL_ADDRESS: PiiAction.MASK,
+ }
+
+ presidio_guardrail = _OPTIONAL_PresidioPIIMasking(
+ pii_entities_config=pii_entities_config,
+ presidio_analyzer_api_base=os.environ.get("PRESIDIO_ANALYZER_API_BASE"),
+ presidio_anonymizer_api_base=os.environ.get("PRESIDIO_ANONYMIZER_API_BASE")
+ )
+
+ # Test text with different PII types
+ test_text = "My credit card number is 4111-1111-1111-1111, my email is [email protected], and my phone is 555-123-4567"
+
+ # Test the analyze request configuration
+ analyze_request = presidio_guardrail._get_presidio_analyze_request_payload(
+ text=test_text,
+ presidio_config=None,
+ request_data={}
+ )
+
+ # Verify entities were passed correctly
+ assert "entities" in analyze_request
+ assert set(analyze_request["entities"]) == set(pii_entities_config.keys())
+
+ # Test the check_pii method - this will call the actual Presidio API
+ redacted_text = await presidio_guardrail.check_pii(
+ text=test_text,
+ output_parse_pii=True,
+ presidio_config=None,
+ request_data={}
+ )
+
+ # Verify PII has been masked/replaced/redacted in the result
+ assert "4111-1111-1111-1111" not in redacted_text
+ assert "[email protected]" not in redacted_text
+
+ # Since this entity is not in the config, it should not be masked
+ assert "555-123-4567" in redacted_text
+
+ # The specific replacements will vary based on Presidio's implementation
+ print(f"Redacted text: {redacted_text}")
+
+
+async def test_presidio_with_blocked_entities():
+ """Test for Presidio guardrail with blocked entities - requires actual Presidio API"""
+ # Setup the guardrail with specific entities config - BLOCK for credit card
+ litellm._turn_on_debug()
+ pii_entities_config = {
+ PiiEntityType.CREDIT_CARD: PiiAction.BLOCK, # This entity should cause a block
+ PiiEntityType.EMAIL_ADDRESS: PiiAction.MASK, # This entity should be masked
+ }
+
+ presidio_guardrail = _OPTIONAL_PresidioPIIMasking(
+ pii_entities_config=pii_entities_config,
+ presidio_analyzer_api_base=os.environ.get("PRESIDIO_ANALYZER_API_BASE"),
+ presidio_anonymizer_api_base=os.environ.get("PRESIDIO_ANONYMIZER_API_BASE")
+ )
+
+ # Test text with blocked PII type
+ test_text = "My credit card number is 4111-1111-1111-1111 and my email is [email protected]"
+
+ # Verify the analyze request configuration
+ analyze_request = presidio_guardrail._get_presidio_analyze_request_payload(
+ text=test_text,
+ presidio_config=None,
+ request_data={}
+ )
+
+ # Verify entities were passed correctly
+ assert "entities" in analyze_request
+ assert set(analyze_request["entities"]) == set(pii_entities_config.keys())
+
+ # Test that BlockedPiiEntityError is raised when check_pii is called
+ with pytest.raises(BlockedPiiEntityError) as excinfo:
+ await presidio_guardrail.check_pii(
+ text=test_text,
+ output_parse_pii=True,
+ presidio_config=None,
+ request_data={}
+ )
+
+ # Verify the error contains the correct entity type
+ assert excinfo.value.entity_type == PiiEntityType.CREDIT_CARD
+ assert excinfo.value.guardrail_name == presidio_guardrail.guardrail_name
+
+
+async def test_presidio_pre_call_hook_with_blocked_entities():
+ """Test for Presidio guardrail pre-call hook with blocked entities on a chat completion request"""
+ # Setup the guardrail with specific entities config
+ pii_entities_config = {
+ PiiEntityType.CREDIT_CARD: PiiAction.BLOCK, # This entity should cause a block
+ PiiEntityType.EMAIL_ADDRESS: PiiAction.MASK, # This entity should be masked
+ }
+
+ presidio_guardrail = _OPTIONAL_PresidioPIIMasking(
+ pii_entities_config=pii_entities_config,
+ presidio_analyzer_api_base=os.environ.get("PRESIDIO_ANALYZER_API_BASE"),
+ presidio_anonymizer_api_base=os.environ.get("PRESIDIO_ANONYMIZER_API_BASE")
+ )
+
+ # Create a sample chat completion request with PII data
+ data = {
+ "messages": [
+ {"role": "system", "content": "You are a helpful assistant."},
+ {"role": "user", "content": "My credit card is 4111-1111-1111-1111 and my email is [email protected]."}
+ ],
+ "model": "gpt-3.5-turbo"
+ }
+
+ # Mock objects needed for the pre-call hook
+ user_api_key_dict = UserAPIKeyAuth(api_key="test_key")
+ cache = DualCache()
+
+ # Call the pre-call hook and expect BlockedPiiEntityError
+ with pytest.raises(BlockedPiiEntityError) as excinfo:
+ await presidio_guardrail.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="completion"
+ )
+
+ print(f"got error: {excinfo}")
+
+ # Verify the error contains the correct entity type
+ assert excinfo.value.entity_type == PiiEntityType.CREDIT_CARD
+ assert excinfo.value.guardrail_name == presidio_guardrail.guardrail_name
+
+
+async def test_presidio_pre_call_hook_with_entities_config():
+ """Test for Presidio guardrail pre-call hook with entities config on a chat completion request"""
+ # Setup the guardrail with specific entities config
+ pii_entities_config = {
+ PiiEntityType.CREDIT_CARD: PiiAction.MASK,
+ PiiEntityType.EMAIL_ADDRESS: PiiAction.MASK,
+ }
+
+ presidio_guardrail = _OPTIONAL_PresidioPIIMasking(
+ pii_entities_config=pii_entities_config,
+ presidio_analyzer_api_base=os.environ.get("PRESIDIO_ANALYZER_API_BASE"),
+ presidio_anonymizer_api_base=os.environ.get("PRESIDIO_ANONYMIZER_API_BASE")
+ )
+
+ # Create a sample chat completion request with PII data
+ data = {
+ "messages": [
+ {"role": "system", "content": "You are a helpful assistant."},
+ {"role": "user", "content": "My credit card is 4111-1111-1111-1111 and my email is [email protected]. My phone number is 555-123-4567"}
+ ],
+ "model": "gpt-3.5-turbo"
+ }
+
+ # Mock objects needed for the pre-call hook
+ user_api_key_dict = UserAPIKeyAuth(api_key="test_key")
+ cache = DualCache()
+
+ # Call the pre-call hook
+ modified_data = await presidio_guardrail.async_pre_call_hook(
+ user_api_key_dict=user_api_key_dict,
+ cache=cache,
+ data=data,
+ call_type="completion"
+ )
+
+ # Verify the messages have been modified to mask PII
+ assert modified_data["messages"][0]["content"] == "You are a helpful assistant." # System prompt should be unchanged
+
+ user_message = modified_data["messages"][1]["content"]
+ assert "4111-1111-1111-1111" not in user_message
+ assert "[email protected]" not in user_message
+
+ # Since this entity is not in the config, it should not be masked
+ assert "555-123-4567" in user_message
+
+ print(f"Modified user message: {user_message}")
@pytest.mark.parametrize(
@@ -236,61 +409,6 @@ async def test_presidio_pii_masking_logging_output_only_no_pre_api_hook():
)
- "sync_mode",
- [True, False],
-)
-async def test_presidio_pii_masking_logging_output_only_logged_response(sync_mode):
- import litellm
-
- litellm.set_verbose = True
- pii_masking = _OPTIONAL_PresidioPIIMasking(
- logging_only=True,
- mock_testing=True,
- mock_redacted_text=input_b_anonymizer_results,
- guardrail_name="presidio",
- )
-
- test_messages = [
- {
- "role": "user",
- "content": "My name is Jane Doe, who are you? Say my name in your response",
- }
- ]
-
- if sync_mode:
- target_function = "log_success_event"
- mock_call = MagicMock()
- else:
- target_function = "async_log_success_event"
- mock_call = AsyncMock()
-
- with patch.object(pii_masking, target_function, new=mock_call) as mock_call:
- litellm.callbacks = [pii_masking]
- if sync_mode:
- response = litellm.completion(
- model="gpt-3.5-turbo", messages=test_messages, mock_response="Hi Peter!"
- )
- time.sleep(3)
- else:
- response = await litellm.acompletion(
- model="gpt-3.5-turbo", messages=test_messages, mock_response="Hi Peter!"
- )
- await asyncio.sleep(3)
-
- assert response.choices[0].message.content == "Hi Peter!" # type: ignore
-
- mock_call.assert_called_once()
-
- print(mock_call.call_args.kwargs["kwargs"]["messages"][0]["content"])
-
- assert (
- mock_call.call_args.kwargs["kwargs"]["messages"][0]["content"]
- == "My name is <PERSON>, who are you? Say my name in your response"
- )
-
-
@pytest.mark.asyncio
async def test_presidio_pii_masking_logging_output_only_logged_response_guardrails_config():
from typing import Dict, List, Optional