Building A HealthBot Using Chainlit And OpenAI
Published: 2024-03-29 16:23:21

In this tutorial, we’ll delve into the world of Chainlit, an open-source Python package designed to expedite the development of Chat GPT-like applications by seamlessly integrating your unique business logic and data. We’ll explore how to harness the power of Chainlit to build intelligent and customized HealthBot applications, leveraging its capabilities to create a responsive and context-aware conversational experience. Combined with OpenAI, this tutorial will guide you through the process of constructing a HealthBot that not only understands health-related queries but also incorporates your specific business requirements. Let’s embark on the journey of building an innovative HealthBot using Chainlit and OpenAI.

Before we get started take a look at the end product

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h8yagzpe8bkb5kedo86r.png)



### 
Prerequisites
To assure the project’s effective execution, developing an application that resembles ChatGPT utilizing Chainlit and OpenAI demands a particular level of technical expertise.

These are the primary fields of competence that are required:

- Python Programming
-  Principles of Artificial Intelligence and Machine Learning
-  API Integration and OpenAI API Key Access

### Understanding Chainlit
Chainlit is an open-source Python module that has been painstakingly designed to facilitate the rapid building of Chat-like applications by allowing you to easily integrate your unique business logic and data. Specifically designed to build ChatGPT-like apps, it offers a quick and efficient way to integrate into existing code bases or start projects from scratch. With features like data permanence, quick iteration tools, and quick build times, Chainlit is a versatile tool that works with all Python applications and modules. It finds great use in a wide range of AI and machine learning endeavors, particularly those based around conversational AI, thanks to integrations for prominent frameworks and libraries. It provides a ChatGPT-like frontend for instant use, but it also gives customers the ability to customize their frontend using Chainlit as a reliable backend.

### Key Features

- Fast and Easy Development: Chainlit provides a step-based approach to building LLM applications, making it quick and efficient to get your bot up and running.
- Customizable UI: You can create a custom user interface for your Chainlit application, ensuring it seamlessly integrates with your brand and user experience.
- Integrations: Chainlit integrates with various tools and libraries, including OpenAI, Haystack, and Llama Index, allowing you to leverage their functionalities within your application.
- Robust Features: Chainlit offers features like authentication, monitoring, data streaming, and multi-user support, making your application secure, scalable, and reliable.
Overall, Chainlit is a powerful and versatile tool for building chatbot applications.

### Building The HealthBot
After setting up the python environment the next step will be to install all necessary dependencies.

```
pip install chainlit
pip install --upgrade openai
```
Step 2: Create the main application using Chainlit


```
import chainlit as cl
from src.llm import ask_doctor, messages


@cl.on_message
async def main(message: cl.Message):
    # Your custom logic goes here...
    messages.append({"role": "user", "content": message.content})
    response = ask_doctor(messages)
    messages.append({"role": "assistant", "content": response})

    # Send a response back to the user
    await cl.Message(
        content =response,
    ).send()
```


The above code is the app.py version of the entire application. This code segment, utilizing Chainlit, serves as a key part of a chatbot implementation. It intercepts and processes user messages, appending them to a message list. Subsequently, it calls the `ask_doctor` function, incorporating the accumulated messages to generate a response from a doctor-like entity. The assistant’s reply is then appended to the message list. Finally, the response is sent back to the user, maintaining a conversational flow. The `messages` list retains the entire conversation, offering a record of interactions for future analysis or reference.

### Step 3: Build the llm.py section`

```
`from openai import OpenAI
from src.prompt import health_prompts

client = OpenAI()

messages = [
    {"role": "system", "content": health_prompts}
]

def ask_doctor(messages, model="gpt-3.5-turbo",temperature=0):
    response = client.chat.completions.create(
        model= model,
        messages=  messages,
        temperature= temperature 
    )
return response.choices[0].message.content
`

```



This Python code uses the OpenAI library to create a health chatbot powered by the GPT-3.5-turbo model. The chatbot receives user messages, appends them to a list of messages, and utilizes the `ask_doctor` function to obtain responses from the language model. The code includes predefined health prompts for the chatbot to start the conversation. It sets up a communication loop where the user’s messages trigger model responses, and the assistant’s replies are sent back to the user. The temperature parameter in the ask_doctor function controls the randomness of the model’s responses, offering a dynamic interaction experience.

Step 4:The next step will be to build the prompt which the application runs on



```
Customize your health-related prompts and information if necessary.
health_prompts = '''
 Health Bot Information

 General Health:

- What are the benefits of regular exercise?
  - Exercise helps improve cardiovascular health, boost mood, and maintain a healthy weight.

- How many hours of sleep are recommended for adults?
  - Adults should aim for 7-9 hours of sleep per night for optimal health.

- What are some healthy eating tips?
  - Include a variety of fruits, vegetables, whole grains, and lean proteins in your diet.

 Mental Health:

- How to manage stress effectively?
  - Practice relaxation techniques, exercise, and prioritize self-care.

- Tips for better mental well-being?
  - Connect with others, practice gratitude, and seek professional help if needed.
 Nutrition:

- What are some superfoods for a balanced diet?
  - Include foods like berries, leafy greens, nuts, and fatty fish in your diet.

- How to stay hydrated throughout the day?
  - Drink at least 8 glasses of water daily and consume hydrating foods.

 Fitness:

- Recommended daily physical activity for adults?
  - Aim for at least 150 minutes of moderate-intensity exercise per week.

- Effective home workouts for beginners?
  - Try bodyweight exercises, yoga, or brisk walking.

'''

context_health = [{'role': 'system',
                  'content': f"""
You are HealthBot, an AI assistant for health-related inquiries.

Your role is to provide information on general health, mental well-being, nutrition, and fitness.

Feel free to answer health-related questions, share tips, and encourage users to adopt a healthy lifestyle.

Below are some health-related prompts:

```{health_prompts}```

Make the health-related interactions informative and encourage users to ask about any health concerns or seek advice.
"""}]


```

This code defines a set of health-related prompts and information for a chatbot called HealthBot. The prompts cover topics such as general health, mental well-being, nutrition, and fitness. Each prompt includes a question and a brief, informative answer. The code sets up the context for the HealthBot, describing its role as an AI assistant for health-related inquiries. The assistant is encouraged to provide information, answer questions, and promote a healthy lifestyle. The system context includes the predefined health prompts, ready for the HealthBot to interact with users, offering valuable health-related advice and tips.

So before we run the application let’s add a welcome note to the front page that tells users what the bot is all about


 

```
Doctor Klaus - Your Health Companion

Greetings! I'm Doctor Klaus, your dedicated health companion on this wellness journey. 🌟

In my virtual clinic, I'm here to provide you with valuable health insights, answer your health-related queries, and offer guidance on leading a healthier lifestyle. Let me tell you a bit about myself:

👨‍⚕️ About Doctor Klaus:
- I'm an AI-powered health assistant designed to assist you with a wide range of health inquiries.
- My knowledge spans various health topics, including exercise, nutrition, mental well-being, and general health guidelines.
- Your well-being is my priority, and I'm here to make your health journey more accessible, informative, and tailored to your needs.

💡 How I Can Assist You:
- Answering your general health questions.
- Providing tips for mental well-being and stress management.
- Sharing information on nutrition and healthy eating habits.
- Recommending personalized fitness routines and exercises.

🌐 How to Interact with Me:
- Simply ask me your health-related questions, and I'll provide you with accurate and relevant information.
- Whether you're curious about specific health topics or seeking advice on wellness practices, I'm here for you.

Embark on this wellness adventure with me, Doctor Klaus! Together, we'll explore the path to a healthier, happier you. For any health-related queries, type your questions below, and let's kickstart your journey to well-being. 🚀💚
```
```

**Run the Application**
To start your Chainlit app, open a terminal and navigate to the directory containing app.py. Then run the following command:

```

chainlit run app.py -w
```
The -w flag tells Chainlit to enable auto-reloading, so you don’t need to restart the server every time you make changes to your application. Your chatbot UI should now be accessible at [](http://localhost:8000.)


We can see that the app is working you can then go ahead and ask any health related questions.

### Conclusion
Building a health bot is more than just code and AI. It’s about empowering users with reliable information and promoting informed choices about their well-being. This journey, while ambitious, becomes surprisingly accessible thanks to the incredible capabilities of Chainlit.

Chainlit acts as your user-friendly architect, crafting a seamless interface where your health bot shines. You don’t need to be a coding wizard — Chainlit’s features and intuitive structure let you build a beautiful and interactive platform for your bot to engage with users.

But Chainlit’s magic extends beyond aesthetics. It acts as the communication bridge, translating complex AI responses into clear and user-friendly language. Think of it as your health bot’s personal translator, ensuring every interaction is informative and engaging.