Demystifying CrewAI: Building a Collaborative AI Healthcare Assistant
- Sangamesh Gella
- May 1
- 5 min read
Updated: May 6
Artificial Intelligence (AI) is rapidly transforming healthcare, but the magic truly happens when multiple AI agents work together, each specialising in a unique aspect of patient care. In this blog, we'll explore how Crew AI enables this collaboration and walk through a practical Python example that brings these concepts to life for everyone, regardless of their technical background.

What is CrewAI?
Crew AI is a framework for building multi-agent AI systems. Instead of relying on a single, monolithic AI, Crew AI lets you create a "crew" of specialised agents, each with its own expertise and role. These agents communicate, share context, and solve complex problems together, much like a team of healthcare professionals.
How Does the Example Healthcare Crew Work?
Let's break down the code and the concepts behind it, step by step.
1. Collecting Patient Information
The first part of the code is a simple, interactive form that gathers patient details:
Name,
Age,
Gender,
Symptoms,
Medical History,
Current Medications and
Allergies
This information is crucial for any healthcare decision and is collected via command-line prompts. The script ensures valid input (e.g., age must be a number) and confirms the data with the user before proceeding.
2. Introducing the Crew: Specialised AI Agents
Each AI agent in Crew AI is like a member of a healthcare team, with a clear role:
Agent Role | Responsibility |
Medical Diagnostician | Analyses symptoms and history to suggest possible diagnoses |
Medical Guidelines Expert | Finds and interprets the latest medical guidelines relevant to the case |
Treatment Plan Specialist | Develops a personalised treatment plan, considering patient specifics and best practices |
Patient Education Specialist | Explains medical information in clear, patient-friendly language |
Each agent is powered by a language model, such as GPT-4o-mini, and some have access to external tools like Serper for research.

3. Assigning Tasks and Workflow
Tasks are defined for each agent, specifying what they're expected to do. For example:
The Diagnostician receives the patient's info and outputs possible diagnoses, ranked by likelihood.
The Guidelines Expert researches best practices for those diagnoses.
The Treatment Planner crafts a tailored treatment plan.
The Patient Educator explains everything in plain language.
Context Sharing: Some tasks depend on the outputs of others. For instance, the treatment plan is based on both the diagnosis and the latest guidelines. This mirrors real-world teamwork in healthcare.
4. Orchestrating the Crew
The agents and their tasks are bundled into a Crew object. The process is set to "sequential," meaning each agent works in turn, passing context to the next, just like a relay race.
When the process_patient function is called, it:
Updates the diagnosis task with the specific patient info
Runs the crew, kicking off the chain of collaboration
Returns the final output: a comprehensive, AI-generated analysis and recommendation
5. Putting It All Together
The main script (patient_input.py) handles user interaction and calls the crew for analysis. The core AI logic is separated in main.py, making the code modular and reusable.
patient_input.py
def get_patient_info():
print("Patient Information Entry Form")
print("-----------------------------")
patient_info = {}
patient_info["name"] = input("Please enter patient name: ")
# For age, ensure we get a valid integer
while True:
try:
patient_info["age"] = int(input("Please enter patient age: "))
break
except ValueError:
print("Please enter a valid number for age.")
patient_info["gender"] = input("Please enter patient gender: ")
patient_info["symptoms"] = input("Please enter patient symptoms: ")
patient_info["medical_history"] = input("Please enter patient medical history: ")
patient_info["medications"] = input("Please enter current medications: ")
patient_info["allergies"] = input("Please enter allergies: ")
# Display the entered information for confirmation
print("\nPatient Information Summary:")
for key, value in patient_info.items():
print(f"{key.capitalize()}: {value}")
confirm = input("\nIs this information correct? (y/n): ")
if confirm.lower() != 'y':
print("Let's try again.")
return get_patient_info()
return patient_info
if __name__ == "__main__":
# Import process_patient from main.py
from main import process_patient
# Get patient information
patient_data = get_patient_info()
# Process the patient data using the function from main.py
print("\nProcessing patient information...")
result = process_patient(patient_data)
# Display the result
print("\nAI Analysis Result:")
print(result)
from crewai import Agent, Task, Crew, Process
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from crewai_tools import SerperDevTool
# Load environment variables
load_dotenv()
# Initialize the LLM
llm = ChatOpenAI(model_name="gpt-4o-mini")
# Create specialized healthcare agents
guideline_expert = Agent(
role="Medical Guidelines Expert",
goal="Retrieve and interpret relevant medical guidelines for the patient's condition",
backstory="You are a medical professional with extensive knowledge of clinical guidelines and best practices. You excel at finding the most relevant and up-to-date medical guidelines for specific conditions.",
llm=llm,
tools=[SerperDevTool()],
verbose=True
)
diagnostician = Agent(
role="Medical Diagnostician",
goal="Analyze patient symptoms and medical history to provide preliminary diagnosis options",
backstory="You are an experienced diagnostician with a talent for connecting symptoms to potential conditions. You're careful to consider the full patient history and avoid jumping to conclusions.",
llm=llm,
verbose=True
)
treatment_planner = Agent(
role="Treatment Plan Specialist",
goal="Develop personalized treatment recommendations based on diagnosis and patient profile",
backstory="You specialize in creating treatment plans that balance clinical effectiveness with patient preferences and quality of life considerations.",
llm=llm,
verbose=True
)
patient_educator = Agent(
role="Patient Education Specialist",
goal="Translate medical information into clear, patient-friendly language",
backstory="You excel at communicating complex medical concepts in accessible ways, ensuring patients understand their conditions and treatment options.",
llm=llm,
verbose=True
)
# Define tasks for each agent
diagnosis_task = Task(
description="Analyze the patient's symptoms and medical history to provide potential diagnoses. Consider all relevant factors including age, gender, risk factors, and symptom duration.",
expected_output="A list of potential diagnoses ranked by likelihood, with reasoning for each.",
agent=diagnostician
)
guideline_task = Task(
description="Research and retrieve the latest medical guidelines relevant to the potential diagnoses. Focus on treatment options, risk stratification, and recommended diagnostic tests.",
expected_output="Summary of relevant guidelines with citations to medical authorities.",
agent=guideline_expert
)
treatment_task = Task(
description="Develop a personalized treatment plan based on the diagnosis and guidelines. Consider patient-specific factors such as age, comorbidities, and potential drug interactions.",
expected_output="Detailed treatment recommendations with rationale and alternatives.",
agent=treatment_planner,
context=[diagnosis_task, guideline_task]
)
education_task = Task(
description="Create patient-friendly explanations of the diagnosis, treatment options, and next steps. Use clear language and helpful analogies.",
expected_output="Patient education materials that clearly explain the medical condition and treatment plan.",
agent=patient_educator,
context=[diagnosis_task, treatment_task]
)
# Create the healthcare crew
healthcare_crew = Crew(
agents=[diagnostician, guideline_expert, treatment_planner, patient_educator],
tasks=[diagnosis_task, guideline_task, treatment_task, education_task],
process=Process.sequential,
verbose=True
)
# Function to process patient information
def process_patient(patient_info):
"""
Process patient information and generate diagnosis and treatment recommendations
Args:
patient_info: Dictionary containing patient details
Returns:
The final output from the crew
"""
# Update task descriptions with patient-specific information
diagnosis_task.description = f"Analyze the following patient case: {patient_info}. " + diagnosis_task.description
# Run the crew
result = healthcare_crew.kickoff()
return result
# Example usage
if __name__ == "__main__":
print("This script is designed to be imported and used by patient_input.py")
print("Please run patient_input.py instead.")
Why Is This Approach Powerful?
Specialisation: Each agent is an expert in its domain, leading to more accurate and nuanced results.
Transparency: Tasks and agent roles are clearly defined, making it easier to understand and trust the AI's decisions.
Extensibility: New agents (e.g., a billing expert, a follow-up coordinator) can be added as needed.
Patient-Centric: The final output isn't just clinical- it includes patient education, empowering individuals to understand their health.
A Glimpse Into the Future
Imagine this system integrated into a hospital's workflow. Nurses enter patient data, the AI crew provides a preliminary analysis, doctors review and adjust the recommendations, and patients receive clear explanations—all in just minutes.
Crewai isn't just about automation; it's about collaboration between humans and AI agents as well as among AI agents themselves.
Conclusion
By breaking down complex healthcare tasks into specialised roles and fostering teamwork among AI agents, Crewai offers a blueprint for building smarter, more transparent, and patient-friendly AI systems. Whether you're a developer, a healthcare professional, or simply curious about AI, this approach makes the future of medicine more accessible and understandable to everyone.
Ready to try it yourself? Clone the code, define your agents, and see how Crewai can revolutionise any workflow!


Comments