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}]
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}]
code
# 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
Assistant
def upvote_click(chat_history, messages, dataset):
notification = "Your feedback has been submitted! Feel free to keep chatting or clear the history."
if len(messages) >= 2:
# Construct the full conversation history
full_conversation = ""
for msg in messages:
if msg['role'] == 'system':
full_conversation += f"<|im_start|>system\n{msg['content']}<|im_end|>\n"
elif msg['role'] == 'user':
full_conversation += f"<|im_start|>user\n{msg['content']}<|im_end|>\n"
elif msg['role'] == 'assistant':
full_conversation += f"<|im_start|>assistant\n{msg['content']}<|im_end|>"
code
# Split the conversation into prompt and completion
prompt_parts = full_conversation.rsplit("<|im_start|>assistant", 1)
prompt = prompt_parts[0]
completion = f"<|im_start|>assistant{prompt_parts[1]}" if len(prompt_parts) > 1 else ""
# 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': []}
# 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(True)
# Save to feedback.json
with open('feedback.json', 'w') as f:
json.dump(existing_data, f)
dataset = existing_data
print("Upvoted the response! YAAY!!!")
else:
notification = "You have already submitted feedback for this conversation."
else:
notification = "No conversation to submit feedback for."
return dataset, notification
def downvote_click(chat_history, messages, dataset):
notification = "Your feedback has been submitted! Feel free to keep chatting or clear the history."
if len(messages) >= 2:
# Construct the full conversation history
full_conversation = ""
for msg in messages:
if msg['role'] == 'system':
full_conversation += f"<|im_start|>system\n{msg['content']}<|im_end|>\n"
elif msg['role'] == 'user':
full_conversation += f"<|im_start|>user\n{msg['content']}<|im_end|>\n"
elif msg['role'] == 'assistant':
full_conversation += f"<|im_start|>assistant\n{msg['content']}<|im_end|>"
code
# Split the conversation into prompt and completion
prompt_parts = full_conversation.rsplit("<|im_start|>assistant", 1)
prompt = prompt_parts[0]
completion = f"<|im_start|>assistant{prompt_parts[1]}" if len(prompt_parts) > 1 else ""
# 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': []}
# 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(False)
# Save to feedback.json
with open('feedback.json', 'w') as f:
json.dump(existing_data, f)
dataset = existing_data
print("Downvoted the response!")
else:
notification = "You have already submitted feedback for this conversation."
else:
notification = "No conversation to submit feedback for."
return dataset, notification
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}]
code
# Update the chat history
chat_history = chat_history + [(user_message, 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)
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("")
Help me with this problem: The model needs to have a more cohesive feedback that the user can provide, but it must be in the dataset format of: prompt, completion, and label. The label is only binary of true and false and the format is unable to change. But you are free to do anything to help make the model's feedback more useful for training. Feel free to add more UI elements, e.g. when downvoting or upvoting, to do this. (Have a slider allowing the user to rate usefulness, accuracy, fluency plus a comment box the user can use)
To enhance the feedback mechanism for your language model while maintaining the required dataset format (prompt, completion, label), you can introduce additional UI elements such as sliders for rating usefulness, accuracy, and fluency, along with a comment box. These enhancements will provide more granular feedback without altering the primary dataset structure. Here's how you can implement these improvements:
Add Additional UI Elements:
Sliders: Allow users to rate the response on different dimensions.
Comment Box: Let users provide free-form feedback or suggestions.
Modify Feedback Functions:
Upvote/Downvote Functions: Collect additional feedback and store it separately.
Data Storage: Maintain the original feedback.json for the dataset and create a new detailed_feedback.json for the additional feedback.
Update the Gradio Interface:
Integrate the new UI components seamlessly with the existing interface.
Step-by-Step Implementation
1. Update Imports and Initialize Additional Feedback Storage
Ensure you import necessary modules and set up storage for detailed feedback.
python
import gradio as gr
from llama_cpp import Llama
import os
import json
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
from huggingface_hub import hf_hub_download
from llama_cpp import Llama
# Initialize the Llama 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"
model_path = hf_hub_download(model_name, filename=model_file)
llm = Llama(
model_path=model_path,
n_ctx=1024,
n_threads=2,
n_gpu_layers=-1,
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 datasets
dataset = {
"prompt": [],
"completion": [],
"label": []
}
detailed_feedback = {
"prompt": [],
"completion": [],
"label": [],
"usefulness": [],
"accuracy": [],
"fluency": [],
"comment": []
}
2. Modify Feedback Functions to Collect Additional Data
Update the upvote_click and downvote_click functions to handle extra feedback inputs.
python
3. Update the Gradio Interface with New UI Elements
Incorporate sliders and a comment box into the interface and connect them to the feedback functions.
python
4. Explanation of Changes
Additional UI Elements:
Accordions: Added an accordion titled "Provide Detailed Feedback" to house the sliders and comment box. This keeps the interface clean and allows users to choose when to provide detailed feedback.
Sliders: Three sliders are added for Usefulness, Accuracy, and Fluency, each ranging from 0 to 5.
Comment Box: A textbox for users to add any additional comments or suggestions.
Feedback Functions:
Parameters: The upvote_click and downvote_click functions now accept additional parameters: usefulness, accuracy, fluency, and comment.
Detailed Feedback Storage: Besides updating the main feedback.json, these functions also log the additional feedback into a separate detailed_feedback.json file to preserve the dataset format.
UI Integration:
Inputs for Feedback: The additional feedback elements are passed as inputs to the feedback functions.
Outputs: The main feedback functions return the updated dataset and a notification message.
5. Benefits of This Approach
Maintains Dataset Integrity: The primary feedback.json remains unchanged with only the required prompt, completion, and label fields, ensuring compatibility with your training pipeline.
Rich Feedback Data: The additional detailed_feedback.json captures nuanced user opinions, which can be invaluable for model analysis, fine-tuning, and improving user experience.
User-Friendly Interface: By using accordions and organized UI elements, users can provide detailed feedback without feeling overwhelmed.
6. Potential Enhancements
Validation: Implement validation to ensure that users provide meaningful ratings and comments.
Feedback Summary: Display summaries or aggregated feedback statistics to inform users how their feedback is being utilized.
Privacy Considerations: Ensure that comments and detailed feedback are stored securely, respecting user privacy.
Final Notes
By following the above implementation, you enhance the feedback mechanism, providing a more comprehensive understanding of user interactions with your model. This approach strikes a balance between maintaining the necessary dataset format and enriching feedback data for continuous improvement.