This prompt is designed for a single, high-stakes job: identifying and extracting the 18 HIPAA Safe Harbor identifiers from unstructured clinical, operational, or patient-generated text before that text enters any downstream AI workflow, model training pipeline, or analytics system. The ideal user is a healthcare compliance architect, a security engineer on a health-tech platform, or an MLOps engineer responsible for the data sanitization layer. The required context is any free-text string that may contain PHI—this includes clinical notes, patient messages, call transcripts, or email bodies. The prompt is not a general-purpose medical NLP tool; it is a focused classification and extraction gate.
Prompt
Protected Health Information (PHI) Extraction Prompt

When to Use This Prompt
Defines the specific job, the ideal user, and the critical constraints for deploying the PHI extraction prompt in a production healthcare AI system.
You should use this prompt when the primary goal is to prevent regulated data from leaking into general-purpose models, logs, or vector databases. It is appropriate as a pre-processing step before RAG indexing, before sending data to an external model API, or as part of an on-premises data loss prevention (DLP) pipeline. The prompt is designed to output a structured, machine-readable JSON object that flags each identifier's presence, location, and a confidence score, making it directly integrable into a redaction or quarantine service. It is not a substitute for a full de-identification pipeline that includes date shifting or synthetic data generation; it is the detection and extraction component.
Do not use this prompt as a clinical decision support tool or to infer medical diagnoses. It is not designed to understand medical context, only to recognize the syntactic and semantic patterns of the 18 identifiers. For ambiguous cases—such as a string of numbers that could be a medical record number or a lab value—the prompt is instructed to flag the finding with low confidence and mark it for human review. Relying on this prompt for automated de-identification without a human-in-the-loop review for low-confidence extractions creates a direct risk of non-compliance with the HIPAA Privacy Rule. The next step is to copy the prompt template and adapt the [CONSTRAINTS] and [OUTPUT_SCHEMA] placeholders to match your specific data model and compliance requirements.
Use Case Fit
Where this prompt works and where it does not. PHI extraction is a high-stakes classification task with zero tolerance for silent failure.
Good Fit: Pre-Processing Pipeline
Use when: you need to sanitize free-text clinical notes, patient messages, or medical transcripts before they enter a general-purpose LLM, vector database, or analytics pipeline. Guardrail: Run extraction as a synchronous gate. Block downstream processing until the PHI redaction or quarantine step completes successfully.
Bad Fit: Standalone De-Identification
Avoid when: you need HIPAA Safe Harbor compliant de-identification as the final output. This prompt extracts identifiers but does not guarantee the resulting text is no longer PHI. Guardrail: Always route extracted identifiers to a deterministic redaction service. Never rely on the prompt alone for compliance.
Required Inputs
What you must provide: Unstructured clinical or administrative text, a defined PHI taxonomy (the 18 HIPAA identifiers), and an output schema specifying entity type, offset, and confidence. Guardrail: Validate input encoding. Malformed UTF-8 or binary blobs will cause silent extraction failures.
Operational Risk: Ambiguous Context
What to watch: Medical terms that overlap with personal names (e.g., 'Parkinson', 'Alzheimer') or geographic locations that are also diseases. Guardrail: Flag all low-confidence extractions for human review. Implement a mandatory review queue for any entity with a confidence score below 0.85.
Operational Risk: Structured Data Leakage
What to watch: PHI embedded in JSON fields, HL7 segments, or DICOM metadata that the prompt may not parse as natural language. Guardrail: Pre-process structured data with a deterministic parser before the prompt. Use the LLM only for unstructured free-text fields.
Operational Risk: Volume and Latency
What to watch: Large clinical documents exceeding the model's context window or causing timeouts in real-time applications. Guardrail: Chunk documents by section or paragraph. Run extraction in parallel on each chunk, then deduplicate and merge results. Set a hard latency budget with a fallback to human review.
Copy-Ready Prompt Template
A reusable prompt template for extracting Protected Health Information (PHI) identifiers from unstructured text, designed for direct adaptation into healthcare compliance pipelines.
The following prompt template is designed to identify the 18 HIPAA Safe Harbor PHI identifiers within a provided text block. It is structured to be dropped directly into an AI pipeline, with square-bracket placeholders for the dynamic inputs your application will provide at runtime. The prompt instructs the model to extract findings into a strict JSON schema, include confidence scores, and flag any ambiguous context for mandatory human review, which is a critical control for healthcare compliance workflows.
textYou are a HIPAA compliance analysis engine. Your task is to extract all instances of the 18 Protected Health Information (PHI) identifiers from the provided text, as defined by the HIPAA Safe Harbor method. INPUT TEXT: [INPUT_TEXT] OUTPUT_SCHEMA: Return a valid JSON object with the following structure. Do not include any text outside the JSON object. { "findings": [ { "phi_type": "String (one of the 18 HIPAA identifiers)", "value": "String (the exact extracted text)", "position": { "start": Integer, "end": Integer }, "confidence": "String (HIGH, MEDIUM, LOW)", "requires_review": Boolean } ], "review_required": Boolean, "review_reason": "String (explain why human review is needed, or null if not required)" } CONSTRAINTS: 1. Extract only identifiers that match the 18 HIPAA Safe Harbor categories: Names; Geographic subdivisions smaller than a State; Dates (except year) directly related to an individual; Phone numbers; Fax numbers; Email addresses; Social Security numbers; Medical record numbers; Health plan beneficiary numbers; Account numbers; Certificate/license numbers; Vehicle identifiers and serial numbers, including license plate numbers; Device identifiers and serial numbers; Web URLs; IP addresses; Biometric identifiers, including finger and voice prints; Full-face photographic images and any comparable images; Any other unique identifying number, characteristic, or code. 2. If a potential identifier is ambiguous (e.g., a name that could be a common word or a non-PHI entity), set confidence to LOW and requires_review to true. 3. Do not extract the year from a date unless it is part of a full date (e.g., month-day-year) directly linked to an individual. 4. If no PHI is found, return an empty findings array and set review_required to false. 5. Set the top-level review_required to true if any finding has requires_review set to true.
To adapt this template for your environment, replace the [INPUT_TEXT] placeholder with the unstructured text your application needs to scan. The OUTPUT_SCHEMA and CONSTRAINTS sections are the core of the prompt's reliability; modify the schema only if your downstream ingestion expects a different JSON shape. The constraints are designed to minimize false positives and enforce the Safe Harbor standard. Before deploying, run this prompt against a golden dataset of de-identified records to calibrate the confidence thresholds and ensure the requires_review flag triggers correctly for ambiguous cases, preventing automated redaction errors.
Prompt Variables
Required inputs for the PHI extraction prompt. Each placeholder must be populated before the prompt is sent to the model. Validate inputs at the application layer before substitution to prevent injection and ensure extraction quality.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[INPUT_TEXT] | The unstructured text to scan for PHI identifiers | Patient John Doe (DOB 05/12/1965) presented with chest pain. MRN 12345678. | Required. Must be a non-empty string. Truncate to model context window minus prompt overhead. Reject binary or base64-encoded payloads at this layer; use document intelligence pipeline upstream. |
[PHI_CATEGORIES] | The subset of 18 HIPAA identifiers to extract | ["patient_name", "date_of_birth", "medical_record_number", "phone_number", "email_address"] | Required. Must be a valid JSON array of strings drawn from the 18 HIPAA safe harbor identifier list. Reject unknown category names. An empty array means no extraction is requested. |
[CONFIDENCE_THRESHOLD] | Minimum confidence score (0.0-1.0) for including a finding in the output | 0.75 | Required. Float between 0.0 and 1.0. Values below 0.5 produce noisy extractions. Values above 0.95 increase false negatives. Default 0.75 for balanced precision-recall. |
[OUTPUT_SCHEMA] | The exact JSON schema the model must conform to for each extracted PHI instance | {"type": "object", "properties": {"category": {"type": "string"}, "value": {"type": "string"}, "confidence": {"type": "number"}, "offset_start": {"type": "integer"}, "offset_end": {"type": "integer"}, "safe_harbor_qualifies": {"type": "boolean"}}, "required": ["category", "value", "confidence", "offset_start", "offset_end"]} | Required. Must be a valid JSON Schema object. Include character offset fields for downstream redaction. Validate schema parseability before prompt assembly. |
[CONTEXT_WINDOW] | Additional context about the document type or clinical setting to improve disambiguation | Emergency department triage note from urban Level 1 trauma center. Contains abbreviated clinical shorthand. | Optional. String or null. Use to disambiguate medical context (clinical note vs. billing record vs. patient portal message). Null allowed. Keep under 200 tokens to preserve extraction space. |
[REDACTION_MODE] | Whether to return extracted values verbatim or redacted placeholders | extract | Required. Enum: extract, redact, or both. extract returns raw PHI values. redact returns [REDACTED] with category label. both returns both forms. Governed by downstream processing permissions. |
[HUMAN_REVIEW_FLAG_CONDITIONS] | Rules for when the model should set a human_review_required flag on a finding | ["confidence < 0.85", "category == 'patient_name' AND value contains only first name", "ambiguous_date_format"] | Required. Array of condition strings the model can evaluate. Use simple boolean expressions referencing confidence, category, and value fields. Null or empty array disables human review flagging. |
Implementation Harness Notes
How to wire the PHI extraction prompt into a production application with validation, human review, and audit logging.
The PHI extraction prompt is not a standalone chatbot interaction—it must be embedded in a controlled pipeline that enforces data handling rules before and after model invocation. The implementation harness should treat the LLM call as one step in a broader compliance workflow. Before the prompt runs, the system should verify that the input source is authorized for PHI processing, log the processing purpose, and ensure the model endpoint meets your HIPAA Business Associate Agreement (BAA) requirements. After the prompt returns, the harness must validate the output schema, apply confidence thresholds, and route ambiguous extractions to human review before any downstream system consumes the results.
Wire the prompt into your application with a structured request wrapper that includes: [INPUT_TEXT] as the raw clinical note or message, [EXTRACTION_MODE] set to strict (safe harbor) or relaxed (flag potential PHI for review), and [CONFIDENCE_THRESHOLD] as a float between 0.0 and 1.0. The model should return a JSON array of extracted PHI objects, each containing phi_type (mapped to the 18 HIPAA identifiers), value, start_char, end_char, confidence, and needs_review (boolean). Implement a post-processing validator that checks: (1) all phi_type values are valid HIPAA identifier categories, (2) character offsets align with the original input text, (3) needs_review is true when confidence falls below your threshold, and (4) no PHI object is missing required fields. Failed validation should trigger a retry with the same prompt and a repair instruction appended, not silent acceptance.
Human review integration is mandatory for any extraction where needs_review is true or where the validator rejects the output after maximum retries. Route these cases to a review queue with the original text, the model's extraction attempt, and the specific validation failure. Log every extraction request and result—including the prompt version, model ID, timestamp, reviewer decision, and final disposition—to an append-only audit store. This audit trail is essential for demonstrating HIPAA compliance during an OCR investigation. Do not send PHI-containing text to non-BAA-covered model endpoints, and never cache PHI inputs or outputs in shared prompt caches unless the cache is explicitly scoped to your compliant environment. For high-throughput pipelines, consider batching non-PHI text through a pre-filter before invoking the extraction prompt to reduce cost and latency on clean inputs.
Common Failure Modes
PHI extraction prompts fail in predictable ways that create regulatory exposure. These cards cover the most common failure modes and the operational guardrails that prevent them from reaching production.
De-Identification Over-Redaction
What to watch: The model aggressively redacts non-PHI terms that resemble identifiers, such as medical record numbers that look like dates, or generic numeric lab values mistaken for phone numbers. This destroys clinical utility and creates false confidence in the redaction pipeline. Guardrail: Implement a two-pass verification where a second prompt reviews redacted spans against the 18 Safe Harbor identifiers, flagging potential over-redaction for human audit before downstream consumption.
Contextual PHI Leakage Through Inference
What to watch: The model misses PHI that requires contextual reasoning, such as a rare disease name that effectively identifies a patient in a small geographic region, or a unique combination of dates and procedures that enables re-identification even after individual fields are redacted. Guardrail: Add a re-identification risk assessment step that evaluates the uniqueness of remaining data combinations against population statistics, and escalate high-risk outputs for human review before release.
Structured Field Extraction Failures
What to watch: The model extracts PHI correctly but places it in the wrong schema fields, such as putting a phone number in the address field or a date of birth in the admission date slot. Downstream systems then fail validation or, worse, process data incorrectly while appearing compliant. Guardrail: Implement schema validation with field-type checks and cross-field consistency rules, and use a retry prompt that shows the specific field mismatch error to the model for correction.
Ambiguous Medical Context Misclassification
What to watch: The model cannot distinguish between a family history mention and a patient's own condition, or between a hypothetical discussion and an actual diagnosis. This leads to both false positives and false negatives in PHI extraction, undermining the reliability of the entire pipeline. Guardrail: Require the model to output a confidence score and a context label for each extracted PHI element, and route low-confidence or ambiguous-context items to a human review queue with the surrounding text for adjudication.
Free-Text Narrative PHI Misses
What to watch: The model reliably extracts structured PHI like dates and names but misses PHI embedded in clinical narratives, such as a physician's note that mentions a patient's employer or a social history that reveals a unique life circumstance. These narrative PHI elements are the most common source of re-identification in de-identified datasets. Guardrail: Use a dedicated narrative PHI detection pass that specifically scans free-text sections for the 18 identifiers in unstructured prose, separate from the structured field extraction pass.
Safe Harbor Standard Drift
What to watch: The model's understanding of the 18 PHI identifiers drifts over time or across model versions, missing newer identifier patterns or applying outdated Safe Harbor interpretations. This creates a false sense of compliance that only surfaces during an audit or breach. Guardrail: Maintain a golden dataset of annotated PHI examples covering all 18 identifiers with edge cases, and run regression tests against this dataset on every prompt or model change before deployment approval.
Evaluation Rubric
Criteria for evaluating PHI extraction quality before production deployment. Use this rubric to build a test harness that catches false negatives, false positives, and ambiguous cases requiring human review.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Safe Harbor Identifier Recall | All 18 HIPAA Safe Harbor identifiers present in the input are extracted with correct type labels | Any Safe Harbor identifier is missing from the output or mislabeled as a non-PHI type | Run against a golden dataset of 100 de-identified records with known PHI spans; require 100% recall on direct identifiers |
Non-PHI Over-Extraction Rate | Fewer than 5% of extracted spans are false positives on non-PHI text | Common numeric patterns, medical codes, or generic dates are incorrectly flagged as PHI | Feed 50 non-PHI clinical narratives; measure precision; flag any extraction of facility names or ages without context |
Ambiguous Context Flagging | Any span where PHI status depends on context is marked with a confidence score below 0.85 and routed for human review | Ambiguous spans are either silently extracted as PHI or silently dropped without review flag | Use 30 borderline examples with mixed PHI/non-PHI context; verify all have confidence < 0.85 and review flag set to true |
De-identification Safe Harbor Compliance | Output after redaction contains zero instances of the 18 identifiers when applied to test records | Redacted output still contains names, dates, SSNs, or geographic subdivisions smaller than state | Apply extraction output to redact 50 known-PHI records; scan redacted text with regex and manual review for residual identifiers |
Structured Output Schema Validity | Every output record conforms to the [OUTPUT_SCHEMA] with all required fields present and correctly typed | Missing fields, null values for required fields, or type mismatches in extracted PHI records | Validate 200 output records against JSON Schema; reject any record that fails schema validation |
Confidence Score Calibration | Extractions with confidence >= 0.95 have precision >= 98% on held-out test data | High-confidence extractions contain false positives above 2% rate | Bin extractions by confidence decile; measure precision per bin; require precision >= 0.98 for top bin |
Cross-Model Consistency | Two different model runs on the same input produce identical PHI type labels for all high-confidence spans | Model A extracts a name where Model B extracts a medical term for the same span | Run 50 inputs through two model variants; compare span-level agreement; require 100% agreement on spans with confidence >= 0.90 |
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
Start with the base prompt and a small set of test notes. Use a frontier model (GPT-4o, Claude 3.5 Sonnet) with default temperature. Focus on extracting the 18 HIPAA identifiers into a flat JSON list without strict schema enforcement.
codeExtract all PHI identifiers from [INPUT_TEXT]. Return JSON with keys matching HIPAA safe harbor categories.
Watch for
- Model missing partial dates or ages over 89
- Confusing medical terms with names (e.g., "Parkinson's" as a person)
- No confidence scoring on ambiguous extractions
- Over-extraction of non-PHI numeric patterns as medical record numbers

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