In the chat application example given to you, I want you to make the elements wider in the page. Currently, chat boxes are quite narrow, and it would be nice if they could adapt better to the width of the window.
py
Assistant
import streamlit as st
from gradio_client import Client
import json
import os
# 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()
st.title("Interactive Chat Interface")
st.markdown("### Chat History")
# Display and edit history
for idx, entry in enumerate(st.session_state.history):
with st.expander(f"Exchange {idx + 1}", expanded=True):
user_key = f"user_{idx}"
bot_key = f"bot_{idx}"
# Editable text areas
user_text = st.text_area("User:", value=entry.get('user', ''), key=user_key, height=100)
bot_text = st.text_area("Bot:", value=entry.get('bot', ''), key=bot_key, height=100)
# Update history with edited text
st.session_state.history[idx]['user'] = user_text
st.session_state.history[idx]['bot'] = bot_text
st.markdown("---")
st.markdown("### New Message")
# Input for new message
new_message = st.text_area("Enter your message here:", height=100)
# Button to send message
if st.button("Send"):
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)
# Clear the input area
st.rerun()
# Button to save edits
if st.button("Save Edits"):
save_history(st.session_state.history)
st.success("Edits saved successfully!")
To make your chat application elements wider and ensure they adapt better to the window's width, you can adjust the Streamlit page configuration and apply some custom CSS styling. Here's how you can achieve this:
Set the Page Layout to Wide:
Streamlit allows you to set the page layout to "wide," which utilizes the entire browser window's width. This is the first step to making your chat boxes wider.
Apply Custom CSS for Maximum Width:
By default, Streamlit applies a maximum width to the main content area. You can override this limitation using custom CSS to ensure that your chat boxes occupy more horizontal space.
Adjust Text Areas and Expanders:
Ensure that the text areas and expanders are set to utilize the available width effectively.
Below is the modified version of your code with these enhancements:
python
import streamlit as st
from gradio_client import Client
import json
import os
# Set page configuration to wide layout
st.set_page_config(layout="wide")
# Apply custom CSS to expand the maximum width
st.markdown(
"""
<style>
/* Remove Streamlit's default padding */
.reportview-container .main .block-container {
padding-left: 2rem;
padding-right: 2rem;
max-width: 100%;
}
/* Make text areas take full width */
textarea, .stTextArea > div > div > textarea {
width: 100% !important;
}
</style>
""",
unsafe_allow_html=True
)
# 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()
st.title("Interactive Chat Interface")
st.markdown("### Chat History")
# Use a container to hold the chat history with expanded width
with st.container():
for idx, entry in enumerate(st.session_state.history):
with st.expander(f"Exchange {idx + 1}", expanded=True):
user_key = f"user_{idx}"
bot_key = f"bot_{idx}"
# Editable text areas
user_text = st.text_area("**User:**", value=entry.get('user', ''), key=user_key, height=100)
bot_text = st.text_area("**Bot:**", value=entry.get('bot', ''), key=bot_key, height=100)
# Update history with edited text
st.session_state.history[idx]['user'] = user_text
st.session_state.history[idx]['bot'] = bot_text
st.markdown("---")
st.markdown("### New Message")
# Input for new message
new_message = st.text_area("Enter your message here:", height=100)
# Arrange buttons side by side using columns
col1, col2 = st.columns([1, 1])
with col1:
if st.button("Send"):
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)
# Clear the input area by rerunning the script
st.experimental_rerun()
with col2:
if st.button("Save Edits"):
save_history(st.session_state.history)
st.success("Edits saved successfully!")
Explanation of the Changes:
Setting the Page Layout to Wide:
python
st.set_page_config(layout="wide")
This line sets the Streamlit page to use the full width of the browser window, allowing your chat elements to expand accordingly.
Custom CSS for Enhanced Width Control:
python
st.markdown(
"""
<style>
/* Remove Streamlit's default padding */
.reportview-container .main .block-container {
padding-left: 2rem;
padding-right: 2rem;
max-width: 100%;
}
/* Make text areas take full width */
textarea, .stTextArea > div > div > textarea {
width: 100% !important;
}
</style>
""",
unsafe_allow_html=True
)
Padding Adjustment: Reduces the default padding on the left and right to allow more space for your content.
Text Area Width: Ensures that all text areas (st.text_area) occupy the full available width, making them appear wider.
Using Containers for Better Layout Control:
python
with st.container():
for idx, entry in enumerate(st.session_state.history):
with st.expander(f"Exchange {idx + 1}", expanded=True):
# Text areas...
Wrapping the chat history within a st.container() helps in managing the layout more effectively, especially when combined with the wide page configuration.
Arranging Buttons Side by Side:
python
col1, col2 = st.columns([1, 1])
with col1:
if st.button("Send"):
# Send functionality
with col2:
if st.button("Save Edits"):
# Save edits functionality
Using st.columns, the "Send" and "Save Edits" buttons are placed side by side, making better use of the horizontal space.
Additional Tips:
Responsive Design: While the above changes make the application wider, ensure that it remains user-friendly on different screen sizes. Test the application on various devices to verify its responsiveness.
Streamlit Updates: Streamlit is actively developed, and new features related to layout and styling may become available. Keep your Streamlit version updated to leverage the latest improvements.
Advanced Styling: For more advanced layout and styling, consider integrating libraries like Streamlit Components or leveraging additional CSS techniques. However, use them judiciously to maintain the simplicity and readability of your application.
By implementing these changes, your chat application should now have wider chat boxes that adapt more effectively to the browser window's width, enhancing the overall user experience.
Not yet included in a published release.
Miscellaneous Enhancements:
Bold Labels: Added ** around "User:" and "Bot:" labels for better visibility.
Improved Button Functionality: Replaced st.rerun() with st.experimental_rerun() for clearer intention, although both achieve similar outcomes.