To ensure that your chatbot exclusively handles medical-related queries, you can enhance both the system prompt and implement additional safeguards within your code. Below are steps and code modifications to achieve this:
-
Strengthen the System Prompt:
Make the system message more explicit about the chatbot's role and the scope of its responses. This helps guide the language model to focus solely on medical topics.
-
Implement Input Validation:
Before processing user input, check whether the query is related to medical topics. If it's not, inform the user accordingly.
-
Add a Disclaimer:
Include a disclaimer to inform users that the chatbot provides informational purposes only and is not a substitute for professional medical advice.
-
Optional - Use a Medical-Specific Model:
Consider using models trained specifically for medical purposes, such as BioGPT, to enhance the chatbot's medical knowledge and reliability.
Below is the revised code incorporating these enhancements:
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 a simple function to check if the input is medical-related
def is_medical_query(query):
# Define keywords related to medical topics
medical_keywords = [
"symptom", "diagnosis", "treatment", "medication", "disease",
"illness", "doctor", "health", "medicine", "therapy", "clinic",
"hospital", "surgery", "injury", "vaccine", "virus", "bacteria",
"blood pressure", "heart rate", "allergy", "diabetes", "cancer",
"anxiety", "depression", "nutrition", "exercise", "wellness"
]
# Convert query to lowercase for case-insensitive matching
query_lower = query.lower()
# Check if any medical keyword is present in the query
return any(keyword in query_lower for keyword in medical_keywords)
# Define the chatbot logic
def respond(symptom_input, history: list[tuple[str, str]]):
# Include the system message in the prompt
system_message = (
"You are a healthcare assistant chatbot. Provide accurate and reliable medical advice and "
"suggestions based on the user's symptoms. If the user's question is not related to medical topics, "
"politely inform them that you can only assist with medical-related inquiries."
)
max_tokens = 150
temperature = 0.7
top_p = 0.95
# 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:"
# Check if the input is medical-related
if not is_medical_query(symptom_input):
return (
"I'm sorry, but I can only assist with medical-related questions. "
"Please consult a healthcare professional for other inquiries."
)
response = ""
try:
# Pass the user symptoms 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: Add a medical disclaimer at the end of responses
disclaimer = "\n\n*Please note that I am an AI assistant and not a licensed medical professional. For personalized medical advice, consult a healthcare provider.*"
response += disclaimer
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 medical symptoms or questions, and the chatbot will provide health-related advice. "
"This service is for informational purposes only and is not a substitute for professional medical advice."
)
)
if __name__ == "__main__":
demo.launch(server_name="10.172.2.37", server_port=5001)
Explanation of the Modifications:
-
System Message Enhancement:
The system_message has been updated to clearly define the chatbot's role and explicitly state that it should only handle medical-related queries. This helps the language model stay within the desired scope.
-
Medical Query Validation:
The is_medical_query function uses a list of predefined medical keywords to determine if the user's input pertains to medical topics. This is a basic form of input validation. For more robust validation, consider integrating natural language understanding (NLU) techniques or using more advanced keyword extraction methods.
-
Handling Non-Medical Queries:
If the user's input does not contain any medical-related keywords, the chatbot responds with a polite message informing them that it can only assist with medical inquiries.
-
Medical Disclaimer:
A disclaimer is appended to every response to emphasize that the chatbot is not a substitute for professional medical advice. This is crucial for legal and ethical considerations, especially when dealing with health-related information.
-
UI Description Update:
The Gradio interface description now includes a statement that the service is for informational purposes only, reinforcing the purpose and limitations of the chatbot.
Additional Recommendations:
-
Use a Medical-Specific Model:
While tiiuae/falcon-7b-instruct is a capable general-purpose language model, models like BioGPT or ClinicalBERT are trained specifically on medical literature and may provide more accurate and reliable medical information.
-
Implement More Sophisticated Intent Recognition:
Instead of relying solely on keyword matching, consider implementing intent recognition using NLU libraries like spaCy or Rasa to more accurately determine if a query is medical-related.
-
Regulatory Compliance:
Ensure that your chatbot complies with relevant healthcare regulations and standards, such as HIPAA in the United States, especially if it handles sensitive user data.
-
Continuous Monitoring and Feedback:
Regularly monitor the chatbot's interactions to identify and rectify instances where it may provide incorrect or inappropriate information. Implement a feedback mechanism for users to report issues.
By implementing these modifications and recommendations, your chatbot will be better equipped to handle medical-related queries responsibly and effectively.