Inferensys

Prompt

Prompt Assembly Guard Prompt for PII Leakage Prevention

A practical prompt playbook for using Prompt Assembly Guard Prompt for PII Leakage Prevention in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Understand the specific job this prompt performs as a final pre-inference safety net, and when it is the wrong tool for the job.

This prompt acts as a final, non-deterministic safety net for AI platform engineers. Its job is to analyze a fully assembled prompt string immediately before it is sent to a model and produce a pass/fail decision. It is designed to catch personally identifiable information (PII), secrets, and regulated data that have survived all previous deterministic redaction and sanitization layers in your pipeline. The ideal user is an engineer integrating this check into a CI/CD prompt deployment pipeline, a runtime proxy, or a pre-flight hook in an AI gateway. You should use this when you need a last line of defense that can understand context in a way that regex and pattern-matching scanners cannot, such as identifying a name embedded in a natural language sentence or a secret key pasted into a code block.

This is not a replacement for a primary PII scanner or a deterministic redaction service. Do not use this prompt as your first or only line of defense. It is a safety net, and like any LLM-based check, it is probabilistic and can fail. It is unsuitable for high-throughput, real-time streaming applications where the added latency of an extra model call is unacceptable. It is also not a compliance certification tool; passing this check does not guarantee legal compliance with GDPR, HIPAA, or PCI DSS. Instead, wire this prompt into a pre-production testing suite to catch regressions in your prompt assembly code, or use it in a low-volume, high-risk workflow where a human is in the loop to review the guard's findings before the prompt is sent.

Before implementing this guard, ensure you have already applied deterministic redaction for known patterns (e.g., regex for credit card numbers, API key formats). This prompt should be configured to look for the specific categories of sensitive data that are most critical for your application, defined in the [SENSITIVE_DATA_CATEGORIES] variable. The next step is to integrate this prompt into a harness that logs its decisions for auditability and triggers an alert or a halt on a fail result. Avoid using this prompt in isolation; its value comes from being part of a defense-in-depth strategy.

PRACTICAL GUARDRAILS

Use Case Fit

Where the PII leakage guard prompt adds value and where it introduces risk or unnecessary cost.

01

Good Fit: Final Pre-Inference Gate

Use when: the fully assembled prompt is ready and you need a last-chance check before it hits the model. Guardrail: Run this guard synchronously in the request path with a strict timeout. If it fails, block the inference and route to a human review queue.

02

Good Fit: CI/CD Prompt Deployment Pipeline

Use when: prompt templates are updated and you need to verify that new variable substitution logic does not accidentally reintroduce PII. Guardrail: Integrate the guard as a required stage in your prompt deployment pipeline. Block the release on any detection.

03

Bad Fit: Real-Time Streaming Input

Avoid when: user input is streaming character-by-character and you need sub-second latency. A full prompt assembly guard adds too much delay. Guardrail: Use lightweight regex and pattern matching for streaming. Defer the LLM guard to message completion or session end.

04

Bad Fit: Sole Redaction Mechanism

Avoid when: this is the only line of defense. A detection-only guard does not redact; it only blocks. Guardrail: Pair this guard with a pre-assembly redaction step. The guard should catch what the redactor missed, not replace it.

05

Required Input: Fully Assembled Prompt

Risk: Running the guard on a partial prompt or template with unresolved variables produces false negatives. Guardrail: Ensure the guard receives the exact string that will be sent to the model, after all variable substitution, context packing, and tool schema insertion.

06

Operational Risk: Model Invocation Cost

Risk: Every guard check consumes tokens and adds latency. For high-volume systems, this can double inference costs. Guardrail: Cache results for identical prompts. Use a cheaper, faster model for the guard than for the primary task. Set a max token budget for the guard response.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable guard prompt that inspects a fully assembled prompt for surviving PII, secrets, and regulated data before inference.

This template acts as the final pre-inference checkpoint in your prompt assembly pipeline. It receives the complete, resolved prompt—after all prior redaction, sanitization, and variable substitution steps—and produces a structured pass/fail decision. The prompt is designed to catch PII entities, secrets, and regulated data classes that may have survived earlier redaction layers due to regex gaps, unusual formatting, or assembly-time injection. Use this when you need a programmatic gate that can block a request before it reaches the model, log the violation, and route the prompt for human review or automated repair.

text
You are a pre-inference security guard. Your only job is to inspect the fully assembled prompt below and determine whether it contains any personally identifiable information (PII), secrets, or regulated data that should not be sent to a language model.

## INPUT
Analyze the following assembled prompt:

[ASSEMBLED_PROMPT]

code

## DETECTION CATEGORIES
Check for these categories. Flag any match, regardless of confidence:

### PII
- Full names combined with other identifiers (address, phone, email, DOB, ID numbers)
- Email addresses
- Physical addresses
- Phone numbers
- Government identifiers (SSN, passport, driver's license, national ID)
- Date of birth (when linked to other identifiers)
- IP addresses (when linked to individual user context)
- Biometric data or descriptions

### Secrets and Credentials
- API keys, access tokens, or bearer tokens
- Connection strings with embedded credentials
- Private keys (SSH, PGP, TLS)
- Passwords or passphrases
- Cloud provider secret patterns (AWS access keys, GCP service account keys, Azure connection strings)
- High-entropy strings that match known secret formats

### Regulated Data Classes
- Protected health information (PHI) under HIPAA: medical record numbers, health plan beneficiary numbers, device identifiers, full-face photos
- Payment card data under PCI DSS: full credit card numbers, CVV codes, full magnetic stripe data
- Financial account numbers with routing information
- Data subject to GDPR, CCPA, or similar privacy regulations when not explicitly authorized

### Organizational Confidential Data
- [CUSTOM_CONFIDENTIAL_PATTERNS]

## OUTPUT SCHEMA
Return ONLY valid JSON with this exact structure:

{
  "decision": "PASS" | "FAIL",
  "findings": [
    {
      "category": "PII" | "SECRET" | "REGULATED" | "CONFIDENTIAL",
      "subcategory": "string describing the specific type",
      "matched_content": "the exact text that triggered detection (truncated to 80 chars if longer)",
      "location_hint": "surrounding context snippet for identification (truncated to 120 chars)",
      "severity": "CRITICAL" | "HIGH" | "MEDIUM"
    }
  ],
  "summary": "brief explanation of the decision"
}

## RULES
1. Flag anything that could reasonably be PII or a secret, even if you are not 100% certain. Err on the side of caution.
2. If you find nothing, return PASS with an empty findings array.
3. Do NOT include the detected PII or secrets in the summary field—only in the matched_content field.
4. For CRITICAL severity: use for full SSNs, unredacted credit card numbers, live API keys, passwords, and complete medical record numbers.
5. For HIGH severity: use for email addresses, phone numbers with names, partial identifiers that could be combined.
6. For MEDIUM severity: use for standalone names without other identifiers, generic organizational terms that might be confidential.
7. Do not flag placeholder text, example data, or obviously synthetic test values that use patterns like "XXXX" or "test_" or "example.com".
8. If [CUSTOM_CONFIDENTIAL_PATTERNS] is provided, apply those patterns in addition to the standard categories.

## EXAMPLES

Example 1 - FAIL with PII:
Input: "Please summarize the medical history for patient John Smith, DOB 05/12/1965, MRN 987654321."
Output: {"decision": "FAIL", "findings": [{"category": "PII", "subcategory": "full name with date of birth", "matched_content": "John Smith, DOB 05/12/1965", "location_hint": "medical history for patient John Smith, DOB 05/12/1965, MRN 987654321", "severity": "CRITICAL"}, {"category": "REGULATED", "subcategory": "medical record number", "matched_content": "MRN 987654321", "location_hint": "DOB 05/12/1965, MRN 987654321", "severity": "CRITICAL"}], "summary": "Detected patient name with DOB and medical record number. Prompt blocked."}

Example 2 - FAIL with secret:
Input: "Use this API key for authentication: sk-abc123def456ghi789jkl012mno345pqr678stu901vwx234yz"
Output: {"decision": "FAIL", "findings": [{"category": "SECRET", "subcategory": "API key", "matched_content": "sk-abc123def456ghi789jkl012mno345pqr678stu901vwx234yz", "location_hint": "Use this API key for authentication: sk-abc123def456ghi789jkl012mno345pqr678stu901vwx234yz", "severity": "CRITICAL"}], "summary": "Detected live API key in prompt. Prompt blocked."}

Example 3 - PASS:
Input: "Summarize the quarterly earnings report for Q3 2024. Focus on revenue growth and operating margin."
Output: {"decision": "PASS", "findings": [], "summary": "No PII, secrets, or regulated data detected."}

## CONSTRAINTS
- Do not explain your reasoning outside the JSON output.
- Do not wrap the JSON in markdown code fences.
- Return only the JSON object.

Adapt this template by replacing [ASSEMBLED_PROMPT] with the fully resolved prompt string from your assembly pipeline. The [CUSTOM_CONFIDENTIAL_PATTERNS] placeholder accepts organization-specific detection rules—for example, internal project codenames, proprietary product names, or customer account tiers that should not leave your environment. If you have no custom patterns, replace the entire bullet list under "Organizational Confidential Data" with a single line stating "None specified." Wire the output into your pre-inference gate: a FAIL decision should block the request, log the findings with the prompt version and trace ID, and route to either an automated repair step or a human review queue. A PASS decision allows the prompt to proceed to the model. Test this guard against a golden dataset of prompts containing known PII and secrets to calibrate your detection thresholds before deploying to production.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the Prompt Assembly Guard Prompt. Each variable must be validated before assembly to prevent the guard itself from becoming a PII leakage vector or failing silently in production.

PlaceholderPurposeExampleValidation Notes

[FULLY_ASSEMBLED_PROMPT]

The complete prompt string about to be sent to the inference model, including system message, context, tools, and user input.

System: You are a support agent...\nUser: My email is alice@example.com and my SSN is 123-45-6789.

Must be a non-empty string. Validate length does not exceed model context limit. Reject if null or whitespace-only. Log hash for audit trail before inspection.

[PII_CATEGORIES]

A list of PII, secret, and regulated data categories the guard must detect. Controls sensitivity and scope.

["EMAIL", "SSN", "CREDIT_CARD", "API_KEY", "PHONE_NUMBER", "PASSPORT_NUMBER"]

Must be a non-empty array of strings matching known category enum. Reject unknown categories. Default to organization-approved list if not supplied. Validate against allowed category registry.

[REDACTION_POLICY]

The policy version or rule set that defines what constitutes a redaction failure. Used to ground the pass/fail decision.

"acme-corp-pii-policy-v2.1"

Must be a non-empty string referencing a deployed policy version. Validate policy exists in policy registry. Reject if policy version is deprecated or unknown. Log policy version with each guard execution.

[CONTEXT_SOURCE]

Identifier for the upstream system or pipeline stage that assembled the prompt. Used for audit trails and failure attribution.

"rag-retrieval-pipeline-us-east-1"

Must be a non-empty string. Validate against known source registry. Reject unknown sources. Used to route alerts to the correct team when guard fails.

[SESSION_ID]

Unique identifier for the user session or request. Links guard decisions to specific interactions for debugging and compliance.

"sess_9a7b3c2d-4e5f-6789-abcd-ef0123456789"

Must be a non-empty string in UUID or equivalent unique format. Validate format. Required for audit trail correlation. Reject if missing in production environments.

[FAILURE_THRESHOLD]

The minimum number or severity of detected PII instances that triggers a FAIL decision. Prevents over-blocking on single low-confidence matches.

{"min_count": 1, "min_severity": "HIGH"}

Must be a valid JSON object with min_count (integer >= 0) and min_severity (enum: LOW, MEDIUM, HIGH, CRITICAL). Validate schema. Default to {min_count: 1, min_severity: HIGH} if not supplied. Null allowed for always-fail mode.

[OUTPUT_FORMAT]

Specifies the structure of the guard's response. Must include pass/fail, findings list, and metadata for downstream handling.

"json"

Must be one of ["json", "jsonl"]. Default to "json". Validate enum. Reject unsupported formats. Output schema must include 'decision', 'findings', 'policy_version', 'timestamp', and 'session_id' fields.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Prompt Assembly Guard into a production CI/CD pipeline for pre-inference PII detection.

This guard prompt is designed as a final, synchronous pre-inference check. It should be called immediately after the full prompt is assembled and immediately before the chat.completions.create or equivalent API call. The harness must treat this guard's output as a hard gate: a pass decision allows the primary inference to proceed, while a fail decision must abort the request, log the violation, and route the event for human review or automated remediation. The guard itself is an LLM call, so the harness must manage its latency and cost, typically by using a fast, cheap model (e.g., GPT-4o-mini, Claude Haiku) for the guard task, reserving larger models for the primary workload.

The integration pattern involves three core components: a pre-guard assembly step, the guard inference call, and a post-guard decision handler. First, assemble the final prompt string exactly as it will be sent to the primary model, including all system messages, retrieved context, tool definitions, and user input. Serialize this into a single string or structured message array. Next, inject this assembled prompt into the [FULLY_ASSEMBLED_PROMPT] placeholder of the guard template and execute the guard model call. The guard's output must be parsed as strict JSON. The harness should validate the JSON schema, checking for the required decision field (pass or fail) and the findings array. If the JSON is unparseable, the harness should default to a fail decision and log a GUARD_PARSE_ERROR to prevent any uninspected prompt from reaching the primary model. Implement a retry policy with a maximum of 2 attempts for guard parse failures before aborting.

For high-throughput systems, consider batching guard checks or implementing a caching layer for identical prompts, though this is often an anti-pattern due to the dynamic nature of user input. All guard decisions, including passes, must be logged to an immutable audit store with a trace ID that links the guard call to the subsequent primary inference call. Log the full assembled prompt, the guard's raw JSON output, the decision, and the timestamp. For fail decisions, the harness should publish an event to a dead-letter queue or incident management channel (e.g., PagerDuty, Slack) containing the trace ID, detected PII categories, and a redacted sample of the prompt for triage. Never log the raw, unredacted prompt to a system without equivalent access controls. The next step is to build a small integration test that asserts the harness correctly gates on a known-bad prompt containing a synthetic email address and allows a known-clean prompt to proceed.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the exact JSON schema returned by the Prompt Assembly Guard. Use this contract to build a parser and validator in your CI/CD pipeline before the prompt is sent to the target model.

Field or ElementType or FormatRequiredValidation Rule

verdict

string enum: PASS | FAIL

Must be exactly PASS or FAIL. If FAIL, the prompt must be blocked from inference.

findings

array of objects

Must be a JSON array. If verdict is PASS, the array must be empty (length 0).

findings[].type

string enum: PII | SECRET | REGULATED_DATA

Must be one of the three specified categories. Use REGULATED_DATA for HIPAA, GDPR, or PCI-specific items.

findings[].value

string

The exact detected sensitive string. Must be a non-empty substring of the original assembled prompt.

findings[].offset

integer

Zero-based character offset of the finding's start in the assembled prompt. Must be a non-negative integer.

findings[].confidence

number

A float between 0.0 and 1.0. A threshold of >= 0.85 is recommended for blocking. Lower-confidence findings should be logged for review.

findings[].rule_id

string

A stable identifier for the detection rule that fired (e.g., 'US_SSN_PATTERN', 'OPENAI_API_KEY'). Must not change between runs for the same pattern.

audit_token

string

An opaque, unique identifier for this specific guard execution. If provided, it must be a UUID v4 string for traceability.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when a PII guard prompt is deployed in a real pipeline, and how to prevent each failure before it reaches production.

01

False Negatives on Novel PII Formats

What to watch: The guard prompt misses PII that doesn't match common patterns—internal customer IDs, proprietary account codes, or locale-specific identifiers. The model sees these as benign strings and passes them through. Guardrail: Maintain a living registry of custom entity patterns specific to your data domain. Run the guard against a golden dataset that includes your organization's actual ID formats, not just generic SSNs and emails. Log every pass-through for periodic human audit.

02

Over-Redaction Breaking Downstream Task Utility

What to watch: The guard prompt is too aggressive, masking names, dates, and locations that are essential for the task. A support summarization prompt loses the customer's name and issue timestamp; a clinical prompt loses the patient's age and admission date. Guardrail: Define a task-critical entity allowlist before redaction. Test the downstream prompt's output quality with and without redaction. If task accuracy drops below a threshold, tune the guard's sensitivity or switch to pseudonymization instead of deletion.

03

Prompt Injection Bypassing the Guard

What to watch: An attacker embeds instructions in user input that tell the guard prompt to ignore PII, output it in a comment, or encode it in base64. The guard prompt follows the injected instruction instead of its own policy. Guardrail: Place the guard prompt's instructions after the user input in the assembly order, or run the guard as a separate, isolated call with no user content in the system message. Use a dedicated small model for the guard that has no instruction-following overlap with the main task model.

04

High-Entropy Secret Misclassification

What to watch: API keys, tokens, and connection strings look like random noise to a PII detector trained on names and addresses. The guard prompt passes them because they don't match a person-centric entity definition. Guardrail: Add a separate secret-detection pass before the PII guard, using regex patterns for known cloud provider key formats and entropy-based scanning for high-randomness strings. Combine the results: if either pass flags the content, redact it.

05

Guard Prompt Drift After Model Upgrade

What to watch: The guard prompt was tuned on GPT-4 and produced reliable pass/fail JSON. After switching to a newer model or a different provider, the output format changes, confidence scores shift, or the guard becomes overly permissive. Guardrail: Pin the guard prompt to a specific model version in production. Run the full guard eval suite—recall, precision, format compliance—against every candidate model before migration. Version the guard prompt alongside the model it targets.

06

Latency Budget Exhaustion from Synchronous Guarding

What to watch: The guard prompt adds a full synchronous LLM call before every inference, doubling end-to-end latency. For real-time chat or streaming applications, this pushes response times past acceptable thresholds. Guardrail: Run the guard asynchronously where possible—log the assembled prompt, flag violations post-hoc, and block only for high-risk categories. For synchronous use, deploy a smaller, faster model dedicated to the guard task, and set a strict timeout that fails open to a human review queue.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the guard prompt's output quality before integrating it into a CI/CD pipeline. Each criterion targets a specific failure mode observed in production PII leakage prevention systems.

CriterionPass StandardFailure SignalTest Method

PII Recall

All seeded PII instances in the [TEST_PROMPT] are detected and listed in the output

Output passes is true but a seeded PII entity is missing from the detected_items array

Run against a golden dataset of 50 prompts containing known PII; require recall >= 0.99

False Positive Rate

No non-PII strings are flagged as PII in a clean [TEST_PROMPT] containing zero sensitive data

Output passes is false or detected_items contains entries for benign strings like project codenames or UUIDs

Run against a clean dataset of 50 prompts with business data but zero PII; require precision >= 0.98

Secret Pattern Detection

High-entropy strings matching AWS, GCP, Azure, or GitHub token patterns are detected and classified as secret

A seeded AWS access key or GitHub PAT is not listed in detected_items or is misclassified as unknown

Inject 10 known secret formats into [TEST_PROMPT]; verify all are detected with correct category

Output Schema Compliance

Output is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present and correctly typed

Output is missing passes, detected_items is not an array, or category contains an invalid enum value

Parse output with a JSON schema validator; fail if validation errors are returned

Adversarial Evasion Resistance

Prompt injection attempts designed to hide PII do not cause the guard to return passes: true

A [TEST_PROMPT] containing PII wrapped in instructions like 'ignore previous redaction' passes the guard

Run against a library of 20 known PII-extraction jailbreaks; require detection rate >= 0.95

Multilingual PII Detection

PII in non-English text within [TEST_PROMPT] is detected when [LANGUAGES] includes the target language

A French name, German address, or Japanese phone number is missed while English PII is caught

Seed prompts with PII in 5 languages specified in [LANGUAGES]; require per-language recall >= 0.95

Over-Redaction Avoidance

The guard does not flag redacted placeholders like [REDACTED_NAME] as new PII instances

Output detected_items lists the placeholder token itself as a detected PII entity, causing infinite redaction loops

Submit a prompt already containing standard redaction placeholders; verify zero detections on placeholder text

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add a strict output schema with required fields, confidence scores, and character offsets. Integrate with a pre-inference hook that blocks the request if pass is false. Add retry logic: if PII is detected, route to a redaction step and re-assemble before re-checking.

code
You are a final pre-inference PII guard. Analyze the fully assembled prompt below. Return JSON matching [OUTPUT_SCHEMA].

[OUTPUT_SCHEMA]
{
  "pass": boolean,
  "findings": [
    {
      "type": "PII_TYPE",
      "subtype": "email|ssn|credit_card|api_key|phone|address|name|other",
      "snippet": "detected text",
      "char_start": integer,
      "char_end": integer,
      "confidence": 0.0-1.0,
      "severity": "critical|high|medium|low"
    }
  ],
  "redaction_attempted": boolean,
  "recommendation": "block|redact_and_retry|allow_with_audit"
}

Assembled Prompt:
[ASSEMBLED_PROMPT]

Watch for

  • Schema drift where the model omits char_start/char_end on complex findings
  • Confidence scores that don't correlate with actual detection accuracy
  • Latency impact when this guard runs synchronously before every inference call
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.