This prompt acts as a secondary, model-graded security scanner for your prompt assembly pipeline. Its job is to inspect the fully assembled prompt string—including system instructions, retrieved context, tool schemas, and user input—to detect Personally Identifiable Information (PII), secrets, and other sensitive data before transmission to a model provider. Use this when you need a programmatic gate that catches patterns deterministic regex-based redaction at the application layer might miss, such as PII embedded in retrieved documents, malformed API keys that slipped through a linter, or email addresses inside code snippets that a static rule didn't flag. The ideal user is a security or privacy engineer integrating this check into a CI/CD pipeline, a pre-inference request hook, or an observability platform that logs prompt assembly traces.
Prompt
PII Leak Detection in Assembled Prompt

When to Use This Prompt
Deploy a semantic safety net that catches PII and secrets in assembled prompts before they leave your application boundary.
This is not a replacement for deterministic redaction. You must still strip known PII patterns at the application layer before assembly. This prompt is the safety net that catches what your regex missed. It is also not a general-purpose data classifier, a compliance audit tool, or a substitute for data loss prevention (DLP) infrastructure. Do not use it as the sole defense for regulated data under GDPR, HIPAA, or PCI-DSS. The model's detection is probabilistic and can miss obfuscated or novel PII formats. Always pair this with deterministic scanning, and route high-severity findings to a human review queue before blocking or redacting automatically. For production systems, log every scan result with the prompt's trace ID, the model's verdict, and the specific spans flagged so you can audit false negatives and refine your regex rules over time.
Before wiring this into your pipeline, define your severity thresholds and action map. A low-confidence phone number match in a public FAQ document might warrant a log entry; a high-confidence API key match in a customer support transcript should halt the request and trigger an alert. Start by running this prompt against a golden dataset of prompts containing known PII, benign structured data that looks like PII (e.g., fake credit card numbers in documentation), and edge cases like PII split across multiple context blocks. Measure false positive and false negative rates against your deterministic scanner. Use those results to decide whether this prompt gates requests, enriches logs, or feeds a human review queue. The next section provides the copy-ready template you can adapt and embed directly into your assembly harness.
Use Case Fit
Where PII leak detection in assembled prompts works and where it does not. Use these cards to decide if this preflight check fits your pipeline before investing in integration.
Good Fit: Pre-Model Sanitization
Use when: you assemble prompts from multiple sources (user input, retrieved documents, CRM data) and need to catch PII before it reaches a third-party model endpoint. Guardrail: run detection as a synchronous preflight gate; block or redact before the inference call leaves your boundary.
Good Fit: Audit Trail Generation
Use when: compliance requires a record of what data was detected and redacted before model processing. Guardrail: persist the redaction map with severity classification alongside the prompt trace; make it queryable for DPO and audit reviews.
Bad Fit: Unstructured Free-Text Only
Avoid when: your prompt is a single block of unstructured text with no variable boundaries. Regex-based PII scanners produce high false-positive rates on prose. Guardrail: use this prompt only when you can isolate structured fields or clearly delimited context blocks for scanning.
Bad Fit: Real-Time Streaming Pipelines
Avoid when: you need sub-millisecond latency and cannot afford a synchronous preflight check before every token is streamed. Guardrail: batch-scan assembled prompts asynchronously for monitoring; use a lightweight deny-list for known patterns at the edge instead.
Required Inputs
You must provide: the fully assembled prompt string, a configurable list of PII patterns to detect (email, phone, credit card, API key, SSN), and a severity classification policy. Guardrail: maintain the pattern list as code; version it alongside the prompt template to avoid drift.
Operational Risk: False Positives on Benign Data
Risk: structured data like UUIDs, base64-encoded images, or hex strings can trigger false PII matches, blocking legitimate requests. Guardrail: include an allow-list for known safe patterns and a human-review escalation path for borderline detections before blocking production traffic.
Copy-Ready Prompt Template
A reusable prompt template that scans assembled prompts for PII and sensitive data patterns, returning a structured JSON report with severity classification and redaction mapping.
This template instructs the model to act as a security auditor, scanning the fully assembled prompt for sensitive data patterns before transmission to the model. It covers email addresses, phone numbers, credit card numbers, API keys, social security numbers, and other regulated identifiers. The prompt is designed to be dropped into a preflight validation pipeline where it inspects the final prompt string that would otherwise be sent to a generative model.
textYou are a security auditor specialized in detecting sensitive data in text before it reaches external systems. Your task is to scan the provided assembled prompt for personally identifiable information (PII), secrets, and regulated data patterns. ## INPUT Analyze the following assembled prompt text: [ASSEMBLED_PROMPT] ## DETECTION RULES Scan for these categories with the specified patterns: 1. **EMAIL**: Patterns matching username@domain.tld 2. **PHONE**: US and international phone number formats including (XXX) XXX-XXXX, XXX-XXX-XXXX, +X-XXX-XXX-XXXX 3. **CREDIT_CARD**: 13-19 digit sequences that pass Luhn validation patterns, with or without separators 4. **SSN**: XXX-XX-XXXX pattern (US Social Security) 5. **API_KEY**: Patterns matching common API key formats (sk-, pk-, api-, key-, token prefixes, long base64 strings, hex strings > 32 chars) 6. **IP_ADDRESS**: IPv4 and IPv6 addresses 7. **DOB**: Date patterns in MM/DD/YYYY, DD-MM-YYYY, or written forms near age indicators 8. **ADDRESS**: Street address patterns with numbers, street names, city, state, ZIP 9. **PASSPORT**: Alphanumeric patterns matching passport number formats 10. **DRIVERS_LICENSE**: State-specific license number patterns ## CONSTRAINTS - Do NOT flag placeholder text like [USER_NAME], {{variable}}, or template tokens - Do NOT flag example/test data that is clearly synthetic (e.g., test@example.com, 555-0100) - Do NOT flag benign structured data like UUIDs, database IDs, or non-secret hex strings - If uncertain about a match, mark it as LOW severity with a note - Consider context: a 9-digit number in an error log is not necessarily an SSN ## OUTPUT_SCHEMA Return ONLY valid JSON with this structure: { "scan_result": { "findings": [ { "category": "EMAIL|PHONE|CREDIT_CARD|SSN|API_KEY|IP_ADDRESS|DOB|ADDRESS|PASSPORT|DRIVERS_LICENSE", "severity": "CRITICAL|HIGH|MEDIUM|LOW", "match": "the exact matched text", "position": {"start": 0, "end": 0}, "context_snippet": "surrounding text for verification", "recommended_action": "REDACT|MASK|REMOVE|REVIEW", "confidence": 0.0-1.0 } ], "summary": { "total_findings": 0, "critical_count": 0, "high_count": 0, "medium_count": 0, "low_count": 0, "requires_human_review": true|false }, "redaction_map": [ { "original": "matched text", "replacement": "[REDACTED_EMAIL]|[REDACTED_PHONE]|etc", "category": "EMAIL|PHONE|etc" } ] } } ## INSTRUCTIONS 1. Scan the entire [ASSEMBLED_PROMPT] systematically 2. For each finding, determine severity: CRITICAL for credentials/secrets, HIGH for direct PII, MEDIUM for potentially sensitive, LOW for ambiguous matches 3. Set requires_human_review to true if any CRITICAL or HIGH findings exist 4. Provide a redaction_map with safe replacements for every finding 5. If no findings exist, return the JSON with empty findings array and zero counts
To adapt this template, replace [ASSEMBLED_PROMPT] with the actual prompt string your system constructs before inference. The detection rules can be extended or narrowed based on your jurisdiction's data protection requirements. For production use, consider adding [EXCLUDED_PATTERNS] as an additional input to pass known-safe strings that should not trigger false positives, such as internal test identifiers or synthetic data markers used in your development environment. The confidence scoring enables downstream systems to apply different thresholds based on risk tolerance.
Prompt Variables
Inputs required by the PII Leak Detection prompt. Substitute these placeholders before assembly to ensure the scanner has the target prompt and the correct detection rules.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[ASSEMBLED_PROMPT] | The fully assembled prompt string to scan for PII before transmission to the model. | "System: You are a support agent. User email: jane.doe@company.com" | Must be a non-empty string. Validate length > 0. If null or empty, abort scan and return error. |
[DETECTION_CATEGORIES] | Array of PII types to scan for, controlling scope and false-positive tolerance. | ["EMAIL_ADDRESS", "PHONE_NUMBER", "CREDIT_CARD", "API_KEY"] | Must be a non-empty array of valid enum strings. Reject unknown categories. Validate against allowed category list. |
[ALLOWED_DOMAINS] | List of internal domains to exclude from email redaction to prevent flagging corporate addresses. | ["company.com", "subsidiary.net"] | Optional array of domain strings. If provided, emails matching these domains are classified as INTERNAL and severity is downgraded. Validate each entry as a valid domain pattern. |
[REDACTION_METHOD] | Specifies the output format for redacted values: MASK, HASH, or PLACEHOLDER. | "MASK" | Must be one of the allowed enum values. Default to MASK if not provided. Reject unknown methods. |
[SEVERITY_THRESHOLD] | Minimum severity level to include in the redaction map. Lower-severity findings are omitted. | "MEDIUM" | Must be one of LOW, MEDIUM, HIGH, CRITICAL. Validate against enum. If null, default to LOW (report all). |
[CONTEXT_WINDOW_CHARS] | Number of characters before and after a match to include in the evidence snippet. | 40 | Must be a positive integer between 10 and 200. Clamp or reject out-of-range values. Default to 40 if null. |
[BENIGN_PATTERN_EXCEPTIONS] | Array of regex patterns for known false-positive triggers in structured data like IDs or tokens. | ["^[A-Z]{2}-\d{6}$", "^tok_[a-z0-9]{24}$"] | Optional array of valid regex strings. Validate each entry compiles without error. Skip entries that fail compilation and log warning. |
Implementation Harness Notes
How to wire the PII leak detection prompt into a production application with validation, retries, logging, and human review.
The PII leak detection prompt is designed to run as a preflight guard in your prompt assembly pipeline—after all variables, context, and evidence are substituted into the final prompt string but before that string is transmitted to the inference model. This placement ensures that no sensitive data reaches the model provider's infrastructure. The harness should intercept the assembled prompt, invoke the detection prompt, parse the structured output, and either block the request, redact matched spans, or escalate for human review depending on severity classification and your organization's data handling policy.
For a production implementation, wrap the prompt call in a validation layer that enforces the output schema. The detection prompt returns a JSON object with a redaction_map array and a severity_classification field. Your harness must validate that every entry in the redaction map contains a span_start, span_end, match_type, and confidence field. If the model returns malformed JSON or missing required fields, retry once with a repair prompt that includes the raw output and schema constraints. Log every detection event—including the match type, severity, and whether the request was blocked, redacted, or allowed—to your observability platform with the prompt's trace ID attached. This audit trail is essential for security reviews and for tuning false positive thresholds over time.
Model choice matters here. Use a fast, cheaper model for this preflight check (such as GPT-4o-mini, Claude Haiku, or a fine-tuned small classifier) because the task is narrow and latency directly adds to your end-to-end request time. Avoid routing this check to the same large model that will handle the primary task, as that defeats the purpose of keeping PII out of the primary model's context. If your system processes high volumes, consider batching detection requests or implementing a regex pre-filter for high-precision patterns (credit card numbers, API key formats) before invoking the LLM-based detector. The LLM detector should handle ambiguous cases—like email-like strings in code comments or phone-number-like patterns in identifiers—that regex alone would misclassify.
For high-risk domains (healthcare, finance, legal), implement a human review queue for any detection with severity_classification: high and confidence below 0.90. The harness should serialize the flagged prompt segment, the detection output, and surrounding context into a review ticket. Do not send the full prompt to the reviewer if it contains the suspected PII—show only the matched span and enough context to make a judgment. After review, feed the decision (block, redact, allow) back into your detection eval dataset to improve future threshold tuning. For low-risk, high-confidence detections, automated redaction with a placeholder token like [REDACTED_EMAIL] or [REDACTED_CCN] is usually sufficient, but always verify that redaction didn't break the semantic coherence of the prompt before proceeding to inference.
Finally, test this harness with a dedicated eval suite before deployment. Your eval dataset should include prompts with known PII injected at various positions, benign prompts with PII-like patterns (e.g., user@example in documentation, 1234-5678-9012-3456 as a transaction ID), and edge cases with overlapping or malformed sensitive data. Measure false positive rate on benign structured data and false negative rate on obfuscated PII (e.g., john dot doe at gmail dot com). Run these evals as part of your CI/CD pipeline whenever the detection prompt or assembly logic changes. A silent PII leak into model inference is a data breach—treat this harness with the same rigor you'd apply to any security-critical code path.
Expected Output Contract
Defines the structured JSON output contract for the PII Leak Detection prompt. Use this schema to parse and validate the model's response before acting on redaction recommendations.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
status | string enum: pass | fail | error | Must be exactly one of the three allowed values. Fail if missing or invalid. | |
findings | array of objects | Must be a JSON array. Fail if null, missing, or not an array. Allow empty array only if status is pass. | |
findings[].type | string enum from [PII_TYPE_LIST] | Must match a value from the provided PII_TYPE_LIST exactly. Fail on unknown types. | |
findings[].value | string | Must be a non-empty string representing the detected PII. Fail if null or empty. | |
findings[].severity | string enum: high | medium | low | Must be one of the three allowed values. Fail if missing or invalid. | |
findings[].location | object with start_char and end_char integers | Both start_char and end_char must be non-negative integers. end_char must be greater than start_char. Fail on type mismatch or invalid range. | |
findings[].redaction_suggestion | string | Must be a non-empty string. Fail if null or empty. Should contain a masked or redacted version of the value. | |
error_message | string or null | If status is error, this field must be a non-empty string. If status is pass or fail, this field must be null. Fail on contract violation. |
Common Failure Modes
PII leak detection in assembled prompts is a high-stakes preflight check. These are the most common failure modes that let sensitive data slip through to the model, along with practical mitigations to catch them before inference.
False Negatives on Obfuscated PII
What to watch: Attackers or users may split PII across multiple variables (e.g., [FIRST_NAME] + [LAST_NAME] concatenated at runtime) or use base64 encoding, leetspeak, or character substitution to evade regex-based scanners. A simple email regex will miss user [at] domain [dot] com. Guardrail: Implement a multi-pass scanner that first normalizes the assembled prompt (decode base64, collapse whitespace, reverse common substitutions) before running detection patterns. Add eval test cases with obfuscated PII variants to measure recall.
False Positives on Benign Structured Data
What to watch: UUIDs, cryptographic hashes, base64-encoded images, session tokens, and version strings can match PII regex patterns (e.g., a hex string that looks like a credit card number). Over-blocking breaks legitimate application functionality and erodes trust in the guardrail. Guardrail: Maintain a allowlist of known benign patterns specific to your application (e.g., your internal ID format). Implement a confidence scoring system that combines regex matches with entropy checks and context analysis. Log all redactions with the matched pattern for audit and tuning.
Context Window Blind Spots from Truncation
What to watch: If PII scanning happens after context truncation or summarization, sensitive data in the dropped portion is never checked. Conversely, if scanning happens before truncation, the redaction map may point to offsets that no longer exist in the truncated prompt, causing downstream processing errors. Guardrail: Perform PII detection on the fully assembled prompt before any truncation step. If truncation is required, re-scan the truncated prompt and regenerate the redaction map. Never apply a stale redaction map to a modified prompt string.
Retrieval-Induced PII Injection
What to watch: Retrieved documents, database records, or tool outputs inserted into the prompt may contain PII that was not present in the original user input. A support ticket lookup might pull a full email thread with customer phone numbers into the context. Guardrail: Extend PII scanning to all dynamically inserted context, not just user input. Treat retrieved evidence as untrusted data. Implement a post-assembly scan that covers the entire prompt string, including all RAG results, tool outputs, and system context.
Redaction Map Drift After Assembly
What to watch: The scanner outputs a redaction map with character offsets, but if any upstream process modifies the prompt string after scanning (e.g., adding trace IDs, timestamps, or formatting), the offsets become invalid. Downstream systems may redact the wrong spans or crash on out-of-bounds indices. Guardrail: Make PII scanning the absolute final step before the prompt is sent to the model. If post-scan modification is unavoidable, use a content-addressed redaction strategy (e.g., replace PII with placeholder tokens and store the mapping separately) rather than relying on brittle character offsets.
Silent Failure on Unsupported Locales
What to watch: Regex patterns for phone numbers, national IDs, and addresses are often locale-specific. A scanner tuned for US formats will silently miss UK National Insurance numbers, Indian Aadhaar numbers, or Japanese My Number IDs. This creates a false sense of security in global applications. Guardrail: Maintain a locale-aware PII pattern library that activates based on the user's region or the detected language of the input. Include locale-specific eval test cases. When locale is unknown, run a broad multi-locale scan and flag any uncertainty for human review rather than assuming safety.
Evaluation Rubric
Criteria for evaluating the PII Leak Detection prompt's output quality before deployment. Use these tests to measure false positive rates, severity classification accuracy, and redaction map completeness against a labeled dataset.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Recall on PII entities |
| Known PII present in the assembled prompt but missing from the redaction map | Run against a golden dataset of 100 prompts with injected PII; count missed detections |
False positive rate on benign structured data | <= 0.05 false positive rate on non-PII structured strings (UUIDs, base64, timestamps, hex hashes) | Benign structured data flagged as PII in the redaction map | Run against a curated set of 50 prompts containing only benign structured data; count false flags |
Severity classification accuracy |
| Credit card number classified as low severity or UUID classified as critical | Compare severity labels against a pre-labeled severity map for the golden dataset |
Redaction map completeness | Every detected PII instance includes: start_offset, end_offset, entity_type, severity, and redacted_value | Missing fields in any redaction map entry | Schema validation check on the output JSON; assert all required fields are present and non-null |
Redacted value correctness | Redacted value preserves character count and type hint (e.g., [EMAIL] for email, [CC] for credit card) | Redacted value reveals original data or uses wrong placeholder format | Compare redacted_value against expected placeholder format per entity_type |
Boundary offset accuracy | start_offset and end_offset correctly locate the PII substring in the original prompt | Offsets point to wrong substring or are out of range | Extract substrings using reported offsets and compare against known PII positions in test cases |
No hallucinated detections | Zero detections of PII patterns not present in the input prompt | Redaction map contains entries for PII that does not exist in the assembled prompt | Diff the redaction map against the golden dataset's ground truth; flag any extra entries |
Handling of obfuscated PII | Detects common obfuscation patterns (e.g., 'user [at] domain [dot] com', '555-12-34') with >= 0.90 recall | Obfuscated PII passes through undetected | Include 20 obfuscated PII variants in the test set; measure detection rate |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt\nStart with the base prompt and a simple regex pre-filter for high-confidence patterns (email, credit card). Skip severity classification and redaction mapping. Use a single pass/fail output.\n\n```\n[SYSTEM]\nYou are a PII scanner. Scan the following text for email addresses and credit card numbers. Return ONLY a JSON object with a single field 'contains_pii' set to true or false.\n\n[TEXT_TO_SCAN]\n[ASSEMBLED_PROMPT]\n```\n\n### Watch for\n- False positives on UUIDs, base64 strings, and version numbers that look like credit cards\n- Missing detection of phone numbers, SSNs, and API keys\n- No severity differentiation—everything looks like a critical finding\n- Regex pre-filter may miss PII that the model would catch, or vice versa

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us