AI-Powered Healthcare Assistant with Streamlit and CrewAI

Β·

4 min read

AI-Powered Healthcare Assistant with Streamlit and CrewAI

In today's fast-paced world, healthcare professionals are often overwhelmed with the sheer volume of patient data they need to process. What if we could leverage AI to assist doctors in diagnosing conditions and recommending treatment plans? In this blog post, we'll explore how to build an AI-powered healthcare assistant using Streamlit, CrewAI, and LangChain. This tool will help doctors by providing preliminary diagnoses and treatment recommendations based on patient symptoms and medical history.

Introduction

The healthcare industry is ripe for AI-driven innovation. By automating routine tasks like preliminary diagnosis and treatment recommendations, we can free up valuable time for healthcare professionals to focus on more complex cases. In this project, we'll build a Streamlit app that uses AI agents to analyze patient data and generate actionable insights.

Prerequisites

Before we dive into the code, make sure you have the following installed:

  • Python 3.8+

  • Streamlit

  • CrewAI

  • LangChain

  • python-docx

  • dotenv

You can install these packages using pip:

bash

pip install streamlit crewai python-docx dotenv

Setting Up the Environment

First, let's set up our environment by loading necessary API keys and configuring the Streamlit app.

python

import streamlit as st
from crewai import Agent, Task, Crew, Process
import os
from crewai_tools import ScrapeWebsiteTool, SerperDevTool, GroqAPIKeyTool
from dotenv import load_dotenv
from langchain_llama import LlamaModel
from docx import Document
from io import BytesIO
import base64

# Load environment variables from a .env file
load_dotenv()

# Set API keys for tools
os.environ["GROQ_API_KEY"] = os.getenv("GROQ_API_KEY")
os.environ["SERPER_API_KEY"] = os.getenv("SERPER_API_KEY")

Building the Streamlit App

User Inputs

We'll start by creating a simple user interface where doctors can input patient details such as gender, age, symptoms, and medical history.

pytho

# Set Streamlit page configuration
st.set_page_config(
    layout="wide"
)

# Set title for the Streamlit app
st.title("AI Agents to Empower Doctors")

# Get user inputs: gender, age, symptoms, and medical history
gender = st.selectbox('Select Gender', ('Male', 'Female', 'Other'))
age = st.number_input('Enter Age', min_value=0, max_value=120, value=25)
symptoms = st.text_area('Enter Symptoms', 'e.g., fever, cough, headache')
medical_history = st.text_area('Enter Medical History', 'e.g., diabetes, hypertension')

Initializing Tools and Agents

Next, we'll initialize the tools and agents that will help us in diagnosing and recommending treatments.

python

# Initialize tools for web scraping, search, and Groq API
search_tool = SerperDevTool()
scrape_tool = ScrapeWebsiteTool()
groq_tool = GroqAPIKeyTool(api_key=os.getenv("GROQ_API_KEY"))

# Initialize the language model
llm = LlamaModel(
    model="llama-2-13b",
    temperature=0.1,
    max_tokens=8000
)

# Define the Medical Diagnostician agent
diagnostician = Agent(
    role="Medical Diagnostician",
    goal="Analyze patient symptoms and medical history to provide a preliminary diagnosis.",
    backstory="This agent specializes in diagnosing medical conditions based on patient-reported symptoms and medical history. It uses advanced algorithms and medical knowledge to identify potential health issues.",
    verbose=True,
    allow_delegation=False,
    tools=[search_tool, scrape_tool, groq_tool],
    llm=llm
)

# Define the Treatment Advisor agent
treatment_advisor = Agent(
    role="Treatment Advisor",
    goal="Recommend appropriate treatment plans based on the diagnosis provided by the Medical Diagnostician.",
    backstory="This agent specializes in creating treatment plans tailored to individual patient needs. It considers the diagnosis, patient history, and current best practices in medicine to recommend effective treatments.",
    verbose=True,
    allow_delegation=False,
    tools=[search_tool, scrape_tool, groq_tool],
    llm=llm
)

Defining Tasks

We'll define two tasks: one for diagnosing the patient's condition and another for recommending treatment plans.

python

# Define the task for diagnosing the patient's condition
diagnose_task = Task(
    description=(
        "1. Analyze the patient's symptoms ({symptoms}) and medical history ({medical_history}).\n"
        "2. Provide a preliminary diagnosis with possible conditions based on the provided information.\n"
        "3. Limit the diagnosis to the most likely conditions."
    ),
    expected_output="A preliminary diagnosis with a list of possible conditions.",
    agent=diagnostician
)

# Define the task for recommending treatment plans
treatment_task = Task(
    description=(
        "1. Based on the diagnosis, recommend appropriate treatment plans step by step.\n"
        "2. Consider the patient's medical history ({medical_history}) and current symptoms ({symptoms}).\n"
        "3. Provide detailed treatment recommendations, including medications, lifestyle changes, and follow-up care."
    ),
    expected_output="A comprehensive treatment plan tailored to the patient's needs.",
    agent=treatment_advisor
)

Executing the Tasks

Finally, we'll create a crew with the defined agents and tasks, and execute them when the user clicks the "Get Diagnosis and Treatment Plan" button.

python

# Create a crew with the defined agents and tasks
crew = Crew(
    agents=[diagnostician, treatment_advisor],
    tasks=[diagnose_task, treatment_task],
    verbose=2
)

# Execute the tasks and generate the diagnosis and treatment plan
if st.button("Get Diagnosis and Treatment Plan"):
    with st.spinner('Generating recommendations...'):
        result = crew.kickoff(inputs={"symptoms": symptoms, "medical_history": medical_history})
        st.write(result)
        docx_file = generate_docx(result)

        download_link = get_download_link(docx_file, "diagnosis_and_treatment_plan.docx")

        st.markdown(download_link, unsafe_allow_html=True)

Generating and Downloading the Report

To make the diagnosis and treatment plan more accessible, we'll generate a Word document and provide a download link.

python

def generate_docx(result):
    """
    Generate a Word document with the given result.
    """
    doc = Document()
    doc.add_heading('Healthcare Diagnosis and Treatment Recommendations', 0)
    doc.add_paragraph(result)
    bio = BytesIO()
    doc.save(bio)
    bio.seek(0)
    return bio

def get_download_link(bio, filename):
    """
    Generate a download link for the Word document.
    """
    b64 = base64.b64encode(bio.read()).decode()
    return f'<a href="data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,{b64}" download="{filename}">Download Diagnosis and Treatment Plan</a>'

Conclusion

In this blog post, we've built an AI-powered healthcare assistant using Streamlit and CrewAI. This tool can help doctors by providing preliminary diagnoses and treatment recommendations based on patient symptoms and medical history. By automating these routine tasks, we can empower healthcare professionals to focus on more complex cases, ultimately improving patient care.

Application code: https://github.com/bittush8789/AI-Agents-to-Empower-Doctors.git

Follow me on LinkedIn: https://www.linkedin.com/in/bittu-kumar-54ab13254/

Β