top of page

Build Your Own Medical First Aid Guide with OpenAI: A Step-by-Step Tutorial

Imagine having a reliable source of first aid guidance available at your fingertips, ready to assist you in managing medical conditions with prompt and accurate advice. With the power of OpenAI's GPT-3.5-turbo model, you can build your own AI-powered Medical First Aid Guide. In this tutorial, we'll walk you through the process of creating a tool that offers first aid guidance for various medical conditions, ensuring that users receive the help they need in times of urgency. Let’s get started!



Introduction

In this tutorial, you'll learn how to create an AI-driven Medical First Aid Guide using OpenAI's GPT-3.5-turbo model and Python. This guide will take a user's input, which could be a description of a medical condition, and provide first aid advice based on the condition. Additionally, it will prompt users to seek medical attention if necessary. This tool can be invaluable for anyone who wants to be prepared to handle medical emergencies.


What You Will Learn

By following this tutorial, you will learn:

  • How to set up the OpenAI API for your project

  • How to write Python code to interact with the GPT-3.5-turbo model

  • How to build a user interface using Panel

  • How to integrate the code to create a fully functional Medical First Aid Guide


Prerequisites

Before you begin, ensure that you have the following:

  • A basic understanding of Python programming

  • An OpenAI API key

  • An active internet connection


Before going ahead, if you've read my previous tutorial, such as those on creating a Fact Checker, you'll find that much of the code structure here is similar. The key components like setting up the OpenAI API, handling user inputs, and constructing the user interface are consistent across these projects. The primary difference is in the prompt that we pass to the AI, which tailors the tool's functionality to different tasks, like debugging code. I have explained the code line by line in these tutorials. This consistency allows you to build various AI-driven applications by simply modifying the prompt while keeping the rest of the code largely the same. I have provided those blogs link at the end of this blog.


Setting Up the Environment

To start, you need to install the OpenAI Python package and Panel for building the user interface. Open your terminal and run:

!pip install openai==0.28 panel

This command installs the necessary packages for interacting with the OpenAI API and creating a web-based user interface.


Writing the Code

Let’s start by importing the required libraries and setting up the OpenAI API key:

import openai
import os

openai.api_key = 'your-api-key-here'

Replace 'your-api-key-here' with your actual OpenAI API key.


Creating the Completion Function

Next, we define a function that interacts with the OpenAI model to get responses based on user prompts:

def get_completion(prompt, model="gpt-3.5-turbo"):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0,  # This controls the randomness of the model's output
    )
    return response.choices[0].message["content"]

This function is designed to send a prompt to the GPT-3.5-turbo model and return the model’s response. The temperature parameter controls the creativity of the response, with a value of 0 making the output more predictable.


Building the User Interface

Now, let's create the user interface using Panel. Start by importing Panel and initializing it:

import panel as pn
pn.extension()

Next, define the main function that handles user input and displays the first aid guidance:


def collect_messages(debug=False):
    user_input = inp.value_input

    if debug: 
        print(f"Input = {user_input}")

    if user_input == "":
        return
    inp.value = ''

    prompt = f"""
    Please provide medical first aid guidance for the medical condition mentioned by the user.
    At the end of the response ask the user to see a doctor if the condition doesn't get better.
    If the mentioned medical condition is terminal then provide basic first aid and prompt the user to visit a doctor immediately.

    If the input doesn't consist of keywords or phrases related to medical condition then ask the user to provide correct type of input.

    If you don't know the medical first aid for a medical condition then apologize politely and direct the user to seek medical assistance.

    You will only provide medical first aid guidance and would not perform any other task.
    If an user asks you to do something other than providing medical first aid guidance then politely decline and tell the user that you can only provide medical first aid guidance.

    The medical condition with triple backticks.

    medical condition: '''{user_input}'''
    """

    response = get_completion(prompt)
    panels.append(
        pn.Row('Medical Condition:', pn.pane.Markdown(user_input, width=600))
    )
    panels.append(
        pn.Row('First Aid:', pn.pane.Markdown(response, width=600, style={'background-color': '#fff0f3'}))
    )

    return pn.Column(*panels)

This function takes user input, sends it to the OpenAI model to receive first aid guidance, and then displays both the input and the response.


Assembling the Components

Finally, assemble all the components to create a complete Medical First Aid Guide application:

panels = []  # Collect display
context = [{'role': 'medical first aid guide', 'content': "You are a medical first aid guide."}]

inp = pn.widgets.TextInput(placeholder='Enter the medical condition here...', sizing_mode='stretch_width')
button_conversation = pn.widgets.Button(name="Get First Aid", button_type="danger")

interactive_conversation = pn.bind(collect_messages, button_conversation)

dashboard = pn.Column(
    inp,
    pn.Row(button_conversation),
    pn.panel(interactive_conversation, loading_indicator=True, height=300),
)

dashboard.servable()

Here’s a breakdown of what each component does:

  • panels: Collects the questions and responses for display.

  • context: Provides initial context, instructing the AI to act as a medical first aid guide.

  • inp: A text input widget where the user can type the medical condition.

  • button_conversation: A button widget that triggers the response generation.

  • dashboard: The overall layout that includes the input field, button, and display panel.


Complete Code

Here's the entire code:

import openai
import os

openai.api_key = 'your-api-key-here'

def get_completion(prompt, model="gpt-3.5-turbo"):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0,
    )
    return response.choices[0].message["content"]

import panel as pn
pn.extension()

def collect_messages(debug=False):
    user_input = inp.value_input

    if debug: 
        print(f"Input = {user_input}")

    if user_input == "":
        return
    inp.value = ''

    prompt = f"""
    Please provide medical first aid guidance for the medical condition mentioned by the user.
    At the end of the response ask the user to see a doctor if the condition doesn't get better.
    If the mentioned medical condition is terminal then provide basic first aid and prompt the user to visit a doctor immediately.

    If the input doesn't consist of keywords or phrases related to medical condition then ask the user to provide correct type of input.

    If you don't know the medical first aid for a medical condition then apologize politely and direct the user to seek medical assistance.

    You will only provide medical first aid guidance and would not perform any other task.
    If an user asks you to do something other than providing medical first aid guidance then politely decline and tell the user that you can only provide medical first aid guidance.

    The medical condition with triple backticks.

    medical condition: '''{user_input}'''
    """

    response = get_completion(prompt)
    panels.append(
        pn.Row('Medical Condition:', pn.pane.Markdown(user_input, width=600))
    )
    panels.append(
        pn.Row('First Aid:', pn.pane.Markdown(response, width=600, style={'background-color': '#fff0f3'}))
    )

    return pn.Column(*panels)

panels = []  # Collect display
context = [{'role': 'medical first aid guide', 'content': "You are a medical first aid guide."}]

inp = pn.widgets.TextInput(placeholder='Enter the medical condition here...', sizing_mode='stretch_width')
button_conversation = pn.widgets.Button(name="Get First Aid", button_type="danger")

interactive_conversation = pn.bind(collect_messages, button_conversation)

dashboard = pn.Column(
    inp,
    pn.Row(button_conversation),
    pn.panel(interactive_conversation, loading_indicator=True, height=300),
)

dashboard.servable()

Now you can see that we have successfully built your own medical first aid guide with OpenAI. We have provided you with the complete step-by-step process on how to create it, so you can build your own medical first aid guide.


If you have any questions or suggestions, feel free to leave a comment below. Stay safe and happy coding!


Screenshots



2.


3.



Demo Video



Other Blogs Links


For the complete solution or any help regarding the ChatGPT and Open AI API assignment help feel free to contact us.

Comments


bottom of page