Skip to content

How to Build an AI-Powered Health Diagnosis Assistant

Health Diagnosis Assistant

Imagine you have an AI assistant that can assist you in providing a diagnosis based on the symptoms without needing to visit a doctor. How cool is having an AI-powered health diagnosis assistant, when you’re feeling under the weather and unsure about visiting the clinic? This AI-powered assistant will take your symptoms and provide you with a recovery plan based on your symptoms. Something that feels like chatting with your doctor but from the comfort of your couch.

Doctor checking patient

Here, we will build an AI-powered health diagnosis system that utilizes OpenAI’s model to process the symptoms and provide a diagnosis based on the symptoms. The goal is to stimulate a dialogue between humans and AI. Users will be able to provide the symptoms, and the AI assistant will provide the diagnosis or can ask follow-up questions. By the end of this article, we’ll have a fully functional app and a deep understanding of how different features have interacted to develop such an app.

Sounds very useful, right? Let’s break down how to build it from scratch step by step.

Setting up the development environment

Before we dive deep into the ocean of coding, let’s first set up an environment required to set up our AI-powered health diagnosis app. We’ll be using Python’s Flask server for the backend and the GPT-3.5-turbo model for generating the health advice.

Before diving into setting up a development environment let’s discuss some tools and technologies we are going to use in this journey:

  • HTML/CSS/JS: We’re going to use these tools to develop the front-end side of our application and create the user interface(UI).
  • OpenAI: It will serve as a brain of our tool. We’ll use its API to diagnose the health based on the provided symptoms.
  • Flask and Python: We’ll use these to set up the backend of our tool.

We have decided to use Python programming language, due to its simplicity and perfection for handling APIs.

Setup a Flask project

Have you ever heard of Flask? No, don’t worry. It’s a web framework for Python, we can build simple web apps using it. Let’s first create our project directory to store all of our files. Open the terminal and use the following commands to create and enter into a working directory:

mkdir Health_diagnosis_assistant
cd Health_diagnosis_assistant

Now let’s install Flask and OpenAI, the backbone of our system. Run the following commands inside your terminal.

pip install Flask openai

Install Python

Firstly, you need to ensure Python is installed on your system. Use the terminal to check if it is already installed by running the following command on your terminal.

python --version      

If you see a version number, congrats, you’re good to go. If it’s not installed, don’t panic, you can grab it from python.org and download it on your system. I’ll wait. Got it? cool.

Checking Python version

Now, let’s get a few more things sorted, Ensure that you have access to the following items:

  • Visual Studio or VSCode (or any editor of your choice)
  • Terminal or Command prompt

With that, we are all set to install the required Flask and OpenAI libraries.

Initialize the OpenAI API

Now let’s bring the brain of our system—The OpenAI API. To use OpenAI’s API, we’ll need to sign up over the OpenAl platform and create an account. After signing in, move towards the API keys section and generate a new key. Keep this key safe because it’s your golden ticket to access the GPT models.

OpenAI signup process

If you face any difficulty in during the signup and API key generation follow this guide to use OpenAI API to learn more about OpenAI API’s. We also need to ensure our API is not exposed throughout the creation process of health diagnosis assistant.

Building backend with Flask

Now that our development environment is set, let’s start building our backend using Flask. The task of our AI-powered health diagnosis assistant is to receive user symptoms, send them to OpenAi for diagnosis, and return the response to the user. To accomplish this task, create a new Python file called app.py. Paste the following code in this file to set up a basic Flask app:

from flask import Flask, render_template, request, jsonify
import openai

app = Flask(__name__)
openai.api_key = "ENTER-YOUR-API-KEY"  # Replace with your actual OpenAI API key

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/diagnose', methods=['POST'])
def diagnose():
    try:
        data = request.get_json()  # Use get_json() to handle JSON request
        user_input = data.get('message')  # Get the 'message' key safely
        if not user_input:
            return jsonify({'error': 'No input provided'}), 400

        # Process the user input and send to OpenAI
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": user_input}]
        )
        assistant_message = response['choices'][0]['message']['content']
        return jsonify({'message': assistant_message})

    except Exception as e:
        return jsonify({'error': str(e)})

if __name__ == '__main__':
    app.run(debug=True)

The above code initializes Flask, a lightweight web server. it routes the root URL(’/’) to the index.html to serve the front end of our app. When a user clicks on the “submit” button after entering the symptoms, the /diagnose route is called which sends the symptoms to OpenAI and returns the response to the user. This setup the complete backend logic to handle the complete backend logic of our health diagnosis assistant.

Designing our friendly frontend

Now, it’s time to build our user interface for health diagnosis assistants. It’s our goal to make it simple yet intuitive for our users to share symptoms and receive feedback. Let’s start by building our structure. Create a folder in the project directory named templates and create a file index.html using the following:

mkdir templates
# For MAC users
touch templates/index.html

# For windows users
cd templates
echo. > index.html  # Using command prompt
New-Item -Path index.html -ItemType File # Using PowerShell 

The folder is set up and the file has also been created. Let’s start creating our frontend.

HTML Layout

Now paste the following code inside the index.html file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <title>Health Diagnosis Assistant</title>
</head>
<body>
    <div class="container">
        <h1>Health Diagnosis Assistant</h1>
        <div id="chatbox" class="chatbox"></div>
        <form id="messageForm">
            <input type="text" id="userInput" placeholder="Enter your symptoms..." required>
            <button type="submit">Send</button>
        </form>
    </div>
    <script src="{{ url_for('static', filename='script.js') }}"></script>
</body>
</html>

The above code provides a simple chatbot interface for interacting with the AI. Let’s try to add some life to it by adding colors in the next section.

CSS styling

Let’s style our boring health diagnosis assistant webpage by playing with some colors around it. First, let’s create a folder in the project directory named as static, and inside static folder create a file called styles.css . We can perform this action using the following code:

mkdir static
# For MAC users
touch static/style.css

# For windows users
cd static
echo. > style.css  # Using command prompt
New-Item -Path style.css -ItemType File # Using PowerShell 

Once style.css file is created paste the following code inside it:

body {
    font-family: Arial, sans-serif;
    background-color: #eae7f0; /* Light background for contrast */
    color: #333;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    margin: 0;
}

#chatContainer {
    width: 80%;
    max-width: 600px;
    background-color: #f9f7fc; /* Light purple for chat container */
    border: 1px solid #ddd;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    overflow-y: auto;
    max-height: 70vh; /* Limit height for scroll */
}

input[type="text"] {
    width: 80%;
    max-width: 600px;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin-top: 10px;
}

button {
    padding: 10px 20px;
    margin-left: 5px;
    border: none;
    border-radius: 5px;
    background-color: #5e54f2; /* Dark purple button */
    color: white;
    cursor: pointer;
}

button:hover {
    background-color: #4c43d1; /* Darker purple on hover */
}

div.message {
    margin: 5px 0;
}

.message.user {
    text-align: right; /* Align user messages to the right */
}

.message.assistant {
    text-align: left; /* Align assistant messages to the left */
    color: #5e54f2; /* Color for assistant messages */
    font-weight: bold; /* Make assistant messages bold */
}

#inputContainer {
    display: flex;
    justify-content: center;
    margin-top: 10px;
}

This code provides a modern and clean look. We have used containers to center align the overall design and use some padding to ensure our interface is user-friendly.

Setting up our Javascript

To ensure everything is functional, we will connect the front end with the back end using JavaScript. The JavaScript file will receive the symptoms, forward them to Flask, and then display the results. Let’s create a file called script.js using the following:

# For MAC users
touch static/script.js

# For windows users
cd static
echo. > script.js  # Using command prompt
New-Item -Path script.js -ItemType File # Using PowerShell 

Once script.js file is created paste the following code inside it:

document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('messageForm');
    const input = document.getElementById('userInput');
    const chatbox = document.getElementById('chatbox');

    form.addEventListener('submit', function (e) {
        e.preventDefault(); 

        const message = input.value.trim();
        if (message === '') return;

        chatbox.innerHTML += `<div class="message user-message">${message}</div>`;
        input.value = '';

        fetch('/diagnose', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ message })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if (data.error) {
                chatbox.innerHTML += `<div class="message assistant-message">Error: ${data.error}</div>`;
            } else {
                chatbox.innerHTML += `<div class="message assistant-message">${data.message}</div>`;
            }
        })
        .catch(error => {
            chatbox.innerHTML += `<div class="message assistant-message">Error: Unable to communicate with the server.</div>`;
            console.error('Error:', error);
        });
    });
});

The above code handles the form submission, it prevents the page from reloading and sends the user’s input to the Flask’s backend. Javascript ensures the interaction is conversational and seamless to ensure a smooth user experience. Now, our app is ready to be tested with real-time scenarios.

Testing our app

Now it’s time to run our application and see our AI-powered health diagnosis app in action.

Start the Flask development server by running the following command:

python app.py

It will start the server and launch the app at http://127.0.0.1:5000/. Open this link in the browser where you will be able to see the interface of our tool. Enter all the symptoms in the text box given and click Send to see your diagnosis.

<aside> 🗒️

Note: If you run into any bugs during production, don’t panic! Debugging is a part of the development journey, and it will make you better as a builder.💪

</aside>

Congratulations! You have successfully built an AI-powered Health Diagnosis Assistant using OpenAI’s API, Flask, HTML, and JavaScript. The assistant can take systems from the users, process them using AI, and provide a possible diagnosis in a user-friendly format.

This article opens the door to countless possibilities in healthcare applications. From personalized care to improved accessibility, this app is a step toward the future of AI-driven health diagnosis assistants. Feel free to experiment and enhance this basic healthcare assistant we have set up. Who knows, one day it might save a life.

Explore more on Metaschool

If you found building an AI-powered code review assistant helpful, you might be interested in exploring more hands-on projects to expand your skills. Check out our other resources on Metaschool:

  • How to Build a Code Review Assistant Using AI: We have an AI-based tool that does the heavy lifting—an assistant that reviews our code in seconds and suggests improvements based on industry standards.
  • Build an AI Dating Coach Using NextJS and OpenAI: Ever thought about creating an app that provides personalized dating advice? This course guides you through building a dating coach app that uses OpenAI’s API and NextJS to deliver insightful advice to users.
  • Build a YeBot with OpenAI API: Learn how to create a sophisticated chatbot using OpenAI’s powerful API, perfect for enhancing your understanding of AI-driven applications.

Explore these courses and more to continue your journey in AI on the Metaschool platform

FAQs

How can I get started using the assistant?

After setting up the complete health diagnosis assistant, simply enter your symptoms in the provided input field, and the assistant will generate a response based on the information provided.

Is it possible to deploy the application on a different platform?

Absolutely! You can deploy the health diagnosis assistant application on various platforms such as AWS, Google Cloud, or Azure, depending on your requirements and familiarity with those services.

How can I improve the user interface of the application?

You can enhance the user interface of health diagnos assistant by using modern front-end frameworks like React or Vue.js, and by adding responsive design techniques to improve usability across devices.