HIPAA-Compliant Chatbot: How to Build One With RAG
Compliance is a property of the whole system, not the model. Here is the architecture and the code that keeps patient data protected.
Key takeaways
- No chatbot or model is “HIPAA-compliant” on its own — compliance is a property of the whole system: vendors, storage, access control and logging.
- Every vendor that can see protected health information (PHI) needs a signed Business Associate Agreement (BAA), including the logging and monitoring tools people forget.
- RAG fits healthcare well because answers come from approved documents and can be filtered per user at retrieval time — something a system prompt cannot guarantee.
- Send the model the minimum necessary data, and write audit logs that record IDs and hashes rather than raw PHI.
Not legal advice. HIPAA obligations depend on your organization, your data and your contracts. This is an engineering guide — have your compliance officer or counsel review the final design.
What makes a chatbot HIPAA-compliant?
A HIPAA-compliant chatbot is one that handles protected health information under the safeguards HIPAA requires: signed agreements with every vendor that touches the data, encryption in transit and at rest, access control, and audit logging. The model is only one component. A chatbot built on a perfectly capable model is still non-compliant if its transcripts land in an analytics tool that never signed a BAA.
The most practical architecture for a healthcare assistant is retrieval-augmented generation. Instead of letting the model answer from memory, your system retrieves passages from approved documents — clinic policies, patient education material, scheduling rules — and the model answers only from those, with citations. If the pattern is new to you, start with RAG vs fine-tuning to see why retrieval beats retraining for this kind of work.
First decide: does the chatbot touch PHI?
This one decision changes the whole project, so make it before writing any code. A bot that answers questions from public clinic pages never needs patient identifiers. A bot that discusses a specific patient’s appointments or results does.
| Scenario | Touches PHI? | What it means |
|---|---|---|
| General questions from public clinic content (hours, accepted insurance, visit prep) | No | Far lighter requirements. Still avoid collecting identifiers. |
| Questions about a specific patient (appointments, billing, results) | Yes | Full safeguards and BAAs apply. |
| Staff assistant that summarizes patient records | Yes | Strictest access control and audit needs. |
If you can ship a useful first version that never receives PHI, do that. It is the safest design, and you can add authenticated, PHI-aware features later once the foundations are proven.
Reference architecture
Every component that can see PHI sits inside your compliance boundary and is covered by a BAA. The request path looks like this:
User (authenticated, over TLS)
-> API gateway: authentication + role check
-> PHI redaction / minimum-necessary filter
-> Retriever -> vector store (encrypted, access-filtered, under BAA)
-> Prompt builder (approved passages only)
-> LLM endpoint (under BAA, no training on your data)
-> Response filter + citations
-> Audit log (IDs and hashes, not raw PHI)
Notice that access control appears before retrieval, not after generation. That ordering is the single most important design choice in the whole system.
The compliance decisions that matter
1. Sign a BAA with every vendor that sees PHI
Several major cloud and model providers offer BAAs for eligible services, but not every product or pricing plan qualifies, and terms change. Confirm coverage for each component:
- The LLM provider or hosted model endpoint
- The vector database or search service
- Cloud hosting and storage
- Logging, monitoring and error-tracking tools
The most common accidental violation is shipping full chat transcripts to a third-party analytics or error-tracking service with no BAA. Check every tool that receives request bodies.
If a vendor will not sign a BAA, PHI must not reach it. Many teams solve this by running an open-weight model inside their own cloud account — see our local LLM setup guide for the basics of self-hosting, and which AI model to use if you are comparing hosted options.
2. Apply the minimum necessary standard
Send the model only what it needs to answer. A scheduling question needs an appointment slot, not a diagnosis history. Build the retriever and prompt builder so sensitive fields are excluded by default and added only when a feature genuinely requires them.
3. Encrypt everywhere
Use TLS for data in transit and encryption at rest for the vector store, document storage, backups and logs. Manage keys in your cloud provider’s key management service, never in application code.
4. Enforce access at retrieval time
Never rely on a system prompt such as “only show this user their own records.” Prompts can be bypassed. Instead, filter inside the database query so unauthorized documents are never retrieved in the first place. This is a major reason retrieval beats fine-tuning in regulated settings: you can filter retrieval per user, but you cannot filter what a model has memorized.
5. Keep audit trails and set retention rules
You must be able to answer who accessed what, when, and through which feature. Log identifiers and document IDs rather than raw questions and answers. Decide how long transcripts are kept, who can read them and how they are deleted — shorter retention means less exposure.
Build it: Python implementation
The code below uses small placeholder interfaces — embed, vector_store and llm — so you can plug in any provider that is covered by a BAA. It focuses on the compliance-critical logic rather than on any one SDK.
Step 1: Redact identifiers before they leave your boundary
import re
PATTERNS = {
"SSN": re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),
"PHONE": re.compile(r"\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b"),
"EMAIL": re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b"),
"DATE": re.compile(r"\b\d{1,2}/\d{1,2}/\d{2,4}\b"),
"MRN": re.compile(r"\bMRN[:\s]*\d{5,10}\b", re.IGNORECASE),
}
def redact(text: str) -> str:
for label, pattern in PATTERNS.items():
text = pattern.sub(f"[{label}]", text)
return text
Watch out: regex only catches obvious patterns. Names, street addresses and free-text details slip straight through. In production, use a dedicated de-identification service or a clinical NER model, and treat regex as a safety net rather than the main control.
Step 2: Retrieve with access control inside the query
def retrieve(question: str, user, k: int = 4):
query_vector = embed(redact(question))
# The filter runs inside the vector store, so documents the
# user may not see are never returned.
return vector_store.search(
vector=query_vector,
top_k=k,
filter={
"tenant_id": user.tenant_id,
"allowed_roles": {"contains": user.role},
},
)
Put tenant_id — and, for patient-specific data, patient_id — in the metadata of every chunk when you ingest documents, and always filter on it. How you split documents matters here too: see RAG chunking strategies and vector databases explained for the layers underneath this step.
Step 3: Build a grounded, minimal prompt
SYSTEM_PROMPT = (
"You are a clinic assistant. Answer ONLY from the provided sources. "
"If the sources do not contain the answer, say you don't know and "
"suggest contacting the clinic. Do not give diagnoses or medical "
"advice. Cite the source IDs you used."
)
def build_prompt(question: str, passages: list) -> list[dict]:
context = "\n\n".join(f"[{p.id}] {p.text}" for p in passages)
return [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user",
"content": f"Sources:\n{context}\n\nQuestion: {redact(question)}"},
]
Step 4: Answer, then write an audit record without raw PHI
import hashlib, json, logging, time
audit = logging.getLogger("audit")
def answer(question: str, user) -> dict:
passages = retrieve(question, user)
reply = llm.generate(build_prompt(question, passages))
audit.info(json.dumps({
"ts": int(time.time()),
"user_id": user.id,
"role": user.role,
"question_hash": hashlib.sha256(question.encode()).hexdigest(),
"doc_ids": [p.id for p in passages],
"model": llm.model_name,
}))
return {"answer": reply, "sources": [p.id for p in passages]}
The hash lets you spot repeated queries and investigate incidents without storing the question itself. Ship these logs to a store that is also encrypted and covered by your BAA.
Step 5: Add safety rails for medical content
- Refuse diagnosis and treatment advice and route those questions to a clinician.
- Detect emergency language such as chest pain or suicidal thoughts, and reply with emergency instructions and a human handoff instead of a generated answer.
- Show a clear disclaimer that the assistant is not a substitute for professional care.
- Test refusals the same way you test answers. Build a set of risky questions and check the bot declines every one — the evaluation habit from chunking applies here as well.
Common mistakes
- Logging full conversations to a tool with no BAA. Review every service that receives request bodies, including error trackers.
- Putting access rules in the prompt instead of in the retrieval filter.
- Sending whole patient records to the model “for context” instead of the minimum needed.
- Forgetting that embeddings come from PHI. Treat the vector store as PHI storage, with the same encryption and access rules.
- Using a consumer or free AI tier that offers no BAA or may retain your data.
- Skipping the documented risk assessment. HIPAA expects written risk analysis, not just well-written code.
Launch checklist
- BAAs signed with every vendor that handles PHI
- Encryption in transit and at rest, with keys in a managed service
- Authentication and role-based access on every request
- Access filtering enforced inside the vector store query
- PHI redaction or de-identification tested on realistic data
- Audit logging with no raw PHI, plus a defined retention policy
- Emergency and out-of-scope handling tested
- Security review completed, and compliance or legal sign-off obtained
Where to go next
Once the compliant foundation is in place, quality work begins: tune chunking, pick a model that fits your privacy and budget constraints with the AI model picker, and keep the chat interface fast with Core Web Vitals for AI chat interfaces.
Where you host the system matters as much as the code. The cloud computing and AWS and Google Cloud computing guides cover regions, access control and cost limits.
Frequently asked questions
Is there such a thing as a HIPAA-compliant AI model?
Models are not compliant on their own. A deployment is compliant when every vendor that handles protected health information signs a Business Associate Agreement and your overall system implements the required safeguards, including encryption, access control and audit logging.
Can I use ChatGPT, Claude or Gemini for a HIPAA chatbot?
Only through an offering where the provider will sign a Business Associate Agreement for your use case, and only with the other safeguards in place. Consumer chat apps are generally not appropriate for protected health information, and terms change, so check each provider's current documentation.
Does RAG make a chatbot HIPAA-compliant?
No, but it makes compliance easier. RAG keeps answers grounded in approved documents, makes answers traceable to sources, and lets you filter retrieval per user so unauthorized records are never fetched.
Do I need to de-identify data before sending it to the model?
Not always, but sending de-identified or minimal data reduces risk and supports the minimum necessary standard. If a vendor will not sign a Business Associate Agreement, protected health information must not be sent to it at all.
Can I self-host the model instead?
Yes. Running an open-weight model inside your own cloud account removes one third party from the chain, although you still own all of the security, encryption and logging work.
Is this article legal advice?
No. HIPAA obligations depend on your organization, data and contracts, so have your compliance officer or legal counsel review your final design.