This prompt is designed for privacy engineers and compliance officers who need to audit retrieval-augmented generation (RAG) traces for a specific, high-risk failure mode: indirect PII exposure. The core job-to-be-done is not to find PII in the user's direct input, but to detect when a system retrieves and surfaces documents containing personal information about individuals who are not the current user. This creates a compliance gap where sensitive data is exposed without the data subject's consent or a legitimate processing purpose tied to the original query. The ideal user has access to production trace data that links a user query to the specific documents retrieved, the final generated output, and metadata about both the user and the source documents.
Prompt
Indirect PII Exposure via Context Audit Prompt

When to Use This Prompt
Define the job, reader, and constraints for the Indirect PII Exposure via Context Audit Prompt.
Use this prompt when you have a trace span that captures the full retrieval-to-generation pipeline and you need to programmatically flag instances where a retrieved document contains a different person's PII. The prompt requires a structured input payload that includes the user's query, the retrieved context chunks, the final model output, and any available user or document metadata. It is not suitable for real-time blocking; its strength is in batch auditing and post-hoc compliance review. Do not use this prompt for direct PII detection in user inputs, for scanning system prompts for hardcoded secrets, or for auditing tool-call arguments. Those scenarios require dedicated, narrower prompts. The output is a structured finding that identifies the exposed individual's category (e.g., 'customer', 'employee', 'public figure'), the source document identifier, the specific PII fields found, and a binary assessment of whether the retrieval was necessary for the task.
The prompt's value is in its ability to distinguish between legitimate multi-person context (e.g., a contract between two companies) and accidental exposure (e.g., a customer support ticket that retrieves another customer's account notes). Before integrating this prompt into a production audit pipeline, you must define clear evaluation criteria. Test it against a golden dataset of traces that includes co-mingled multi-person documents, documents with no PII, and documents where the PII belongs to the current user. Common failure modes include false positives on organization names treated as PII and false negatives when PII is embedded in unstructured text without explicit labels. Always route high-severity findings for human review before taking action on the source documents or retrieval pipeline.
Use Case Fit
Where the Indirect PII Exposure via Context Audit Prompt works, where it fails, and the operational prerequisites for safe deployment.
Good Fit: RAG Pipeline Audits
Use when: You have production traces linking a user query to retrieved documents and a final generated response. This prompt excels at finding PII about non-user individuals hidden in those retrieved context chunks. Guardrail: Ensure your trace captures the full retrieved document text, not just a chunk ID, to allow for deep inspection.
Bad Fit: Real-Time Intervention
Avoid when: You need to block a response from being generated in a live, low-latency application. This prompt is designed for asynchronous, post-hoc audit workflows. Guardrail: For real-time blocking, use a dedicated, lightweight PII detection model or a strict pre-generation filter, and reserve this prompt for offline compliance review.
Required Inputs: Linked Trace Data
What to watch: The prompt will fail or hallucinate if it cannot see the direct link between a retrieval step and the final output. Guardrail: The input must include a structured trace object with user_query, retrieved_documents (with source IDs), and the generated_response. A simple log line is insufficient.
Operational Risk: Co-Mingled Documents
What to watch: A single retrieved document containing PII for multiple people (e.g., a family court filing or a group insurance policy) can cause the model to miss an exposed individual or misattribute the PII. Guardrail: Add a specific instruction to enumerate all distinct individuals found in a document, not just the first one, and cross-reference each against the querying user's identity.
Operational Risk: Necessary vs. Excessive Retrieval
What to watch: The prompt must distinguish between a document that was legitimately necessary to answer the query and one that was retrieved due to poor indexing or over-retrieval, causing unnecessary exposure. Guardrail: The output schema must include a retrieval_necessity field (e.g., "necessary" / "excessive") with a required justification, forcing the model to make this distinction explicit.
Bad Fit: Unstructured Log Files
Avoid when: The only available data is a flat, unstructured log file without clear delineation between user input, retrieval context, and model output. The prompt's accuracy will degrade significantly. Guardrail: Invest in structured tracing (e.g., OpenTelemetry with LLM-specific span attributes) before applying this audit. The prompt's value is directly proportional to the quality of its input structure.
Copy-Ready Prompt Template
A reusable prompt template for auditing retrieval-augmented generation traces to detect indirect PII exposure from context documents.
The following prompt template is designed for privacy engineers who need to systematically audit production RAG traces. It focuses on detecting when retrieved context documents contain personally identifiable information about individuals other than the end user, creating indirect exposure that may violate data minimization principles or privacy policies. The template uses square-bracket placeholders that you must replace with actual trace data, policy definitions, and output schema requirements before execution.
textYou are a privacy audit assistant specialized in detecting indirect PII exposure in retrieval-augmented generation (RAG) traces. Your task is to analyze a production trace and identify whether any retrieved context documents contain personally identifiable information about individuals other than the user who initiated the request. ## INPUT DATA **User Query:** [USER_QUERY] **Retrieved Context Documents:** [DOCUMENTS] **Generated Output:** [GENERATED_OUTPUT] **User Identity Context:** [USER_IDENTITY] ## PII DEFINITIONS Apply the following PII categories when scanning context documents: [PII_CATEGORIES] ## CONSTRAINTS 1. Only flag PII that belongs to individuals OTHER than the user who made the request. Do not flag the user's own information. 2. Distinguish between PII that was necessary for answering the query and PII that was retrieved unnecessarily. 3. If a document contains co-mingled PII for multiple individuals, analyze each individual separately. 4. Consider indirect identifiers that could re-identify an individual when combined (e.g., rare job title + small company + city). 5. Mark findings as FALSE POSITIVE if the apparent PII is actually a placeholder, example value, or synthetic data. 6. If no indirect PII exposure is detected, explicitly state that finding rather than returning an empty result. ## OUTPUT SCHEMA Return a JSON object with this structure: [OUTPUT_SCHEMA] ## ANALYSIS STEPS 1. Identify all individuals mentioned in the retrieved context documents. 2. For each individual, determine whether they are the requesting user or a third party. 3. For each third-party individual, catalog all PII fields present in the context. 4. Assess whether each PII field was necessary for answering the user's query. 5. Identify the document source and retrieval query that surfaced each exposure. 6. Assign a risk level based on the sensitivity and necessity of the exposed data. ## RISK LEVELS [RISK_LEVELS] ## EXAMPLES [EXAMPLES]
To adapt this template for your environment, replace the placeholders with concrete values. [PII_CATEGORIES] should contain your organization's specific PII taxonomy, such as names, email addresses, phone numbers, government identifiers, financial account numbers, health information, and precise geolocation. [OUTPUT_SCHEMA] must define the exact JSON structure your logging or compliance system expects, including fields for exposed_individual_category, document_source, retrieval_query, pii_fields_found, necessity_assessment, and risk_level. [RISK_LEVELS] should map to your incident response tiers, such as CRITICAL for exposed financial or health data, HIGH for contact information combined with other identifiers, MEDIUM for standalone contact information, and LOW for information already publicly available. [EXAMPLES] should include at least one positive case showing indirect exposure, one negative case where all PII belongs to the requesting user, and one edge case with co-mingled multi-person documents. Before deploying this prompt to production, validate it against a golden dataset of annotated traces and establish a human review step for any finding rated CRITICAL or HIGH.
Prompt Variables
Inputs required for the Indirect PII Exposure via Context Audit Prompt. Each variable must be populated from production trace data before the prompt is executed. Validation notes describe how to confirm the input is well-formed and safe to process.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TRACE_ID] | Unique identifier for the production trace being audited. Used for logging and linking findings back to the source. | trace-prod-8a3b-2025-07-11 | Must match the regex ^[a-zA-Z0-9-_]+$. Null not allowed. Verify the trace exists in the observability store before running the audit. |
[USER_ID] | Identifier of the end-user who initiated the request. Used to distinguish the user's own PII from third-party PII in retrieved documents. | user-4f2a1c | Must be a non-empty string. Null allowed only if the trace is from an unauthenticated session. If null, the prompt must treat all detected PII as potentially indirect exposure. |
[RETRIEVED_CONTEXT] | Full text of all documents or chunks retrieved during the RAG step and injected into the context window. This is the primary audit surface. | Document 1 (source: hr_policy_v2): Employee John Smith, ID 88421, started on 2023-01-15... | Must be a non-empty string or structured array of document objects. Validate that the text matches the source documents captured in the trace span. Truncation beyond the model's context window must be logged as a limitation. |
[DOCUMENT_SOURCES] | Mapping of each retrieved document chunk to its origin: index name, document ID, version, and retrieval query that fetched it. | [{"chunk_id": "c7", "source": "hr_policy_v2", "doc_id": "HR-2024-003", "query": "employee onboarding dates"}] | Must be a valid JSON array of objects with chunk_id, source, doc_id, and query fields. Null not allowed. If source metadata is missing from the trace, flag it as incomplete evidence before running the audit. |
[DATA_HANDLING_POLICY] | The organization's policy for what PII categories are permitted in retrieval indices and context windows. Used to judge whether exposure is a violation. | PII categories allowed in retrieval: none. All documents must be de-identified before indexing. | Must be a non-empty string summarizing the policy. If the policy is not codified, use the strictest interpretation: no PII allowed. Validate that the policy text is current and approved by the privacy team. |
[OUTPUT_SCHEMA] | JSON schema that defines the structure of each finding the prompt must produce. Ensures machine-readable results for downstream alerting. | {"type": "object", "properties": {"exposed_individual_category": {"type": "string"}, ...}} | Must be a valid JSON Schema object. Validate that required fields include exposed_individual_category, document_source, pii_type, and retrieval_necessary. Schema must be tested against sample outputs before production use. |
[CONSTRAINTS] | Operational constraints for the audit: maximum findings to return, confidence threshold, and whether to halt on critical findings. | Max findings: 20. Min confidence: 0.7. Halt on critical: true. | Must be a non-empty string or structured object. Validate that max_findings is a positive integer and min_confidence is a float between 0.0 and 1.0. If halt_on_critical is true, ensure the calling system can handle an early termination signal. |
Implementation Harness Notes
How to wire the Indirect PII Exposure via Context Audit Prompt into a production trace review pipeline with validation, logging, and human review gates.
This prompt is designed to operate as a post-retrieval audit step within a RAG trace analysis pipeline, not as a real-time guardrail. It should be invoked after a production trace is captured and the full request context—including the user query, retrieved documents, and final generated output—is available for inspection. The harness must extract the retrieved context documents from the trace span, pass them to the prompt alongside the original user query, and collect the structured finding. Because the prompt detects PII about individuals other than the user, the harness must also supply the authenticated user's identity (e.g., user ID, email, or name) as part of the [USER_IDENTITY] placeholder so the model can distinguish between self-PII and third-party PII.
The implementation should wrap the LLM call in a validation layer that enforces the expected output schema before the finding is written to the audit log. Parse the model's JSON response and validate that each finding object contains the required fields: exposed_individual_category, document_source, pii_type, retrieval_necessary, and risk_level. Reject findings where document_source does not match a document ID present in the trace span. For high-risk findings (risk_level: high or pii_type containing government IDs, financial account numbers, or health data), the harness must automatically create a review ticket and quarantine the trace from analytics dashboards until a human reviewer clears it. Implement a retry loop with a maximum of two retries if the model returns malformed JSON or fails schema validation; on the second failure, log the raw response and escalate to manual review.
Model choice matters for this workflow. Use a model with strong instruction-following and JSON mode support, such as Claude 3.5 Sonnet or GPT-4o, because the task requires careful distinction between the user's own PII and third-party PII embedded in retrieved documents. Avoid smaller or faster models that may conflate the two categories, producing false positives that flood the review queue. If you are processing high volumes of traces, consider batching multiple trace contexts into a single request with an array output schema, but cap batch size at five traces to prevent attention dilution. Log every invocation with the trace ID, model version, prompt version, validation result, and reviewer outcome to maintain an audit trail for compliance reporting. The harness should never automatically redact or modify the source documents based on the model's output—this prompt is for detection and alerting only. Remediation actions, such as removing documents from the retrieval index or updating data handling policies, must be performed out-of-band by authorized personnel after human review.
Expected Output Contract
Defines the structured JSON output schema for the Indirect PII Exposure via Context Audit Prompt. Use this contract to validate the model's response before writing results to a review database or compliance log.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
finding_id | string (UUID v4) | Must be a valid UUID v4 string. Reject if null or malformed. | |
exposure_timestamp | string (ISO 8601) | Must parse as a valid ISO 8601 datetime string. Reject if null or unparseable. | |
trace_span_id | string | Must match the [TRACE_SPAN_ID] input exactly. Reject if missing or mismatched. | |
exposed_individual_category | enum string | Must be one of: 'non-user_individual', 'minor', 'deceased_person', 'public_figure', 'unknown'. Reject if not in the allowed set. | |
pii_type_detected | array of enum strings | Array must contain at least one item. Each item must be from the allowed set: 'name', 'email', 'phone', 'address', 'government_id', 'financial_account', 'health_record', 'biometric', 'online_identifier', 'other'. Reject if empty or contains invalid enums. | |
source_document_id | string | Must match a document identifier present in the [RETRIEVED_CONTEXT] input. Reject if the ID cannot be traced back to the provided context. | |
retrieval_necessary | boolean | Must be a strict boolean (true or false). Reject if string, null, or missing. | |
exposure_risk_level | enum string | Must be one of: 'low', 'medium', 'high', 'critical'. Reject if not in the allowed set. |
Common Failure Modes
Indirect PII exposure through retrieval-augmented context is a subtle failure mode that bypasses standard input/output scanning. These cards cover the most common breaks and how to guard against them before they reach production.
Co-Mingled Multi-Person Documents
What to watch: A retrieved document contains PII for multiple individuals (e.g., a family record, joint account, or group policy). The model surfaces PII about Person B while answering a query about Person A, creating indirect exposure that input-only scanners miss. Guardrail: Add a pre-generation context scrub step that detects multi-subject documents and either redacts non-query-subject PII or flags the retrieval for human review before the model sees it.
Unnecessary Retrieval of Sensitive Context
What to watch: The retriever pulls a document containing PII that is irrelevant to answering the user's query. The model may still reference or leak this data in its response because it appears in the context window. Guardrail: Implement a retrieval necessity check that scores each chunk for relevance to the specific query before injection. Drop chunks below a relevance threshold and log the decision for audit.
PII Surfaced Through Citation or Quote
What to watch: The model faithfully cites or quotes a retrieved passage that contains PII, treating the citation as evidence of thoroughness rather than recognizing the privacy violation. Guardrail: Add an explicit instruction in the system prompt: 'Do not quote or cite any passage containing PII about individuals other than the user. Summarize the relevant information without reproducing identifying details.' Validate with citation-span PII scanning in eval.
Context Window Overflow Masking PII
What to watch: When the context window is full, PII-bearing chunks may be truncated or pushed out, creating inconsistent behavior. Sometimes PII is dropped (good), sometimes it's partially retained in ways that make detection harder. Guardrail: Monitor context-window utilization per request. When utilization exceeds 80%, flag the trace for review and consider chunk-priority scoring that deprioritizes PII-heavy chunks before less-sensitive content.
False Negatives from Structured Field Assumptions
What to watch: Scanners assume PII only appears in labeled fields (name, email, phone) but miss it in free-text notes, meeting transcripts, or document bodies embedded in retrieved context. Guardrail: Run a secondary unstructured-text PII scan across all retrieved context fields, not just schema-defined sensitive columns. Use entity recognition on the full text of each chunk before it reaches the model.
Downstream Logging of Exposed Context
What to watch: The model's output is clean, but the retrieved context containing PII is logged in trace spans, prompt logs, or debugging storage without redaction. The exposure happens in observability infrastructure, not in the user-facing response. Guardrail: Apply the same PII redaction policy to trace storage as to model input/output. Redact retrieved context in logs unless a legal hold or incident investigation requires full retention, and then apply access controls.
Evaluation Rubric
Use this rubric to test the Indirect PII Exposure via Context Audit Prompt before deploying it to production. Each criterion targets a specific failure mode observed in retrieval-augmented traces where context documents contain PII about individuals other than the user.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Co-mingled Document Detection | Prompt identifies PII for all distinct individuals in a document containing multiple people, not just the first detected person. | Output lists only one individual when the document contains PII for two or more distinct people. | Provide a retrieved document with PII for three individuals (e.g., a family insurance claim). Verify the output includes three separate entries with distinct exposed_individual_category values. |
Non-User PII Discrimination | Prompt correctly flags PII for individuals other than the user and suppresses or marks as in-scope PII belonging to the user themselves. | Output flags the user's own PII as an exposure or fails to distinguish between user PII and third-party PII. | Supply a trace where the user's own name and address appear alongside a third party's SSN. Confirm the user's PII is not reported as an exposure while the SSN is. |
Retrieval Necessity Assessment | Prompt accurately classifies whether the retrieved document containing PII was necessary for answering the user's query. | Output marks all PII-containing documents as unnecessary or fails to provide a necessity justification. | Test with two traces: one where a medical record with PHI is essential to answer a treatment question, and one where a bystander's contact details appear in an unrelated document. Verify necessity field is true for the first and false for the second. |
Document Source Attribution | Prompt correctly identifies the source document ID, title, or URI for each exposure finding. | Output omits the source field, returns a null source when trace metadata is present, or attributes PII to the wrong document. | Provide a trace with three retrieved documents, only one of which contains PII. Verify the output source field matches the exact document ID from the trace metadata for that document. |
Structured Output Schema Compliance | Output is valid JSON matching the expected schema with all required fields present and correctly typed. | Output is missing required fields, contains extra untyped fields, or returns malformed JSON that fails schema validation. | Run the prompt against 10 diverse traces and validate each output against the JSON schema. Require 100% schema conformance; any parse failure is an automatic fail. |
False Positive Resistance on Business Data | Prompt does not flag business entity names, office addresses, or corporate contact information as PII exposure. | Output flags a company's general office phone number, a publicly listed business address, or a corporate officer's name as personal PII. | Provide a document containing only corporate contact information (e.g., 'Acme Corp, 123 Business Park, info@acme.com'). Verify the output returns an empty findings array or explicitly classifies these as non-PII. |
Null Context Handling | Prompt returns an empty findings array or a structured indication of no exposure when the retrieved context contains no PII. | Output hallucinates PII findings when the context is clean, or returns an error instead of a valid empty result. | Supply a trace where all retrieved documents are public policy pages with no personal data. Verify the output is valid JSON with zero findings and no hallucinated entries. |
Multi-Turn Context Boundary Respect | Prompt only evaluates PII in the retrieved context documents from the current trace span, not from prior conversation turns or system prompts. | Output flags PII from the user's prior messages or the system prompt as if it were retrieved document exposure. | Provide a multi-turn trace where the user mentioned their own email in a prior turn, and the current turn's retrieved documents are clean. Verify the output does not flag the user's prior-turn email as an exposure. |
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
Use the base prompt with a single trace sample and manual review. Drop the strict JSON schema in favor of a structured markdown table. Focus on detecting obvious PII categories (names, emails, phone numbers) without worrying about co-mingled multi-person documents.
Prompt modification
Replace [OUTPUT_SCHEMA] with: Return findings as a markdown table with columns: Finding ID, Exposed Individual Category, Document Source, PII Type, Risk Level.
Watch for
- False positives on organization names that look like person names
- Missing indirect exposure when the retrieved document mentions a third party in passing
- No distinction between the user's own PII and third-party PII

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