Inferensys

Prompt

Healthcare PHI Detection and Refusal Prompt

A practical prompt playbook for using Healthcare PHI Detection and Refusal Prompt in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the precise job-to-be-done, ideal user, required context, and critical limitations for the PHI Detection and Refusal prompt.

This prompt is a pre-processing gate for health-tech engineers who must prevent a Large Language Model (LLM) from processing, echoing, or reasoning about Protected Health Information (PHI). Its sole job is to inspect free-text user input—such as clinical notes, patient messages, or medical documents—and return a deterministic, structured detection result. If PHI is identified against the 18 HIPAA Safe Harbor identifiers, the prompt instructs the model to refuse any further engagement with the content. This is not a redaction or de-identification prompt; it is a binary detection-and-refusal boundary that stops the model from touching PHI at all, preventing downstream leakage in summarization, extraction, or agentic workflows.

Use this prompt when your AI pipeline handles unvetted text that may contain PHI and you need a hard refusal layer before any other processing occurs. The ideal user is an engineer integrating an LLM into a healthcare application, a compliance architect designing AI safety guardrails, or a security engineer building a data loss prevention (DLP) control for model inputs. You must provide the raw user input as the [INPUT] variable. The prompt works best as a synchronous check before the input reaches any other prompt, tool, or retrieval step. It is designed for single-turn classification and refusal, not for multi-turn conversations where a user might try to bypass the gate through follow-up rephrasing.

Do not use this prompt as a standalone HIPAA compliance solution. It is a probabilistic defense, not a legal guarantee. It will not catch PHI embedded in images, scanned PDFs, or audio files without a separate OCR or transcription step. It is also not a substitute for data masking or tokenization in your application layer. If your workflow requires using PHI for a legitimate treatment, payment, or operations purpose, this prompt is the wrong tool—you need a secure data handling pipeline with access controls, audit logs, and a Business Associate Agreement (BAA) in place. The next step after reading this section is to review the prompt template, understand its required inputs, and prepare a test suite of PHI-positive and PHI-negative examples to measure its detection accuracy before deployment.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Match the prompt to the problem before embedding it in a production pipeline.

01

Good Fit: Pre-Processing Gate

Use when: you need a deterministic gate before any model generation or storage. The prompt inspects user input or retrieved documents for PHI and refuses to process it further. Guardrail: Place this prompt as the first step in your inference pipeline, before the main agent or RAG chain, to prevent PHI from entering downstream context windows.

02

Bad Fit: De-Identification Pipeline

Avoid when: your goal is to de-identify data for research or analytics. This prompt is designed to detect and refuse, not to transform PHI into safe surrogates. Guardrail: Use a dedicated de-identification or masking prompt for HIPAA Safe Harbor transformation, and keep this prompt for hard-refusal boundaries.

03

Required Inputs

What you need: raw user text, document chunks, or tool outputs that may contain PHI. The prompt also benefits from a defined PHI taxonomy (HIPAA Safe Harbor 18 identifiers) and a clear refusal policy statement. Guardrail: Always pass the full, unredacted text to the prompt for inspection. Pre-redacting input defeats the purpose and creates a false sense of security.

04

Operational Risk: Over-Refusal on Clinical Terms

What to watch: medical terminology, drug names, or dosages can trigger false positives, blocking legitimate clinical decision support. Guardrail: Implement a confidence threshold. Route low-confidence detections to a human review queue instead of hard-refusing. Log all refusals with the specific identifiers that triggered the block for auditability.

05

Operational Risk: Structured Data Blind Spots

What to watch: PHI embedded in JSON, XML, or tabular formats may be missed if the prompt is tuned only for prose. A patient name inside a patientName key is still PHI. Guardrail: Flatten structured data into a canonical text representation before inspection, or use a dedicated structured-field scanner in parallel with this prompt.

06

Operational Risk: Re-Identification via Context

What to watch: the prompt may correctly refuse a direct PHI match but miss a combination of quasi-identifiers (ZIP + age + rare condition) that enables re-identification. Guardrail: Pair this prompt with a statistical re-identification risk check for de-identified outputs. Never rely solely on pattern matching for Safe Harbor compliance.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable system prompt that detects PHI, refuses to process it, and returns a structured safety result for health-tech AI pipelines.

This prompt template is designed to sit at the system level of a health-tech AI application. It instructs the model to inspect every user input and any attached context for protected health information (PHI) as defined by the HIPAA Safe Harbor method. Instead of echoing, summarizing, or reasoning over PHI, the model must refuse to process the request and return a structured JSON object that your application harness can act on—logging the incident, stripping the data, or escalating for human review. The template uses square-bracket placeholders so you can adapt the risk tolerance, the list of identifiers to scan for, and the exact refusal message without rewriting the core logic.

text
You are a privacy-preserving AI assistant operating in a HIPAA-regulated environment. Your primary directive is to prevent the processing, storage, or exposure of Protected Health Information (PHI).

## INPUT
You will receive user input and, optionally, retrieved context. Inspect all text for the 18 HIPAA Safe Harbor identifiers listed below.

[USER_INPUT]
[RETRIEVED_CONTEXT]

## IDENTIFIERS TO DETECT
[PHI_IDENTIFIER_LIST]

## RULES
1. If you detect any direct identifier (names, SSNs, medical record numbers, email addresses, etc.) OR any combination of quasi-identifiers (dates, ZIP codes, ages over 89) that could reasonably re-identify an individual, you MUST refuse to process the request.
2. Do not echo, summarize, translate, or reason about any text that contains PHI.
3. Do not attempt to de-identify the data yourself. De-identification is a separate, audited process.
4. If no PHI is detected, you may proceed with the user's request, but you must still exclude any incidental identifiers from your response.

## OUTPUT SCHEMA
Respond ONLY with a valid JSON object. Do not include any text outside the JSON.
{
  "phi_detected": boolean,
  "identifiers_found": ["string"],
  "refusal_message": "string",
  "risk_level": "[RISK_LEVEL]"
}

## REFUSAL MESSAGE
If phi_detected is true, set refusal_message to: "[REFUSAL_MESSAGE]"

## EXAMPLES
[FEW_SHOT_EXAMPLES]

## CONSTRAINTS
- Do not include any PHI in the identifiers_found array. Use category labels only (e.g., "NAME", "EMAIL", "DATE_OF_BIRTH").
- If you are uncertain whether a data element qualifies as PHI, err on the side of refusal and set risk_level to "HIGH".
- Never output the original user input or context if PHI is detected.

To adapt this template, start by populating [PHI_IDENTIFIER_LIST] with the specific Safe Harbor identifiers relevant to your data. A standard list includes 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 plates, device identifiers and serial numbers, web URLs, IP addresses, biometric identifiers (including finger and voice prints), full-face photographic images and any comparable images, and any other unique identifying number, characteristic, or code. Next, define [RISK_LEVEL] as a static value like "HIGH" or wire it to a dynamic variable from your application's risk scoring system. The [REFUSAL_MESSAGE] should be a user-facing string that explains the refusal without revealing what was detected—for example, "I can't process this request because it appears to contain personal health information. This incident has been logged." Finally, provide 2–3 [FEW_SHOT_EXAMPLES] that show both a clean input (phi_detected: false) and a PHI-positive input with the correct refusal JSON. This template is designed to be the system prompt; do not let user or developer messages override these rules. In your implementation harness, validate that the model's output is parseable JSON and matches the schema before any downstream action.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Healthcare PHI Detection and Refusal Prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Validation notes describe how to verify the input is safe and well-formed before inference.

PlaceholderPurposeExampleValidation Notes

[USER_INPUT]

The full text of the user request or document to be scanned for PHI

Patient Jane Doe MRN 12345 was admitted on 01/15/2024 with chest pain.

Must be a non-empty string. Check for null, empty, or whitespace-only inputs before sending. Log input hash for audit trail.

[PHI_SAFE_HARBOR_LIST]

The 18 HIPAA Safe Harbor identifiers to detect, provided as a structured list for the model to reference

Names, geographic subdivisions smaller than a state, dates (except year) directly related to an individual, telephone 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 plates, 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

Must be a complete list of all 18 identifiers. Validate against the current HIPAA Safe Harbor rule. Do not allow truncated or abbreviated lists. Store as a versioned configuration artifact.

[OUTPUT_SCHEMA]

The strict JSON schema the model must follow for the detection result and refusal response

{"phi_detected": true, "identifiers_found": [{"type": "NAME", "value": "Jane Doe", "position": {"start": 8, "end": 16}}], "safe_harbor_identifiers_triggered": ["Names", "Medical record numbers"], "refusal_message": "I cannot process this request because it contains protected health information (PHI). The following identifier types were detected: Names, Medical record numbers. Please remove all PHI and resubmit.", "redacted_text": "Patient [NAME] MRN [MEDICAL_RECORD_NUMBER] was admitted on [DATE] with chest pain."}

Schema must include required fields: phi_detected (boolean), identifiers_found (array of objects with type, value, position), safe_harbor_identifiers_triggered (array of strings), refusal_message (string), redacted_text (string or null). Validate with JSON Schema validator before use. Reject schemas missing refusal_message field.

[REFUSAL_POLICY]

The organization's policy statement defining when and how to refuse PHI-containing requests

If any of the 18 HIPAA Safe Harbor identifiers are detected in user input, refuse to process the request. Do not echo, summarize, or analyze the PHI. Provide a clear refusal message listing the identifier types detected. Offer a redacted version of the input if safe to do so. Never store or log the original PHI.

Must be a non-empty string with explicit refusal criteria. Policy must reference the 18 Safe Harbor identifiers. Validate that policy does not contain contradictory instructions (e.g., refuse and also summarize). Version and approve through policy governance.

[REDACTION_PLACEHOLDER_MAP]

Mapping of PHI identifier types to their redaction replacement strings

{"NAME": "[NAME]", "DATE": "[DATE]", "MEDICAL_RECORD_NUMBER": "[MEDICAL_RECORD_NUMBER]", "EMAIL": "[EMAIL]", "PHONE": "[PHONE]", "SSN": "[SSN]", "ADDRESS": "[ADDRESS]", "IP_ADDRESS": "[IP_ADDRESS]"}

Must be a valid JSON object mapping each Safe Harbor identifier type to a placeholder string. Placeholders must not resemble real PHI values. Validate that all 18 identifier types have entries. Reject maps that use empty strings or null values as placeholders.

[CONFIDENCE_THRESHOLD]

Minimum confidence score for PHI detection before triggering refusal, as a float between 0.0 and 1.0

0.85

Must be a float between 0.0 and 1.0. Values below 0.7 risk false negatives; values above 0.95 risk false positives. Validate as numeric and in range. Log threshold in audit trail for each request. Consider separate thresholds for high-sensitivity identifiers like SSN.

[MAX_REDACTED_LENGTH]

Maximum character length allowed for the redacted_text field to prevent accidental PHI leakage through verbose redaction

4096

Must be a positive integer. Validate that value does not exceed model context window minus prompt overhead. Set conservatively; redacted text should be minimal. Truncate with warning if exceeded. Log truncation events.

[AUDIT_LOG_ENABLED]

Boolean flag controlling whether detection events are logged for compliance and monitoring

Must be a boolean. When true, ensure audit log destination is configured and writeable before inference. Log must capture: timestamp, input hash, phi_detected result, identifiers_found types (not values), refusal triggered, and prompt version. Never log raw PHI values. Validate log destination connectivity at startup.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the PHI detection prompt into a production application with validation, retries, logging, and human review.

This prompt is designed to be a pre-processing gate in a health-tech pipeline. It should sit between the user's input and any downstream model that might process, store, or summarize clinical text. The primary job of the harness is to call this prompt, parse its structured refusal or detection result, and enforce a hard block before PHI reaches another model, a vector database, or an observability log. Do not treat this as an advisory check—the application must halt processing on a positive detection unless an authorized human reviewer explicitly overrides it.

The recommended implementation pattern is a synchronous validation layer with a strict schema contract. Wrap the prompt call in a function that: (1) sends the user input with the [INPUT] placeholder populated; (2) parses the JSON response against a schema that requires phi_detected (boolean), detected_identifiers (array of objects with type, value, and safe_harbor_match fields), and action (enum of BLOCK, REDACT, or PASS); (3) validates that every detected identifier maps to one of the 18 HIPAA Safe Harbor categories; and (4) logs the detection result to a dedicated audit store that is excluded from model training and general observability pipelines. If the model returns malformed JSON, retry once with a repair prompt that includes the raw output and the expected schema. If the retry also fails, escalate to a human review queue and block the request.

For model choice, prefer a model with strong instruction-following and structured output support, such as gpt-4o or claude-3.5-sonnet, with response_format set to json_object and a JSON schema provided in the [OUTPUT_SCHEMA] placeholder. Set temperature to 0 to minimize variance in detection boundaries. If you are running in a local-first or air-gapped deployment, test open-weight models like llama-3.1-70b against your PHI test suite before committing—smaller models often miss partial identifiers and de-identified re-identification risks. The [RISK_LEVEL] placeholder should be set to high for production, which instructs the prompt to err on the side of blocking ambiguous cases. For lower-stakes internal tooling, you can set it to moderate to reduce false positives, but never set it below moderate when real patient data is possible.

Eval integration is mandatory before production. Build a test harness that runs this prompt against a golden dataset containing: (a) clearly identified PHI with known Safe Harbor categories, (b) de-identified text that should pass, (c) borderline cases like doctor names, hospital names, and dates that could be re-identified when combined, and (d) adversarial inputs that try to hide PHI through character substitution, whitespace manipulation, or clinical jargon embedding. Measure precision, recall, and F1 against the Safe Harbor categories. A recall below 0.98 on known PHI is a release blocker. Also test for over-refusal by running 500 de-identified clinical notes through the prompt and verifying that the false-positive rate stays below 2%. Log every mismatch for human review.

What to avoid: Do not send the raw user input to a logging system, analytics pipeline, or LLM observability tool before this prompt runs. Do not cache the prompt response in a shared context window that could leak PHI across sessions. Do not rely on this prompt alone for HIPAA compliance—it is a technical control that must be paired with access controls, audit trails, BAAs with model providers, and regular security review. If the prompt returns REDACT, your application must perform the redaction before any downstream processing; do not pass the original text and the redaction instruction to another model and trust it to self-censor. Finally, if you are processing high volumes, batch inputs and monitor latency—this prompt should complete in under 2 seconds for inputs under 4,000 tokens; slower responses indicate a need for model routing or prompt compression.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the PHI detection and refusal response. Use this contract to parse, validate, and route model outputs in production.

Field or ElementType or FormatRequiredValidation Rule

phi_detected

boolean

Must be true if any PHI indicator is present; false otherwise. Reject if missing or non-boolean.

phi_indicators

array of strings

Each element must match a HIPAA Safe Harbor identifier category (e.g., 'NAME', 'DATE', 'PHONE', 'SSN', 'EMAIL', 'MEDICAL_RECORD', 'IP_ADDRESS'). Reject if array contains unrecognized categories.

refusal_message

string

Must be non-empty when phi_detected is true. Must not echo or repeat any detected PHI values. Must include a clear statement that processing cannot continue due to PHI presence.

safe_alternative

string or null

Must be null when phi_detected is false. When phi_detected is true, must provide a constructive next step (e.g., 'Please resubmit without patient identifiers' or 'Use de-identified data only'). Must not suggest workarounds that bypass PHI protections.

confidence_score

float between 0.0 and 1.0

Must be present for every response. Score below 0.7 with phi_detected true should trigger human review. Score above 0.3 with phi_detected false should trigger re-scan. Reject if out of range.

scan_timestamp

ISO 8601 UTC string

Must be a valid ISO 8601 datetime in UTC. Used for audit trail. Reject if unparseable or in the future.

re_identification_risk

string enum: LOW, MEDIUM, HIGH, NONE

Must be NONE when phi_detected is false. Must be LOW, MEDIUM, or HIGH when phi_detected is true, based on whether de-identified data could be re-identified when combined with other fields. Reject if invalid enum value.

human_review_required

boolean

Must be true if confidence_score is below 0.7 or re_identification_risk is HIGH. Must be false only when phi_detected is false and confidence_score is above 0.95. Reject if inconsistent with confidence_score or re_identification_risk.

PRACTICAL GUARDRAILS

Common Failure Modes

PHI detection prompts fail in predictable ways that create compliance risk. These are the most common production failure modes and the guardrails that catch them before they reach a user or an audit.

01

De-identified Data Re-identification

What to watch: The model treats a de-identified clinical narrative as safe and echoes it verbatim, but the combination of dates, rare conditions, and demographic fragments allows re-identification. HIPAA Safe Harbor requires removal of all 18 identifiers—not just names. Guardrail: Add a secondary evaluation step that checks the output for quasi-identifier combinations (zip + age + rare diagnosis) before release. Flag any output containing three or more indirect identifiers for human review.

02

PHI in Unstructured Free-Text Fields

What to watch: The prompt correctly catches structured PHI (name, MRN, DOB) but misses PHI embedded in clinician notes, patient messages, or referral letters. Free-text fields are the most common source of undetected PHI in production. Guardrail: Run a regex-based pre-scan for known PHI patterns before the model call, and use the model's detection as a second pass. Combine both signals—if either flags PHI, refuse processing. Never rely on the model alone for unstructured text.

03

Over-Refusal on Benign Clinical Terms

What to watch: The model refuses to process text containing disease names, medication lists, or procedure codes because it confuses clinical terminology with PHI. This blocks legitimate clinical workflows and trains users to bypass the safety system. Guardrail: Maintain an allowlist of clinical terms that are not PHI (condition names, drug classes, procedure types). Test refusal rates against a benchmark of de-identified clinical text and tune the prompt to distinguish clinical data from patient identifiers.

04

Inconsistent Refusal Across Similar Inputs

What to watch: The prompt refuses one instance of a PHI-containing text but processes a nearly identical text with the same PHI presented in a different format (e.g., table vs. narrative, or with slight obfuscation). Inconsistent refusal is a compliance finding in an audit. Guardrail: Build a regression test suite with PHI presented in multiple formats—narrative, JSON, table, image description, and obfuscated variants. Require consistent refusal across all formats before promoting the prompt to production.

05

PHI Leakage Through Safe Alternative Text

What to watch: The prompt correctly refuses to process PHI but generates a safe-alternative response that inadvertently includes the PHI it was supposed to protect (e.g., 'I cannot process John Doe's record from 01/15/2024'). The refusal itself becomes the disclosure. Guardrail: Add an output validation step that scans the refusal response for the same PHI patterns the input detection was supposed to catch. Block any refusal that echoes detected identifiers. Use placeholder-only language in refusal templates.

06

Context Window PHI Persistence

What to watch: In multi-turn conversations, PHI from an earlier refused turn persists in the context window and influences later responses, even after the refusal. The model may reference the PHI in a subsequent turn that passes detection. Guardrail: Implement session-level PHI tracking. Once PHI is detected in a session, flag the entire session as contaminated and apply refusal or redaction to all subsequent turns. Clear or truncate context windows when PHI is detected rather than relying on per-turn detection alone.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Healthcare PHI Detection and Refusal Prompt before production deployment. Each criterion targets a specific failure mode common in HIPAA-regulated AI workflows. Run these tests against a golden dataset of de-identified and PHI-containing clinical text samples.

CriterionPass StandardFailure SignalTest Method

HIPAA Safe Harbor Identifier Recall

Detects all 18 HIPAA Safe Harbor identifiers present in the input with >= 99% recall on a 500-sample test set

A known identifier (e.g., a medical record number or full-face photo description) is missed in the detection output

Run against a labeled dataset of clinical notes containing all 18 identifier types; measure recall per identifier category

De-identified Data Pass-Through

Correctly classifies de-identified text as 'No PHI Detected' with >= 98% specificity on a 200-sample de-identified test set

A de-identified note is flagged as containing PHI, causing unnecessary refusal and workflow blockage

Curate a dataset of de-identified clinical text verified by a HIPAA compliance officer; measure false positive rate

Refusal Consistency

Returns a refusal response for 100% of inputs where PHI is detected, with no PHI echoed in the refusal message itself

The model refuses to process but echoes the detected PHI in the refusal explanation (e.g., 'I cannot process John Doe's record')

Automated scan of refusal outputs for regex-matched PHI patterns; manual review of 50 refusal samples for contextual leakage

Re-identification Risk Blocking

Refuses to process or combine quasi-identifiers when the combination would create re-identification risk (e.g., ZIP + age + gender)

The model processes a request to combine quasi-identifiers from separate de-identified sources without flagging re-identification risk

Test with pairs of de-identified datasets that together meet HIPAA expert determination thresholds for re-identification; verify refusal or warning

Structured Output Schema Compliance

Returns valid JSON matching the defined [OUTPUT_SCHEMA] for 100% of test cases, including when PHI is detected and when it is absent

Output is malformed JSON, missing required fields, or contains free-text refusal outside the schema structure

Schema validation with a JSON Schema validator; check for presence of required fields: detection_result, refusal_message, detected_identifiers

Safe Harbor Identifier Granularity

Correctly categorizes detected identifiers by type (e.g., 'NAME', 'MRN', 'DATE') with >= 95% accuracy on a 200-sample labeled set

A phone number is labeled as 'NAME' or a date is labeled as 'AGE', causing downstream misrouting or incorrect redaction

Confusion matrix analysis comparing predicted identifier type labels against ground-truth labels from a HIPAA compliance expert

Edge Case: Embedded PHI in Unstructured Text

Detects PHI embedded in narrative text, such as 'the patient, a 45-year-old from Springfield, presented with...'

PHI in free-text clinical narratives is missed while structured fields are correctly detected, creating a false sense of safety

Test with 100 clinical narrative snippets containing PHI in prose form; measure recall against structured-field-only baseline

Latency and Timeout Behavior

Completes detection and refusal decision within [LATENCY_BUDGET_MS] milliseconds for 99th percentile of requests

Timeout causes the application to fall through to an unsafe default or to surface raw model output without PHI screening

Load test with 1000 concurrent requests of varying input lengths; measure p50, p95, p99 latency and timeout rate

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base PHI detection prompt and a simple JSON output schema. Use a lightweight test set of 20-30 synthetic clinical notes containing known PHI and de-identified examples. Run the prompt against a frontier model without additional guardrails to establish baseline recall and precision.

Add a [CONFIDENCE] field to the output schema so you can review low-confidence detections manually. Keep refusal language simple: "PHI detected. Processing halted."

Watch for

  • Over-detection of benign medical terms as PHI (e.g., condition names flagged as patient identifiers)
  • Missed PHI in unstructured fields like physician notes or radiology reports
  • Inconsistent JSON structure when multiple PHI types appear in one input
  • No handling of near-miss identifiers (e.g., "the 45-year-old female" without an explicit name)
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.