Certainly! Let's transform your CLI application into a graphical web application using Streamlit, a powerful and easy-to-use Python library for building web interfaces. The application will allow you to:
- View the history of messages in a chat-like interface.
- Edit existing messages.
- Add new messages.
- Persist the history in a
history.json file.
Below is the complete implementation along with step-by-step instructions to set it up.
Table of Contents
- Prerequisites
- Project Structure
- Installation
- The Streamlit Application (
app.py)
- Running the Application
- Usage
- Complete Code
Prerequisites
Ensure you have the following installed on your system:
- Python 3.7 or higher: Download Python
- pip: Python package manager (usually comes with Python)
Project Structure
Create a new directory for your project. Inside this directory, you'll have:
your_project/
├── app.py
└── history.json (automatically created)
Installation
-
Navigate to your project directory:
cd your_project
-
Create a virtual environment (optional but recommended):
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install the required libraries:
pip install streamlit gradio-client
- Streamlit: For building the web interface.
- gradio-client: To communicate with the Gradio model.
The Streamlit Application (app.py)
Create a file named app.py in your project directory and add the following code:
import streamlit as st
from gradio_client import Client
import json
import os
# Initialize the Gradio client
client = Client('yuntian-deng/o1mini')
# Define the path for history file
HISTORY_FILE = 'history.json'
def load_history():
if os.path.exists(HISTORY_FILE):
with open(HISTORY_FILE, 'r') as f:
try:
return json.load(f)
except json.JSONDecodeError:
return []
return []
def save_history(history):
with open(HISTORY_FILE, 'w') as f:
json.dump(history, f, indent=2)
def get_response(history):
# Send the history to the model and get the response
try:
result = client.predict(
inputs=history,
top_p=1,
temperature=1,
chat_counter=0,
chatbot=[],
api_name='/predict'
)
output = result[0][0][1]
return output
except Exception as e:
return f"Error: {e}"
# Load history
if 'history' not in st.session_state:
st.session_state.history = load_history()
st.set_page_config(page_title="Chat Interface", layout="wide")
st.title("🌐 Chat Interface")
# Display the chat history
st.header("💬 Chat History")
# Allow editing of history
with st.form(key='edit_form'):
edited_history = []
for idx, message in enumerate(st.session_state.history):
# Alternate between user and assistant messages
if idx % 2 == 0:
# User message
edited_msg = st.text_input(f"Edit User Message #{idx//2 + 1}", value=message, key=f"user_{idx}")
else:
# Assistant message
edited_msg = st.text_area(f"Edit Assistant Response #{idx//2 + 1}", value=message, key=f"assistant_{idx}")
edited_history.append(edited_msg)
submit_edit = st.form_submit_button(label='Save Edits')
if submit_edit:
st.session_state.history = edited_history
save_history(st.session_state.history)
st.success("History updated successfully!")
st.markdown("---")
# Input for new message
st.header("✍️ Send a New Message")
with st.form(key='message_form'):
user_input = st.text_input("Your Message:")
submit_message = st.form_submit_button(label='Send')
if submit_message and user_input.strip() != '':
# Append user message to history
st.session_state.history.append(user_input.strip())
save_history(st.session_state.history)
# Get response from model
with st.spinner("Generating response..."):
response = get_response(st.session_state.history)
# Append assistant response to history
st.session_state.history.append(response)
save_history(st.session_state.history)
st.success("Response received!")
st.markdown("---")
# Display updated chat history
st.header("🔄 Updated Chat History")
for idx, message in enumerate(st.session_state.history):
if idx % 2 == 0:
# User message
st.markdown(f"**You:** {message}")
else:
# Assistant message
st.markdown(f"**Assistant:** {message}")
Explanation of the Code
-
Imports:
streamlit for the web interface.
gradio_client.Client to interact with the Gradio model.
json and os for handling the history file.
-
Functions:
load_history(): Loads the chat history from history.json if it exists.
save_history(history): Saves the chat history to history.json.
get_response(history): Sends the current history to the model and retrieves the response.
-
Streamlit Components:
- Chat History Display & Editing:
- Uses forms to allow users to edit existing messages.
- Differentiates between user and assistant messages based on their position in the list.
- New Message Input:
- Users can send new messages which are appended to the history.
- Upon sending, the app retrieves a response from the model and updates the history.
- Updated Chat History Display:
- Shows the latest chat history after any updates.
Running the Application
-
Ensure you are in your project directory and the virtual environment is activated (if you created one).
-
Run the Streamlit app:
streamlit run app.py
-
Access the Application:
- After running the above command, Streamlit will provide a local URL, typically http://localhost:8501
- Open this URL in your web browser to interact with the application.
Usage
-
Viewing Chat History:
- The "💬 Chat History" section displays all past messages.
- You can edit any message by modifying the text in the provided input fields and clicking "Save Edits".
-
Sending New Messages:
- In the "✍️ Send a New Message" section, enter your message and click "Send".
- The application will send this message to the model and display the response.
-
Updated Chat History:
- The "🔄 Updated Chat History" section shows the latest state of the conversation.
-
Persistence:
- All messages are saved in
history.json, ensuring your chat history is retained between sessions.
Complete Code
Here's the complete app.py for your convenience:
import streamlit as st
from gradio_client import Client
import json
import os
# Initialize the Gradio client
client = Client('yuntian-deng/o1mini')
# Define the path for history file
HISTORY_FILE = 'history.json'
def load_history():
if os.path.exists(HISTORY_FILE):
with open(HISTORY_FILE, 'r') as f:
try:
return json.load(f)
except json.JSONDecodeError:
return []
return []
def save_history(history):
with open(HISTORY_FILE, 'w') as f:
json.dump(history, f, indent=2)
def get_response(history):
# Send the history to the model and get the response
try:
result = client.predict(
inputs=history,
top_p=1,
temperature=1,
chat_counter=0,
chatbot=[],
api_name='/predict'
)
output = result[0][0][1]
return output
except Exception as e:
return f"Error: {e}"
# Load history
if 'history' not in st.session_state:
st.session_state.history = load_history()
st.set_page_config(page_title="Chat Interface", layout="wide")
st.title("🌐 Chat Interface")
# Display the chat history
st.header("💬 Chat History")
# Allow editing of history
with st.form(key='edit_form'):
edited_history = []
for idx, message in enumerate(st.session_state.history):
# Alternate between user and assistant messages
if idx % 2 == 0:
# User message
edited_msg = st.text_input(f"Edit User Message #{idx//2 + 1}", value=message, key=f"user_{idx}")
else:
# Assistant message
edited_msg = st.text_area(f"Edit Assistant Response #{idx//2 + 1}", value=message, key=f"assistant_{idx}")
edited_history.append(edited_msg)
submit_edit = st.form_submit_button(label='Save Edits')
if submit_edit:
st.session_state.history = edited_history
save_history(st.session_state.history)
st.success("History updated successfully!")
st.markdown("---")
# Input for new message
st.header("✍️ Send a New Message")
with st.form(key='message_form'):
user_input = st.text_input("Your Message:")
submit_message = st.form_submit_button(label='Send')
if submit_message and user_input.strip() != '':
# Append user message to history
st.session_state.history.append(user_input.strip())
save_history(st.session_state.history)
# Get response from model
with st.spinner("Generating response..."):
response = get_response(st.session_state.history)
# Append assistant response to history
st.session_state.history.append(response)
save_history(st.session_state.history)
st.success("Response received!")
st.markdown("---")
# Display updated chat history
st.header("🔄 Updated Chat History")
for idx, message in enumerate(st.session_state.history):
if idx % 2 == 0:
# User message
st.markdown(f"**You:** {message}")
else:
# Assistant message
st.markdown(f"**Assistant:** {message}")
Additional Considerations
-
Concurrency: This simple implementation is suitable for single-user scenarios. If you plan to deploy this for multiple users, consider implementing user authentication and managing separate histories.
-
Error Handling: The get_response function includes basic error handling. You might want to enhance it based on the specific errors you encounter.
-
Styling: Streamlit offers various options to style your application. Refer to the Streamlit documentation to customize the look and feel as per your preferences.
By following the above steps, you'll have a functional web-based chat interface that mirrors the functionality of your original CLI application, enhanced with a user-friendly GUI. This setup allows you to interact with the Gradio model, view and edit your chat history, and persist conversations seamlessly.