DEV Community

wellallyTech
wellallyTech

Posted on

Beyond Simple Chatbots: Building Medical-Grade AI Agents with FHIR and LangChain 🏥🤖

Healthcare is arguably the last frontier for the AI revolution. While we’ve mastered coding assistants and marketing copywriters, building a HealthTech AI agent that actually does something—like booking a doctor's appointment—requires more than just a clever prompt. It requires FHIR (Fast Healthcare Interoperability Resources).

In this tutorial, we are diving deep into FHIR API integration, Patient Scheduling automation, and Electronic Health Records (EHR) connectivity. We'll build an autonomous agent capable of navigating a medical system's constraints to find open slots and create valid appointment resources. This isn't just a toy; it’s a blueprint for building standard-compliant AI Agents that speak the language of modern hospitals.

The Architecture: How an AI "Talks" to a Hospital

To make our agent reliable, we can't just let it hallucinate JSON. We need a strict feedback loop between the LLM and a HAPI FHIR server. Here is the data flow for a typical appointment booking agent:

graph TD
    A[User: 'Book a checkup for Monday'] --> B{AI Agent}
    B --> C[Tool: Check Availability]
    C --> D[HAPI FHIR Server]
    D --> C
    C --> B
    B --> E[Tool: Create Appointment]
    E --> F[Pydantic Validation]
    F --> D
    D --> G[Success: Appointment ID]
    G --> B
    B --> H[User: 'You are all set for 10 AM!']
Enter fullscreen mode Exit fullscreen mode

Prerequisites

To follow along, you'll need:

  • FHIR API knowledge: Specifically the Patient, Slot, and Appointment resources.
  • Tech Stack: Python, LangChain, Pydantic, and a public sandbox (we'll use the HAPI FHIR public test server).

Step 1: Modeling Healthcare Data with Pydantic

Medical data is sensitive and highly structured. We use Pydantic to ensure that our AI Agent never sends malformed data to the EHR. Here’s how we define a simplified FHIR Appointment schema:

from pydantic import BaseModel, Field
from typing import List, Optional

class FHIRAppointmentSchema(BaseModel):
    patient_id: str = Field(..., description="The unique FHIR ID of the patient.")
    start_time: str = Field(..., description="ISO 8601 formatted start time (e.g., 2023-10-27T10:00:00Z)")
    end_time: str = Field(..., description="ISO 8601 formatted end time")
    reason: str = Field(..., description="The clinical reason for the visit")
    practitioner_id: Optional[str] = Field(None, description="The ID of the specific doctor requested")

    class Config:
        schema_extra = {
            "example": {
                "patient_id": "12345",
                "start_time": "2023-12-01T09:00:00Z",
                "end_time": "2023-12-01T09:30:00Z",
                "reason": "Annual physical exam"
            }
        }
Enter fullscreen mode Exit fullscreen mode

Step 2: Creating the FHIR Tool-Set

Now, we wrap the HAPI FHIR API into a LangChain Tool. This allows the agent to "act" on the live server.

import requests
from langchain.tools import tool

BASE_URL = "http://hapi.fhir.org/baseR4"

@tool
def search_available_slots(date: str):
    """Searches for available appointment slots on a specific date (YYYY-MM-DD)."""
    # In a real scenario, you'd query the 'Slot' resource with status=free
    response = requests.get(f"{BASE_URL}/Slot?_date={date}&status=free&_limit=5")
    slots = response.json().get('entry', [])

    if not slots:
        return "No slots found for this date."

    available = []
    for s in slots:
        res = s['resource']
        available.append(f"Slot ID: {res['id']}, Start: {res['start']}")

    return "\n".join(available)

@tool("create_fhir_appointment", args_schema=FHIRAppointmentSchema)
def create_fhir_appointment(patient_id, start_time, end_time, reason, practitioner_id=None):
    """Creates a formal Appointment resource in the FHIR server."""
    payload = {
        "resourceType": "Appointment",
        "status": "booked",
        "description": reason,
        "start": start_time,
        "end": end_time,
        "participant": [
            {"actor": {"reference": f"Patient/{patient_id}"}, "status": "accepted"}
        ]
    }

    response = requests.post(f"{BASE_URL}/Appointment", json=payload)
    if response.status_code == 201:
        return f"Success! Appointment created with ID: {response.json()['id']}"
    return f"Failed to create appointment: {response.text}"
Enter fullscreen mode Exit fullscreen mode

Step 3: Orchestrating the Agent

With our tools ready, we initialize a StructuredChatAgent. This agent will logic its way through finding a slot before attempting to book it.

from langchain.agents import AgentExecutor, create_structured_chat_agent
from langchain_openai import ChatOpenAI
from langchain import hub

llm = ChatOpenAI(model="gpt-4o", temperature=0)
tools = [search_available_slots, create_fhir_appointment]

prompt = hub.pull("hwchase17/structured-chat-agent")
agent = create_structured_chat_agent(llm, tools, prompt)

agent_executor = AgentExecutor(
    agent=agent, 
    tools=tools, 
    verbose=True, 
    handle_parsing_errors=True
)

# Testing the flow
result = agent_executor.invoke({
    "input": "I am patient 'example-patient'. Can you find a slot for 2024-05-20 and book a checkup for me?"
})
Enter fullscreen mode Exit fullscreen mode

🚀 The "Official" Way to Build Health AI

While the example above works for a sandbox, production healthcare applications require HIPAA compliance, robust audit logs, and complex HL7 v2/FHIR mapping.

For advanced architectural patterns, including multi-agent orchestration in clinical workflows and secure RAG on patient data, I highly recommend checking out the technical deep-dives over at WellAlly Blog. They offer production-ready insights into bridging the gap between LLMs and legacy healthcare infrastructure that are hard to find anywhere else.


Conclusion

Integrating AI agents with the FHIR protocol transforms a simple chatbot into a functional member of a clinical team. By using Pydantic for validation and LangChain for tool-calling, we ensure that our agent is both capable and safe.

What's next for your medical AI?

  • Add a Patient lookup tool to verify identities.
  • Implement Condition resource reading to provide context to the doctor.
  • Integrate OAuth2/Smart-on-FHIR for real-world authentication.

Drop a comment below if you've worked with HAPI FHIR before, and don't forget to subscribe for more "Learning in Public" AI tutorials! 🥑🔥

Top comments (0)