Certainly! Below is the modified Streamlit code incorporating your requested changes:
- Default to Wide Mode: The app is set to use Streamlit's wide layout for a better viewing experience.
- Single Exchange Display: Removed the "Exchange 1" labels and instead display user and bot messages side by side without exchange numbering.
- Ctrl + Return to Submit: Added JavaScript to listen for the
Ctrl + Enter key combination to submit the message.
- Clear Input Field on Submit: The input field is cleared automatically after the message is sent.
import streamlit as st
from gradio_client import Client
import json
import os
# 1. Set the page to wide mode
st.set_page_config(layout="wide")
# Initialize client
@st.cache_resource
def get_client():
return Client('yuntian-deng/o1mini')
client = get_client()
# File path for history
HISTORY_FILE = 'history.json'
# Load history
def load_history():
if os.path.exists(HISTORY_FILE):
try:
with open(HISTORY_FILE, 'r') as f:
history = json.load(f)
# Ensure history is a list of dictionaries with 'user' and 'bot'
if isinstance(history, list) and all(isinstance(entry, dict) for entry in history):
return history
except:
pass
return []
# Save history
def save_history(history):
with open(HISTORY_FILE, 'w') as f:
json.dump(history, f, indent=2)
# Initialize session state
if 'history' not in st.session_state:
st.session_state.history = load_history()
if 'new_message' not in st.session_state:
st.session_state.new_message = ''
st.title("Interactive Chat Interface")
st.markdown("### Chat History")
# 2. Display and edit history without "Exchange N" labels
for idx, entry in enumerate(st.session_state.history):
user_key = f"user_{idx}"
bot_key = f"bot_{idx}"
# Display user and bot messages side by side
col1, col2 = st.columns(2)
with col1:
st.text_area("User:", value=entry.get('user', ''), key=user_key, height=100)
with col2:
st.text_area("Bot:", value=entry.get('bot', ''), key=bot_key, height=100)
# Update history with edited text
st.session_state.history[idx]['user'] = st.session_state[user_key]
st.session_state.history[idx]['bot'] = st.session_state[bot_key]
st.markdown("---")
st.markdown("### New Message")
# 3. Input for new message with a unique key
new_message = st.text_area("Enter your message here:", height=100, key='new_message')
# 4. Button to send message with a unique key
send_button = st.button("Send", key='send_button')
if send_button:
if new_message.strip() != "":
# Append user message to history
st.session_state.history.append({'user': new_message.strip(), 'bot': ""})
save_history(st.session_state.history)
# Prepare inputs for the model
inputs = []
for entry in st.session_state.history:
inputs.append(entry['user'])
if entry['bot']:
inputs.append(entry['bot'])
# Call the model
try:
result = client.predict(
inputs=inputs,
top_p=1,
temperature=1,
chat_counter=0,
chatbot=[],
api_name='/predict'
)
if result and len(result) > 0 and len(result[0]) > 0 and len(result[0][0]) > 1:
output = result[0][0][1]
else:
output = "Sorry, I couldn't generate a response."
except Exception as e:
output = f"Error: {str(e)}"
# Append bot response to history
st.session_state.history[-1]['bot'] = output
save_history(st.session_state.history)
# 4. Clear the input area
st.session_state.new_message = ''
st.experimental_rerun()
# Button to save edits
if st.button("Save Edits", key='save_edits_button'):
save_history(st.session_state.history)
st.success("Edits saved successfully!")
# 3. Add JavaScript for Ctrl + Enter to send the message
st.components.v1.html("""
<script>
// Function to send the message when Ctrl + Enter is pressed
document.addEventListener('keydown', function(e) {
if (e.ctrlKey && e.key === 'Enter') {
e.preventDefault();
// Find the send button by its label
const buttons = window.parent.document.querySelectorAll('button');
for (let btn of buttons) {
if (btn.innerText === 'Send') {
btn.click();
break;
}
}
}
});
</script>
""", height=0, width=0)
Explanation of the Changes:
-
Wide Mode Configuration:
st.set_page_config(layout="wide")
This line ensures that the Streamlit app uses the entire width of the browser window, providing a more spacious layout.
-
Removing "Exchange N" Labels:
Instead of using expanders labeled "Exchange 1", "Exchange 2", etc., the code now displays user and bot messages side by side using Streamlit's columns feature. This simplifies the chat history display.
col1, col2 = st.columns(2)
with col1:
st.text_area("User:", ...)
with col2:
st.text_area("Bot:", ...)
-
Ctrl + Return to Submit:
Added a JavaScript snippet that listens for the Ctrl + Enter key combination. When detected, it programmatically clicks the "Send" button to submit the message.
<script>
document.addEventListener('keydown', function(e) {
if (e.ctrlKey && e.key === 'Enter') {
e.preventDefault();
const buttons = window.parent.document.querySelectorAll('button');
for (let btn of buttons) {
if (btn.innerText === 'Send') {
btn.click();
break;
}
}
}
});
</script>
Note: This approach searches for the "Send" button by its label. Ensure that the button's label remains "Send" for this script to work correctly. If you change the button text in the future, update the script accordingly.
-
Clearing the Input Field After Submission:
After a message is sent and processed, the input field is cleared by resetting the st.session_state.new_message to an empty string and rerunning the app to reflect the change.
st.session_state.new_message = ''
st.experimental_rerun()
Additional Notes:
-
Session State Management: The app uses st.session_state to persist chat history and manage the current input message across reruns.
-
Editing Chat History: Users can edit both user and bot messages directly in the chat history section. After making edits, clicking the "Save Edits" button will save the changes to the history.json file.
-
Error Handling: If the model prediction fails, the app will display an appropriate error message to the user.
-
JavaScript Integration: Streamlit allows embedding HTML and JavaScript using st.components.v1.html. This feature is leveraged here to add custom keyboard shortcuts.
Final Remarks:
This implementation should meet all your specified requirements. Ensure that the history.json file has the appropriate read/write permissions and that the Gradio client is correctly set up to interact with the specified model. If you encounter any issues with the JavaScript key binding, double-check the button labels and ensure there are no naming conflicts.