How to Create a Healthcare Assistant Chatbot Using Rasa and Python
With the rise of AI and conversational interfaces, healthcare assistants are becoming increasingly valuable for providing support, information, and even triage in medical settings. Using Rasa, an open-source framework for building conversational AI, you can develop a healthcare assistant tailored to meet specific needs in the healthcare industry. This guide will walk you through the steps to develop an AI chatbot using Rasa and Python.
This repository contains the code for the Shipment Tracking and healthcare-related Domain questions. The goal of this project is to create an interactive chatbot that allows users to track the status of their shipment orders and handle queries related to healthcare domain and weight loss programs, including 3-month, 6-month, and trial plans. The chatbot uses Rasa for natural language understanding and dialogue management, integrates with shipment tracking APIs, and utilizes a web interface for user interaction.
Features
- Email verify: Verify the email to check user is existing or not in real time.
- Order Tracking: Track the status of shipment orders in real-time.
- Plans for weight loss: you can ask questions related to plans for weight loss.
- Interactive Q&A: Ask questions and receive answers related to Healthcare Domain.
- User-Friendly Interface: Built with a web framework for ease of use.
- Integration with Shipment APIs: Retrieves real-time shipment data.
- Natural Language Understanding : Utilizes Rasa for robust dialogue management.
- Integrated to whatsapp using twillo : The chatbot is integrated with WhatsApp using Twilio for seamless user interaction..
Github Link for the code:
https://github.com/langchain-tech/rasa-bot
Setting Up Your Rasa Environment
Before we start building our healthcare assistant, ensure Python and pip are installed on your system. Here are the steps to set up the Rasa environment:
1. Install Rasa:
Open your terminal and run:
pip install rasa
2. Create a Rasa Project:
Navigate to your desired directory and initialize a new Rasa project:
rasa init
Follow the prompts to set up your project.
Understanding Key Rasa Concepts
- Intents: The goals or intentions behind user messages (e.g., asking for symptoms, requesting appointment details).
- Entities: Specific pieces of information in user messages (e.g., symptoms, dates).
- Actions: The responses or tasks executed by the chatbot.
- Stories: Sequences of user intents and chatbot actions that represent dialogues.
Rasa Project Structure
Your Rasa project will have a structure similar to this:
my_healthcare_assistant/
├── actions/
│ ├── actions.py
│ ├── data/
│ │ ├── weight_management_plans.csv
│ │ └── dummy_data_200_rows.csv
│ └── helpers/
│ └── reply_helper.py
├── data/
│ ├── nlu.yml
│ ├── rules.yml
│ └── stories.yml
├── models/
├── config.yml
├── credentials.yml
├── domain.yml
├── endpoints.yml
└── tests/
└── conversation_tests/
Define Intents:
In nlu.yml
, define the intents and regex related to healthcare. For example:
nlu:
- intent: ask_order
examples: |
- What's the status of my order?
- Can you tell me where my order is?
- intent: ask_order_number
examples: |
- [274305793037](tracking_number)
- [274455580039](tracking_number)
- intent: ask_program
examples: |
- what plans do you have
- what programs you will provide
- intent: ask_email
examples: |
- [[email protected]](email)
- [[email protected]](email)
- intent: ask_number
examples: |
- [0](program_number)
- [1](program_number)
- intent: greet
examples: |
- hey
- hello
- intent: goodbye
examples: |
- cu
- good by
- intent: bot_challenge
examples: |
- are you a bot?
- are you a human?
- regex: tracking_number
examples: |
- [0-9]{12}
- regex: program_number
examples: |
- [0-9]{1}
2. Create Responses:
In domain.yml
, define responses for each intent:
responses:
utter_greet:
- text: "Hey! How are you?"
utter_ask_email:
- text: "Please enter your email?"
utter_ask_order_number:
- text: "Sure, What is your order number?"
utter_cheer_up:
- text: "Here is something to cheer you up:"
image: "https://i.imgur.com/nGF1K8f.jpg"
utter_goodbye:
- text: "Bye"
utter_iamabot:
- text: "I am a bot, powered by Rasa."
3. Configure Actions and Domain:
Also in domain.yml
, list your intents, actions, entities, and slots:
intents:
- greet
- goodbye
- bot_challenge
- ask_order
- ask_order_number
- ask_program
- ask_number
- ask_email
entities:
- tracking_number
- program_number
slots:
email:
type: text
mappings:
- type: from_entity
entity: email
tracking_number:
type: text
mappings:
- type: from_entity
entity: tracking_number
program_number:
type: text
mappings:
- type: from_entity
entity: program_number
results:
type: text
mappings:
- type: custom
action: action_show_program
actions:
- action_order_details
- action_show_program
- action_show_details
- action_verify_email
4. Implement Custom Actions:
In actions/actions.py
, implement logic for checking order status.
import os
from typing import Any, Text, Dict, List
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
from .helpers.reply_helper import extract_name_from_excel
from rasa_sdk.events import SlotSet
import pandas as pd
import logging
import requests
from dotenv import load_dotenv
load_dotenv()
HOME_DIR = os.getenv("HOME_DIR")
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
class DataloadAPI(object):
def __init__(self):
file_path=f"{HOME_DIR}/actions/data/weight_management_plans.csv"
self.db = pd.read_csv(file_path)
def fetch_data(self):
return self.db.head()
def format_data(self, df, header=True) -> Text:
return df.to_csv(index=False, header=header)
dataload_api = DataloadAPI()
class ActionVerifyEmail(Action):
def name(self) -> Text:
return "action_verify_email"
def run(self, dispatcher: CollectingDispatcher,tracker: Tracker,domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
email_slot = next(tracker.get_latest_entity_values("email"), None)
email = tracker.get_slot("email") or email_slot
session_id=tracker.sender_id
logging.info(session_id)
if email:
name = extract_name_from_excel(email=email)
if name:
result = f"Hello {name}, welcome to Rasa bot! We're here to assist with any questions you might have about your orders and weight loss programs. Feel free to ask!"
else:
result = "We couldn't find any data associated with this email, but we have received your information. We're here to assist with any questions you might have about your orders and weight loss programs. Feel free to ask!"
dispatcher.utter_message(text=result)
return []
class ActionOrderDetails(Action):
def name(self) -> Text:
return "action_order_details"
def run(self, dispatcher: CollectingDispatcher,tracker: Tracker,domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
tracking_number_slot = next(tracker.get_latest_entity_values("tracking_number"), None)
tracking_number = tracker.get_slot("tracking_number") or tracking_number_slot
data=self.get_data(tracking_number)
res=f"The tracking number is: {tracking_number} and the related information for this order is shown below \n{data}"
dispatcher.utter_message(text=res)
return []
@staticmethod
def get_data(tracking_number: str) -> Dict[Text, Any]:
try:
file_path=f"{HOME_DIR}/actions/data/dummy_data_200_rows.csv"
df = pd.read_csv(file_path)
df['Tracking Number'] = df['Tracking Number'].astype(str)
result = df[df['Tracking Number'] == tracking_number]
if result.empty:
return "Data is not availbe with this tracking number please recheck it and try again.."
first_name =result["First Name"].values[0]
last_name = result["Last Name"].values[0]
email = result["Email"].values[0]
order_date = result["Order date"].values[0]
medication = result["Medication"].values[0]
delivery_status = result["Delivery Status"].values[0]
vial_size = result["Vial size"].values[0]
formatted_result = (
f"First name: {first_name}\n"
f"Last name: {last_name}\n"
f"Email: {email}\n"
f"Order date: {order_date}\n"
f"Medication: {medication}\n"
f"Delivery status: {delivery_status}\n"
f"Vial size: {vial_size}\n"
)
return formatted_result
except:
return "Some issue: with dataframe"
In actions/helpers/reply_helper.py
, implement logic for read data from csv file.
import os
import pandas as pd
import json
import logging
from dotenv import load_dotenv
load_dotenv()
HOME_DIR = os.getenv("HOME_DIR")
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
import pdb
def extract_rows_excel(email: str):
file_path = f"{HOME_DIR}/actions/data/dummy_data_200_rows.csv"
df = pd.read_csv(file_path)
matching_rows = df[df['Email'] == email]
logger.info(matching_rows)
matching_rows_json = matching_rows.to_json(orient='records')
matching_rows_dict = json.loads(matching_rows_json)
logger.info(matching_rows_dict)
return matching_rows_dict
def extract_name_from_excel(email: str):
matching_rows = extract_rows_excel(email)
if matching_rows:
first_name = matching_rows[0]['First Name']
last_name = matching_rows[0]['Last Name']
return f"{first_name} {last_name}"
else:
return None
5. Define Stories:
In data/stories.yml
, outline example conversations:
stories:
- story: track order by order number
steps:
- intent: ask_order
- action: utter_ask_order_number
- intent: ask_order_number
entities:
- tracking_number: "274305793037"
- action: action_order_details
- story: program details
steps:
- intent: ask_program
- action: action_show_program
- intent: ask_number
entities:
- program_number: "1"
- action: action_show_details
- story: happy path
steps:
- intent: greet
- action: utter_greet
- action: utter_ask_email
- intent: ask_email
- action: action_verify_email
6. Train Your Chatbot:
Train your model by running:
rasa train
7. Test Your Chatbot:
Test the chatbot locally using:
rasa shell
Result:
Deployment Strategies
Deploying your Rasa chatbot to production with expert Rasa developers requires thoughtful planning. Consider the following deployment strategies:
- Containerization: Utilize Docker to containerize your Rasa chatbot, facilitating deployment and scalability.
- Webhooks: Integrate your chatbot with messaging platforms or web applications using webhooks, enabling seamless communication.
- Chatbot Hosting Platforms: Explore chatbot hosting platforms that offer simplified deployment and management, streamlining the deployment process.
These strategies ensure a smooth transition of your medical AI chatbot from development to production, providing scalability, reliability, and ease of management.
Dynamic Responses with Custom Actions
Custom actions in Rasa enable dynamic responses in AI chatbot development based on user input and external data sources. For instance, you can create a check order status chatbot that fetches real-time weather information from an API, providing personalized weather updates to users based on their location.
To implement custom actions:
- Define the actions in your
domain.yml
file. - Create Python scripts to handle the logic.
- Connect them to your chatbot using Rasa's action server.
This setup allows your healthcare AI chatbot to deliver tailored and up-to-date responses, significantly enhancing user interaction and engagement.
Slot Filling Strategies
Slot filling is essential for conversational agents, especially in complex scenarios where multiple user inputs contribute to filling a single slot. Rasa enables you to define custom slot-filling strategies to manage these situations effectively.
By leveraging Rasa's flexible slot-filling capabilities, you can:
- Specify required slots in the
domain.yml
file. - Use forms to systematically gather slot information from users.
- Implement custom slot mapping logic in your Python scripts.
This approach ensures that your chatbot accurately captures and processes the necessary information from users, enhancing the overall conversational experience.
Conclusion
By following these steps, you can create robust medical assistant bots using Rasa and Python. This assistant can handle basic tracking order status and show programs for weight loss and provide initial symptom assessments, improving the efficiency and accessibility of healthcare services. With continuous iteration and enhancement, your healthcare assistant can become an invaluable tool in delivering quality healthcare support.
FAQ's
1. What is Rasa in chatbot?
Rasa is a tool to build custom AI chatbots using Python and natural language understanding (NLU). Rasa provides a framework for developing AI chatbots that use natural language understanding (NLU). It also allows the user to train the model and add custom actions.
2. Is Rasa AI free?
Yes, Rasa offers an open-source framework for building conversational AI assistants, which is free to use. This open-source framework provides the tools needed to build, train, and deploy AI-powered chatbots and virtual assistants. However, they also offer additional enterprise features and support through their Rasa Platform, which is a paid offering.
3. Does Rasa use Python?
Yes, Rasa is primarily built using Python. It's an open-source framework that leverages Python to develop conversational AI assistants. Python is a popular programming language in the field of artificial intelligence and machine learning, making it a natural choice for developing such frameworks. With Python's extensive libraries and community support, Rasa developers can efficiently create and customize chatbots and virtual assistants.
4. What is the full form of Rasa?
Rasa doesn't have a specific full form like some acronyms do. Instead, Rasa is a word derived from Sanskrit, meaning essence, taste, or flavor. In the context of the Rasa framework for conversational AI, it signifies the essence of natural language understanding and dialogue management, which are central components of building effective chatbots and virtual assistants.
5. What is the benefit of Rasa?
Rasa offers a powerful open-source framework for building conversational AI assistants, providing flexibility and control over every aspect of development. Its natural language understanding (NLU) capabilities enable precise interpretation of user inputs, enhancing the conversational experience. With Rasa's dialogue management, developers can create contextually aware interactions, leading to more meaningful conversations. The platform supports integration with various channels, including web, messaging apps, and voice interfaces, ensuring broad accessibility. Furthermore, Rasa's active community and extensive documentation empower developers to innovate and scale their AI projects efficiently.
6. How to host Rasa chatbot?
To host a Rasa chatbot, you can deploy it on cloud platforms like AWS, Google Cloud, or Azure using Docker containers. Alternatively, you can use services like Heroku for simpler deployment, utilizing their container or web dynos. Once deployed, configure a web server (like NGINX or Apache) to route incoming requests to your Rasa chatbot instance for interaction.
7. What is a medical chatbot using Rasa?
A medical chatbot using Rasa could be designed to assist users with various healthcare-related tasks, such as symptom checking, medication reminders, appointment scheduling, and providing general health information. It would leverage Rasa's natural language understanding (NLU) capabilities to interpret user queries accurately and respond with relevant information or actions. Additionally, the chatbot could integrate with external databases or APIs to access medical knowledge bases, drug databases, or appointment systems for more comprehensive functionality.
8. Is Rasa good for chatbots?
Yes, Rasa is well-regarded for building chatbots and conversational AI assistants. Its open-source framework provides developers with extensive flexibility and control over the chatbot's behavior and functionality. With features like natural language understanding (NLU), dialogue management, and integrations with various platforms, Rasa enables the creation of sophisticated and effective chatbot solutions. Additionally, Rasa has a thriving community and comprehensive documentation, making it a popular choice for building chatbots across various industries and use cases.
9. How do I create a chatbot for healthcare?
To create a healthcare chatbot, start by defining its purpose, such as symptom checking, appointment scheduling, or medication reminders. Next, choose a platform like Rasa for building the chatbot, leveraging its NLU capabilities for understanding user queries accurately. Design conversational flows tailored to healthcare scenarios, ensuring the bot can guide users through relevant interactions. Integrate the chatbot with medical databases or APIs to provide accurate information and assistance based on user inquiries. Continuously iterate and improve the chatbot's performance by gathering feedback and refining its responses and functionality over time.
10. What type of AI is Rasa?
Rasa is a framework for building conversational AI, specifically focusing on chatbots and virtual assistants. It incorporates various techniques from artificial intelligence, including natural language understanding (NLU) for interpreting user inputs, dialogue management for guiding conversations, and machine learning for improving its performance over time. Rasa can be categorized as a tool for developing AI-powered conversational agents, designed to understand and respond to human language in a natural and contextually aware manner.