Certainly! Below is a minimal Streamlit-based GUI for your chat application with an editable chat history. This application allows users to interact with an LLM, view and edit the chat history, and highlights the latest messages by making them larger.
Features:
- Chat History Display: Displays user and chatbot messages in two columns.
- Editable History: Users can edit previous messages using Streamlit's data editor.
- Highlight Latest Messages: The most recent user message and chatbot response are displayed larger for emphasis.
- Persistent Storage: Chat history is saved to and loaded from a
history.json file.
Requirements:
- Streamlit: Install using
pip install streamlit.
- Gradio Client: Ensure you have the
gradio_client installed (pip install gradio-client).
- JSON File: The application reads from and writes to
history.json for maintaining chat history.
Streamlit Application Code:
import streamlit as st
from gradio_client import Client
import json
import os
# Function to load history from JSON
def load_history(file_path='history.json'):
if os.path.exists(file_path):
with open(file_path, 'r') as f:
return json.load(f)
return []
# Function to save history to JSON
def save_history(history, file_path='history.json'):
with open(file_path, '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()
# Page configuration
st.set_page_config(page_title="LLM Chat Application", layout="wide")
st.title("🗨️ LLM Chat Application")
# Editable chat history
st.header("📝 Chat History")
# Create a DataFrame for editable history
import pandas as pd
# Prepare data for DataFrame
if st.session_state.history:
data = []
for i in range(0, len(st.session_state.history), 2):
user_msg = st.session_state.history[i]
bot_msg = st.session_state.history[i+1] if i+1 < len(st.session_state.history) else ""
data.append({'User': user_msg, 'Chatbot': bot_msg})
df = pd.DataFrame(data)
else:
df = pd.DataFrame(columns=['User', 'Chatbot'])
# Editable DataFrame
edited_df = st.experimental_data_editor(df, num_rows="dynamic")
# Update history from edited DataFrame
if st.button("Update History"):
new_history = []
for _, row in edited_df.iterrows():
if row['User']:
new_history.append(row['User'])
if row['Chatbot']:
new_history.append(row['Chatbot'])
st.session_state.history = new_history
save_history(st.session_state.history)
st.success("History updated successfully!")
st.markdown("---")
# Chat interface
st.header("💬 Start Chatting")
# Input box for user message
user_input = st.text_input("You:", value="", key="input")
# Function to get chatbot response
def get_bot_response(history):
client = Client('yuntian-deng/o1mini') # Replace with your model name
result = client.predict(
inputs=history,
top_p=1,
temperature=1,
chat_counter=0,
chatbot=[],
api_name='/predict'
)
return result[0][0][1]
# Handle user input and get response
if st.button("Send"):
if user_input.strip() != "":
# Append user message to history
st.session_state.history.append(user_input)
# Get bot response
bot_response = get_bot_response(st.session_state.history)
# Append bot response to history
st.session_state.history.append(bot_response)
# Save updated history
save_history(st.session_state.history)
# Clear input box
st.session_state.input = ""
st.experimental_rerun()
# Display chat messages
if st.session_state.history:
st.header("🗨️ Conversation")
for i in range(0, len(st.session_state.history), 2):
user_msg = st.session_state.history[i]
bot_msg = st.session_state.history[i+1] if i+1 < len(st.session_state.history) else ""
# Determine if it's the latest message
is_latest = (i == len(st.session_state.history) - 2) or (i == len(st.session_state.history) -1)
# Display user message
if user_msg:
if is_latest:
st.markdown(f"**<div style='font-size:20px; color:blue;'>You:</div>**", unsafe_allow_html=True)
st.markdown(f"<div style='font-size:20px; padding-left:20px;'>{user_msg}</div>", unsafe_allow_html=True)
else:
st.markdown(f"**You:**")
st.markdown(f"> {user_msg}")
# Display bot message
if bot_msg:
if is_latest:
st.markdown(f"**<div style='font-size:20px; color:green;'>Chatbot:</div>**", unsafe_allow_html=True)
st.markdown(f"<div style='font-size:20px; padding-left:20px;'>{bot_msg}</div>", unsafe_allow_html=True)
else:
st.markdown(f"**Chatbot:**")
st.markdown(f"> {bot_msg}")
Explanation of the Code:
-
Imports and Utility Functions:
- Streamlit and Gradio Client: For the UI and interacting with the LLM.
- JSON and OS: To handle reading and writing the chat history.
- Pandas: To create an editable DataFrame for the chat history.
-
Session State Initialization:
- The chat history is stored in
st.session_state.history to maintain state across user interactions.
- On the first run, it attempts to load existing history from
history.json. If not found, it initializes an empty history.
-
Editable Chat History Section:
- Converts the history list into a Pandas DataFrame with two columns: "User" and "Chatbot".
- Uses
st.experimental_data_editor to allow users to edit the DataFrame directly within the app.
- Upon clicking the "Update History" button, the edited DataFrame is converted back into the history list and saved to
history.json.
-
Chat Interface:
- Provides a text input for the user to enter messages.
- On clicking the "Send" button:
- The user message is appended to the history.
- The entire history is sent to the LLM using the Gradio client to get a chatbot response.
- The chatbot response is appended to the history.
- The updated history is saved to
history.json.
- The interface reruns to display the updated conversation.
-
Displaying Conversation:
- Iterates through the history and displays user and chatbot messages in order.
- The most recent user message and chatbot response are styled with larger font sizes and colors to make them stand out.
- Previous messages are displayed in a standard format using Markdown.
-
Styling:
- Uses HTML within Markdown to apply custom styles for the latest messages.
- Colors and font sizes differentiate between user and chatbot messages.
Running the Application:
-
Save the Code:
- Save the above code in a file named, for example,
llm_chat_app.py.
-
Install Dependencies:
pip install streamlit gradio-client pandas
-
Run the Streamlit App:
streamlit run llm_chat_app.py
-
Interact with the App:
- A browser window will open displaying the chat interface.
- You can view and edit the chat history in the "Chat History" section.
- Use the input box to send new messages to the chatbot.
Notes:
-
LLM Endpoint: Ensure that 'yuntian-deng/o1mini' is a valid Gradio model endpoint. If you're using a different model or hosting your own, update the Client instantiation accordingly.
-
Editable History: Editing the history allows you to modify both past user messages and chatbot responses. Ensure that the sequence of messages is maintained correctly to avoid inconsistencies.
-
Persistence: The chat history is saved to history.json in the same directory as the script. Ensure that the application has read/write permissions to this file.
-
Security: For a production environment, consider implementing proper error handling, input validation, and securing the endpoints.
This minimal GUI should provide a solid foundation for your chat application using Streamlit. You can further enhance it with additional features such as message timestamps, better styling, or integrating more advanced chat functionalities.