Integrate a nicer chatting interface from learning the following document for my code:
Code:
import gradio as gr
from gradio_client import Client
Initialize the client by pointing to the Gradio Space
client = Client("yuntian-deng/ChatGPT4")
def chat_with_model(user_input, existing_history):
"""
Interact with the chatbot while maintaining conversation context.
code
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.
"""
chatbot_history = existing_history or [] # Initialize history if it's None
if user_input.strip(): # Avoid empty input
# 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" # API endpoint exposed from Gradio Space
)
# Extract updated conversation history
updated_history = result[0] # Gradio Space response (chat history)
return updated_history, "" # Reset the input box after sending
else:
return chatbot_history, user_input # No input change, just return current state
def clear_chat():
"""
Clears the chatbot history and resets the UI chat.
code
Returns:
list: An empty list to reset the chatbot UI interface.
"""
return [] # Empty list for completely resetting chat UI
Build Gradio App
with gr.Blocks() as app:
gr.Markdown("## 🤖 ChatBot UI\nInteract with GPT-4 and reset the chat when needed.")
Assistant
code
# Chatbot UI Component
chatbot = gr.Chatbot(label="Chatbot Conversation")
# User Input Box
user_input = gr.Textbox(placeholder="Enter your message...", label="Your Message")
# Buttons
send_button = gr.Button("Send")
clear_button = gr.Button("Clear Chat")
# Handle the "Send" button click
send_button.click(
fn=chat_with_model,
inputs=[user_input, chatbot], # User input and the chat history
outputs=[chatbot, user_input] # Update chat UI and reset input box
)
# Handle the "Clear Chat" button click
clear_button.click(
fn=clear_chat,
inputs=[], # No input required to clear
outputs=[chatbot] # Pass an empty list to reset the chat UI
)
Launch the app
app.launch(debug=True, server_port=80)
Document:
How to Create a Chatbot with Gradio
Introduction
Chatbots are a popular application of large language models (LLMs). Using Gradio, you can easily build a demo of your LLM and share that with your users, or try it yourself using an intuitive chatbot UI.
This tutorial uses gr.ChatInterface(), which is a high-level abstraction that allows you to create your chatbot UI fast, often with a single line of Python. It can be easily adapted to support multimodal chatbots, or chatbots that require further customization.
Prerequisites: please make sure you are using the latest version of Gradio:
$ pip install --upgrade gradio
Defining a chat function
When working with gr.ChatInterface(), the first thing you should do is define your chat function. In the simplest case, your chat function should accept two arguments: message and history (the arguments can be named anything, but must be in this order).
code
message: a str representing the user's most recent message.
history: a list of openai-style dictionaries with role and content keys, representing the previous conversation history. May also include additional keys representing message metadata.
For example, the history could look like this:
[
{"role": "user", "content": "What is the capital of France?"},
{"role": "assistant", "content": "Paris"}
]
Your chat function simply needs to return:
code
a str value, which is the chatbot's response based on the chat history and most recent message.
Let's take a look at a few example chat functions:
Example: a chatbot that randomly responds with yes or no
Let's write a chat function that responds Yes or No randomly.
Tip: Always set type="messages" in gr.ChatInterface. The default value (type="tuples") is deprecated and will be removed in a future version of Gradio.
Based on the document's recommendation, we can simplify and improve the chatbot interface using gr.ChatInterface. Replace your current Gradio setup with gr.ChatInterface to create a more streamlined and modern chatbot interface. Below is the updated code:
python
import gradio as gr
from gradio_client import Client
# Initialize the client by pointing to the Gradio Space
client = Client("yuntian-deng/ChatGPT4")
def chat_with_model(message, history):
"""
Interact with the chatbot while maintaining conversation context.
Args:
message (str): User's most recent message.
history (list of dict): Conversation history with 'role' and 'content' keys.
Returns:
str: The chatbot's response to the latest user message.
"""
# Transform history from OpenAI-style dicts to a list of tuples for compatibility
formatted_history = [(entry["role"], entry["content"]) for entry in history]
if message.strip(): # Avoid empty input
# Call the Gradio backend Space
result = client.predict(
message, # User message
1.0, # Top-p value for creativity
0.7, # Temperature for randomness
len(formatted_history), # Chat counter
formatted_history, # Conversation history context
api_name="/predict" # API endpoint exposed from Gradio Space
)
# Extract updated conversation response (simplify for gr.ChatInterface)
updated_response = result[0][-1][1] # Get the chatbot's latest message
return updated_response
else:
return "Please enter a valid message."
# Use gr.ChatInterface for a modern chatbot UI
app = gr.ChatInterface(
fn=chat_with_model,
type="messages", # Ensure compatibility with message history
title="🤖 ChatGPT-4 Chatbot",
description="Interact with GPT-4 using a sleek chat interface. Type your message below!"
)
# Launch the app
app.launch(debug=True, server_port=80)
Explanation of Changes
Using gr.ChatInterface:
gr.ChatInterface replaces the older combination of gr.Blocks, gr.Chatbot, gr.Button, and gr.Textbox.
It streamlines the process of building a chatbot UI and handles most of the layout and design automatically.
History Type Changed to messages:
The type="messages" mode ensures compatibility with OpenAI-style dictionaries where each entry consists of role and content keys.
Simplified Input/Output Handling:
The input argument (message) is a string with the latest user input.
The history is a list of dictionaries (e.g., {"role": "user", "content": "Hello"}).
Compatibility with Gradio Space:
The user's input is sent via client.predict to the backend API, and the chat history is extracted and sent back in the expected format.
Minimal and Intuitive UI:
A title and description were added for a cleaner interface.
Benefits of gr.ChatInterface
Ease of Use: Just define the chat_with_model function and pass it to the interface.
Modern Design: Automatically adapts the UI for a sleek and user-friendly experience.
Ready for Future Features:gr.ChatInterface is actively maintained and provides better forward compatibility compared to the older custom styles using gr.Blocks.