import gradio as gr
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
import logging
Set up logging
logging.basicConfig(level=logging.INFO)
Load the model and tokenizer
model_name = "tiiuae/falcon-7b-instruct"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
Initialize the text-generation pipeline
text_generator = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer,
device=0 # Use GPU if available; remove or set to -1 for CPU
)
Define the chatbot logic
def respond(symptom_input, history: list[tuple[str, str]]):
system_message = (
"You are a healthcare assistant chatbot. Your goal is to provide health-related information "
"and suggest possible non-diagnostic insights. Encourage users to consult healthcare professionals for diagnosis."
)
code
max_tokens = 150
temperature = 0.7
top_p = 0.95
# Construct the prompt with the system message
prompt = f"{system_message}\n\n"
# Append conversation history with clear roles
for user_msg, assistant_msg in history:
if user_msg:
prompt += f"User: {user_msg}\n"
if assistant_msg:
prompt += f"Assistant: {assistant_msg}\n"
# Append the latest user input
prompt += f"User: {symptom_input}\nAssistant:"
logging.info(f"Constructed Prompt:\n{prompt}")
try:
# Generate a response from 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
)
response_content = generated[0]['generated_text'][len(prompt):].strip()
logging.info(f"Model Response:\n{response_content}")
# Post-processing
if not response_content.endswith('.'):
response_content += '.'
if 'consult a healthcare professional' not in response_content.lower():
response_content += " Please consult a healthcare professional for personalized advice."
response = response_content
except Exception as e:
response = f"Error during text generation: {str(e)}"
logging.error(f"Generation Error: {str(e)}")
return response
Assistant
Define the Gradio Chat Interface
demo = gr.ChatInterface(
fn=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.0.233", server_port=5001) # Adjust server_name as needed
The response generation have this "User" Can you remove it
Certainly! To remove the "User:" prefix from the generated responses in your chatbot, you can adjust how you process the model's output. There are a couple of approaches to achieve this:
Trim the Response at the Next "User:" Occurrence:
Ensure that if the model tries to continue the conversation by adding another "User:", you truncate the response right before that happens.
Use Regular Expressions to Extract the Assistant's Response:
Utilize regex to extract only the text following "Assistant:" and before any subsequent "User:" or end of the text.
Below, I'll demonstrate both methods and incorporate them into your existing code.
Method 1: Truncate at the Next "User:"
This method involves splitting the generated text at the next occurrence of "User:" and retaining only the assistant's response.
python
import gradio as gr
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
import logging
# Set up logging
logging.basicConfig(level=logging.INFO)
# Load the model and tokenizer
model_name = "tiiuae/falcon-7b-instruct"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
# Initialize the text-generation pipeline
text_generator = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer,
device=0 # Use GPU if available; remove or set to -1 for CPU
)
# Define the chatbot logic
def respond(symptom_input, history: list[tuple[str, str]]):
system_message = (
"You are a healthcare assistant chatbot. Your goal is to provide health-related information "
"and suggest possible non-diagnostic insights. Encourage users to consult healthcare professionals for diagnosis."
)
max_tokens = 150
temperature = 0.7
top_p = 0.95
# Construct the prompt with the system message
prompt = f"{system_message}\n\n"
# Append conversation history with clear roles
for user_msg, assistant_msg in history:
if user_msg:
prompt += f"User: {user_msg}\n"
if assistant_msg:
prompt += f"Assistant: {assistant_msg}\n"
# Append the latest user input
prompt += f"User: {symptom_input}\nAssistant:"
logging.info(f"Constructed Prompt:\n{prompt}")
try:
# Generate a response from 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
)
generated_text = generated[0]['generated_text']
response_content = generated_text[len(prompt):].strip()
logging.info(f"Model Response (Raw):\n{response_content}")
# Truncate at the next "User:" if present
if "User:" in response_content:
response_content = response_content.split("User:")[0].strip()
# Post-processing
if not response_content.endswith('.'):
response_content += '.'
if 'consult a healthcare professional' not in response_content.lower():
response_content += " Please consult a healthcare professional for personalized advice."
response = response_content
except Exception as e:
response = f"Error during text generation: {str(e)}"
logging.error(f"Generation Error: {str(e)}")
return response
# Define the Gradio Chat Interface
demo = gr.ChatInterface(
fn=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.0.233", server_port=5001) # Adjust server_name as needed
Method 2: Using Regular Expressions
Alternatively, you can use the re module to extract the assistant's response more precisely.
python
import gradio as gr
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
import logging
import re # Import the regex module
# Set up logging
logging.basicConfig(level=logging.INFO)
# Load the model and tokenizer
model_name = "tiiuae/falcon-7b-instruct"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
# Initialize the text-generation pipeline
text_generator = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer,
device=0 # Use GPU if available; remove or set to -1 for CPU
)
# Define the chatbot logic
def respond(symptom_input, history: list[tuple[str, str]]):
system_message = (
"You are a healthcare assistant chatbot. Your goal is to provide health-related information "
"and suggest possible non-diagnostic insights. Encourage users to consult healthcare professionals for diagnosis."
)
max_tokens = 150
temperature = 0.7
top_p = 0.95
# Construct the prompt with the system message
prompt = f"{system_message}\n\n"
# Append conversation history with clear roles
for user_msg, assistant_msg in history:
if user_msg:
prompt += f"User: {user_msg}\n"
if assistant_msg:
prompt += f"Assistant: {assistant_msg}\n"
# Append the latest user input
prompt += f"User: {symptom_input}\nAssistant:"
logging.info(f"Constructed Prompt:\n{prompt}")
try:
# Generate a response from 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
)
generated_text = generated[0]['generated_text']
response_content = generated_text[len(prompt):].strip()
logging.info(f"Model Response (Raw):\n{response_content}")
# Use regex to extract text until the next "User:" or end of string
match = re.search(r"^(.*?)(User:|$)", response_content, re.DOTALL)
if match:
response_content = match.group(1).strip()
# Post-processing
if not response_content.endswith('.'):
response_content += '.'
if 'consult a healthcare professional' not in response_content.lower():
response_content += " Please consult a healthcare professional for personalized advice."
response = response_content
except Exception as e:
response = f"Error during text generation: {str(e)}"
logging.error(f"Generation Error: {str(e)}")
return response
# Define the Gradio Chat Interface
demo = gr.ChatInterface(
fn=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.0.233", server_port=5001) # Adjust server_name as needed
Explanation of Changes
Truncating at the Next "User:"
After generating the response, check if "User:" exists in the response_content.
If it does, split the content at "User:" and retain only the part before it.
This ensures that any unintended continuation of the conversation is discarded.
Using Regular Expressions
The regex pattern r"^(.*?)(User:|$)" captures everything from the start until it encounters "User:" or the end of the string.
re.DOTALL allows the . character in the regex to match newline characters, ensuring multi-line responses are handled correctly.
This method is more robust, especially if the assistant's response spans multiple lines.
Post-processing Steps
Ensure that the response ends with a period for proper formatting.
Append a reminder to consult a healthcare professional if it's not already present in the response.
Additional Recommendations
Setting a Stop Sequence (Advanced):
While the above methods handle the removal of "User:" from the responses, another approach is to instruct the model to stop generating further text once it begins a new user input. This can be achieved by defining custom stopping criteria. However, this requires more advanced manipulation of the generation process and may involve subclassing or modifying the generation pipeline.
Input Sanitization:
Always sanitize user inputs to prevent any potential security issues, especially when deploying the chatbot in a public or sensitive environment.
Logging:
Ensure that sensitive information from user inputs or model responses is handled appropriately in logs to maintain user privacy.
Final Note
By implementing one of the above methods, your chatbot should generate responses without the unwanted "User:" prefix, resulting in cleaner and more user-friendly interactions.
If you encounter any further issues or have additional requirements, feel free to ask!