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
fix: clean approach instead of UUID
Harshit28j12de8a724f57
diff --git a/litellm/proxy/guardrails/guardrail_hooks/presidio.py b/litellm/proxy/guardrails/guardrail_hooks/presidio.pyindex ec139020704..8496a63ec31 100644--- a/litellm/proxy/guardrails/guardrail_hooks/presidio.py+++ b/litellm/proxy/guardrails/guardrail_hooks/presidio.py@@ -36,7 +36,6 @@ from litellm.types.utils import GenericGuardrailAPIInputsif TYPE_CHECKING:from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj-from litellm._uuid import uuidfrom litellm.caching.caching import DualCachefrom litellm.exceptions import BlockedPiiEntityError, GuardrailRaisedExceptionfrom litellm.integrations.custom_guardrail import (@@ -490,8 +489,6 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):end = item["end"]replacement = item["text"] # replacement tokenif item["operator"] == "replace" and output_parse_pii is True:- # check if token in dict- # if exists, add a uuid to the replacement token for swapping back to the original text in llm response output parsingif request_data is None:verbose_proxy_logger.warning("Presidio anonymize_text called without request_data — "@@ -507,9 +504,16 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):request_data["metadata"]["pii_tokens"] = {}pii_tokens = request_data["metadata"]["pii_tokens"]- # Always append a UUID to ensure the replacement token is unique to this request and session.- # This prevents collisions where the LLM might hallucinate a generic token like [PHONE_NUMBER].- replacement = f"{replacement}_{str(uuid.uuid4())[:12]}"+ # Append a sequential number to make each token unique+ # per request, so unmasking maps back to the correct+ # original value. Format: <PHONE_NUMBER_1>, <PHONE_NUMBER_2>+ # This is LLM-friendly and degrades gracefully if the+ # LLM doesn't echo the token verbatim.+ seq = len(pii_tokens) + 1+ if replacement.endswith(">"):+ replacement = f"{replacement[:-1]}_{seq}>"+ else:+ replacement = f"{replacement}_{seq}"pii_tokens[replacement] = new_text[start:end@@ -521,12 +525,13 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):masked_entity_count[entity_type] = (masked_entity_count.get(entity_type, 0) + 1)- # When output_parse_pii is True, new_text contains UUID-suffixed- # tokens that match the keys in pii_tokens. Returning- # redacted_text["text"] (Presidio's original output) would send- # un-suffixed tokens to the LLM, making unmasking impossible.+ # When output_parse_pii is True, new_text contains sequentially+ # numbered tokens (e.g. <PHONE_NUMBER_1>) that match the keys+ # in pii_tokens. Returning redacted_text["text"] (Presidio's+ # original output) would send un-numbered tokens to the LLM,+ # making unmasking impossible.# When output_parse_pii is False, new_text == redacted_text["text"]- # because no UUID suffix is appended.+ # because no suffix is appended.return new_textelse:raise Exception("Invalid anonymizer response: received None")diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_presidio.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_presidio.pyindex 57f55fadb22..6b3fdf2a81f 100644--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_presidio.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_presidio.py@@ -1640,15 +1640,14 @@ async def test_pii_tokens_stored_in_metadata_not_top_level(presidio_guardrail):async def mock_check_pii(text, output_parse_pii, presidio_config, request_data):# Simulate PII masking with token storage (mimics real anonymize_text behavior)- import uuid-if request_data is not None and output_parse_pii:if "metadata" not in request_data:request_data["metadata"] = {}if "pii_tokens" not in request_data["metadata"]:request_data["metadata"]["pii_tokens"] = {}pii_tokens = request_data["metadata"]["pii_tokens"]- token = f"<PERSON>_{str(uuid.uuid4())[:12]}"+ seq = len(pii_tokens) + 1+ token = f"<PERSON_{seq}>"pii_tokens[token] = "John"text = text.replace("John", token)return text@@ -1685,7 +1684,7 @@ async def test_pii_tokens_in_metadata_used_for_unmasking():output_parse_pii=True,)- token_key = "<PERSON>_abc123def456"+ token_key = "<PERSON_1>"request_data = {"model": "claude-haiku-4-5-20251001","metadata": {"pii_tokens": {token_key: "John"}},@@ -1755,7 +1754,7 @@ async def test_metadata_none_does_not_crash():output_parse_pii=True,)- token_key = "<PERSON>_abc123def456"+ token_key = "<PERSON_1>"# metadata explicitly None — must not crashrequest_data = {"model": "gpt-3.5-turbo",@@ -1786,3 +1785,61 @@ async def test_metadata_none_does_not_crash():assert (response.choices[0].message.content == f"Hello {token_key}, how can I help you?")+++# ---------------------------------------------------------------------------+# Tests for sequential-numbered token unmasking in _unmask_pii_text+# ---------------------------------------------------------------------------+++def test_unmask_exact_match_with_sequential_tokens():+ """+ Normal unmasking: LLM echoes numbered tokens verbatim → original PII restored.+ """+ from litellm.proxy.guardrails.guardrail_hooks.presidio import (+ _OPTIONAL_PresidioPIIMasking,+ )++ pii_tokens = {+ "<PERSON_1>": "John Smith",+ "<PHONE_NUMBER_1>": "555-123-4567",+ }+ text = "Hello <PERSON_1>, your number is <PHONE_NUMBER_1>."+ result = _OPTIONAL_PresidioPIIMasking._unmask_pii_text(text, pii_tokens)+ assert result == "Hello John Smith, your number is 555-123-4567."+++def test_unmask_multiple_same_entity_type():+ """+ Two phone numbers get distinct numbered tokens and unmask correctly.+ """+ from litellm.proxy.guardrails.guardrail_hooks.presidio import (+ _OPTIONAL_PresidioPIIMasking,+ )++ pii_tokens = {+ "<PHONE_NUMBER_1>": "555-111-0000",+ "<PHONE_NUMBER_2>": "555-222-0000",+ }+ text = "Call <PHONE_NUMBER_1> or <PHONE_NUMBER_2>."+ result = _OPTIONAL_PresidioPIIMasking._unmask_pii_text(text, pii_tokens)+ assert result == "Call 555-111-0000 or 555-222-0000."+++def test_unmask_graceful_degradation():+ """+ If the LLM doesn't echo the token back, the numbered label stays+ in the output — clean and readable, not garbage hex.+ """+ from litellm.proxy.guardrails.guardrail_hooks.presidio import (+ _OPTIONAL_PresidioPIIMasking,+ )++ pii_tokens = {+ "<PERSON_1>": "John",+ }+ # LLM paraphrased instead of echoing the token+ text = "I see you provided a name."+ result = _OPTIONAL_PresidioPIIMasking._unmask_pii_text(text, pii_tokens)+ # No change — no garbage, just clean text+ assert result == text