This prompt is designed for ML teams who need to audit existing fine-tuning datasets, pre-training corpora, or any text collection for personally identifiable information (PII) before it is used for model training or retraining. It is a retrospective scan, meaning the data already exists and you need to find contamination, not prevent it at generation time. Use this when you inherit a dataset, aggregate data from multiple sources, or prepare a compliance review before a training run. The prompt instructs the model to act as a data hygiene auditor, scanning each provided sample for common PII categories, assigning a contamination severity score, and recommending a remediation action. It supports batch processing by accepting multiple records in a structured input format.
Prompt
Model Training Data PII Retrospective Scan Prompt Template

When to Use This Prompt
Understand the specific job, ideal user, and operational boundaries for the retrospective PII scan prompt before integrating it into your training data pipeline.
This is not a real-time output guard or a replacement for deterministic PII detection libraries. Do not use this prompt on live user traffic, streaming model outputs, or in any latency-sensitive path. It is a pre-training data quality and compliance gate, best run as an offline batch job over static datasets. The prompt is most effective when paired with a validation layer that checks the output schema and a human review step for high-severity findings. For production output sanitization, use the sibling PII Detection and Redaction Prompt Template instead.
Before using this prompt, ensure you have a clear inventory of the data sources to be scanned, a defined PII taxonomy that matches your regulatory obligations, and a remediation playbook that specifies what happens to contaminated records (e.g., redaction, deletion, quarantine). The prompt assumes you can provide records in a structured batch format with unique identifiers. If your data is in raw documents, PDFs, or unstructured logs, pre-process it into the expected input schema first. After running the scan, always review high-severity findings manually and log all remediation actions for auditability.
Use Case Fit
Where this prompt works, where it fails, and the operational prerequisites for running a PII retrospective scan on training data at scale.
Good Fit: Pre-Training Dataset Audits
Use when: you are preparing a fine-tuning dataset or curating a pre-training corpus and need to identify inadvertently included PII before training begins. Guardrail: Run this scan as a mandatory gate in your data preparation pipeline, blocking contaminated samples from reaching the training job.
Bad Fit: Real-Time Inference Guarding
Avoid when: you need to catch PII in streaming model outputs with sub-second latency. This template is designed for batch retrospective analysis, not token-by-token streaming redaction. Guardrail: Use a streaming PII guard prompt for real-time use cases and reserve this scan for offline dataset hygiene.
Required Inputs
What you must provide: a representative sample or full dataset of training texts, a defined PII taxonomy (names, emails, SSNs, etc.), and a remediation strategy (redact, quarantine, or flag). Guardrail: Without a clear taxonomy, the model will over-flag or miss categories. Define your PII classes explicitly in the prompt's [PII_CATEGORIES] variable.
Operational Risk: High-Volume False Positives
What to watch: scanning millions of records can produce a flood of false positives, overwhelming review queues and eroding trust in the pipeline. Guardrail: Implement a confidence threshold and route low-confidence detections to a human review sample rather than auto-redacting everything.
Operational Risk: Contextual PII Misses
What to watch: the model may miss PII embedded in code comments, log traces, or concatenated strings that don't match standard formats. Guardrail: Combine this prompt with regex-based pre-scanning for known patterns (credit cards, API keys) and use the LLM scan as a second pass for contextual disambiguation.
Scale Consideration: Batch Processing
What to watch: processing a full training corpus through a single prompt context will hit token limits and increase latency. Guardrail: Chunk the dataset into manageable batches, run parallel scans, and aggregate results with deduplication logic to avoid re-reviewing the same sample multiple times.
Copy-Ready Prompt Template
A reusable prompt with square-bracket placeholders for scanning training datasets for PII before model training or fine-tuning.
This prompt template is designed for ML teams auditing fine-tuning datasets and training corpora. It scans existing records for inadvertently included PII—such as names, emails, phone numbers, and credentials—before training or retraining. The template is structured for batch processing: you can iterate over a dataset, feed each record into the prompt, and collect structured findings for remediation. The output includes a per-record risk classification, a list of detected PII instances with character offsets, and a recommended remediation action. This is not a real-time guard; it is a retrospective scan meant to run offline over static datasets.
textYou are a PII detection specialist auditing a training dataset before model fine-tuning. Your task is to scan the provided [RECORD] for personally identifiable information (PII), credentials, and other sensitive data that should not be included in training corpora. ## Input [RECORD] ## Detection Categories Scan for the following categories and sub-types: - **Direct Identifiers**: full names, email addresses, physical addresses, phone numbers, government IDs (SSN, passport, driver's license), dates of birth. - **Credentials and Secrets**: API keys, passwords, tokens, connection strings, private keys. - **Financial Data**: credit card numbers, bank account numbers, routing numbers. - **Protected Health Information**: medical record numbers, patient IDs, diagnosis codes linked to individuals. - **Network Identifiers**: internal IP addresses, hostnames, URLs with embedded credentials. - **Contextual PII**: combinations of quasi-identifiers (e.g., ZIP + birthdate + gender) that could re-identify individuals. ## Output Schema Return a valid JSON object with this exact structure: { "record_index": [RECORD_INDEX], "risk_level": "high" | "medium" | "low" | "none", "findings": [ { "category": "[CATEGORY]", "sub_type": "[SUB_TYPE]", "value": "[DETECTED_VALUE]", "char_offset_start": [INTEGER], "char_offset_end": [INTEGER], "confidence": 0.0-1.0, "is_false_positive_likely": true | false, "remediation": "redact" | "mask" | "remove_record" | "quarantine" | "review" } ], "summary": "[ONE_SENTENCE_SUMMARY]" } ## Constraints - Only report findings with confidence >= [CONFIDENCE_THRESHOLD]. - If no PII is detected, return an empty `findings` array and risk_level "none". - Do not hallucinate findings. If a string looks like PII but you are uncertain, set `is_false_positive_likely` to true and `remediation` to "review". - For test or example data (e.g., "123-45-6789" in documentation), flag it but set `is_false_positive_likely` to true. - Preserve the original record content; do not modify it in your response. ## Examples [EXAMPLES] ## Risk Level Definitions - **high**: Contains direct identifiers or credentials that could cause harm if exposed. - **medium**: Contains quasi-identifiers or contextual PII that could contribute to re-identification. - **low**: Contains only benign personal references unlikely to cause harm (e.g., public figures, test data). - **none**: No PII detected.
To adapt this template, replace the square-bracket placeholders with your actual values. [RECORD] should be a single training example as a string. [RECORD_INDEX] is the row number or ID for traceability. [CONFIDENCE_THRESHOLD] should be a float between 0.0 and 1.0—start at 0.7 and adjust based on your false positive tolerance. [EXAMPLES] should contain 2-4 few-shot examples showing correct output format for both clean and contaminated records. If your dataset contains domain-specific PII (e.g., proprietary customer IDs), add those categories to the Detection Categories list. For batch processing, wrap this prompt in a script that iterates over your dataset, collects all findings into a remediation report, and quarantines high-risk records before training begins. Always run this scan offline on a static dataset snapshot, not on live production data streams.
Before running this prompt at scale, validate the output schema with a small sample of 50-100 records that include known PII and known clean records. Measure recall (did you catch the known PII?) and precision (did you flag clean records?). If false positives exceed 10%, raise the confidence threshold or add negative examples to [EXAMPLES]. For high-risk datasets—healthcare, finance, or customer support logs—require human review of all high and medium risk findings before remediation. Never rely solely on this prompt for compliance; it is a detection aid, not a legal safeguard. After remediation, re-run the scan to verify that redacted records now return risk_level: "none".
Prompt Variables
Inputs the prompt needs to work reliably. Validate these before sending the request.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[DATASET_SAMPLE] | The raw text or JSON record from the training dataset to scan for PII. | {"id": "rec-001", "text": "Patient John Doe, MRN 12345, admitted on 01/15/2024."} | Must be a non-empty string or valid JSON object. Reject if null or undefined. |
[PII_CATEGORIES] | A list of PII types to detect, aligned with the compliance framework in use. | ["PERSON_NAME", "MEDICAL_RECORD_NUMBER", "DATE", "EMAIL_ADDRESS"] | Must be a valid JSON array of strings. Validate against an allowed enum list. Reject unknown categories. |
[COMPLIANCE_FRAMEWORK] | The regulatory standard governing the scan rules and remediation actions. | "HIPAA_SAFE_HARBOR" | Must be a string from a predefined set: HIPAA_SAFE_HARBOR, GDPR, PCI_DSS, CCPA. Reject on mismatch. |
[CONTEXT_WINDOW_SIZE] | The number of tokens or characters of surrounding context to include in the flagged sample report. | 200 | Must be a positive integer. Default to 100 if not provided. Clamp to a maximum of 500 to avoid oversized reports. |
[CONFIDENCE_THRESHOLD] | The minimum confidence score (0.0 to 1.0) for a PII detection to be included in the output. | 0.85 | Must be a float between 0.0 and 1.0. Default to 0.8. A lower threshold increases recall but may increase false positives. |
[REMEDIATION_ACTION] | The instruction for handling a contaminated sample: REDACT, PSEUDONYMIZE, FLAG_FOR_REVIEW, or DELETE. | "FLAG_FOR_REVIEW" | Must be a string from the allowed action set. REDACT and DELETE are destructive; require explicit confirmation in high-risk environments. |
[OUTPUT_FORMAT] | The desired structure for the scan report. | "JSON_LINES" | Must be a string: JSON_LINES, CSV, or JSON_ARRAY. Validate before processing. JSON_LINES is preferred for streaming large datasets. |
[BATCH_SIZE] | The number of records to process in a single prompt call to balance throughput and context limits. | 50 | Must be a positive integer. Validate against the model's context window. A batch that is too large may cause truncation; too small increases API cost. |
Implementation Harness Notes
How to wire the PII retrospective scan prompt into a batch MLOps pipeline with validation, retries, and audit logging.
This prompt is designed as a batch processing step, not a one-off chat interaction. You will feed it individual training samples—text strings, JSON records, or conversation turns—from a fine-tuning dataset or pre-training corpus. The prompt returns a structured JSON verdict per sample: a PII detection flag, a list of found PII types with character offsets, a confidence score, and a remediation recommendation. The application layer is responsible for iterating over the dataset, calling the model for each sample, collecting results, and deciding what to quarantine, redact, or discard.
Build the harness around a retryable, idempotent processing loop. For each sample, store a unique sample_id before calling the model. On a malformed JSON response, retry up to two times with a repair prompt that includes the raw output and the expected schema. If the model returns a valid JSON payload but the confidence field is below your threshold (e.g., < 0.85), route that sample to a human review queue rather than auto-redacting. Log every decision—sample ID, model response, retry count, final action—to an audit table. For high-compliance datasets (healthcare, finance), require a second reviewer sign-off on any sample flagged for PII before it is removed from the training set.
Model choice matters. Use a model with strong instruction-following and JSON mode support (GPT-4o, Claude 3.5 Sonnet, or equivalent). Avoid smaller open-weight models for this task unless you have calibrated their PII recall against a labeled test set. If your dataset is large, batch samples into groups of 50–100 and process them concurrently with rate limiting. Do not send the entire dataset in a single prompt context—the model will miss PII in long contexts and hallucinate offsets. Wire the output into your data versioning system (DVC, Pachyderm, or a feature store) so that the scanned, redacted dataset is tracked as a new artifact with a clear provenance link to the scan results.
Expected Output Contract
Fields, format, and validation rules for the model's response when performing a PII retrospective scan on training data. Use this contract to parse and validate the output before downstream remediation.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
scan_id | string (UUID v4) | Must be a valid UUID v4 string. Reject if missing or malformed. | |
sample_index | integer | Must be a non-negative integer corresponding to the input sample's position in the batch. Reject if null or negative. | |
pii_detected | boolean | Must be true or false. If true, the findings array must contain at least one object. | |
findings | array of objects | Must be a valid JSON array. If pii_detected is false, this array must be empty. Each object must conform to the finding_object schema. | |
findings[].category | string (enum) | Must be one of: [EMAIL, PHONE, SSN, CREDIT_CARD, PERSON_NAME, ADDRESS, IP_ADDRESS, API_KEY, MEDICAL_RECORD, PASSWORD, OTHER]. Reject if value is not in the enum. | |
findings[].value_snippet | string | Must be a non-empty string containing the detected PII substring as it appears in the sample. Length must be <= 200 characters. | |
findings[].confidence | number (float) | Must be a float between 0.0 and 1.0 inclusive. Values below 0.7 should be flagged for human review. | |
remediation_action | string (enum) | Must be one of: [REDACT, MASK, DELETE_SAMPLE, QUARANTINE, NO_ACTION]. If pii_detected is false, this must be NO_ACTION. |
Common Failure Modes
Production failures that derail PII retrospective scans and how to prevent them before they contaminate training pipelines.
Pattern-Match Over-Reliance Misses Contextual PII
What to watch: Regex-only scans flag test SSNs and sample credit card numbers while missing PII embedded in prose, concatenated fields, or non-standard formats. Guardrail: Layer regex pre-filters with an LLM disambiguation pass that evaluates surrounding context and flags borderline cases for human review.
Batch Boundary Truncation Splits PII Tokens
What to watch: Fixed-window chunking cuts PII entities in half across batch boundaries, causing both halves to evade detection. Guardrail: Implement overlapping windows with entity-aware segmentation and merge partial detections at batch boundaries before final redaction decisions.
Remediation Overwrites Destroy Audit Trail
What to watch: Automated redaction replaces PII in-place without logging original values, making it impossible to verify completeness or recover from over-redaction. Guardrail: Produce a sidecar audit log mapping each redaction to its original sample ID, field path, and detection method before any destructive write.
Multi-Language PII Evasion in Unicode Payloads
What to watch: Scanners tuned for Latin-script names and addresses miss PII in CJK, Cyrillic, Arabic, or right-to-left scripts that appear in multilingual training corpora. Guardrail: Include locale-specific entity recognizers and Unicode-aware normalization before scanning, with per-language recall tests in the eval suite.
False Positives Trigger Over-Redaction and Data Loss
What to watch: Aggressive redaction rules strip benign strings that resemble PII patterns, removing useful training signal and degrading model performance on legitimate content. Guardrail: Apply confidence thresholds with a three-tier action policy—auto-redact above 0.95, queue for review between 0.7 and 0.95, and retain below 0.7 with optional masking.
Scan Exhaustion on Large-Scale Training Corpora
What to watch: Full-corpus scans time out or exhaust rate limits on billion-token datasets, leaving unreviewed segments that silently enter training. Guardrail: Implement stratified sampling with progressive scan escalation—fast regex pass on full corpus, LLM review on flagged samples, and full rescan only on high-risk strata.
Evaluation Rubric
How to test output quality before shipping this prompt into your dataset audit pipeline. Run these checks on a labeled golden dataset.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
PII Recall |
| Any known PII sample in the golden set is not flagged in the output | Automated comparison of flagged spans against labeled ground truth spans using exact and partial match scoring |
PII Precision |
| More than 10% of flagged spans are benign strings incorrectly marked as PII | Manual review of 50 randomly sampled flagged spans from a clean dataset containing no real PII |
Category Classification Accuracy |
| Detected PII is assigned an incorrect category in more than 5% of cases | Compare output category labels against golden dataset labels for each detected span |
Remediation Recommendation Quality |
| Remediation suggests deletion when masking would suffice, or vice versa, in more than 10% of cases | Manual review of remediation suggestions for 50 contaminated samples by a security engineer |
Batch Processing Completeness | 100% of input records appear in the output with a scan result; no dropped records | Output record count does not match input record count | Assert output array length equals input array length in automated test |
Output Schema Compliance | 100% of output records conform to the defined output schema with all required fields present | Missing required fields, extra fields, or type mismatches in any output record | Validate entire output payload against the JSON Schema definition programmatically |
False Negative on Edge Cases | Zero false negatives on obfuscated PII variants in the edge-case test set | PII with separator characters, mixed encodings, or partial redaction is missed | Run prompt against a curated edge-case dataset of 50 obfuscated PII samples and verify all are detected |
Latency and Token Efficiency | Average processing time under 2 seconds per record; output tokens within 3x of input tokens | Processing time exceeds 5 seconds per record or output token count exceeds 5x input token count | Measure wall-clock time and token usage across a batch of 100 records and compute averages |
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 small sample of [TRAINING_DATA_SAMPLE] and lighter validation. Focus on recall over precision. Accept the model's native output format without strict schema enforcement.
Watch for
- Over-redaction of benign strings that match PII patterns (e.g., test SSNs, placeholder emails)
- Missing structured remediation recommendations
- No confidence scoring on redaction decisions

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