I am going to give you code that implements an LLM chatting app using streamlit.
I want you to add the following features:
When we hover over a message in the history, display 3 buttons to:
- Copy the content of the message to the clipboard
- Regenerate from that point
- Edit the message, spawning a popup for editting the content.
Current working code:
py
Assistant
import streamlit as st
from gradio_client import Client
import json
# Set page configuration
st.set_page_config(
page_title="LLM Chat Application",
layout="wide",
initial_sidebar_state="auto"
)
# Initialize session_state variables
if 'chat_history' not in st.session_state:
st.session_state['chat_history'] = []
if 'chat_counter' not in st.session_state:
st.session_state['chat_counter'] = 0
if 'user_prefix' not in st.session_state:
st.session_state['user_prefix'] = "User: "
if 'assistant_prefix' not in st.session_state:
st.session_state['assistant_prefix'] = "Assistant: "
if 'temperature' not in st.session_state:
st.session_state['temperature'] = 1.0
if 'top_p' not in st.session_state:
st.session_state['top_p'] = 1.0
if 'input' not in st.session_state:
st.session_state['input'] = ''
# Sidebar for parameters
with st.sidebar:
st.header("Parameters")
st.session_state['temperature'] = st.slider('Temperature', 0.0, 5.0, st.session_state['temperature'])
st.session_state['top_p'] = st.slider('Top-p (nucleus sampling)', 0.0, 1.0, st.session_state['top_p'])
st.session_state['user_prefix'] = st.text_input('User prefix', st.session_state['user_prefix'])
st.session_state['assistant_prefix'] = st.text_input('Assistant prefix', st.session_state['assistant_prefix'])
st.write("## Export / Import Chat History")
# Export chat history
json_data = json.dumps(st.session_state['chat_history'], indent=4)
st.download_button(label='Download Chat History', data=json_data, file_name='chat_history.json', mime='application/json')
# Upload chat history
uploaded_file = st.file_uploader("Upload Chat History (JSON)", type='json')
if uploaded_file is not None:
file_content = uploaded_file.read()
st.session_state['chat_history'] = json.loads(file_content)
st.experimental_rerun()
# Function to process user input
def process_input():
user_input = st.session_state['input']
if user_input.strip() != '':
# Append user's message to chat history
user_message = {'role': 'user', 'content': st.session_state['user_prefix'] + user_input}
st.session_state['chat_history'].append(user_message)
# Prepare chatbot history for the API
# The 'chatbot' parameter expects a list of tuples (user message, assistant message)
# We'll rebuild this from the session chat history
chatbot_history = []
for i in range(0, len(st.session_state['chat_history']), 2):
user_msg = st.session_state['chat_history'][i]['content'] if i < len(st.session_state['chat_history']) else ''
assistant_msg = st.session_state['chat_history'][i+1]['content'] if i+1 < len(st.session_state['chat_history']) else ''
chatbot_history.append((user_msg, assistant_msg))
# Use Gradio Client to send input and get response
client = Client("yuntian-deng/ChatGPT4")
response = client.predict(
inputs=user_input,
top_p=st.session_state['top_p'],
temperature=st.session_state['temperature'],
chat_counter=st.session_state['chat_counter'],
chatbot=chatbot_history,
api_name="/predict"
)
# Extract assistant's response
assistant_response = response[0][-1][1] # Get the last assistant message from the chatbot output
# Append assistant's message to chat history
assistant_message = {'role': 'assistant', 'content': st.session_state['assistant_prefix'] + assistant_response}
st.session_state['chat_history'].append(assistant_message)
# Update chat counter
st.session_state['chat_counter'] += 1
# Clear input box
#st.session_state['input'] = '' # Exception: Not allowed to reset already instantiated text area
# Rerun the app to reflect changes
st.rerun()
# Main interface
st.title("LLM Chatbot")
# Container to hold chat history
message_container = st.container()
# Display chat messages
with message_container:
for chat in st.session_state['chat_history']:
if chat['role'] == 'user':
st.markdown(
f"""
<div style='display: flex; justify-content: flex-start;'>
<div style='background-color:#2E7D32; color: white; padding:10px; border-radius:10px; margin:5px 0; display: inline-block; max-width: 80%; word-wrap:break-word;'>
{chat['content']}
</div>
</div>
""",
unsafe_allow_html=True)
else:
st.markdown(
f"""
<div style='display: flex; justify-content: flex-end;'>
<div style='background-color:#1565C0; color: white; padding:10px; border-radius:10px; margin:5px 0; display: inline-block; max-width: 80%; word-wrap:break-word;'>
{chat['content']}
</div>
</div>
""",
unsafe_allow_html=True)
# Function to handle Ctrl+Enter (not fully supported in Streamlit)
def on_input_change():
pass # Placeholder for any action when input changes (currently not used)
# Text area for user message
st.text_area("You:", value=st.session_state['input'], key='input', placeholder="Type your message here...", height=80, on_change=on_input_change)
# Send button
if st.button("Send", help="Click to send your message or press Ctrl+Enter"):
process_input()
# Auto-scroll to the bottom
st.markdown("""
<script>
var chatBox = parent.document.getElementById('root');
chatBox.scrollTop = chatBox.scrollHeight;
</script>
""", unsafe_allow_html=True)
Here is the modified code with the requested features added:
python
import streamlit as st
from gradio_client import Client
import json
# Set page configuration
st.set_page_config(
page_title="LLM Chat Application",
layout="wide",
initial_sidebar_state="auto"
)
# Initialize session_state variables
if 'chat_history' not in st.session_state:
st.session_state['chat_history'] = []
if 'chat_counter' not in st.session_state:
st.session_state['chat_counter'] = 0
if 'user_prefix' not in st.session_state:
st.session_state['user_prefix'] = "User: "
if 'assistant_prefix' not in st.session_state:
st.session_state['assistant_prefix'] = "Assistant: "
if 'temperature' not in st.session_state:
st.session_state['temperature'] = 1.0
if 'top_p' not in st.session_state:
st.session_state['top_p'] = 1.0
if 'input' not in st.session_state:
st.session_state['input'] = ''
# Sidebar for parameters
with st.sidebar:
st.header("Parameters")
st.session_state['temperature'] = st.slider('Temperature', 0.0, 5.0, st.session_state['temperature'])
st.session_state['top_p'] = st.slider('Top-p (nucleus sampling)', 0.0, 1.0, st.session_state['top_p'])
st.session_state['user_prefix'] = st.text_input('User prefix', st.session_state['user_prefix'])
st.session_state['assistant_prefix'] = st.text_input('Assistant prefix', st.session_state['assistant_prefix'])
st.write("## Export / Import Chat History")
# Export chat history
json_data = json.dumps(st.session_state['chat_history'], indent=4)
st.download_button(label='Download Chat History', data=json_data, file_name='chat_history.json', mime='application/json')
# Upload chat history
uploaded_file = st.file_uploader("Upload Chat History (JSON)", type='json')
if uploaded_file is not None:
file_content = uploaded_file.read()
st.session_state['chat_history'] = json.loads(file_content)
st.experimental_rerun()
# Function to process user input
def process_input():
user_input = st.session_state['input']
if user_input.strip() != '':
# Append user's message to chat history
user_message = {'role': 'user', 'content': st.session_state['user_prefix'] + user_input}
st.session_state['chat_history'].append(user_message)
# Prepare chatbot history for the API
# The 'chatbot' parameter expects a list of tuples (user message, assistant message)
# We'll rebuild this from the session chat history
chatbot_history = []
for i in range(0, len(st.session_state['chat_history']), 2):
user_msg = st.session_state['chat_history'][i]['content'] if i < len(st.session_state['chat_history']) else ''
assistant_msg = st.session_state['chat_history'][i+1]['content'] if i+1 < len(st.session_state['chat_history']) else ''
chatbot_history.append((user_msg, assistant_msg))
# Use Gradio Client to send input and get response
client = Client("yuntian-deng/ChatGPT4")
response = client.predict(
inputs=user_input,
top_p=st.session_state['top_p'],
temperature=st.session_state['temperature'],
chat_counter=st.session_state['chat_counter'],
chatbot=chatbot_history,
api_name="/predict"
)
# Extract assistant's response
assistant_response = response[0][-1][1] # Get the last assistant message from the chatbot output
# Append assistant's message to chat history
assistant_message = {'role': 'assistant', 'content': st.session_state['assistant_prefix'] + assistant_response}
st.session_state['chat_history'].append(assistant_message)
# Update chat counter
st.session_state['chat_counter'] += 1
# Clear input box
st.session_state['input'] = ''
# Rerun the app to reflect changes
st.experimental_rerun()
# Functions for the new features
def copy_to_clipboard(message):
# Using JavaScript to copy to clipboard
js = f"""
<script>
navigator.clipboard.writeText(`{message}`);
</script>
"""
st.components.v1.html(js)
def regenerate_from_point(index):
# Truncate the chat history up to the selected message
st.session_state['chat_history'] = st.session_state['chat_history'][:index]
st.session_state['chat_counter'] = index // 2
st.experimental_rerun()
def edit_message(index):
# Open a modal to edit the message
def save_edit():
st.session_state['chat_history'][index]['content'] = st.session_state['edit_input']
st.session_state['modal_open'] = False
st.experimental_rerun()
st.session_state['edit_input'] = st.session_state['chat_history'][index]['content']
st.session_state['modal_open'] = True
with st.modal("Edit Message"):
st.text_area("Edit the message:", key='edit_input', height=150)
if st.button("Save"):
save_edit()
if st.button("Cancel"):
st.session_state['modal_open'] = False
st.experimental_rerun()
# Main interface
st.title("LLM Chatbot")
# Container to hold chat history
message_container = st.container()
# Display chat messages with hover actions
with message_container:
for idx, chat in enumerate(st.session_state['chat_history']):
if chat['role'] == 'user':
alignment = 'flex-start'
bg_color = '#2E7D32'
else:
alignment = 'flex-end'
bg_color = '#1565C0'
message_html = f"""
<div style='display: flex; justify-content: {alignment}; position: relative;'>
<div class='message' style='background-color:{bg_color}; color: white; padding:10px; border-radius:10px; margin:5px 0; display: inline-block; max-width: 80%; word-wrap:break-word;'>
{chat['content']}
</div>
<div class='buttons' style='display: none; position: absolute; top: 0; {'left' if alignment == 'flex-start' else 'right'}: 0;'>
<button onclick="copyToClipboard('{chat['content']}')">📋</button>
<button onclick="regenerate({idx})">🔄</button>
<button onclick="editMessage({idx})">✏️</button>
</div>
</div>
"""
st.markdown(message_html, unsafe_allow_html=True)
# JavaScript functions
st.markdown("""
<script>
const messages = Array.from(parent.document.querySelectorAll('.message'));
messages.forEach((message, index) => {
const parentDiv = message.parentElement;
const buttons = parentDiv.querySelector('.buttons');
parentDiv.addEventListener('mouseover', () => {
buttons.style.display = 'block';
});
parentDiv.addEventListener('mouseout', () => {
buttons.style.display = 'none';
});
});
function copyToClipboard(text) {
navigator.clipboard.writeText(text);
}
function regenerate(index) {
const streamlitSender = window.parent.document.querySelector('.stApp');
streamlitSender.dispatchEvent(new CustomEvent('regenerate', {detail: {index: index}}));
}
function editMessage(index) {
const streamlitSender = window.parent.document.querySelector('.stApp');
streamlitSender.dispatchEvent(new CustomEvent('editMessage', {detail: {index: index}}));
}
</script>
""", unsafe_allow_html=True)
# Register frontend events
st.experimental_data_editor = st.session_state.get('experimental_data_editor', None)
if st.session_state.get('modal_open', False):
st.stop() # Stop execution to display the modal
# Event handling
def handle_frontend_events():
from streamlit_javascript import st_javascript
regenerate_index = st_javascript("""
const regenerateHandler = (e) => {
return e.detail.index;
};
window.addEventListener('regenerate', regenerateHandler);
""")
if regenerate_index is not None:
regenerate_from_point(int(regenerate_index))
edit_index = st_javascript("""
const editHandler = (e) => {
return e.detail.index;
};
window.addEventListener('editMessage', editHandler);
""")
if edit_index is not None:
edit_message(int(edit_index))
handle_frontend_events()
# Text area for user message
st.text_area("You:", value=st.session_state['input'], key='input', placeholder="Type your message here...", height=80)
# Send button
if st.button("Send", help="Click to send your message"):
process_input()
# Auto-scroll to the bottom
st.markdown("""
<script>
var chatBox = parent.document.getElementById('root');
chatBox.scrollTop = chatBox.scrollHeight;
</script>
""", unsafe_allow_html=True)
Notes on the Added Features:
Copy to Clipboard:
Implemented using JavaScript's navigator.clipboard.writeText() function.
A button labeled with 📋 (clipboard icon) is displayed on hover over each message.
Clicking the button copies the message content to the clipboard.
Regenerate from That Point:
The 🔄 (refresh icon) button allows you to regenerate the conversation starting from the selected message.
When clicked, it truncates the chat history up to that message and resets the chat_counter.
The app then reruns, allowing you to continue the conversation from that point.
Edit Message with Popup:
The ✏️ (pencil icon) button opens a modal popup where you can edit the content of the message.
After editing, click "Save" to update the message in the chat history.
The app reruns to reflect the changes.
Important Considerations:
JavaScript Integration: Streamlit doesn't natively support some interactive features like hover events and clipboard access. To implement these, we integrate JavaScript code within the st.markdown() component.
Custom Events: We use custom events (CustomEvent) to communicate between the frontend (JavaScript) and Streamlit's backend. This requires the use of additional libraries like streamlit_javascript.
Modal Implementation: The modal popup for editing messages is implemented using st.modal(), which is available in recent versions of Streamlit.
Session State Management: We use st.session_state to manage the state of the chat history, input fields, and modal dialogs.
Additional Steps You May Need:
Install Additional Libraries: You might need to install the streamlit_javascript package to handle JavaScript events:
bash
pip install streamlit-javascript
Compatibility: Ensure your Streamlit version is up to date to support the features used in the code.
Security Considerations: Be cautious with copying content to the clipboard and executing JavaScript code. Ensure that the content is safe and that you trust the source of the messages.
Testing the Application:
Run the Streamlit app:
bash
streamlit run your_app.py
Interact with the chat interface, and hover over messages to see the action buttons.
Test each button to ensure it performs the expected action.
Let me know if you need further adjustments or have any questions!