Skip to main content

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.

  1. 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-mask as the Guardrail Name, pick Presidio PII as the Guardrail Provider, keep Mode at pre_call, fill presidio_analyzer_api_base and presidio_anonymizer_api_base if they are not set as environment variables, and click Next. On Configure PII Protection tick PERSON, PHONE_NUMBER and EMAIL_ADDRESS with the action MASK, tick CREDIT_CARD and 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-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

    Expected result: a 200 with the stored guardrail and a new row on the Guardrails page. With default_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.

  2. 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 400 with Blocked entity detected: CREDIT_CARD by Guardrail: pii-mask. This entity is not allowed to be used in this request.

  3. 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​

FieldDefaultWhat it does
pii_entities_configevery entity Presidio finds is maskedMaps 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_scopebothDecides 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_piifalseOn 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_languageenThe 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_thresholdsnoneA minimum confidence per entity type. Detections below it are ignored.
presidio_entities_deny_listnoneEntity types to drop from the results, for false positives such as US_DRIVER_LICENSE on code.
presidio_ad_hoc_recognizersnoneA JSON file of extra recognizers, for example an employee id pattern.
presidio_analyze_chunk_size_bytes500000Longer texts are split into chunks of at most this size for each analyze call.
presidio_analyzer_api_base, presidio_anonymizer_api_basethe environment variablesThe 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.
timeoutnoneSeconds 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​

StatusWhereMeaningFix
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_guardrailThe 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 UINeither 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 guardrailsCreate, update, deleteThe key is not a proxy admin.Use an admin key.
404 Guardrail 'pii-mask' not foundPOST /guardrails/apply_guardrailThe 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 requestThe 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 requestPresidio 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 maskedAny requestPresidio 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​

LevelLineWhat it meansAction
WARNINGPresidio analyzer <reason>, returning empty listPresidio gave a bad answer and nothing protective is configured, so the text went through unmasked.Action needed. Check the Presidio services.
WARNINGFailed 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.
DEBUGPresidio analyze: text exceeds <n> bytes, analyzing in <n> overlapping chunksA long text was split, see presidio_analyze_chunk_size_bytes.Normal.
DEBUGMaking 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.