To enhance your Gradio application by allowing users to provide more cohesive and detailed feedback while maintaining the required dataset format (prompt, completion, and label), you can implement additional UI elements such as a slider and a comment box that appear in a popup when users upvote or downvote a response. Here's a step-by-step guide to achieve this:
-
Introduce a Modal for Detailed Feedback:
Utilize Gradio's gr.Modal to create a popup that prompts users for additional feedback whenever they click the upvote or downvote buttons.
-
Manage Voting State:
Use Gradio's gr.State to keep track of whether the user is upvoting or downvoting. This information is essential to correctly label the feedback.
-
Collect and Store Additional Feedback:
After users submit their detailed feedback via the modal, store this information separately from the primary dataset to maintain the required format. This can be saved in an additional JSON file.
-
Update the UI to Integrate the Modal:
Modify the existing UI to include the modal and ensure it interacts seamlessly with the current layout and functionalities.
Below is the updated code incorporating these enhancements:
import gradio as gr
from llama_cpp import Llama
import os
import json
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
# Imports
from huggingface_hub import hf_hub_download
from llama_cpp import Llama
# Initialize the Llama model
# Download the GGUF model
model_name = "johnpaulbin/qwen2.5-3b-tokipona-v4-merged-fp16-chat-Q8_0-GGUF"
model_file = "qwen2.5-3b-tokipona-v4-merged-fp16-chat-q8_0.gguf" # This is the specific model file we'll use in this example.
model_path = hf_hub_download(model_name, filename=model_file)
# Instantiate model from downloaded file
llm = Llama(
model_path=model_path,
n_ctx=1024, # Context length to use
n_threads=2, # Number of CPU threads to use
n_gpu_layers=-1, # Number of model layers to offload to GPU
chat_format="chatml",
flash_attn=True
)
# Initialize the conversation with a system prompt
system_prompt = "sina ilo Elelen. sina jan pona pi wile pali. sina pona tawa jan ante li wile pali pona tawa ona."
initial_messages = [{"role": "system", "content": system_prompt}]
# Initialize the dataset
dataset = {
"prompt": [],
"completion": [],
"label": []
}
# Initialize additional feedback storage
additional_feedback = {
"slider": [],
"comment": []
}
def generate_response(user_message, chat_history, messages):
# Append the user's message to the conversation history
messages = messages + [{"role": "user", "content": user_message}]
print(messages)
# Call the model to get assistant's response
try:
response = llm.create_chat_completion(
messages=messages,
temperature=0.0,
top_p=1,
top_k=1,
frequency_penalty=1
)
assistant_response = response['choices'][0]['message']['content']
# Append the assistant's response to the conversation history
messages = messages + [{"role": "assistant", "content": assistant_response}]
# Update the chat history
chat_history = chat_history + [(user_message, assistant_response)]
return "", chat_history, messages
except ValueError as e:
print(f"Error: You've reached the max context length for the model. Clear the conversation to continue typing.")
assistant_response = "Error: You've reached the max context length for the model. Clear the conversation to continue typing."
# Append the assistant's response to the conversation history
messages = messages + [{"role": "assistant", "content": assistant_response}]
# Update the chat history
chat_history = chat_history + [(user_message, assistant_response)]
return "", chat_history, messages
def prepare_feedback(prompt, completion, label, slider, comment):
# Read existing data from feedback.json
try:
with open('feedback.json', 'r') as f:
existing_data = json.load(f)
except FileNotFoundError:
existing_data = {'prompt': [], 'completion': [], 'label': []}
try:
with open('additional_feedback.json', 'r') as f:
existing_additional = json.load(f)
except FileNotFoundError:
existing_additional = {'slider': [], 'comment': []}
# Check for duplicates
duplicate = False
for p, c in zip(existing_data['prompt'], existing_data['completion']):
if p == prompt and c == completion:
duplicate = True
break
if not duplicate:
existing_data['prompt'].append(prompt)
existing_data['completion'].append(completion)
existing_data['label'].append(label)
# Save to feedback.json
with open('feedback.json', 'w') as f:
json.dump(existing_data, f, ensure_ascii=False, indent=4)
# Save additional feedback
existing_additional['slider'].append(slider)
existing_additional['comment'].append(comment)
with open('additional_feedback.json', 'w') as f:
json.dump(existing_additional, f, ensure_ascii=False, indent=4)
print("Feedback has been submitted! Thank you for your input.")
notification = "Your feedback has been submitted! Thank you for your input."
else:
notification = "You have already submitted feedback for this conversation."
return notification
def open_feedback_modal(vote_type, state_vote_type):
# Set the current vote type and open the modal
state_vote_type = vote_type
return gr.update(visible=True), state_vote_type
def submit_feedback(slider_value, comment_text, state_vote_type, messages_state, chat_history):
if len(messages_state) < 2:
return "No conversation to submit feedback for."
# Construct the full conversation history
full_conversation = ""
for msg in messages_state:
if msg['role'] == 'system':
full_conversation += f"system\n{msg['content']}\n"
elif msg['role'] == 'user':
full_conversation += f"user\n{msg['content']}\n"
elif msg['role'] == 'assistant':
full_conversation += f"assistant\n{msg['content']}"
# Split the conversation into prompt and completion
prompt_parts = full_conversation.rsplit("assistant", 1)
prompt = prompt_parts[0]
completion = f"assistant{prompt_parts[1]}" if len(prompt_parts) > 1 else ""
# Determine label based on vote_type
label = True if state_vote_type == "upvote" else False
# Prepare and save feedback
notification = prepare_feedback(prompt, completion, label, slider_value, comment_text)
return notification, gr.update(visible=False), "", [] # Clear slider and comment after submission
def clear_history():
return [], initial_messages
def retry_response(chat_history, messages):
notification = ""
# Check if there is an assistant response to retry
if len(messages) >= 2 and messages[-1]['role'] == 'assistant':
# Remove the last assistant message from messages
messages = messages[:-1]
# Remove the last exchange from chat_history
if len(chat_history) >= 1:
chat_history = chat_history[:-1]
# Regenerate the assistant's response
try:
response = llm.create_chat_completion(
messages=messages,
temperature=0.2,
top_p=0.95,
top_k=5,
frequency_penalty=1
)
assistant_response = response['choices'][0]['message']['content']
# Append the assistant's response to the conversation history
messages = messages + [{"role": "assistant", "content": assistant_response}]
chat_history = chat_history + [(messages[-2]['content'], assistant_response)]
return chat_history, messages, notification
except ValueError as e:
assistant_response = "Error: You've reached the max context length for the model. Clear the conversation to continue typing."
# Append the assistant's response to the conversation history
messages = messages + [{"role": "assistant", "content": assistant_response}]
# Update the chat history
chat_history = chat_history + [(messages[-2]['content'], assistant_response)]
return chat_history, messages, notification
else:
notification = "Nothing to retry."
return chat_history, messages, notification
with gr.Blocks() as demo:
gr.Markdown("# Toki Pona LLM")
gr.Markdown("Help improve the model by voting after testing it! Note: The model best performs in a toki-pona-only conversation.")
messages_state = gr.State(initial_messages)
dataset_state = gr.State(dataset)
additional_feedback_state = gr.State(additional_feedback)
vote_type_state = gr.State(value=None) # To store whether it's an upvote or downvote
chat_history = gr.Chatbot()
with gr.Row():
user_message = gr.Textbox(placeholder="Enter your message")
send_button = gr.Button("Send")
with gr.Row():
upvote_button = gr.Button("Upvote 👍")
downvote_button = gr.Button("Downvote 👎")
retry_button = gr.Button("Retry ♻️")
clear_button = gr.Button("Clear History 🗑️")
notification = gr.Markdown("")
# Define the feedback modal
with gr.Modal() as feedback_modal:
gr.Markdown("## Additional Feedback")
slider = gr.Slider(label="Satisfaction", minimum=0, maximum=10, step=1, value=5)
comment = gr.Textbox(label="Comments", placeholder="Enter your comments here...")
submit_feedback_button = gr.Button("Submit Feedback")
# When upvote is clicked
upvote_button.click(
lambda: open_feedback_modal("upvote", "upvote"),
inputs=[],
outputs=[feedback_modal, vote_type_state]
)
# When downvote is clicked
downvote_button.click(
lambda: open_feedback_modal("downvote", "downvote"),
inputs=[],
outputs=[feedback_modal, vote_type_state]
)
# When feedback is submitted
submit_feedback_button.click(
submit_feedback,
inputs=[slider, comment, vote_type_state, messages_state, chat_history],
outputs=[notification, feedback_modal, slider, comment]
)
send_button.click(
generate_response,
inputs=[user_message, chat_history, messages_state],
outputs=[user_message, chat_history, messages_state]
)
# for the ENTER key
user_message.submit(
generate_response,
inputs=[user_message, chat_history, messages_state],
outputs=[user_message, chat_history, messages_state]
)
retry_button.click(
retry_response,
inputs=[chat_history, messages_state],
outputs=[chat_history, messages_state, notification]
)
clear_button.click(
clear_history,
outputs=[chat_history, messages_state]
)
demo.launch(debug=True)
Detailed Explanation of Enhancements
-
Feedback Modal Implementation:
- Modal Creation: A Gradio
gr.Modal named feedback_modal is created to collect additional feedback. This modal contains a slider for satisfaction rating and a comment box for user comments.
- Opening the Modal: When the user clicks either the Upvote or Downvote button, the
open_feedback_modal function is triggered, setting the current vote type (upvote or downvote) and making the modal visible.
-
Managing Vote Type:
- State Variable: A new state variable
vote_type_state is introduced using gr.State(value=None) to keep track of whether the user is upvoting or downvoting. This ensures that the correct label (True for upvote, False for downvote) is assigned when storing feedback.
-
Submitting Additional Feedback:
- Feedback Submission Function: The
submit_feedback function handles the submission of detailed feedback. It retrieves the satisfaction slider value and the user's comments, determines the label based on the vote type, and calls the prepare_feedback function to store the feedback.
- Storing Feedback: The
prepare_feedback function ensures that duplicate feedback is not stored and appends both the primary feedback (prompt, completion, label) and the additional feedback (slider, comment) to their respective JSON files (feedback.json and additional_feedback.json).
-
UI Integration:
- Buttons Interaction: The Upvote and Downvote buttons are linked to functions that open the feedback modal and set the appropriate vote type.
- Feedback Modal Interaction: Within the modal, users can adjust the satisfaction slider and provide comments. Upon clicking the Submit Feedback button, their inputs are processed and stored accordingly.
-
Preserving Dataset Format:
- Separate Storage for Additional Feedback: To adhere to the requirement of maintaining the , , and structure, additional feedback (slider values and comments) are stored separately in . This ensures that the primary dataset remains unaffected and suitable for training purposes.
Benefits of These Enhancements
-
Enhanced Feedback Quality: By allowing users to provide a satisfaction rating and comments, you gain more nuanced insights into user experiences, which can be invaluable for refining and improving the model.
-
Maintained Dataset Integrity: The primary dataset remains clean and adheres to the required format, ensuring compatibility with training pipelines and other downstream processes.
-
Improved User Engagement: Offering users the opportunity to provide detailed feedback can increase their engagement and sense of contribution, fostering a more interactive and community-driven development environment.
Additional Recommendations
-
Validation and Error Handling: Ensure that user inputs in the feedback modal are validated. For instance, you might want to enforce that comments are not left empty or that the slider is moved to a meaningful value before submission.
-
Feedback Analysis: Consider developing separate scripts or tools to analyze the additional feedback stored in additional_feedback.json. This can help in identifying common issues, understanding user sentiments, and prioritizing model improvements.
-
Data Privacy: If deploying this application publicly, be mindful of data privacy concerns. Ensure that collected feedback does not contain personally identifiable information unless explicitly intended and consented to by users.
By implementing these enhancements, your Gradio application will not only collect structured feedback suitable for model training but also gather rich, qualitative insights that can drive meaningful improvements.