How to Integrate CrewAI for healthcare with FastAPI for AI agents

By Cyprian AaronsUpdated 2026-04-22
crewai-for-healthcarefastapiai-agents

CrewAI for healthcare gives you the agent orchestration layer. FastAPI gives you the HTTP surface to expose those agents as production services.

Put them together and you get a clean pattern for healthcare workflows: triage assistants, prior-auth helpers, patient intake summarizers, and clinical document routers behind a typed API.

Prerequisites

  • Python 3.10+
  • fastapi
  • uvicorn
  • crewai
  • crewai-tools if you plan to add tools
  • A valid LLM provider configured for CrewAI
  • Basic familiarity with Pydantic models and REST APIs
  • A local or remote environment where you can run async HTTP services

Install the dependencies:

pip install fastapi uvicorn crewai crewai-tools pydantic

Integration Steps

  1. Create your FastAPI app and define request/response models.

Keep your API contract strict. In healthcare, that means no loose JSON blobs unless you enjoy debugging garbage inputs at 2 a.m.

from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI(title="Healthcare Agent API")

class TriageRequest(BaseModel):
    patient_id: str = Field(..., examples=["P12345"])
    symptoms: str = Field(..., examples=["chest pain and shortness of breath"])
    age: int = Field(..., ge=0, le=120)

class TriageResponse(BaseModel):
    summary: str
    urgency: str
    next_action: str
  1. Define CrewAI agents and tasks for the healthcare workflow.

Use an agent for clinical summarization and a task that produces a structured triage output. CrewAI’s Agent, Task, and Crew classes are the core primitives here.

from crewai import Agent, Task, Crew, Process

clinical_agent = Agent(
    role="Healthcare Triage Analyst",
    goal="Assess patient-reported symptoms and produce a safe triage summary",
    backstory="You assist clinical operations teams by structuring symptom reports into actionable next steps.",
    verbose=True,
)

triage_task = Task(
    description=(
        "Review the patient symptoms, age, and patient ID. "
        "Return a concise summary, urgency level (low/medium/high), "
        "and recommended next action."
    ),
    expected_output="A structured triage assessment with summary, urgency, and next_action.",
    agent=clinical_agent,
)

crew = Crew(
    agents=[clinical_agent],
    tasks=[triage_task],
    process=Process.sequential,
)
  1. Wrap the CrewAI execution inside a FastAPI endpoint.

This is the integration point. The endpoint receives a request, injects context into the task description, runs the crew with kickoff(), then returns a typed response.

from fastapi import HTTPException

@app.post("/triage", response_model=TriageResponse)
async def triage_patient(payload: TriageRequest):
    try:
        dynamic_task = Task(
            description=(
                f"Patient ID: {payload.patient_id}\n"
                f"Age: {payload.age}\n"
                f"Symptoms: {payload.symptoms}\n\n"
                "Return summary, urgency (low/medium/high), and next_action."
            ),
            expected_output="Structured triage assessment.",
            agent=clinical_agent,
        )

        runtime_crew = Crew(
            agents=[clinical_agent],
            tasks=[dynamic_task],
            process=Process.sequential,
        )

        result = runtime_crew.kickoff()

        return TriageResponse(
            summary=str(result),
            urgency="medium",
            next_action="Route to clinical review"
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
  1. Add health checks and startup wiring so the service is deployable.

Don’t ship only business endpoints. Add /health so Kubernetes, load balancers, and ops tooling can tell whether the service is alive.

@app.get("/health")
async def health_check():
    return {"status": "ok"}

Run it locally:

uvicorn main:app --reload --host 0.0.0.0 --port 8000
  1. If you need tool access, attach external healthcare systems through CrewAI tools.

That’s where this becomes useful in real systems. You can connect an agent to EHR search, claims lookup, or document retrieval via custom tools.

from crewai_tools import tool

@tool("get_patient_history")
def get_patient_history(patient_id: str) -> str:
    # Replace with FHIR/EHR integration or internal service call.
    return f"History for {patient_id}: hypertension, asthma"

history_agent = Agent(
    role="Clinical Context Assistant",
    goal="Fetch relevant patient context before triage",
    backstory="You retrieve structured patient history from approved systems.",
)

history_task = Task(
    description="Fetch relevant history for the given patient ID.",
    expected_output="A concise patient history summary.",
    agent=history_agent,
)

history_crew = Crew(agents=[history_agent], tasks=[history_task], process=Process.sequential)

Testing the Integration

Use FastAPI’s TestClient to verify the endpoint returns a valid response shape.

from fastapi.testclient import TestClient

client = TestClient(app)

def test_triage_endpoint():
    response = client.post(
        "/triage",
        json={
            "patient_id": "P12345",
            "symptoms": "chest pain and shortness of breath",
            "age": 58
        }
    )
    assert response.status_code == 200
    print(response.json())

test_triage_endpoint()

Expected output:

{
  "summary": "Structured triage assessment...",
  "urgency": "medium",
  "next_action": "Route to clinical review"
}

If you want stricter validation in tests, assert on fields rather than raw text. Crew outputs are often LLM-generated, so shape matters more than exact wording.

Real-World Use Cases

  • Patient intake summarization
    Turn free-text symptoms into structured summaries before they hit an EHR or nurse queue.

  • Prior authorization support
    Use agents to gather chart context, policy rules, and missing documentation before submitting requests.

  • Clinical document routing
    Classify inbound faxes, referral notes, and discharge summaries into the right workflow automatically.

The pattern is simple: FastAPI handles transport and validation; CrewAI handles reasoning and task orchestration. Keep those boundaries clean and your healthcare agent system stays maintainable under real load.


Keep learning

By Cyprian Aarons, AI Consultant at Topiax.

Want the complete 8-step roadmap?

Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.

Get the Starter Kit

Related Guides