Redact emails, phone numbers and card numbers before text reaches a model
Why it matters Guardrails in front of LLM APIs and agent logs redact PII like this to meet privacy rules such as India's DPDP Act.
Before user text is logged or sent to an outside model, a guardrail masks personal data. Card numbers need a checksum so random long numbers such as order IDs are not masked.
Write redact_pii(text). Apply these in order and return (redacted text, counts dict with keys "EMAIL", "PHONE", "CARD"):
1. EMAIL: pattern [A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,} becomes "[EMAIL]".
2. CARD: a run of 13 to 19 digits where single spaces or hyphens may separate digits, not touching other digits on either side. Replace with "[CARD]" only if the digits pass the Luhn check; otherwise leave it.
3. PHONE: an optional "+91" followed by an optional space or hyphen, then 10 digits starting with 6, 7, 8 or 9, not touching other digits. Becomes "[PHONE]".
Luhn: from the rightmost digit, double every second digit, subtract 9 from any result above 9, sum all digits; valid if the sum is divisible by 10.
def redact_pii(text)Example
redact_pii("mail a.b@x.io or call +91 9876543210") gives ('mail [EMAIL] or call [PHONE]', {'EMAIL': 1, 'PHONE': 1, 'CARD': 0}).
Understand the idea
A PII guardrail is a filter that masks personal data before text is stored or sent to another service. Regular expressions find the candidates; extra checks cut false alarms. Card numbers carry a built-in checksum, the Luhn rule, so we can tell a real card from an order ID.
Luhn by hand on 4111 1111 1111 1111: from the right, every second digit is doubled. The eight doubled digits are seven 1s (each becomes 2) and the leading 4 (becomes 8): 7 * 2 + 8 = 22. The eight undoubled 1s add 8. Total 30, divisible by 10, so it is valid.
Rules: email regex then [EMAIL]; digit run 13 to 19 with Luhn then [CARD]; +91 optional plus 10 digits starting 6 to 9 then [PHONE]; lookarounds stop partial matches.
Production LLM gateways run filters like this on prompts, tool outputs and logs.