Introducing Gradio Clients

Watch
  1. Components
  2. Chatbot

New to Gradio? Start here: Getting Started

See the Release History

To install Gradio from main, run the following command:

pip install https://gradio-builds.s3.amazonaws.com/bbd7625ecbdc71aed58148d2237bda1dc5d1b74c/gradio-4.42.0-py3-none-any.whl

*Note: Setting share=True in launch() will not work.

Chatbot

gradio.Chatbot(type="messages", ···)
import gradio as gr with gr.Blocks() as demo: gr.Chatbot(value=[ {"role": "user", "content": "Hello World"}, {"role": "assistant", "content": "Hey Gradio!"}, {"role": "user", "content": "❤️"}, {"role": "assistant", "content": "😍"} ], type="messages") demo.launch()

Description

Creates a chatbot that displays user-submitted messages and responses. Supports a subset of Markdown including bold, italics, code, tables. Also supports audio/video/image files, which are displayed in the Chatbot, and other kinds of files which are displayed as links. This component is usually used as an output component.

Behavior

The data format accepted by the Chatbot is dictated by the type parameter. This parameter can take two values, 'tuples' and 'messages'. The 'tuples' type is deprecated and will be removed in a future version of Gradio.

Message format

If the type is 'messages', then the data sent to/from the chatbot will be a list of dictionaries with role and content keys. This format is compliant with the format expected by most LLM APIs (HuggingChat, OpenAI, Claude). The role key is either 'user' or 'assistant' and the content key can be one of the following:

  1. A string (markdown/html is also supported).
  2. A dictionary with path and alt_text keys. In this case, the file at path will be displayed in the chat history. Image, audio, and video files are fully embedded and visualized in the chat bubble. The path key can point to a valid publicly available URL. The alt_text key is optional but it’s good practice to provide alt text.
  3. An instance of another Gradio component.

We will show examples for all three cases below -
def generate_response(history):
    # A plain text response
    history.append(
        {"role": "assistant", content="I am happy to provide you that report and plot."}
    )
    # Embed the quaterly sales report in the chat
    history.append(
        {"role": "assistant", content={"path": "quaterly_sales.txt", "alt_text": "Sales Report for Q2 2024"}}
    )
    # Make a plot of sales data
    history.append(
        {"role": "assistant", content=gr.Plot(value=make_plot_from_file('quaterly_sales.txt'))}
    )
    return history

For convenience, you can use the ChatMessage dataclass so that your text editor can give you autocomplete hints and typechecks.

from gradio import ChatMessage

def generate_response(history):
    history.append(
        ChatMessage(role="assistant",
                    content="How can I help you?")
        )
    return history

Tuples format

If type is 'tuples', then the data sent to/from the chatbot will be a list of tuples. The first element of each tuple is the user message and the second element is the bot’s response. Each element can be a string (markdown/html is supported), a tuple (in which case the first element is a filepath that will be displayed in the chatbot), or a gradio component (see the Examples section for more details).

Initialization

Parameters

Shortcuts

Class Interface String Shortcut Initialization

gradio.Chatbot

"chatbot"

Uses default values

Examples

Displaying Thoughts/Tool Usage

When type is messages, you can provide additional metadata regarding any tools used to generate the response. This is useful for displaying the thought process of LLM agents. For example,

def generate_response(history):
    history.append(
        ChatMessage(role="assistant",
                    content="The weather API says it is 20 degrees Celcius in New York.",
                    metadata={"title": "🛠️ Used tool Weather API"})
        )
    return history

Would be displayed as following:

Gradio chatbot tool display

You can also specify metadata with a plain python dictionary,

def generate_response(history):
    history.append(
        dict(role="assistant",
             content="The weather API says it is 20 degrees Celcius in New York.",
             metadata={"title": "🛠️ Used tool Weather API"})
        )
    return history

Using Gradio Components Inside gr.Chatbot

The Chatbot component supports using many of the core Gradio components (such as gr.Image, gr.Plot, gr.Audio, and gr.HTML) inside of the chatbot. Simply include one of these components in your list of tuples. Here’s an example:

import gradio as gr

def load():
    return [
        ("Here's an audio", gr.Audio("https://github.com/gradio-app/gradio/raw/main/test/test_files/audio_sample.wav")),
        ("Here's an video", gr.Video("https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/world.mp4"))
    ]

with gr.Blocks() as demo:
    chatbot = gr.Chatbot()
    button = gr.Button("Load audio and video")
    button.click(load, None, chatbot)

demo.launch()

Demos

import gradio as gr
import random
import time

with gr.Blocks() as demo:
    chatbot = gr.Chatbot(type="messages")
    msg = gr.Textbox()
    clear = gr.ClearButton([msg, chatbot])

    def respond(message, chat_history):
        bot_message = random.choice(["How are you?", "Today is a great day", "I'm very hungry"])
        chat_history.append({"role": "user", "content": message})
        chat_history.append({"role": "assistant", "content": bot_message})
        time.sleep(2)
        return "", chat_history

    msg.submit(respond, [msg, chatbot], [msg, chatbot])

if __name__ == "__main__":
    demo.launch()

		

Event Listeners

Description

Event listeners allow you to respond to user interactions with the UI components you've defined in a Gradio Blocks app. When a user interacts with an element, such as changing a slider value or uploading an image, a function is called.

Supported Event Listeners

The Chatbot component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below.

Listener Description

Chatbot.change(fn, ···)

Triggered when the value of the Chatbot changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See .input() for a listener that is only triggered by user input.

Chatbot.select(fn, ···)

Event listener for when the user selects or deselects the Chatbot. Uses event data gradio.SelectData to carry value referring to the label of the Chatbot, and selected to refer to state of the Chatbot. See EventData documentation on how to use this event data

Chatbot.like(fn, ···)

This listener is triggered when the user likes/dislikes from within the Chatbot. This event has EventData of type gradio.LikeData that carries information, accessible through LikeData.index and LikeData.value. See EventData documentation on how to use this event data.

Event Parameters

Parameters

Guides