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]

Add presidio_language yaml configuration support for guardrails (#11331)

Cole McIntosh702e399d944b
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 c93eb52a2a7..74d26e7e178 100644
--- a/docs/my-website/docs/proxy/guardrails/pii_masking_v2.md
+++ b/docs/my-website/docs/proxy/guardrails/pii_masking_v2.md
@@ -13,6 +13,7 @@ import TabItem from '@theme/TabItem';
| Supported Entity Types | All Presidio Entity Types |
| Supported Actions | `MASK`, `BLOCK` |
| Supported Modes | `pre_call`, `during_call`, `post_call`, `logging_only` |
+| Language Support | Configurable via `presidio_language` parameter (supports multiple languages including English, Spanish, German, etc.) |
## Deployment options
@@ -48,6 +49,18 @@ Now select the entity types you want to mask. See the [supported actions here](#
style={{width: '50%', display: 'block', margin: '0'}}
/>
+#### 1.3 Set Default Language (Optional)
+
+You can also configure a default language for PII analysis using the `presidio_language` field in the UI. This sets the default language that will be used for all requests unless overridden by a per-request language setting.
+
+**Supported language codes include:**
+- `en` - English (default)
+- `es` - Spanish
+- `de` - German
+
+
+If not specified, English (`en`) will be used as the default language.
+
</TabItem>
@@ -67,6 +80,7 @@ guardrails:
litellm_params:
guardrail: presidio # supported values: "aporia", "bedrock", "lakera", "presidio"
mode: "pre_call"
+ presidio_language: "en" # optional: set default language for PII analysis
```
Set the following env vars
@@ -380,6 +394,86 @@ print(response)
</Tabs>
+### Set default `language` in config.yaml
+
+You can configure a default language for PII analysis in your YAML configuration using the `presidio_language` parameter. This language will be used for all requests unless overridden by a per-request language setting.
+
+```yaml title="Default Language Configuration" 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-german"
+ litellm_params:
+ guardrail: presidio
+ mode: "pre_call"
+ presidio_language: "de" # Default to German for PII analysis
+ pii_entities_config:
+ CREDIT_CARD: "MASK"
+ EMAIL_ADDRESS: "MASK"
+ PERSON: "MASK"
+
+ - guardrail_name: "presidio-spanish"
+ litellm_params:
+ guardrail: presidio
+ mode: "pre_call"
+ presidio_language: "es" # Default to Spanish for PII analysis
+ pii_entities_config:
+ CREDIT_CARD: "MASK"
+ PHONE_NUMBER: "MASK"
+```
+
+#### Supported Language Codes
+
+Presidio supports multiple languages for PII detection. Common language codes include:
+
+- `en` - English (default)
+- `es` - Spanish
+- `de` - German
+
+For a complete list of supported languages, refer to the [Presidio documentation](https://microsoft.github.io/presidio/analyzer/languages/).
+
+#### Language Precedence
+
+The language setting follows this precedence order:
+
+1. **Per-request language** (via `guardrail_config.language`) - highest priority
+2. **YAML config language** (via `presidio_language`) - medium priority
+3. **Default language** (`en`) - lowest priority
+
+**Example with mixed languages:**
+
+```yaml title="Mixed Language Configuration" showLineNumbers
+guardrails:
+ - guardrail_name: "presidio-multilingual"
+ litellm_params:
+ guardrail: presidio
+ mode: "pre_call"
+ presidio_language: "de" # Default to German
+ pii_entities_config:
+ CREDIT_CARD: "MASK"
+ PERSON: "MASK"
+```
+
+```shell title="Override with per-request language" 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": "Mi tarjeta de crédito es 4111-1111-1111-1111"}
+ ],
+ "guardrails": ["presidio-multilingual"],
+ "guardrail_config": {"language": "es"}
+ }'
+```
+
+In this example, the request will use Spanish (`es`) for PII detection even though the guardrail is configured with German (`de`) as the default language.
+
### Output parsing
diff --git a/litellm/proxy/guardrails/guardrail_hooks/presidio.py b/litellm/proxy/guardrails/guardrail_hooks/presidio.py
index 3c5ca3d9c23..c7ac00ee812 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/presidio.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/presidio.py
@@ -69,6 +69,7 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
presidio_ad_hoc_recognizers: Optional[str] = None,
logging_only: Optional[bool] = None,
pii_entities_config: Optional[Dict[PiiEntityType, PiiAction]] = None,
+ presidio_language: Optional[str] = None,
**kwargs,
):
if logging_only is True:
@@ -83,6 +84,7 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
self.pii_entities_config: Dict[PiiEntityType, PiiAction] = (
pii_entities_config or {}
)
+ self.presidio_language = presidio_language or "en"
if mock_testing is True: # for testing purposes only
return
@@ -161,7 +163,7 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
"""
analyze_payload: PresidioAnalyzeRequest = PresidioAnalyzeRequest(
text=text,
- language="en",
+ language=self.presidio_language,
)
##################################################################
###### Check if user has configured any params for this guardrail
diff --git a/litellm/proxy/guardrails/guardrail_initializers.py b/litellm/proxy/guardrails/guardrail_initializers.py
index 9cd952e6849..03673350d0f 100644
--- a/litellm/proxy/guardrails/guardrail_initializers.py
+++ b/litellm/proxy/guardrails/guardrail_initializers.py
@@ -113,6 +113,7 @@ def initialize_presidio(litellm_params: LitellmParams, guardrail: Guardrail):
pii_entities_config=litellm_params.pii_entities_config,
presidio_analyzer_api_base=litellm_params.presidio_analyzer_api_base,
presidio_anonymizer_api_base=litellm_params.presidio_anonymizer_api_base,
+ presidio_language=litellm_params.presidio_language,
)
litellm.logging_callback_manager.add_litellm_callback(_presidio_callback)
@@ -125,6 +126,7 @@ def initialize_presidio(litellm_params: LitellmParams, guardrail: Guardrail):
default_on=litellm_params.default_on,
presidio_analyzer_api_base=litellm_params.presidio_analyzer_api_base,
presidio_anonymizer_api_base=litellm_params.presidio_anonymizer_api_base,
+ presidio_language=litellm_params.presidio_language,
)
litellm.logging_callback_manager.add_litellm_callback(_success_callback)
diff --git a/litellm/types/guardrails.py b/litellm/types/guardrails.py
index 7b24f6340df..baabfa0a178 100644
--- a/litellm/types/guardrails.py
+++ b/litellm/types/guardrails.py
@@ -234,6 +234,10 @@ class PresidioPresidioConfigModelUserInterface(BaseModel):
# extra param to let the ui know this is a boolean
json_schema_extra={"ui_type": GuardrailParamUITypes.BOOL},
)
+ presidio_language: Optional[str] = Field(
+ default="en",
+ description="Language code for Presidio PII analysis (e.g., 'en', 'de', 'es', 'fr')",
+ )
class PresidioConfigModel(PresidioPresidioConfigModelUserInterface):
diff --git a/tests/guardrails_tests/test_presidio_pii.py b/tests/guardrails_tests/test_presidio_pii.py
index 25e027c0c2f..e3f811ba7df 100644
--- a/tests/guardrails_tests/test_presidio_pii.py
+++ b/tests/guardrails_tests/test_presidio_pii.py
@@ -490,3 +490,105 @@ async def test_presidio_pii_masking_logging_output_only_logged_response_guardrai
assert pii_masking_obj.should_run_guardrail(
data={}, event_type=GuardrailEventHooks.logging_only
)
+
+
+async def test_presidio_language_configuration():
+ """Test that presidio_language parameter is properly set and used in analyze requests"""
+ litellm._turn_on_debug()
+
+ # Test with German language using mock testing to avoid API calls
+ presidio_guardrail_de = _OPTIONAL_PresidioPIIMasking(
+ pii_entities_config={},
+ presidio_language="de",
+ mock_testing=True # This bypasses the API validation
+ )
+
+ test_text = "Meine Telefonnummer ist +49 30 12345678"
+
+ # Test the analyze request configuration
+ analyze_request = presidio_guardrail_de._get_presidio_analyze_request_payload(
+ text=test_text,
+ presidio_config=None,
+ request_data={}
+ )
+
+ # Verify the language is set to German
+ assert analyze_request["language"] == "de"
+ assert analyze_request["text"] == test_text
+
+ # Test with Spanish language
+ presidio_guardrail_es = _OPTIONAL_PresidioPIIMasking(
+ pii_entities_config={},
+ presidio_language="es",
+ mock_testing=True
+ )
+
+ test_text_es = "Mi número de teléfono es +34 912 345 678"
+
+ analyze_request_es = presidio_guardrail_es._get_presidio_analyze_request_payload(
+ text=test_text_es,
+ presidio_config=None,
+ request_data={}
+ )
+
+ # Verify the language is set to Spanish
+ assert analyze_request_es["language"] == "es"
+ assert analyze_request_es["text"] == test_text_es
+
+ # Test default language (English) when not specified
+ presidio_guardrail_default = _OPTIONAL_PresidioPIIMasking(
+ pii_entities_config={},
+ mock_testing=True
+ )
+
+ test_text_en = "My phone number is +1 555-123-4567"
+
+ analyze_request_default = presidio_guardrail_default._get_presidio_analyze_request_payload(
+ text=test_text_en,
+ presidio_config=None,
+ request_data={}
+ )
+
+ # Verify the language defaults to English
+ assert analyze_request_default["language"] == "en"
+ assert analyze_request_default["text"] == test_text_en
+
+
+async def test_presidio_language_configuration_with_per_request_override():
+ """Test that per-request language configuration overrides the default configured language"""
+ litellm._turn_on_debug()
+
+ # Set up guardrail with German as default language
+ presidio_guardrail = _OPTIONAL_PresidioPIIMasking(
+ pii_entities_config={},
+ presidio_language="de",
+ mock_testing=True
+ )
+
+ test_text = "Test text with PII"
+
+ # Test with per-request config overriding the default language
+ presidio_config = PresidioPerRequestConfig(language="fr")
+
+ analyze_request = presidio_guardrail._get_presidio_analyze_request_payload(
+ text=test_text,
+ presidio_config=presidio_config,
+ request_data={}
+ )
+
+ # Verify the per-request language (French) overrides the default (German)
+ assert analyze_request["language"] == "fr"
+ assert analyze_request["text"] == test_text
+
+ # Test without per-request config - should use default language
+ analyze_request_default = presidio_guardrail._get_presidio_analyze_request_payload(
+ text=test_text,
+ presidio_config=None,
+ request_data={}
+ )
+
+ # Verify the default language (German) is used
+ assert analyze_request_default["language"] == "de"
+ assert analyze_request_default["text"] == test_text