We built a HIPAA compliant AI chat for a multi clinic provider. The model helps staff answer operational questions and draft patient friendly messages without ever seeing raw PHI. Auditors reviewed the design and the logs. Here is the exact approach that worked, where it broke, and what we would change.
The constraints that matter
We set four non negotiables:
- No raw PHI goes to the model. Redact before prompt, rehydrate after response only for the UI.
- Context is bounded and predictable. No accidental transcript dump. Keep at least 20 percent headroom under model limits.
- Audit logs are complete, structured, and do not contain PHI. Retain immutably.
- BAA in place for every processor that might touch PHI. We still do redaction so the model does not see PHI at all.
Two practical notes:
- Regulators ask how you guarantee no PHI in prompts. Pattern only NER misses things. We combine deterministic patterns with a patient context dictionary. This lifted recall.
- Auditors care about proof. We linked design controls to logs. That is where a targeted architecture review saved time.
If you need help scoping the HIPAA surfaces and system boundaries, read our AWS specific checklist in AWS integration and HIPAA compliance, and if you want a partner to design this with you, our HIPAA systems team has templates for the controls described below.
The data flow that kept PHI out of prompts
This is the flow we shipped:
-
Chat UI collects input. It never sends full EHR objects. It sends free text and a small patient context stub with fields the agent is allowed to use.
-
API gateway attaches request ID and tenant ID. We reject any payload with fields outside the allowed schema.
-
PHI detector runs on the server. We replace PHI with stable tokens. We create a per request entity map in a short lived store.
-
Retrieval happens on de identified knowledge only. Our vector store never contains PHI. We gate retrieval by topic and role.
-
Prompt builder assembles system and user messages with strict size limits. We trim or refuse if limits are exceeded.
-
We call an LLM endpoint with a BAA and still only send redacted text. For AWS this was Bedrock. For Azure this would be OpenAI through Azure with HIPAA claims.
-
We rehydrate only in the presentation layer, and only the minimum fields. The model response and all logs remain redacted.
-
We write two records. A transcript for the product team with redacted content, and an immutable audit event with metadata only.
The first three steps are where most teams leak. We treat patient context as a dictionary for the redactor, not as content for the model. That avoids name leaks like Dear John in prompts.
Redaction that actually holds up
The redactor combines three sources:
- Deterministic patterns for phone, email, SSN like identifiers, dates.
- A dictionary from the patient context stub. We only include fields that are allowed for the current feature.
- A lightweight NER pass for addresses and names to catch edge phrasing. We run this locally and never trust it alone.
We generate tokens with an HMAC of the raw value and a rotation key. The token looks like [[PHI:field:hash]]. The hash is stable for a rotation period, which lets us cache and test, without exposing the raw value. We never store the raw value in logs. The per request entity map is in memory or Redis with a 15 minute TTL.
Here is a trimmed TypeScript example that shows the key parts. It redacts, enforces context limits, calls Bedrock, and rehydrates for the UI.
import express from 'express';
import crypto from 'crypto';
import { BedrockRuntimeClient, InvokeModelCommand } from '@aws-sdk/client-bedrock-runtime';
// Config
const bedrock = new BedrockRuntimeClient({ region: process.env.AWS_REGION || 'us-east-1' });
const MODEL_ID = process.env.MODEL_ID || 'anthropic.claude-3-5-sonnet-20241022-v2:0';
const CONTEXT_LIMIT_TOKENS = 6000; // keep ~20 percent headroom under an 8k model
const HMAC_KEY = process.env.REDACTION_HMAC_KEY || crypto.randomBytes(32).toString('hex');
// Very rough token counter. Replace with a proper tokenizer for prod.
function estimateTokens(s: string): number { return Math.ceil(s.length / 4); }
type Entity = { field: string; raw: string; token: string };
function hmacToken(field: string, raw: string): string {
const h = crypto.createHmac('sha256', HMAC_KEY).update(`${field}|${raw}`).digest('hex').slice(0, 10);
return `[[PHI:${field}:${h}]]`;
}
function buildDictionary(patientCtx: any): Record<string, string[]> {
const dict: Record<string, string[]> = {};
if (!patientCtx) return dict;
// Only allow whitelisted fields for this feature
const allow = ['firstName', 'lastName', 'dob', 'mrn'];
for (const k of allow) {
if (!patientCtx[k]) continue;
const v = String(patientCtx[k]).trim();
if (!v) continue;
const field = k.toLowerCase();
dict[field] = dict[field] || [];
dict[field].push(v);
if (field === 'firstName' || field === 'lastName') {
// add naive lowercase variant
dict[field].push(v.toLowerCase());
}
}
return dict;
}
function redact(text: string, dict: Record<string, string[]>): { redacted: string; entities: Entity[] } {
let out = text;
const entities: Entity[] = [];
const patterns: { field: string; re: RegExp }[] = [
{ field: 'email', re: /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi },
{ field: 'phone', re: /(\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}/g },
{ field: 'ssn', re: /\b\d{3}-?\d{2}-?\d{4}\b/g },
{ field: 'dob', re: /\b\d{4}-\d{2}-\d{2}\b/g }, // ISO date
{ field: 'mrn', re: /\bMRN[:\s]*[A-Za-z0-9-]+\b/gi },
];
// Pattern based
for (const { field, re } of patterns) {
out = out.replace(re, (m) => {
const token = hmacToken(field, m);
entities.push({ field, raw: m, token });
return token;
});
}
// Dictionary based
for (const field of Object.keys(dict)) {
for (const raw of dict[field]) {
if (!raw) continue;
const esc = raw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const re = new RegExp(`\\b${esc}\\b`, 'gi');
out = out.replace(re, (m) => {
const token = hmacToken(field, m);
entities.push({ field, raw: m, token });
return token;
});
}
}
return { redacted: out, entities };
}
function enforceContextLimit(messages: { role: 'system' | 'user' | 'assistant'; content: string }[], maxTokens: number) {
// Trim oldest user turns until under limit.
while (true) {
const total = estimateTokens(messages.map(m => m.content).join('\n'));
if (total <= maxTokens) return;
// drop the oldest user message that is not system
const idx = messages.findIndex(m => m.role === 'user');
if (idx === -1) throw new Error('Cannot trim further without removing system prompt');
messages.splice(idx, 1);
}
}
async function callClaude(messages: { role: string; content: string }[]) {
const body = {
anthropic_version: 'bedrock-2023-05-31',
max_tokens: 1000,
messages,
system: 'You are a helpful assistant for clinic staff. Never invent PHI. If asked for PHI, refuse.',
};
const cmd = new InvokeModelCommand({
modelId: MODEL_ID,
contentType: 'application/json',
accept: 'application/json',
body: JSON.stringify(body),
});
const res = await bedrock.send(cmd);
const json = JSON.parse(new TextDecoder().decode(res.body));
const text = json.content?.map((c: any) => c.text).join('\n') || '';
return text;
}
function rehydrate(text: string, entities: Entity[], allowFields: Set<string>): string {
let out = text;
for (const e of entities) {
if (!allowFields.has(e.field)) continue; // strict allowlist for UI
const re = new RegExp(e.token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g');
out = out.replace(re, e.raw);
}
return out;
}
const app = express();
app.use(express.json());
app.post('/chat', async (req, res) => {
const requestId = crypto.randomUUID();
const { text, patientCtx } = req.body || {};
if (typeof text !== 'string') return res.status(400).json({ error: 'text required' });
const dict = buildDictionary(patientCtx);
const { redacted, entities } = redact(text, dict);
const messages = [
{ role: 'user', content: redacted }
];
enforceContextLimit(messages, CONTEXT_LIMIT_TOKENS);
const start = Date.now();
const llm = await callClaude(messages);
const latencyMs = Date.now() - start;
// UI can reveal a subset, logs stay redacted
const uiAllowed = new Set(['firstName', 'lastName']); // keep this tight
const uiText = rehydrate(llm, entities, uiAllowed);
// Structured audit event without PHI
console.log(JSON.stringify({
event: 'chat_inference', requestId, modelId: MODEL_ID,
redaction: { tokensInserted: entities.length },
inputTokens: estimateTokens(redacted), outputTokens: estimateTokens(llm),
latencyMs
}));
res.json({ requestId, message: uiText, redactedMessage: llm });
});
app.listen(3000, () => console.log('HIPAA-safe chat proxy on 3000'));
This is not complete production code, but the pieces that matter are there. Note a few details that auditors liked:
- Tokens are stable within a rotation key, which makes testing deterministic. We rotate monthly and maintain two keys briefly for overlap.
- Logs have counts, not content. They can prove redaction ran. Include per field counts in your own system.
- The allowlist in rehydrate is tight. UI does not automatically restore every token.
If you need an integration pattern that fits your stack, we keep small glue services for this in our AI integration work. The shape is the same in Python or Go.
Context limits that prevent accidental disclosure
We saw three context leak patterns in review:
- Prompt builders that naively include the last N turns, which can include previous patient details.
- RAG that pulls a long de identified policy and still exceeds model limits, then the client library silently truncates at the end where your guardrails sit.
- Agents that add a tool status dump with large internal state.
Controls that worked in practice:
- Hard token ceilings with 20 percent headroom. Refuse if over limit. Do not rely on provider side truncation.
- Role based retrieval. We tag documents by use case and role. A scheduling agent cannot pull clinical guidance.
- System prompt caps at 800 tokens for 8k models and 4k for 32k models. It forces concise guardrails and leaves room for inputs.
- Separate memory stores per tenant and per agent. No cross agent bleed.
If you embed RAG, embed only de identified knowledge. We removed patient free text from the embedding corpus and replaced it with normalized intent labels. That killed the top source of accidental PHI echoes.
Transcript handling and storage boundaries
We split storage into three buckets with different controls:
- Redacted chat transcripts for product analytics. These are encrypted at rest, row level access per tenant, 30 day TTL in lower environments, 180 days in prod.
- PHI maps, which are short lived. In Redis with 15 minute TTL. They never leave the VPC. No backups.
- Audit events, which are immutable. Written to S3 with Object Lock Governance, 6 year retention. Daily Athena queries prove completeness.
Each store has a different IAM role. Only the chat proxy can access the PHI map. Our data warehouse cannot. That boundary simplifies controls and audit.
A basic S3 setup we used:
- Bucket with Object Lock enabled and retention rules per prefix. Logs go to logs prefix.
- Write via a role with PutObject and PutObjectRetention. No DeleteObject.
- Access logs enabled to a separate bucket. We alarm on unexpected principals.
We keep an internal data catalog that marks every column containing PHI or derived data. Derived means you can reconstruct PHI by joining. That catalog feeds automated checks in CI.
Audit trails that pass review
What auditors asked for:
- Evidence that every inference request went through the redactor.
- Evidence that the model never saw raw PHI.
- Who accessed what, when, and why. Including failures and refusals.
- Retention controls and proofs of immutability.
What we logged per request:
- requestId, tenantId, userId, agentId, modelId, region
- redactionStats, like counts by field and boolean redactedAny
- token counts input and output, latencyMs, status
- allowlist used for UI rehydration
- hash of sessionId using HMAC, so we can correlate without exposing the ID
Example line:
{"ts":"2025-02-10T14:03:12.112Z","event":"chat_inference","requestId":"a2f...","tenantId":"t-19","agentId":"scheduling","modelId":"anthropic.claude-3-5-sonnet-20241022-v2:0","region":"us-east-1","redaction":{"byField":{"email":1,"phone":0,"dob":1},"tokensInserted":2,"redactedAny":true},"inputTokens":312,"outputTokens":141,"latencyMs":892,"uiAllow":["firstName","lastName"],"sessionHash":"c97b1d..."}
We also record daily canary calls that prove the redactor still catches a known PHI fixture. Auditors liked seeing a failure from staging with a Jira link to the fix.
If you want a quick external look at your logging and control coverage before audit, we run focused security aware engineering reviews that cover this surface.
Failure modes and how we contained them
We missed nicknames in early tests. The dictionary had a legal first name, but users typed Mike. We added a small alias table derived from registration data and a phonetic pass that maps Michael to Mike and Michele. This increased false positives slightly. We considered that acceptable.
We saw model hallucination of PHI once. It guessed an email format when asked to draft an email and filled a token with john.doe. We blocked patterns that look like PHI from appearing in rehydration unless a matching token was present. The UI now displays a placeholder like [[CONTACT_EMAIL]].
We had timeouts during spikes. The redactor is CPU bound. We moved the NER pass to a thread pool and added a 50 ms budget. If the NER pass exceeds budget, we proceed with dictionary and patterns. That keeps P95 near 120 ms for redact and P99 under 200 ms.
We hit truncation in a vendor SDK that silently dropped the system prompt at 8k. We now compute token counts before sending and enforce our own limits. Never rely on the provider to make smart cuts.
We found a log tail that could expose PHI. An error path dumped the incoming body on exception. We removed body from error logs and added a scrubber for any message text that might appear. We wrote an automated linter that scans code for logger.error with risky variables.
What we would change next time
- Replace the rough tokenizer with the exact tokenizer for the chosen model. This removes headroom guesswork and bumps safe capacity.
- Move the rehydration allowlist into a policy file per agent, editable without a deploy. It is currently code.
- Add a patient intent classifier that runs locally to further shrink inputs to the model. Our tests show a 10 to 15 percent token reduction with no quality loss.
- Pre compute redaction for common snippets stored in templates to shave 20 to 30 ms off P50.
If you are starting fresh, front load the boundaries. Decide which agents can touch which fields, write it down, then encode those rules first. The rest follows cleanly.
Deployment notes
- Put the chat proxy in its own service with a narrow IAM role. No direct database writes except to the PHI map and the audit sink.
- Use per tenant KMS keys for transcript storage. Rotate quarterly. Prove rotation in audit.
- Run chaos tests that inject PHI into prompts in staging. Your detector should always catch them. Alert if not.
- Keep a dry run mode in production that logs what would be redacted for operator visibility without logging raw values. This helps tuning.
For teams adding AI to an existing healthtech product, we can map controls to your architecture quickly. Our AI integration approach covers glue code and model choices, and our HIPAA systems practice has checklists and sample policies that survived audits in multiple providers.



