From this python code, I would like you to implement a web interface, that allows for the user to enter text, like if it was a text application, send the text to the model (prompt) and re-load the history at run-time. It should be possible to edit the model's response as well as a user's text too. You can user textareas, either a single one or multiple appearing for each exchange. Your application should be python only.
Python code:
py
from gradio_client import Client
import json
try:
with open('history.json', 'r') as f:
history = json.load(f)
for h in history:
print(h)
except:
history = []
while True:
client = Client('yuntian-deng/o1mini')
prompt = input()
if prompt != '':
history.append(prompt)
result = client.predict(
inputs=history,
top_p=1,
temperature=1,
chat_counter=0,
chatbot=[],
api_name='/predict'
)
output = result[0][0][1]
history.append(output)
print(f"{output}")
with open('history.json', 'w') as f:
json.dump(history, f, indent=2)
Assistant
Certainly! You can create an interactive web interface using Streamlit, a powerful Python library for building web applications. Below is a complete implementation based on your requirements:
Features Implemented:
Text Input: Users can enter messages in a text area.
Display History: The chat history is displayed with editable text areas for both user inputs and model responses.
Edit Functionality: Users can edit any part of the conversation.
Persist History: The conversation history is loaded from and saved to a history.json file.
Send Messages: Users can send new messages, which are processed by the model and appended to the history.
Setup Instructions:
Install Streamlit: If you haven't installed Streamlit yet, you can do so using pip:
bash
pip install streamlit
Save the Code: Save the following code to a file named chat_app.py.
Run the App: In your terminal, navigate to the directory containing chat_app.py and run:
bash
streamlit run chat_app.py
Complete Code Implementation:
python
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.experimental_rerun()
# Button to save edits
if st.button("Save Edits"):
save_history(st.session_state.history)
st.success("Edits saved successfully!")
Code Explanation:
Imports and Initialization:
Streamlit: Used for building the web interface.
gradio_client.Client: Used to interact with the model.
json & os: For handling the conversation history file.
Client Caching:
Using @st.cache_resource to cache the model client for performance.
History Management:
The history is loaded from history.json if it exists; otherwise, it initializes as an empty list.
Each entry in the history is a dictionary with user and bot keys.
Displaying Chat History:
The history is displayed using expandable sections (st.expander) for each exchange.
Both user and bot messages are shown in editable text areas.
Any edits made by the user are immediately updated in the session state.
Sending New Messages:
Users can enter a new message in a text area.
Upon clicking the "Send" button:
The message is appended to the history.
The entire conversation is sent to the model to generate a response.
The bot's response is appended to the history.
The history is saved to history.json.
The page reruns to display the updated history.
Saving Edits:
A "Save Edits" button allows users to save any manual changes made to the conversation history.
Additional Notes:
Editable History: Users can expand each exchange to edit both user and bot messages.
Persistence: All changes are saved to history.json, ensuring that the conversation persists across sessions.
Error Handling: If there's an issue with the model prediction, an error message is displayed in place of the bot's response.
Running the Application:
After setting up, run the application using Streamlit. It will open in your default web browser, providing an intuitive interface for interacting with the model.
bash
streamlit run chat_app.py
This implementation leverages Streamlit's simplicity and interactivity to fulfill all your requirements using Python only.