Add clear chat feature import gradio as gr from gradioclient import Client Initialize…
- User
Add clear chat feature import gradio as gr from gradio_client import Client
Initialize the client by pointing to the Gradio Space
client = Client("yuntian-deng/ChatGPT4")
Persistent conversation history
chatbot_history = [] # Stores chat history as a list of tuples (user, assistant)
def chat_with_model(user_input, existing_history): """ Interact with the chatbot while maintaining conversation context.
Args: user_input (str): User's most recent message. existing_history (list of tuples): [(user1, bot1), (user2, bot2), ...], conversation context. Returns: updated_history (list of tuples): Chat history after receiving the assistant's response. """ global chatbot_history # Use global chatbot history # Update the global chatbot history with the existing UI history chatbot_history = existing_history print(chatbot_history) if user_input.strip(): # Check if the input is not empty # Call the Gradio backend Space result = client.predict( user_input, # User message 1.0, # Top-p value for creativity 0.7, # Temperature for randomness len(chatbot_history), # Chat counter chatbot_history, # Conversation history context api_name="/predict" # Gradio Space API endpoint ) # Extract updated history updated_history = result[0] # Gradio Space response (chat history) chatbot_history = updated_history # Update global chatbot history return chatbot_history, "" # Return updated chat history and reset input box else: return chatbot_history, user_input # If no user input, just return the existing historyBuild the Gradio app
with gr.Blocks() as app: gr.Markdown("## 🤖 ChatBot UI\nInteract with GPT-4 and reset the chat when needed.")
# Chatbot UI chatbot = gr.Chatbot(label="Chatbot Conversation") # User input for the chatbot user_input = gr.Textbox(placeholder="Enter your message...", label="Your Message") # Buttons for sending a message and clearing chat send_button = gr.Button("Send") clear_button = gr.Button("Clear Chat") # Link the Send button to the chat logic send_button.click( fn=chat_with_model, inputs=[user_input, chatbot], # User input and current conversation history outputs=[chatbot, user_input] # Update the Chatbot UI and clear the user input box )Launch the app
app.launch(debug=True, server_port=80)
- Assistant
- User
clearing chat does not clear the chat interface correctly
- Assistant
- User
It isn't correctly cleared because chatbot history is in the top of the code. FIx it
- Assistant
- User
it is still not working. Even when i click the clear button, it actually clears the chat, but not interface
- Assistant