PII masking with Presidio
The presidio guardrail finds personal data in the text of a request or a response and either replaces it with a placeholder such as <EMAIL_ADDRESS> or refuses the request. It uses two Presidio services that you run yourself, an analyzer that finds the entities and an anonymizer that masks them, so the text never leaves your network for the detection and the model provider only ever sees the masked version. The guardrail is part of the free gateway. Use it when people type customer data into assistants, when logs or tickets flow through a model, or when a regulation says a class of data may not leave your systems.
A real-world scenario
A bank's operations team uses an assistant to summarize customer calls. The transcripts carry names, phone numbers and sometimes a full card number read out by the customer. Compliance allows names and phone numbers to be masked, but a card number must never be sent at all. The platform team configures pii-mask so that PERSON, PHONE_NUMBER and EMAIL_ADDRESS are masked and CREDIT_CARD is blocked, and turns on output_parse_pii with presidio_filter_scope: input so the summary shown to the operator has the real names back in it. The scope matters: with the default scope both, the reply is masked again after the names are restored. A transcript with a card number is refused before it leaves the gateway, and the operator sees a message naming the reason.
Set it up
You need the analyzer and anonymizer reachable from the gateway, for example at http://presidio-analyzer:3000 and http://presidio-anonymizer:3000. The gateway reads their addresses from presidio_analyzer_api_base and presidio_anonymizer_api_base on the guardrail, or from the PRESIDIO_ANALYZER_API_BASE and PRESIDIO_ANONYMIZER_API_BASE environment variables when the guardrail does not set them.
-
Create the guardrail. In the Admin UI open Guardrails under AI Gateway, click Add New Guardrail, then Add Provider Guardrail. On Basic Info enter
pii-maskas the Guardrail Name, pick Presidio PII as the Guardrail Provider, keep Mode atpre_call, fillpresidio_analyzer_api_baseandpresidio_anonymizer_api_baseif they are not set as environment variables, and click Next. On Configure PII Protection tickPERSON,PHONE_NUMBERandEMAIL_ADDRESSwith the action MASK, tickCREDIT_CARDand set its action to BLOCK, then click Create Guardrail. Over the API:curl -X POST http://localhost:4000/guardrails \-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \-d '{"guardrail": {"guardrail_name": "pii-mask","spanway_params": {"guardrail": "presidio","mode": "pre_call","default_on": true,"presidio_analyzer_api_base": "http://presidio-analyzer:3000","presidio_anonymizer_api_base": "http://presidio-anonymizer:3000","pii_entities_config": {"PERSON": "MASK", "PHONE_NUMBER": "MASK", "EMAIL_ADDRESS": "MASK", "CREDIT_CARD": "BLOCK"}},"guardrail_info": {"description": "Masks personal data before the model sees it"}}}'The same guardrail in
config.yaml:guardrails:- guardrail_name: pii-maskspanway_params:guardrail: presidiomode: pre_calldefault_on: truepresidio_analyzer_api_base: http://presidio-analyzer:3000presidio_anonymizer_api_base: http://presidio-anonymizer:3000pii_entities_config:PERSON: MASKPHONE_NUMBER: MASKEMAIL_ADDRESS: MASKCREDIT_CARD: BLOCKExpected result: a
200with the stored guardrail and a new row on the Guardrails page. Withdefault_on: true(Always On in the form) it runs on every request from now on. Leave it off and attach the guardrail to a team or key instead, see guardrails. -
Test it on a sentence. Open the Test Playground tab, select
pii-mask, type a sentence with a phone number and an email address under Input Text and click Test 1 guardrail. Over the API:curl -X POST http://localhost:4000/guardrails/apply_guardrail \-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \-d '{"guardrail_name": "pii-mask", "text": "Call me at 415-555-0100 or email jane.doe@example.com", "language": "en"}'Expected result:
{"response_text": "Call me at <PHONE_NUMBER> or email <EMAIL_ADDRESS>"}Repeat with a card number in the text. Expected result: a
400withBlocked entity detected: CREDIT_CARD by Guardrail: pii-mask. This entity is not allowed to be used in this request. -
Send a real request and read the log. Open Logs, click the request and read the Guardrails & Policy Compliance section. It lists
pii-mask, whether it passed, masked or blocked, the entity types it found with their counts, and the milliseconds it added. The values themselves are not recorded.
Settings
| Field | Default | What it does |
|---|---|---|
pii_entities_config | every entity Presidio finds is masked | Maps an entity type to MASK (replace it with a placeholder such as <EMAIL_ADDRESS>) or BLOCK (refuse the request with a 400). Entity types not listed are left alone once the map is set. In the Admin UI this is the entity list on Configure PII Protection. |
presidio_filter_scope | both | Decides which direction is checked. input checks what the user sends, output checks what the model returns, both checks each. Use input together with output_parse_pii, otherwise the restored values are masked again on the way out. |
output_parse_pii | false | On puts the original values back into the reply for the caller after the model answered on masked text, which helps when people must read real names in a summary. The model and the logs still only see the placeholders. Off keeps the placeholders in the reply. Works only with presidio_filter_scope: input. |
presidio_language | en | The language Presidio analyzes, for example de or es. A wrong language misses names. A request can override it with language on apply guardrail, or with metadata.guardrail_config.language on a model request. |
presidio_score_thresholds | none | A minimum confidence per entity type. Detections below it are ignored. |
presidio_entities_deny_list | none | Entity types to drop from the results, for false positives such as US_DRIVER_LICENSE on code. |
presidio_ad_hoc_recognizers | none | A JSON file of extra recognizers, for example an employee id pattern. |
presidio_analyze_chunk_size_bytes | 500000 | Longer texts are split into chunks of at most this size for each analyze call. |
presidio_analyzer_api_base, presidio_anonymizer_api_base | the environment variables | The two service addresses. A value without a scheme gets http:// in front, and the address is not checked when you save, so a typo shows up as a refused request. |
timeout | none | Seconds to wait for each analyze call before the request fails. |
A request can narrow what is detected with metadata.guardrail_config, for example {"metadata": {"guardrail_config": {"language": "de", "entities": ["PERSON"]}}}. entities only applies when the guardrail has no pii_entities_config of its own, so a caller can never switch off an entity an admin set to BLOCK.
mode decides when it runs, as described in guardrails, and presidio_filter_scope decides which direction is checked. With the default scope both, a pre_call guardrail masks the prompt and also masks the reply.
Privacy
Masked values are replaced before the request is logged, so spend logs and logging integrations only see the placeholders. The gateway's own debug log names only the text length, the language and the entity types, never the text. With output_parse_pii the original values live only in memory for the duration of the request. Retention and data subject requests for spend logs are described on the compliance page.
Errors
| Status | Where | Meaning | Fix |
|---|---|---|---|
400 Blocked entity detected: CREDIT_CARD by Guardrail: pii-mask. This entity is not allowed to be used in this request. | Any model request, POST /guardrails/apply_guardrail | The text holds an entity whose action is BLOCK. The model was not called. | This is the intended answer. To mask instead, set the entity's action to MASK on the guardrail's Settings tab. |
400 Guardrail configuration error: Missing \PRESIDIO_ANALYZER_API_BASE` from environment(orANONYMIZER`) | POST /guardrails, or Failed to create guardrail in the Admin UI | Neither the guardrail nor the environment gives the analyzer or anonymizer address. Nothing was stored and no audit row was written. Entity names and address formats are not checked at this point. | Fill the two addresses or set the environment variables, and pick entity names from GET /guardrails/ui/add_guardrail_settings. |
403 Admin access required to manage guardrails | Create, update, delete | The key is not a proxy admin. | Use an admin key. |
404 Guardrail 'pii-mask' not found | POST /guardrails/apply_guardrail | The name does not match a guardrail. | Copy the name from the Guardrails page. |
422 Invalid guardrail configuration, update rejected: ... | Save Changes on the Settings tab, PUT and PATCH /guardrails/{guardrail_id} | The new parameters do not initialize. The stored guardrail keeps running unchanged. | Fix the field the message names. |
Request fails with Presidio PII analysis failed: <error type> | Any request | The gateway could not reach Presidio. The request always fails, whatever the entity settings. | Check the two addresses and the network path from the gateway. |
Request refused with Presidio analyzer returned invalid response; cannot verify PII when PII protection is configured: <reason> | Any request | Presidio answered with an error status or a body that is not JSON while pii_entities_config, output_parse_pii or output masking is set, so the guardrail fails closed. Without any of those the text goes through unmasked and a warning is logged. | Check the Presidio services and their logs. |
| A value was not masked | Any request | Presidio did not recognise it, or its confidence is below presidio_score_thresholds, or presidio_language does not match the text. | Lower the threshold, set the right language, or add a recognizer in presidio_ad_hoc_recognizers. |
Audit
Creating, changing and deleting the guardrail write audit rows on Spanway_GuardrailsTable with who made the change and the value before and after, with the Presidio addresses kept and any key redacted. See audit logs.
Logs
| Level | Line | What it means | Action |
|---|---|---|---|
| WARNING | Presidio analyzer <reason>, returning empty list | Presidio gave a bad answer and nothing protective is configured, so the text went through unmasked. | Action needed. Check the Presidio services. |
| WARNING | Failed to parse Presidio result item: <item> (error: <error>) | One detection in Presidio's answer had an unexpected shape and was skipped. | Check that the Presidio version matches. |
| DEBUG | Presidio analyze: text exceeds <n> bytes, analyzing in <n> overlapping chunks | A long text was split, see presidio_analyze_chunk_size_bytes. | Normal. |
| DEBUG | Making request to: <url> with <n> characters, language <code> and entities <list> | One analyze call. The text is never logged. | Normal. Shown only with detailed debug logging. |
Related
- Guardrails for modes, attaching guardrails to teams and keys, and the full error list.
- Guardrails quick start for a ten minute walkthrough that starts with this guardrail.
- Secret detection for credentials rather than personal data.
- Apply guardrail for the test call used in step 2 and the
languageandentitiesoverrides. - Guardrails page for the entity picker in the Admin UI.
- Compliance for retention and data subject requests.