DEV Community

Akshay Keerthi
Akshay Keerthi

Posted on

Building a Medical Assistant using Lyzr SDK

In today’s fast-paced world, access to advanced technologies can revolutionize how we manage our health. With the rise of artificial intelligence (AI), analyzing complex medical records has become more efficient than ever. Enter Lyzr’s Medical Assistant, a cutting-edge application designed to simplify the process of medical record analysis using state-of-the-art AI technology.

Image description

Introducing Lyzr’s QABot:

Lyzr’s QABot is a powerful tool powered by the Retrieval-Augmented Generation (RAG) model, designed to provide concise summaries and insightful analyses of various texts.With its ability to understand and generate human-like responses, QABot becomes an invaluable companion in exploring and understanding literary works.

Building the Medical Assistant App:

Using Streamlit, a popular Python library for building applications, we can create an intuitive and user-friendly interface for our app.The app allows users to upload PDF files containing Medical Records, which are then analyzed by Lyzr’s QABot to generate summaries and insights.

Why use Lyzr SDK’s?

With Lyzr SDKs, crafting your own GenAI application is a breeze, requiring only a few lines of code to get up and running swiftly.

Checkout the Lyzr SDK’s

Lets get Started!
Create a new file app.py and use that

import os
import streamlit as st
import shutil
from lyzr import QABot
Enter fullscreen mode Exit fullscreen mode

This Streamlit application utilizes libraries like os, streamlit, shutil, and Lyzr’s QABot to create an interactive platform for medical record analysis. Users upload PDFs, triggering operations for file management and analysis. Lyzr’s QABot extracts detailed insights from medical records, covering medication lists, vital signs, diagnostic results, and progress notes. Overall, it offers a seamless experience for medical record interpretation.

Next Set Up OpenAI API Key and using Streamlit’s secrets management, set up the OpenAI API key within your Streamlit application. Replace "OPENAI_API_KEY" with the actual key name defined in your Streamlit secrets where your OpenAI API key is stored.

os.environ["OPENAI_API_KEY"] = st.secrets["apikey"]
Enter fullscreen mode Exit fullscreen mode
def remove_existing_files(directory):
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        try:
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)
        except Exception as e:
            st.error(f"Error while removing existing files: {e}")
Enter fullscreen mode Exit fullscreen mode

This function removes all existing files and directories within a specified directory path. It iterates through each file in the directory, checks if it’s a file or a directory, and then either deletes the file using os.unlink() or removes the directory using shutil.rmtree(). Any exceptions encountered during this process are caught, and an error message is displayed using st.error(). However, the st.error() function is typically used within Streamlit applications for displaying errors to users, so it's important to ensure that st is imported and available in the scope where this function is called.

# Set the local directory
data_directory = "data"

# Create the data directory if it doesn't exist
os.makedirs(data_directory, exist_ok=True)

# Remove existing files in the data directory
remove_existing_files(data_directory)
Enter fullscreen mode Exit fullscreen mode

This snippet of code first sets a variable data_directory to the string "data", representing the directory where files will be stored. It then creates this directory if it doesn't already exist using os.makedirs(data_directory, exist_ok=True). Finally, it calls the remove_existing_files() function to remove any existing files in the data_directory, ensuring a clean slate before further operations.

uploaded_file = st.file_uploader("Choose PDF file", type=["pdf"])

if uploaded_file is not None:
    # Save the uploaded PDF file to the data directory
    file_path = os.path.join(data_directory, uploaded_file.name)
    with open(file_path, "wb") as file:
        file.write(uploaded_file.getvalue())

    # Display the path of the stored file
    st.success(f"File successfully saved")
Enter fullscreen mode Exit fullscreen mode

This code snippet first uses Streamlit’s file_uploader() function to create a file uploader widget in the user interface, allowing users to select a PDF file. If a file is uploaded (if uploaded_file is not None), the code proceeds to save the uploaded PDF file to the data_directory using the file's original name. It then displays a success message using Streamlit's st.success() function, confirming that the file has been successfully saved

def get_files_in_directory(directory="data"):
    # This function help us to get the file path along with filename.
    files_list = []

    # Ensure the directory exists
    if os.path.exists(directory) and os.path.isdir(directory):
        # Iterate through all files in the directory
        for filename in os.listdir(directory):
            file_path = os.path.join(directory, filename)

            # Check if the path points to a file (not a directory)
            if os.path.isfile(file_path):
                files_list.append(file_path)

    return files_list
Enter fullscreen mode Exit fullscreen mode

This function, get_files_in_directory, retrieves a list of file paths within a specified directory. It takes an optional parameter directory which defaults to "data".

The function first initializes an empty list files_list. Then, it checks if the specified directory exists and is indeed a directory using os.path.exists() and os.path.isdir() functions.

If the directory exists, the function iterates through all the files in that directory using os.listdir(). For each file found, it constructs the full file path using os.path.join() and checks if it's a file (not a directory) using os.path.isfile(). If it's a file, its path is appended to the files_list.

def rag_implementation():
    # This function will implement RAG Lyzr QA bot
    path = get_files_in_directory()
    path = path[0]

    rag = QABot.pdf_qa(
        input_files=[str(path)],
        llm_params={"model": "gpt-3.5-turbo"},
        # vector_store_params=vector_store_params
    )

    return rag
Enter fullscreen mode Exit fullscreen mode

The rag_implementation() function initializes the RAG (Retrieval-Augmented Generation) Lyzr QA bot by retrieving a file path from the specified directory using the get_files_in_directory() function. It selects the first file path obtained and initializes the QA bot using Lyzr's QABot module, configuring it with parameters such as the language model ("gpt-3.5-turbo"). Finally, it returns the initialized RAG Lyzr QA bot for subsequent use within the application.

def resume_response():
    rag = rag_implementation()
    prompt = """  Give the description of the given record in these bullet points,
                    - Medication List: List current prescriptions, note any allergies, and assess compliance.
                    - Vital Signs: Review recent measurements such as blood pressure, heart rate, and temperature.
                    - Diagnostic Tests: Examine results of recent tests like blood work, imaging, or ECGs for any abnormalities.
                    - Progress Notes: Evaluate physician's observations, treatment plans, and any referrals made."""


    response = rag.query(prompt)
    return response.response

if uploaded_file is not None:
    automatice_response = resume_response()
    st.markdown(f"""{automatice_response}""")
Enter fullscreen mode Exit fullscreen mode

The resume_response() function utilizes the rag_implementation() function to initialize the RAG Lyzr QA bot. It then constructs a prompt containing specific instructions for analyzing a medical record, including sections on medication list, vital signs, diagnostic tests, and progress notes. The RAG Lyzr QA bot is queried with this prompt, and the function returns the bot's response, which provides insights into the given medical record. This process is triggered when an uploaded file is available, allowing for automatic analysis of the provided medical document.

Lyzr Medical Assistant represents a significant advancement in healthcare technology, democratizing access to AI-driven medical record analysis. By providing users with instant insights into their health data, the application empowers individuals to take control of their well-being like never before. Try out Lyzr Medical Assistant today and experience the future of medical record analysis firsthand!

App Link: https://medical-assistant-lyzr.streamlit.app/

Youtube Video: https://www.youtube.com/watch?v=e1mbHD7BN7A

References
Lyzr Website: Lyzr

Book a Demo: Demo

Lyzr Community Channels: Discord

Slack : Slack

Top comments (0)