Skip to content
AgenticAIWiki
  1. Learn
  2. Part 12
  3. 64. Guardrails in depth
  4. 64.10

Lesson 64.10 · 10 of 11 · 7 min read · Reviewed 24 Nov 2026

PII and secret detection and redaction

By the end, you can

  • Detect personal data and secrets in prompts, tool results and outputs.
  • Choose between masking, replacing and reversible tokens.

Personal data and secrets get into AI systems from every side: a user pastes a bank statement, a tool returns a customer record, a log line captures an API key from an error message. 65.2 used a regex to catch card numbers. This lesson builds that into a proper detection and redactionRedaction: Removing or masking sensitive data, such as PII or secrets, before it is stored, logged or sent. step.

Where to scan

Boundary Why
User input Stop data reaching a third-party model or a prompt log
Tool results Records often hold more fields than the task needs
Model output The model may repeat data it should not show (64.3)
Logs, traces, checkpoints They live longest and are read by the most people (63.4)

How to detect

No single method finds everything, so combine them:

  • Patterns with validation for structured data: card numbers (with the Luhn checksum to cut false hits), IBANs, phone numbers, national ID formats.
  • Named-entity recognition for names, addresses and organisations, which no regex can find reliably.
  • Secret scanners: known key prefixes, long high-entropy strings, and words such as password= or token: next to a value.
  • Allow-lists for things that look sensitive but are not: your support email, test card numbers in your docs.

Open-source tools package this up. Microsoft Presidio, for example, has an analyser that runs pattern and NER recognisers and returns typed spans with a score, and an anonymiser that replaces them. Secret scanners such as those built into code hosts work the same way for credentials.

How to redact

A worked example, with obviously fake test data:

In:  Hi, I'm Jane Testperson, card 4111 1111 1111 1111 (test card),
     email jane@example.com. Our key is sk-ant-sim-demo-0001 (simulated).
Out: Hi, I'm <PERSON_1>, card <CARD_1>, email <EMAIL_1>.
     Our key is <SECRET_1>.
Method Looks like Use when
Mask ****1111 Showing a person enough to recognise it
Typed placeholder <EMAIL_1> Sending text to a model; keeps meaning
Reversible token <EMAIL_1> plus a vault mapping The final output must contain the real value
Drop (removed) Logs, where the value is never needed

Typed, numbered placeholders matter. With a bare [REDACTED], the model cannot tell two people apart.

Reversible tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id. keep the mapping (<EMAIL_1> to the real address) in your code or a vault, never in the prompt. The model writes “We have sent the receipt to <EMAIL_1>”, and your code swaps the real value in only when the message is sent. The model never sees it, and logs keep the placeholder.

Secrets are different

A leaked email is a privacy problem. A leaked API key is an open door. For secrets:

  • Redact them everywhere, with no reversible option.
  • Treat any detection as an incident: rotate the key, then find how it got there.
  • Keep secrets out of prompts, tool descriptions and model-visible errors in the first place (65.5).

Common mistakes

  • Scanning user input but not tool results or logs.
  • Regex only, so names and addresses sail through.
  • Over-redaction: blanking every number breaks order ids and dates. Measure false hits as well as misses on a labelled sample.
  • Putting the reversible mapping in the context “so the model can use it”, which undoes the whole point.

Key points

  • Scan at every boundary: user input, tool results, model output and anything written to logs.
  • Combine detectors: patterns with checksums for structured data, named-entity models for names and addresses, entropy and known prefixes for secrets.
  • Redact with typed placeholders such as <EMAIL_1> so the model can still reason about the text.
  • Reversible tokens restore the real values only at the last step, in code the model cannot see.
Hands-on labRuns in the Playground

Redact PII and secrets with placeholders

Replace personal data and secrets with typed, numbered placeholders and restore only safe values at the end.

You will have: A redact() and restore() pair with a vault, run on a fake support message, showing what the model saw and what the customer got.

Steps

  1. Run the starter: the raw text, test card and simulated key all go to the model.
  2. Replace each detected value with a typed, numbered placeholder such as <EMAIL_2>.
  3. Use the Luhn check so the order number is not treated as a card.
  4. Keep a vault with emails in full and cards masked to the last 4 digits, never secrets; restore only when sending.
  5. Notice the name that regex cannot find, and note what you would add.

Done when

  • The model sees <EMAIL_1> and <EMAIL_2> as two different people.
  • The order number is unchanged, and the customer's message has the real email and a masked card (****1111).
  • The secret is never stored in the vault and is never restored.

Open in the Playground No API key needed.

Starter code (Python)
import re
# Redact personal data and secrets with typed, numbered placeholders, then restore at the last step.
# All data below is fake test data. The key is a simulated one.
TEXT = ("Hi, this is Jane Testperson. Please refund card 4111 1111 1111 1111 (test card) "
        "and send the receipt to jane@example.com, copy sam@example.com. "
        "Our integration key is sk-ant-sim-demo-0001. Order 1234 5678 9012 3456.")
DETECTORS = [
    ("SECRET", re.compile(r"\bsk-[A-Za-z0-9-]{12,}")),
    ("EMAIL", re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.]+\b")),
    ("CARD", re.compile(r"\b(?:\d[ -]?){12,18}\d\b")),
]

def luhn(number):
    d = [int(c) for c in number if c.isdigit()]
    total = 0
    for i, x in enumerate(reversed(d)):
        if i % 2:
            x = x * 2 - 9 if x * 2 > 9 else x * 2
        total += x
    return total % 10 == 0

def redact(text):
    # TODO: replace each detected value with <TYPE_n>, reusing the same placeholder for a repeated value
    # TODO: skip card-shaped numbers that fail the Luhn check; keep a vault {placeholder: value}:
    #       emails in full, cards masked to the last 4 digits, secrets never
    return text, {}

def restore(text, vault):
    # TODO: swap placeholders back in from the vault (secrets are never restored)
    return text

safe, vault = redact(TEXT)
print("to model:", safe)
Show a solution
import re
TEXT = ("Hi, this is Jane Testperson. Please refund card 4111 1111 1111 1111 (test card) "
        "and send the receipt to jane@example.com, copy sam@example.com. "
        "Our integration key is sk-ant-sim-demo-0001. Order 1234 5678 9012 3456.")
DETECTORS = [
    ("SECRET", re.compile(r"\bsk-[A-Za-z0-9-]{12,}")),
    ("EMAIL", re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.]+\b")),
    ("CARD", re.compile(r"\b(?:\d[ -]?){12,18}\d\b")),
]

def luhn(number):
    d = [int(c) for c in number if c.isdigit()]
    total = 0
    for i, x in enumerate(reversed(d)):
        if i % 2:
            x = x * 2 - 9 if x * 2 > 9 else x * 2
        total += x
    return total % 10 == 0

def redact(text):
    vault, seen, counts = {}, {}, {}
    for kind, rx in DETECTORS:
        def sub(m):
            v = m.group()
            if kind == "CARD" and not luhn(v):
                return v
            if v not in seen:
                counts[kind] = counts.get(kind, 0) + 1
                seen[v] = f"<{kind}_{counts[kind]}>"
                if kind == "CARD":
                    vault[seen[v]] = "****" + re.sub(r"\D", "", v)[-4:]   # people only need the last 4
                elif kind != "SECRET":
                    vault[seen[v]] = v
            return seen[v]
        text = rx.sub(sub, text)
    return text, vault

def restore(text, vault):
    for ph, v in vault.items():
        text = text.replace(ph, v)
    return text

safe, vault = redact(TEXT)
print("to model:", safe)
model_reply = "Done. The receipt for <CARD_1> went to <EMAIL_1>. Please rotate <SECRET_1>."
print("model wrote:", model_reply)
print("sent to customer:", restore(model_reply, vault))
print("secret in vault:", any(v.startswith("sk-") for v in vault.values()))
print("note: 'Jane Testperson' is still visible; names need an entity model such as Presidio's NER recogniser")
Quick checkSupport transcripts are summarised by a model. You replace every email address with [REDACTED], and the summaries now say 'the customer emailed [REDACTED] and [REDACTED]', losing who wrote to whom. What should you change?
How sure are you?
Pick an answer and how sure you are