Hi, the code: [code] Yields the error: [code]
- User
Hi, the code:
py - Assistant
Hi, the code:
import streamlit as st
from gradio_client import Client
import os
# Set page configuration to 'wide' and restore default menu and footer
st.set_page_config(
page_title="LLM Chat Application",
layout="wide", # Sets the interface to wide mode
initial_sidebar_state="auto"
)
# Constants
HISTORY_FILE = 'history.txt'
MODEL_CLIENT_NAME = 'yuntian-deng/ChatGPT4' # Replace with your actual model identifier
# Function to load history from the file
def load_history():
if os.path.exists(HISTORY_FILE):
with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
return f.read()
return ""
# Function to save history to the file
def save_history(history):
with open(HISTORY_FILE, 'w', encoding='utf-8') as f:
f.write(history)
# Initialize session state for history
if 'history' not in st.session_state:
st.session_state.history = load_history()
# Optionally, you can hide the footer if desired, but we'll keep the settings wheel visible
# If you wish to hide the footer, uncomment the following CSS
# hide_footer = """
# <style>
# footer {visibility: hidden;}
# </style>
# """
# st.markdown(hide_footer, unsafe_allow_html=True)
# Create a form for input
with st.form("chat_form", clear_on_submit=False):
# Editable text area for chat history and input
history_input = st.text_area(
"Chat History & Input",
value=st.session_state.history,
height=400,
key='history_input',
placeholder="Start chatting...",
)
# Generate Response button
generate = st.form_submit_button("Generate Response")
# Sliders for Temperature and Top-P sampling
col1, col2 = st.columns(2)
with col1:
temperature = st.slider(
"Temperature",
min_value=0.0,
max_value=5.0,
value=1.0,
step=0.1,
help="Controls the randomness of the model's output. Higher values like 1.0 make the output more random, while lower values like 0.2 make it more focused and deterministic."
)
with col2:
top_p = st.slider(
"Top-P Sampling",
min_value=0.0,
max_value=1.0,
value=1.0,
step=0.05,
help="Nucleus sampling: the model considers the smallest set of tokens with a cumulative probability above this value."
)
# Handle manual edits to the chat history
if history_input != st.session_state.history:
st.session_state.history = history_input
save_history(history_input)
# Handle form submission
if generate:
try:
# Initialize the client
client = Client(MODEL_CLIENT_NAME)
# Prepare inputs - assuming the model expects the full history as a single string
prompt = st.session_state.history
# Call the model to get a response
result = client.predict(
inputs=prompt,
top_p=top_p,
temperature=temperature,
chat_counter=0,
chatbot=[],
api_name='/predict'
)
# Adjust based on actual API response structure
output = result[0][0][1].strip()
# Append model response to history
# Ensure there's a newline before appending
if not st.session_state.history.endswith('\n'):
st.session_state.history += f"\nLLM: {output}"
else:
st.session_state.history += f"LLM: {output}"
# Save the updated history to the file
save_history(st.session_state.history)
# Update the text area to reflect the new history
# This ensures that the UI displays the latest conversation
st.session_state.history_input = st.session_state.history
st.success("LLM response generated and appended to history.")
except Exception as e:
st.error(f"Error communicating with the model: {e}")
Yields the error:
Error communicating with the model: st.session_state.history_input cannot be modified after the widget with key history_input is instantiated.
The error you're encountering arises because in Streamlit, once a widget is instantiated with a specific key (like 'history_input' in your case), you can't directly modify st.session_state corresponding to that key afterward. Specifically, you cannot assign a new value to st.session_state.history_input after the widget has been created.
To fix this issue, you should avoid modifying st.session_state.history_input directly. Instead, you can structure your app to separate the chat history display from the user input. Here's how you can modify your code:
Key Changes:
Separate Chat History Display:
st.text_area or st.write to display the chat history.'history_display') for the history display, and avoid modifying it directly after widget creation.Separate User Input Field:
st.text_input or st.text_area for the user's message input.Avoid Direct Modification of Widget Session State:
st.session_state keys associated with widgets after their creation.st.session_state.history) and let the widgets reflect these updates naturally through re-rendering.Modified Code:
Here's the updated code that incorporates these changes:
import streamlit as st
from gradio_client import Client
import os
# Set page configuration
st.set_page_config(
page_title="LLM Chat Application",
layout="wide",
initial_sidebar_state="auto"
)
# Constants
HISTORY_FILE = 'history.txt'
MODEL_CLIENT_NAME = 'yuntian-deng/ChatGPT4' # Replace with your actual model identifier
# Load history function
def load_history():
if os.path.exists(HISTORY_FILE):
with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
return f.read()
return ""
# Save history function
def save_history(history):
with open(HISTORY_FILE, 'w', encoding='utf-8') as f:
f.write(history)
# Initialize session state
if 'history' not in st.session_state:
st.session_state.history = load_history()
# Create the form
with st.form("chat_form", clear_on_submit=True):
# Display chat history (read-only)
st.text_area(
"Chat History",
value=st.session_state.history,
height=400,
key='history_display',
disabled=True
)
# Input area for user message
user_input = st.text_area(
"Your Message",
height=100,
placeholder="Type your message here..."
)
# Generate Response button
generate = st.form_submit_button("Generate Response")
# Sliders for Temperature and Top-P sampling
col1, col2 = st.columns(2)
with col1:
temperature = st.slider(
"Temperature",
min_value=0.0,
max_value=5.0,
value=1.0,
step=0.1,
help="Controls the randomness of the model's output."
)
with col2:
top_p = st.slider(
"Top-P Sampling",
min_value=0.0,
max_value=1.0,
value=1.0,
step=0.05,
help="Nucleus sampling."
)
# Handle form submission
if generate and user_input.strip() != "":
try:
# Append user's message to history
st.session_state.history += f"You: {user_input.strip()}\n"
# Initialize the client
client = Client(MODEL_CLIENT_NAME)
# Prepare inputs
prompt = st.session_state.history
# Call the model to get a response
result = client.predict(
inputs=prompt,
top_p=top_p,
temperature=temperature,
chat_counter=0,
chatbot=[],
api_name='/predict'
)
# Adjust based on actual API response structure
output = result[0][0][1].strip()
# Append model response to history
st.session_state.history += f"LLM: {output}\n"
# Save the updated history to the file
save_history(st.session_state.history)
# Success message
st.success("LLM response generated and appended to history.")
except Exception as e:
st.error(f"Error communicating with the model: {e}")
# Display updated chat history outside the form to refresh it after submission
st.text_area(
"Chat History",
value=st.session_state.history,
height=400,
key='history_display',
disabled=True
)
Explanation:
Chat History Display: We use st.text_area with disabled=True to display the chat history, assigning it a key 'history_display'. Since we don't attempt to modify st.session_state.history_display after creation, we avoid the error.
User Input Field: A separate st.text_area is used for the user's message input. This field is cleared on form submission due to clear_on_submit=True.
Form Submission Handling:
st.session_state.history.st.session_state.history.save_history.Chat History Update: After form submission and processing, we re-display the chat history outside the form. This ensures that the updated conversation is reflected in the UI without violating Streamlit’s session state rules.
Important Notes:
Avoid Modifying Widget Session State: Do not assign to st.session_state keys that are linked to widget keys after the widget is created. This is a fundamental rule in Streamlit to prevent inconsistencies.
Session State Management: Always update and rely on your main session state variables (like st.session_state.history) to manage your application's state.
By making these changes, you'll eliminate the error and ensure that your chat application functions smoothly.
Not yet included in a published release.