This prompt is designed for privacy engineers and platform developers who need to sanitize tool outputs before they re-enter an agent's context window. The core job-to-be-done is preventing personally identifiable information (PII) from leaking out of a tool's response and into the agent's reasoning, memory, or subsequent tool calls. This is a critical data hygiene control point in agent architectures where a tool might return raw database rows, unstructured API payloads, or unfiltered log data that contains customer emails, phone numbers, or financial identifiers.
Prompt
Tool Output PII Detection and Masking Prompt

When to Use This Prompt
Define the job, the user, and the operational boundaries for the Tool Output PII Detection and Masking Prompt.
Use this prompt when you have a dedicated sanitization step in your agent's tool-call pipeline—after a tool returns a response but before that response is appended to the agent's message history. It is appropriate for synchronous, string-based tool outputs where you need structured detection results (PII type, confidence score, redaction decision) and a masked version of the original text. The prompt expects a raw tool output string as its primary input and returns a JSON object with masked_output, detected_pii array, and redaction_summary. This is not a real-time streaming solution; it works best on complete, discrete tool responses under a defined token budget.
Do not use this prompt as a replacement for deterministic, rule-based PII scrubbing on structured fields you already control. If you own the tool's output schema and know that field user.email is always an email address, apply a regex or hashing function in application code instead of relying on a model's probabilistic detection. This prompt is also not a substitute for data minimization at the source—if a tool is returning full credit card numbers when only the last four digits are needed, fix the tool or its query before adding a masking layer. Finally, avoid using this prompt for real-time, high-throughput streams where latency and cost per token would make model-based detection impractical; prefer a streaming regex engine with a fallback to this prompt for ambiguous or novel PII patterns.
Use Case Fit
Where this prompt works and where it does not. Use these cards to decide if the Tool Output PII Detection and Masking Prompt fits your architecture before you integrate it.
Good Fit: Pre-Context Sanitization
Use when: you need to scrub PII from tool outputs before they enter the agent's context window. Guardrail: Position this prompt as a synchronous gate between tool execution and context assembly. Do not rely on it after the agent has already reasoned over raw data.
Bad Fit: Real-Time Streaming
Avoid when: tool outputs are streamed token-by-token to the user or agent. Risk: Partial PII may leak before the full response is available for detection. Guardrail: Buffer complete tool responses before masking, or use a separate streaming-aware redaction proxy.
Required Inputs
Requires: the raw tool output string, a defined PII taxonomy (e.g., names, emails, SSNs, credit cards), and a masking policy (redact, hash, tokenize, or replace). Guardrail: Without an explicit taxonomy, the model will guess what counts as PII, leading to inconsistent recall.
Operational Risk: Over-Redaction
Risk: the prompt masks too aggressively, removing non-PII data that the agent needs for reasoning. Guardrail: Track over-redaction rates in eval. Add a confidence threshold below which the prompt should flag rather than mask, and route ambiguous cases for human review.
Operational Risk: Context Window Bloat
Risk: large tool outputs with many detected PII instances produce verbose masking reports that consume context budget. Guardrail: Return only the masked output and a compact summary of changes. Move detailed audit logs to a separate observability channel.
Not a Replacement for Transport Security
Avoid using: this prompt as your only PII defense. Risk: PII may still be present in logs, traces, or upstream tool calls before the prompt runs. Guardrail: Combine with transport encryption, log redaction, and least-privilege tool access. This prompt is one layer, not the whole strategy.
Copy-Ready Prompt Template
A reusable prompt template with square-bracket placeholders for detecting and masking PII in tool outputs before they re-enter agent context.
This prompt template is designed to be inserted between a tool's raw output and the agent's context window. It instructs the model to scan the provided text for personally identifiable information (PII), classify each detected instance by type and confidence, and produce a sanitized version with PII replaced by typed placeholders. The template uses square-bracket placeholders so you can wire it into your application's prompt assembly pipeline without manual editing.
textYou are a privacy-preserving sanitization layer operating between an external tool and an AI agent. Your job is to detect and mask personally identifiable information (PII) in the tool output below before it enters the agent's context. [CONSTRAINTS] - Never output unmasked PII under any circumstances. - Do not alter non-PII content, structure, or formatting. - If you are uncertain whether a value is PII, flag it with confidence "low" but still mask it. - Do not add commentary, explanations, or apologies. Return only the JSON object specified in [OUTPUT_SCHEMA]. - If no PII is detected, return an empty detections array and the original text unchanged. [PII_CATEGORIES] Detect and classify the following PII types: - person_name: Full names, first names, last names - email_address: Email addresses - phone_number: Phone numbers in any format - physical_address: Street addresses, postal codes, city/state combinations - government_id: SSN, passport numbers, driver's license numbers, national IDs - financial_account: Credit card numbers, bank account numbers, IBANs - ip_address: IPv4 and IPv6 addresses - date_of_birth: Explicit birth dates - medical_record: Patient IDs, medical record numbers - credential: Passwords, API keys, tokens, secrets [OUTPUT_SCHEMA] Return a single JSON object with this exact structure: { "original_length": <integer>, "sanitized_text": "<text with PII replaced by typed placeholders>", "detections": [ { "type": "<PII category from list above>", "original_value": "<detected PII value>", "placeholder": "<replacement used in sanitized_text>", "confidence": "<high|medium|low>", "char_offset_start": <integer>, "char_offset_end": <integer> } ], "redaction_summary": { "total_detections": <integer>, "by_type": { "<pii_type>": <count> }, "high_confidence_count": <integer>, "medium_confidence_count": <integer>, "low_confidence_count": <integer> } } [PLACEHOLDER_FORMAT] Use the format [REDACTED_<PII_TYPE>_<INDEX>] for all masked values. For example: - [REDACTED_EMAIL_ADDRESS_1] - [REDACTED_PHONE_NUMBER_2] - [REDACTED_PERSON_NAME_3] [EXAMPLES] Input: "Contact John Smith at john.smith@example.com or call 555-123-4567." Output: { "original_length": 65, "sanitized_text": "Contact [REDACTED_PERSON_NAME_1] at [REDACTED_EMAIL_ADDRESS_1] or call [REDACTED_PHONE_NUMBER_1].", "detections": [ { "type": "person_name", "original_value": "John Smith", "placeholder": "[REDACTED_PERSON_NAME_1]", "confidence": "high", "char_offset_start": 8, "char_offset_end": 18 }, { "type": "email_address", "original_value": "john.smith@example.com", "placeholder": "[REDACTED_EMAIL_ADDRESS_1]", "confidence": "high", "char_offset_start": 22, "char_offset_end": 44 }, { "type": "phone_number", "original_value": "555-123-4567", "placeholder": "[REDACTED_PHONE_NUMBER_1]", "confidence": "high", "char_offset_start": 54, "char_offset_end": 65 } ], "redaction_summary": { "total_detections": 3, "by_type": { "person_name": 1, "email_address": 1, "phone_number": 1 }, "high_confidence_count": 3, "medium_confidence_count": 0, "low_confidence_count": 0 } } [RISK_LEVEL] [HIGH] - This prompt handles sensitive PII data. The output JSON contains original PII values in the detections array. Ensure this output is handled in a secure environment and never logged or stored without additional redaction of the detections.original_value field. [INPUT] Tool output to sanitize: """ [TOOL_OUTPUT] """
To adapt this template, replace [TOOL_OUTPUT] with the raw text from your tool call. Adjust [PII_CATEGORIES] to match your organization's data classification policy—add or remove types based on your regulatory requirements. If your application cannot safely handle the original_value field in detections, modify [OUTPUT_SCHEMA] to remove it and rely solely on character offsets for audit trails. For high-throughput production systems, consider adding a [MAX_LENGTH] constraint to prevent context window overflow from large tool responses, and pair this prompt with the Tool Output Context Window Budget Check Prompt for defense in depth.
Before deploying this prompt, validate it against your PII detection eval suite. Test with known PII datasets to measure recall and precision per category, and check over-redaction rates on non-PII text. Pay special attention to edge cases: PII in nested JSON structures, PII split across line breaks, non-Latin scripts, and values that resemble PII but are not (e.g., fake phone numbers in documentation). If your risk tolerance requires human review, route low-confidence detections or detections in the government_id and medical_record categories to a review queue before the sanitized output reaches the agent.
Prompt Variables
Required inputs for the Tool Output PII Detection and Masking Prompt. Each placeholder must be populated before the prompt is assembled and sent. Validation notes describe how to confirm the input is safe and well-formed before it reaches the model.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TOOL_OUTPUT] | Raw string or structured object returned by a tool before it enters agent context. | {"user": {"name": "Jane Doe", "email": "jane@example.com"}, "query_result": "Account #1234-5678 found."} | Must be a non-empty string or valid JSON. Reject null, undefined, or binary blobs. Check length does not exceed [MAX_INPUT_LENGTH]. |
[PII_CATEGORIES] | List of PII entity types the prompt must detect and mask. | ["EMAIL", "PHONE_NUMBER", "CREDIT_CARD", "SSN", "PERSON_NAME", "IP_ADDRESS", "ACCOUNT_NUMBER"] | Must be a non-empty array of strings from the approved PII taxonomy. Reject unknown categories. Validate against [ALLOWED_PII_CATEGORIES] schema. |
[REDACTION_STRATEGY] | Instruction for how detected PII should be masked. | REPLACE_WITH_ENTITY_TYPE | Must be one of: REPLACE_WITH_ENTITY_TYPE, REPLACE_WITH_PLACEHOLDER, or REMOVE_FIELD. Reject free-text strategies. Default to REPLACE_WITH_ENTITY_TYPE if missing. |
[CONFIDENCE_THRESHOLD] | Minimum confidence score (0.0-1.0) required to apply redaction. | 0.85 | Must be a float between 0.0 and 1.0. Values below 0.7 risk over-redaction; values above 0.95 risk missed PII. Default to 0.85 if not provided. Reject non-numeric values. |
[OUTPUT_SCHEMA] | Expected JSON structure for the detection and masking result. | {"original_length": int, "masked_output": string, "detections": [{"type": string, "value": string, "confidence": float, "span": [int, int], "action": string}]} | Must be a valid JSON Schema or example object. Validate parseability before prompt assembly. Reject schemas missing required fields: masked_output, detections. |
[CONTEXT_NOTE] | Optional metadata about the tool call origin for audit trail inclusion. | {"tool_name": "customer_lookup", "call_id": "req-abc123", "timestamp": "2024-01-15T10:30:00Z"} | If provided, must be valid JSON with tool_name and call_id fields. Reject objects exceeding 1KB. Null is allowed when no audit context is available. |
[MAX_INPUT_LENGTH] | Maximum character length of [TOOL_OUTPUT] to process before truncation. | 50000 | Must be a positive integer. Reject values over 100000 to prevent context window exhaustion. Truncation warning must be included in output if input exceeds this value. |
Implementation Harness Notes
How to wire the PII detection prompt into a production agent pipeline with validation, retries, and audit logging.
The PII detection and masking prompt operates as a synchronous pre-processing gate between a tool's raw output and the agent's context window. Every tool response that might contain user data, API payloads, or unstructured text must pass through this prompt before the agent can reason over it. The harness should treat the prompt as a deterministic filter: same input produces the same masking decisions, which makes caching and regression testing straightforward. Wire it as a middleware function in your agent framework—after the tool executor returns but before the response is appended to the message list. For high-throughput pipelines, batch multiple tool outputs into a single prompt call with clear delimiters to reduce latency overhead.
Validation and retry logic is critical because a malformed JSON response from the PII prompt can corrupt downstream agent state. Implement a strict schema validator that checks for the required fields: masked_output, detections (array of objects with type, confidence, start, end, action), and redaction_summary. If validation fails, retry once with the error message injected into the prompt as [PREVIOUS_ERROR]. If the second attempt also fails, log the raw tool output and the failed prompt responses, then fall back to a conservative redaction strategy—strip all potential PII fields using regex patterns for emails, phone numbers, and credit card numbers—and flag the interaction for human review. Never let unvalidated output enter the agent's context.
Model selection matters for both accuracy and cost. Use a fast, cheaper model (GPT-4o-mini, Claude Haiku, or a fine-tuned small model) for the detection pass because the task is classification-heavy rather than generation-heavy. Reserve larger models only when the confidence scores from the primary model fall below your threshold (e.g., <0.85) or when the output contains complex nested structures like legal documents or medical records. Logging and audit trails should capture: the original tool output hash, the masked output, detection counts by PII type, confidence distributions, the model used, latency, and any validation failures. This audit log serves both debugging and compliance needs—you can prove what data was seen, what was masked, and when the system made errors.
Human review integration is mandatory for high-risk domains. When the prompt detects high-severity PII types (government IDs, financial account numbers, health records) or when confidence scores are below your threshold, route the interaction to a review queue rather than silently masking. The review interface should show the original text with detected spans highlighted, the proposed masked version, and allow one-click approval or correction. Track review decisions to build a feedback dataset for fine-tuning or prompt improvement. Avoid over-redaction by monitoring the false-positive rate—if your system is masking names that are actually product codes or masking dates that are not birthdates, your eval harness should catch this drift before users notice broken agent behavior.
Testing before deployment requires a labeled dataset of tool outputs containing known PII at known positions. Run the prompt against this dataset and measure: recall (did we catch all PII?), precision (did we mask non-PII?), and over-redaction rate (what percentage of masked spans were false positives?). Automate this as a pre-commit or CI check so that prompt changes don't silently degrade detection quality. For streaming tool outputs, buffer the response until complete before running detection—partial outputs can split PII spans across chunks, causing missed detections. If latency is critical, implement a sliding window approach that processes chunks as they arrive but holds back the last N tokens until the next chunk confirms no split entities.
Expected Output Contract
The sanitized output object that the prompt must return. Every field is validated before the masked content re-enters the agent context.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
masked_output | string | Must not contain any substring present in the original [INPUT_TEXT] that matches a detected PII pattern. Length must be > 0. | |
detections | array of objects | Must be a JSON array. Each element must conform to the detection_item schema. Array can be empty if no PII found. | |
detections[].type | enum string | Must be one of the allowed PII types defined in [PII_TYPE_WHITELIST]. No free-text or unknown types allowed. | |
detections[].original | string | Must be an exact, verbatim substring from [INPUT_TEXT]. If not found in source, the detection is invalid and must be discarded. | |
detections[].masked | string | Must match the pattern <[TYPE]:[HASH]> where [TYPE] is the detected type and [HASH] is a SHA-256 hex digest of the original value. | |
detections[].confidence | float | Must be a number between 0.0 and 1.0 inclusive. Values below [CONFIDENCE_THRESHOLD] must be excluded from the detections array. | |
detections[].char_offset | array of two integers | Must contain exactly two integers [start, end] representing the zero-indexed character span in [INPUT_TEXT]. Span must resolve to the exact original string. | |
redaction_summary | object | Must contain keys total_detections (integer), types_found (array of strings), and over_redaction_flag (boolean). total_detections must equal length of detections array. |
Common Failure Modes
PII detection prompts fail in predictable ways that leak sensitive data or break downstream processing. These are the most common failure modes and how to guard against them.
Over-Redaction Destroys Context
What to watch: The prompt masks too aggressively, redacting names, dates, and locations that are not actually PII. This strips essential context from tool outputs, making them useless for the agent's reasoning. Guardrail: Implement a tiered masking strategy with configurable entity types. Test against a golden dataset of non-PII sentences and measure the over-redaction rate. Require a confidence threshold below which entities are preserved rather than masked.
Structured Data Field Leakage
What to watch: The prompt scans free text but misses PII embedded in JSON fields, XML attributes, or nested objects within tool responses. Email addresses inside a metadata field or phone numbers in a notes array pass through unmasked. Guardrail: Require recursive traversal of all string values in structured outputs before PII detection. Validate with test payloads that hide PII at varying nesting depths and in non-obvious field names.
Context Window Truncation Bypass
What to watch: Large tool outputs exceed the detection prompt's context window. The model only scans the first portion and misses PII in truncated sections, producing a false sense of safety. Guardrail: Chunk large outputs with overlapping windows and run detection on each chunk independently. Merge results with deduplication. Set a hard size limit above which tool outputs are rejected rather than partially scanned.
Adversarial Obfuscation Evasion
What to watch: Tool outputs contain deliberately obfuscated PII—split across tokens, encoded in base64, or hidden with zero-width characters. The detection prompt misses these because it relies on surface-level pattern matching. Guardrail: Add a pre-processing step that normalizes Unicode, decodes common encodings, and strips zero-width characters before PII detection. Test against an adversarial eval set with known obfuscation techniques.
Confidence Score Calibration Drift
What to watch: The prompt returns confidence scores that are consistently overconfident on borderline cases. Entities that could be PII or could be benign are classified with high confidence, leading to either leaks or unnecessary redaction with no audit trail. Guardrail: Calibrate confidence scores against a labeled dataset with ambiguous cases. Flag low-confidence detections for human review rather than making automated redaction decisions. Log confidence distributions in production to detect drift.
Redaction Marker Information Leakage
What to watch: The prompt replaces PII with markers like [EMAIL_REDACTED] or [SSN] that reveal the type of data that was present. This metadata leakage can be exploited to infer sensitive attributes about individuals. Guardrail: Use generic redaction tokens like [REDACTED] that do not disclose entity type. If entity type must be preserved for downstream processing, store it in a separate, access-controlled audit log rather than in the agent-visible output.
Evaluation Rubric
Use this rubric to test the PII detection and masking prompt before deploying it in a production agent pipeline. Each criterion targets a specific failure mode observed in tool-output sanitization workflows.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
PII Recall on Standard Dataset |
| Recall below 0.90 on any single PII category; missed SSNs or credit card numbers in structured tool output | Run prompt against labeled PII test set; compute per-category and overall recall; flag categories below threshold |
Over-Redaction Rate | <= 5% of non-PII tokens incorrectly masked across 200 clean tool responses | Over-redaction above 10%; common nouns, product names, or UUIDs incorrectly masked as PII | Feed clean tool outputs with zero PII through prompt; count masked tokens vs total tokens; measure false-positive rate |
Confidence Score Calibration | Mean confidence >= 0.85 for true PII detections; mean confidence <= 0.30 for false detections | High confidence (>0.80) assigned to false positives; low confidence (<0.50) assigned to obvious PII like plain-text emails | Extract confidence scores from prompt output; compute mean confidence for true-positive and false-positive subsets; check separation |
Output Schema Compliance | 100% of outputs parse as valid JSON matching the defined [OUTPUT_SCHEMA] with all required fields present | Missing | Validate 200 prompt outputs against JSON Schema; flag any structural violations or missing required fields |
Masking Consistency | Same PII entity masked identically across repeated occurrences within a single tool output | Email | Insert repeated PII entities in test payloads; verify mask tokens are consistent per entity across the full output |
Boundary Adversarial Robustness | PII adjacent to punctuation, markdown, or code fences is detected with recall >= 0.90 | Email inside parentheses | Construct test cases with PII adjacent to common delimiters, code blocks, and markdown syntax; measure recall on boundary cases |
Non-Latin Script PII Detection | PII in CJK, Cyrillic, or Arabic scripts detected with recall >= 0.85 | Chinese personal name or Russian phone number in tool output not flagged; Latin-only bias in detection | Include non-Latin PII samples in test set; verify detection spans across supported character sets; log script-specific recall |
Latency Budget Compliance | Prompt processes a 4K-token tool output in <= 2 seconds at p95 latency | p95 latency exceeds 5 seconds for typical tool response sizes; timeout errors in production tool pipeline | Benchmark prompt with 100 tool outputs at 1K, 2K, 4K, and 8K token lengths; measure p50 and p95 latency; flag if budget exceeded |
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 small set of PII types (email, phone, SSN). Use a lightweight JSON schema for the output. Skip confidence thresholds initially—just return detected/masked pairs. Run against 20-30 known samples manually.\n\n```\n[SYSTEM]\nYou are a PII detection tool. Detect and mask the following PII types in the tool output: [PII_TYPES].\nReturn JSON with "detected" array and "masked_output" string.\n\n[TOOL_OUTPUT]\n[INPUT]\n```\n\n### Watch for\n- Over-masking common nouns that look like names\n- Missing PII in nested JSON or code blocks\n- No handling of partial matches or truncated values\n- Model refusing to process tool output it misclassifies as user input

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