Sub topic 2
Detecting and Redacting Personal Data
Assume you know basic Python, regular expressions, JSON, and how to call an LLM. This chapter focuses on checks around the model call, not on training the model.
Detecting and Redacting Personal Data
Personally identifiable information (PII) is data that can identify a person, such as an email address, phone number, or Social Security number. An input guardrail checks for PII before sending text to the model. Redaction replaces detected values with safe placeholders.
import re
EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
US_SSN = re.compile(r"\b\d{3}-\d{2}-\d{4}\b")
def redact_pii(text: str) -> str:
text = EMAIL.sub("[EMAIL]", text)
return US_SSN.sub("[SSN]", text)
print(redact_pii("Mail [email protected], SSN 123-45-6789"))
# Mail [EMAIL], SSN [SSN]This approach is fast and predictable, but patterns miss unusual formats and can match harmless text. Record whether redaction occurred without logging the original sensitive value.
Reducing the Impact of Prompt Injection
Prompt injection is untrusted text that tries to change the model's instructions, such as “ignore previous instructions.” Length limits, content checks, and separating system instructions from user data reduce risk. They cannot prove that text is safe. Keep sensitive actions behind application-level authorization, even if the model requests them.
Validating Structured Output
When an LLM must return JSON, parse it and validate its schema. Check required fields, types, and allowed values. If validation fails, retry with a bounded attempt count. Never execute arbitrary model output as code.
Classifier and Moderation Models
A classifier is a model trained to assign labels, such as spam, violence, or self-harm risk. It can detect meaning that regular expressions miss, but it adds latency and may produce false positives or false negatives. Use thresholds appropriate to the consequence of an error.
Using an LLM to Judge Another LLM's Output
An LLM judge can compare an answer with source text or a policy and return a pass/fail decision. It handles nuanced language but shares many weaknesses with the judged model. Require structured judge output, test it against labeled examples, and keep high-impact decisions under deterministic or human review.
Exercise
Which check should you use first for a known Social Security number pattern?
Show answer
Use a deterministic regular-expression check before the model call, then redact or block the matched value.