To enhance your healthcare chatbot's responses, especially to handle general greetings appropriately and provide relevant medical advice only when symptoms are mentioned, consider the following improvements:
-
Refine the System Prompt:
- Clearly instruct the model to respond differently based on whether the user is greeting or providing symptoms.
- Emphasize understanding user intent to differentiate between casual conversation and medical inquiries.
-
Implement Intent Recognition:
- Before generating a response, determine if the user's input is a general greeting or contains specific symptoms.
- This can be achieved by using simple keyword matching or integrating a more sophisticated intent recognition system.
-
Update the Chatbot Logic:
- Modify the
respond function to handle different intents accordingly.
- Provide appropriate responses for greetings and only invoke the text-generation pipeline when medical advice is needed.
Updated Code with Enhancements
Here's an improved version of your chatbot code incorporating the above suggestions:
import gradio as gr
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
import re
# Load an open-source LLM (e.g., Falcon-7B-Instruct for better conversational capabilities)
model_name = "tiiuae/falcon-7b-instruct"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
# Create a text generation pipeline
text_generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
# Define keywords that indicate medical symptom input
SYMPTOM_KEYWORDS = [
"fever", "cough", "headache", "sore throat", "nausea", "dizziness",
"fatigue", "rash", "chest pain", "shortness of breath", "vomiting",
"diarrhea", "congestion", "sneezing", "muscle ache", "loss of taste",
"loss of smell", "abdominal pain"
]
def contains_symptoms(user_input):
# Simple keyword matching to detect symptoms
pattern = re.compile(r'\b(' + '|'.join(SYMPTOM_KEYWORDS) + r')\b', re.IGNORECASE)
return bool(pattern.search(user_input))
# Define the chatbot logic
def respond(symptom_input, history: list[tuple[str, str]]):
# Define system messages for different intents
system_message_general = (
"You are a friendly and helpful healthcare assistant chatbot. "
"Respond to the user's messages appropriately. If the user shares symptoms, "
"provide medical advice and suggestions based on those symptoms."
)
system_message_medical = (
"You are a healthcare assistant chatbot. Provide medical advice and suggestions "
"based on the user's symptoms."
)
max_tokens = 150
temperature = 0.7
top_p = 0.95
# Determine if the user input contains symptoms
if contains_symptoms(symptom_input):
system_message = system_message_medical
else:
system_message = system_message_general
# Start the prompt with the system message
prompt = f"{system_message}\n\n"
# Append conversation history
for val in history:
if val[0]:
prompt += f"User: {val[0]}\n"
if val[1]:
prompt += f"Assistant: {val[1]}\n"
prompt += f"User: {symptom_input}\nAssistant:"
response = ""
try:
# Pass the user input and conversation history to the model
generated = text_generator(
prompt,
max_new_tokens=max_tokens,
num_return_sequences=1,
temperature=temperature,
top_p=top_p,
pad_token_id=tokenizer.eos_token_id
)
# Get only the assistant's response
response = generated[0]['generated_text'][len(prompt):].strip()
# Optional: Truncate the response at the first stop signal
for stop in ["\nUser:", "\nAssistant:"]:
if stop in response:
response = response.split(stop)[0].strip()
except Exception as e:
response = f"Error during text generation: {str(e)}"
return response
# Define the UI with minimal user input
demo = gr.ChatInterface(
respond,
title="Healthcare Chatbot Assistant",
description="Enter your symptoms, and the chatbot will provide health-related advice."
)
if __name__ == "__main__":
demo.launch(server_name="10.172.2.37", server_port=5001)
Explanation of Improvements
-
Intent Recognition with contains_symptoms:
- Utilizes a simple regular expression to detect if the user's input contains any predefined symptom keywords.
- This helps the chatbot decide whether to engage in casual conversation or provide medical advice.
-
Dynamic System Messages:
- General Conversations: If the input doesn't contain symptoms, the chatbot uses a friendly and general-purpose system message to handle greetings and casual interactions.
- Medical Inquiries: When symptoms are detected, it switches to a focused system message aimed at providing medical advice.
-
Enhanced Prompt Construction:
- The prompt now dynamically includes the appropriate system message based on the detected intent.
- Ensures that the model's responses are contextually relevant to the user's input.
-
Response Truncation (Optional):
- After generating the response, the code checks for any unintended continuations (like another user's input) and truncates the response to maintain clarity.
Additional Recommendations
Sample Improved Interaction
User: Hi
Assistant: Hello! How can I assist you with your health today?
User: I've been having a severe headache and dizziness.
Assistant: I'm sorry to hear that you're experiencing a severe headache and dizziness. It's important to stay hydrated, rest, and monitor your symptoms. If the headache persists or worsens, please consult a healthcare professional.
This setup ensures that greetings are handled gracefully while medical advice is provided only when appropriate, resulting in a more natural and helpful user experience.