Inferensys

Prompt

Output PII Leakage Detection Prompt for Model Responses

A practical prompt playbook for scanning model-generated text for PII, secrets, and sensitive data before it reaches end users, with a structured alert for human review.
Data scientist building training data pipeline on laptop, data preprocessing visible, technical workspace.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job-to-be-done, the ideal user, and the operational boundaries for deploying an output PII leakage detection prompt as a post-generation guardrail.

This prompt is designed for AI safety and privacy engineers who need to inspect model-generated outputs for personally identifiable information (PII), secrets, or other sensitive data that may have been memorized from training data or hallucinated during generation. It acts as a post-generation guardrail, producing a structured alert that can be routed to a human review queue before the output is returned to the user. Use this when you cannot guarantee that your model has never been exposed to sensitive data, or when you operate in a regulated environment where output inspection is a compliance requirement. This is not a pre-processing redaction tool; it inspects what the model already produced.

The ideal user is an engineer integrating this prompt into a production AI pipeline, specifically within a streaming response handler or a post-inference validation layer. The required context includes the raw model output string, a defined risk level that controls detection sensitivity, and a target output schema for the alert. You should not use this prompt as a real-time user-facing filter because it adds latency and requires a human-in-the-loop decision step. It is also inappropriate for inspecting outputs that are already guaranteed to be PII-free by a pre-processing redaction layer, as it would create redundant processing and false positives. Instead, deploy it as a safety net for high-risk use cases like customer-facing chatbots, clinical note summarization, or code generation where secrets might leak.

Before implementing, define your human review queue and service-level objectives (SLOs) for alert response. A common failure mode is alert fatigue, where the prompt flags too many low-risk entities and reviewers start ignoring alerts. Mitigate this by tuning the [RISK_LEVEL] parameter and by combining the prompt with a regex-based pre-filter for high-confidence patterns like credit card numbers. The next step is to wire this prompt into your application harness, ensuring that any output flagged with a block: true result is never returned to the user until a human clears it.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use this to decide if the Output PII Leakage Detection Prompt is the right tool for your production pipeline.

01

Good Fit: Streaming Response Inspection

Use when: You need to inspect model outputs in real-time before they reach the user. Guardrail: Integrate the prompt into a streaming middleware that chunks the response and runs detection on each chunk, buffering output until the scan is clean.

02

Good Fit: Human Review Queue Triage

Use when: You need to flag potentially leaking responses for a human moderator instead of blocking them outright. Guardrail: Configure the output schema to include a review_priority field (LOW/MEDIUM/HIGH) based on PII type and confidence, so your queue system can sort effectively.

03

Bad Fit: Source-of-Truth PII Database

Avoid when: You need to verify if a detected PII entity actually belongs to a real user in your system. Guardrail: This prompt detects patterns, not identity. Always pair it with a deterministic lookup against your user database before taking action on a detected entity.

04

Bad Fit: Pre-Inference Prevention

Avoid when: Your primary goal is to stop PII from entering the model in the first place. Guardrail: This is a post-hoc detection tool. Use the sibling "PII Detection Prompt Template for Pre-LLM Redaction" for input-side filtering, and keep this prompt as a defense-in-depth safety net.

05

Required Inputs: Structured Output Schema

Risk: Without a strict output schema, the model may return verbose explanations instead of machine-readable alerts. Guardrail: Always provide a JSON schema requiring pii_detected (boolean), findings (array of type, value, offset), and confidence (float). Reject any non-conforming response.

06

Operational Risk: High Latency on Long Outputs

Risk: Scanning a very long generated response can add unacceptable latency to a real-time chat application. Guardrail: Implement a sliding window or chunking strategy. If the output exceeds a token threshold, scan it asynchronously, log the result, and trigger a retroactive alert or deletion if PII is found post-delivery.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A production-ready prompt template for scanning model outputs for PII, secrets, and sensitive data, returning structured alerts for human review.

This prompt template is designed to be integrated into a post-processing step within your inference pipeline. Its sole job is to act as a safety scanner, analyzing a model's generated text for any personally identifiable information (PII), secrets, or other sensitive data that may have been memorized or hallucinated. It does not modify or redact the original text; it only produces a structured, machine-readable alert if a finding is detected. This separation of concerns—generation vs. detection—is critical for maintaining an auditable log and ensuring that redaction logic doesn't interfere with the primary task's output quality.

text
Analyze the following model-generated text for any personally identifiable information (PII), secrets, or sensitive data. Your task is to produce a structured alert if any such data is detected. Do not modify the original text. Do not redact. Only report findings.

### PII Categories to Scan For:
[DETECTION_CATEGORIES]

### Sensitivity Threshold:
[SENSITIVITY_THRESHOLD]

### Model Output to Scan:

[MODEL_OUTPUT_TEXT]

code

### Output Format:
Return a single JSON object with the following schema. If no PII is detected, return an empty `findings` array and set `alert_triggered` to false.

```json
{
  "alert_triggered": boolean,
  "findings": [
    {
      "category": string,
      "type": string,
      "value_fragment": string,
      "char_offset_start": integer,
      "char_offset_end": integer,
      "confidence": float,
      "recommended_action": string
    }
  ],
  "summary": string
}

To adapt this template, you must define the [DETECTION_CATEGORIES] and [SENSITIVITY_THRESHOLD] placeholders based on your specific compliance requirements. For example, [DETECTION_CATEGORIES] could be a comma-separated list like "email addresses, phone numbers, social security numbers, API keys, credit card numbers". The [SENSITIVITY_THRESHOLD] is a natural language instruction that calibrates the scanner's aggressiveness, such as "Flag only high-confidence, well-formed PII. Ignore common dictionary words that look like names." or "Flag any potential PII, even if fragmented or low confidence.". The [MODEL_OUTPUT_TEXT] placeholder should be populated with the exact string from your upstream model's completion. The output JSON schema is the contract your application code must parse to decide whether to escalate for human review, log an incident, or trigger a redaction workflow.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the PII leakage detection prompt. Each variable must be validated before assembly to prevent the detection prompt itself from becoming a leakage vector.

PlaceholderPurposeExampleValidation Notes

[MODEL_OUTPUT]

The raw text generated by the model that must be scanned for PII leakage.

Here is your summary, John. Your account 4111-1111-1111-1111 was charged.

Required. Must be a non-empty string. Truncate to 32k characters if longer to stay within context limits.

[PII_CATEGORIES]

A JSON array of PII entity types to scan for, aligned with your data classification policy.

["PERSON_NAME", "CREDIT_CARD", "EMAIL_ADDRESS", "PHONE_NUMBER", "SSN"]

Required. Must be a valid JSON array of strings. Reject if empty. Use an allowlist of known category labels.

[CONTEXT_WINDOW_PREFIX]

Optional preceding user prompt or retrieved context to help disambiguate whether an entity is a real PII leak or a benign reference.

"User asked: What is my account status?"

Optional. If provided, must be a string under 2k characters. Null allowed. Sanitize for PII before passing.

[CONFIDENCE_THRESHOLD]

Minimum confidence score (0.0 to 1.0) for a detected entity to be included in the alert.

0.85

Required. Must be a float between 0.0 and 1.0. Default to 0.85 if not specified. Lower values increase false positives.

[OUTPUT_SCHEMA]

The exact JSON schema the detection prompt must conform to in its response.

{"type": "object", "properties": {"leaks": {"type": "array"}}, "required": ["leaks"]}

Required. Must be a valid JSON Schema object. Validate with a schema validator before prompt assembly. Reject if missing required fields.

[ALLOWLIST_TERMS]

A JSON array of strings that should never be flagged as PII, such as test account numbers or demo data.

Optional. Must be a valid JSON array of strings. Null allowed. Each term must be an exact string match candidate.

[SESSION_ID]

An opaque identifier for the current inference session, used for audit logging and trace correlation.

"sess_9a7b3f2c1d"

Required. Must be a non-empty string. Must not contain PII itself. Use a UUID or similar opaque token.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the PII leakage detection prompt into a production inference pipeline with validation, streaming support, and human review gating.

Wire this prompt as a post-processing step in your inference pipeline, positioned after the primary model generates its response but before that response is returned to the user. The detection prompt receives the raw model output as its [MODEL_OUTPUT] input and returns a structured JSON object containing an alert_triggered boolean and a list of detected entities. For standard request-response flows, call the detection prompt synchronously after the primary inference completes. For streaming responses, buffer the full output before scanning, or implement a sliding window scan that processes chunks as they arrive and aggregates findings—this is critical because PII can span chunk boundaries in token-by-token streaming.

The alert_triggered boolean must gate the response path. When alert_triggered is true, do not return the original model output to the user. Instead, queue both the original output and the scan result JSON to a human review queue—this should be a durable, asynchronous work queue (SQS, Pub/Sub, Redis streams) that your operations team monitors. Return a safe fallback message to the user such as: "I wasn't able to generate a safe response. Our team has been notified and will review this shortly." When alert_triggered is false, return the original output normally. Log every scan result, including negative scans, with the inference trace ID, timestamp, model version, and scan outcome for full auditability. These logs are essential for compliance reporting and for debugging false negatives later.

Use a strict JSON validator on the detection prompt's response before trusting the alert_triggered field. The expected schema is: {"alert_triggered": boolean, "detected_entities": [{"type": string, "value": string, "confidence": float}]}. If JSON parsing fails, the model returns unexpected keys, or the schema is violated, treat this as a potential detection failure and escalate the original output to the review queue with a scan_error flag. Never default to alert_triggered: false on parse failure—a broken scanner is a silent failure mode that can leak PII into production. Implement a circuit breaker that tracks scan failure rate and halts responses if the failure rate exceeds a threshold (e.g., 5% over a rolling window).

This prompt is not a replacement for deterministic regex-based secret scanning. Run both in parallel and union the results for defense in depth. Your regex scanner should cover known patterns (AWS keys, credit card numbers, SSNs) with high precision, while the LLM-based scanner catches contextual PII that regex misses (names in prose, addresses in narratives, phone numbers in unconventional formats). If either scanner triggers, escalate. For model selection, prefer fast, cost-efficient models for this scanning task—a smaller model like Claude Haiku or GPT-4o-mini is usually sufficient and keeps scanning latency low. Set a timeout on the scan call (e.g., 2 seconds); if it expires, treat it as a scan failure and escalate. Finally, version your detection prompt alongside your primary prompt in your prompt registry so you can trace which scanner version produced which result during incident reviews.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structured JSON alert that the PII Leakage Detection Prompt must return. Use this contract to build a post-processing validator in your application harness before routing to a human review queue.

Field or ElementType or FormatRequiredValidation Rule

verdict

string enum: ["CLEAN", "ALERT"]

Must be exactly "CLEAN" or "ALERT". If any finding exists, verdict must be "ALERT".

findings

array of objects

Must be a JSON array. If verdict is "CLEAN", array must be empty. If "ALERT", array must contain at least one object.

findings[].type

string enum: ["PII", "SECRET", "CREDENTIAL", "PHI", "PCI", "CUSTOM"]

Must match one of the allowed enum values. Use "CUSTOM" only if a custom category is provided in [REDACTION_CATEGORIES].

findings[].value

string

The exact substring detected in the output. Must be non-empty. The validator should confirm this substring exists in the raw model response.

findings[].confidence

number

Float between 0.0 and 1.0. Values below [CONFIDENCE_THRESHOLD] should be filtered out by the application harness before human review.

findings[].evidence

string

A brief, non-empty justification for the classification. Must not itself contain the raw PII value if it is a high-risk type like SECRET or CREDENTIAL.

findings[].span

object with start and end integers

Character offsets of the finding in the original output string. If present, start must be less than end, and both must be within the output length.

remediation

string

A concise, actionable suggestion for the human reviewer. Must be non-empty. If verdict is "CLEAN", this should state "No action required."

PRACTICAL GUARDRAILS

Common Failure Modes

Output PII leakage detection fails in predictable ways. These are the most common failure modes when scanning model responses for memorized or hallucinated PII, and how to guard against them before they reach a user or log.

01

False Negatives on Hallucinated PII

What to watch: The model generates realistic-looking but fake PII (e.g., a synthetic SSN or email) that matches no real person. The detection prompt misses it because it looks for known patterns but the hallucinated data is novel. Guardrail: Add a secondary check that flags any output matching PII structural patterns (not just known entities) and routes it for human review, even if confidence is low.

02

Memorized Training Data Leakage

What to watch: The model regurgitates verbatim PII from its training data (names, addresses, phone numbers). Standard regex-based detection fails because the output is fluent prose, not structured fields. Guardrail: Use an LLM-based detection prompt with few-shot examples of memorized text leakage, and compare output n-grams against a canary dataset if available.

03

PII Fragmented Across Tokens

What to watch: Sensitive data is split across multiple tokens or sentences (e.g., 'John' in one paragraph, 'Smith' in another, '555-1234' in a third). A single-pass scan misses the composite identity. Guardrail: Implement a sliding window or full-response context scan that correlates entities across the entire output, not just within sentence boundaries.

04

Over-Redaction Breaking Task Utility

What to watch: The detection prompt is too aggressive and flags benign content as PII (e.g., common names, generic business phone numbers, placeholder values). This floods the review queue and blocks legitimate outputs. Guardrail: Calibrate detection thresholds with a precision/recall trade-off analysis on your domain's golden dataset. Allow a safelist of known non-sensitive entities.

05

Streaming Response Inspection Gaps

What to watch: PII appears in an early streaming chunk but the detection prompt only runs on the complete response. The leaked data is already displayed to the user or logged before inspection completes. Guardrail: Buffer streaming chunks and run incremental detection on partial responses. If PII is suspected mid-stream, halt generation and escalate before the full output is exposed.

06

Adversarial Obfuscation in Output

What to watch: A malicious prompt causes the model to output PII encoded in base64, leetspeak, ROT13, or split across code comments. The detection prompt only looks for plaintext patterns. Guardrail: Pre-process the output with a decoding/detection layer that normalizes common obfuscation techniques before the PII scan runs. Include obfuscated examples in your few-shot detection prompt.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Output PII Leakage Detection Prompt before deploying it to a production review queue. Each criterion targets a specific failure mode observed in PII scanning of model-generated text.

CriterionPass StandardFailure SignalTest Method

PII Recall

All seeded PII entities in the test output are detected and flagged in the structured alert

A known email, phone, or SSN in the model output is missing from the detection results

Run against a golden dataset of 50 model-generated texts with known PII inserted; require 100% recall

False Positive Rate

No non-PII text is flagged as PII in a clean validation set

A UUID, version hash, or mathematical constant is incorrectly flagged as a secret or identifier

Run against 50 clean model outputs with no real PII; require zero false positives

Entity Type Classification

Each detected entity is assigned the correct type from the [PII_CATEGORIES] schema

An email address is classified as a phone number or a name is classified as an address

Validate output against expected entity types in the golden dataset; require >99% type accuracy

Offset Accuracy

Character offsets for each detected entity match the actual position in the output text

Offsets point to the wrong substring, causing downstream redaction to mask incorrect text

Assert that extracting the substring at reported offsets matches the detected entity value exactly

Confidence Score Calibration

High-confidence detections (>0.9) are correct; low-confidence detections (<0.5) are genuinely ambiguous

A clearly fake hallucinated SSN receives a 0.99 confidence score

Bin detections by confidence and measure precision per bin; high-confidence bin must have >99% precision

Streaming Chunk Handling

PII spanning a chunk boundary is detected as a single entity, not fragmented

An email split across two streaming chunks is reported as two separate partial detections or missed entirely

Simulate streaming by splitting test outputs at random byte offsets; verify entity completeness

Hallucinated PII Flagging

Outputs containing hallucinated PII are flagged with a hallucination_risk: true field

A model-generated fake name and address is treated as benign and not escalated

Provide outputs with known hallucinated PII; assert the alert schema includes the hallucination risk flag

Review Queue Schema Compliance

Output strictly matches the [ALERT_SCHEMA] with all required fields present and correctly typed

The detected_entities array is missing the confidence field or timestamp is not ISO 8601

Validate output against the JSON Schema definition; reject any non-conforming response

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single model call and minimal post-processing. Replace the [OUTPUT_SCHEMA] placeholder with a simple JSON structure containing pii_detected (boolean), findings (array of strings), and confidence (low/medium/high). Run against a small set of hand-crafted test outputs containing known PII.

code
[OUTPUT_SCHEMA]: {
  "pii_detected": boolean,
  "findings": [{"type": "string", "value": "string", "confidence": "low|medium|high"}],
  "summary": "string"
}

Watch for

  • Missing schema checks leading to unparseable JSON
  • Overly broad instructions that flag common nouns as names
  • No streaming support; entire response must complete before inspection
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.