# Chatbot

```python
gradio.Chatbot(···)
```

### 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 Chatbot component accepts a list of messages, where each message is a dictionary with `role` and `content` keys. This format is compatible with the message format expected by most LLM APIs (OpenAI, Claude, HuggingChat, etc.), making it easy to pipe model outputs directly into the component.

The `role` key should be either `'user'` or `'assistant'`, and the `content` key can be a string (rendered as markdown/HTML) or a Gradio component (useful for displaying files, images, plots, and other media).

As an example:

```python
import gradio as gr

history = [
    {"role": "assistant", "content": "I am happy to provide you that report and plot."},
    {"role": "assistant", "content": gr.Plot(value=make_plot_from_file('quaterly_sales.txt'))}
]

with gr.Blocks() as demo:
    gr.Chatbot(history)

demo.launch()
```

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

```python
import gradio as gr

history = [
    gr.ChatMessage(role="assistant", content="How can I help you?"),
    gr.ChatMessage(role="user", content="Can you make me a plot of quarterly sales?"),
    gr.ChatMessage(role="assistant", content="I am happy to provide you that report and plot.")
]

with gr.Blocks() as demo:
    gr.Chatbot(history)

demo.launch()
```

### Initialization

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `value` | `list[MessageDict \| Message] \| Callable \| None` | `None` | Default list of messages to show in chatbot, where each message is of the format {"role": "user", "content": "Help me."}. Role can be one of "user", "assistant", or "system". Content should be either text, or media passed as a Gradio component, e.g. {"content": gr.Image("lion.jpg")}. If a function is provided, the function will be called each time the app loads to set the initial value of this component. |
| `label` | `str \| I18nData \| None` | `None` | the label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to. |
| `every` | `Timer \| float \| None` | `None` | Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer. |
| `inputs` | `Component \| list[Component] \| set[Component] \| None` | `None` | Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change. |
| `show_label` | `bool \| None` | `None` | if True, will display label. |
| `container` | `bool` | `True` | If True, will place the component in a container - providing some extra padding around the border. |
| `scale` | `int \| None` | `None` | relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True. |
| `min_width` | `int` | `160` | minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first. |
| `visible` | `bool \| Literal['hidden']` | `True` | If False, component will be hidden. If "hidden", component will be visually hidden and not take up space in the layout but still exist in the DOM |
| `elem_id` | `str \| None` | `None` | An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
| `elem_classes` | `list[str] \| str \| None` | `None` | An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
| `autoscroll` | `bool` | `True` | If True, will automatically scroll to the bottom of the textbox when the value changes, unless the user scrolls up. If False, will not scroll to the bottom of the textbox when the value changes. |
| `render` | `bool` | `True` | If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later. |
| `key` | `int \| str \| tuple[int \| str, ...] \| None` | `None` | in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render. |
| `preserved_by_key` | `list[str] \| str \| None` | `"value"` | A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor. |
| `height` | `int \| str \| None` | `400` | The height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If messages exceed the height, the component will scroll. |
| `resizable` | `bool` | `False` | If True, the user of the Gradio app can resize the chatbot by dragging the bottom right corner. |
| `max_height` | `int \| str \| None` | `None` | The maximum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If messages exceed the height, the component will scroll. If messages are shorter than the height, the component will shrink to fit the content. Will not have any effect if `height` is set and is smaller than `max_height`. |
| `min_height` | `int \| str \| None` | `None` | The minimum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If messages exceed the height, the component will expand to fit the content. Will not have any effect if `height` is set and is larger than `min_height`. |
| `editable` | `Literal['user', 'all'] \| None` | `None` | Allows user to edit messages in the chatbot. If set to "user", allows editing of user messages. If set to "all", allows editing of assistant messages as well. |
| `latex_delimiters` | `list[dict[str, str \| bool]] \| None` | `None` | A list of dicts of the form {"left": open delimiter (str), "right": close delimiter (str), "display": whether to display in newline (bool)} that will be used to render LaTeX expressions. If not provided, `latex_delimiters` is set to `[{ "left": "$$", "right": "$$", "display": True }]`, so only expressions enclosed in $$ delimiters will be rendered as LaTeX, and in a new line. Pass in an empty list to disable LaTeX rendering. For more information, see the [KaTeX documentation](https://katex.org/docs/autorender.html). |
| `rtl` | `bool` | `False` | If True, sets the direction of the rendered text to right-to-left. Default is False, which renders text left-to-right. |
| `buttons` | `list[Literal['share', 'copy', 'copy_all'] \| Button] \| None` | `None` | A list of buttons to show in the top right corner of the component. Valid options are "share", "copy", "copy_all", or a gr.Button() instance. The "share" button allows the user to share outputs to Hugging Face Spaces Discussions. The "copy" button makes a copy button appear next to each individual chatbot message. The "copy_all" button appears at the component level and allows the user to copy all chatbot messages. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. By default, "share" and "copy_all" buttons are shown. |
| `watermark` | `str \| None` | `None` | If provided, this text will be appended to the end of messages copied from the chatbot, after a blank line. Useful for indicating that the message is generated by an AI model. |
| `avatar_images` | `tuple[str \| Path \| None, str \| Path \| None] \| None` | `None` | Tuple of two avatar image paths or URLs for user and bot (in that order). Pass None for either the user or bot image to skip. Must be within the working directory of the Gradio app or an external URL. |
| `sanitize_html` | `bool` | `True` | If False, will disable HTML sanitization for chatbot messages. This is not recommended, as it can lead to security vulnerabilities. |
| `render_markdown` | `bool` | `True` | If False, will disable Markdown rendering for chatbot messages. |
| `feedback_options` | `list[str] \| tuple[str, ...] \| None` | `('Like', 'Dislike')` | A list of strings representing the feedback options that will be displayed to the user. The exact case-sensitive strings "Like" and "Dislike" will render as thumb icons, but any other choices will appear under a separate flag icon. |
| `feedback_value` | `list[str \| None] \| None` | `None` | A list of strings representing the feedback state for entire chat. Only works when type="messages". Each entry in the list corresponds to that assistant message, in order, and the value is the feedback given (e.g. "Like", "Dislike", or any custom feedback option) or None if no feedback was given for that message. |
| `line_breaks` | `bool` | `True` | If True (default), will enable Github-flavored Markdown line breaks in chatbot messages. If False, single new lines will be ignored. Only applies if `render_markdown` is True. |
| `layout` | `Literal['panel', 'bubble'] \| None` | `None` | If "panel", will display the chatbot in a llm style layout. If "bubble", will display the chatbot with message bubbles, with the user and bot messages on alterating sides. Will default to "bubble". |
| `placeholder` | `str \| None` | `None` | a placeholder message to display in the chatbot when it is empty. Centered vertically and horizontally in the Chatbot. Supports Markdown and HTML. If None, no placeholder is displayed. |
| `examples` | `list[ExampleMessage] \| None` | `None` | A list of example messages to display in the chatbot before any user/assistant messages are shown. Each example should be a dictionary with an optional "text" key representing the message that should be populated in the Chatbot when clicked, an optional "files" key, whose value should be a list of files to populate in the Chatbot, an optional "icon" key, whose value should be a filepath or URL to an image to display in the example box, and an optional "display_text" key, whose value should be the text to display in the example box. If "display_text" is not provided, the value of "text" will be displayed. |
| `allow_file_downloads` | `bool` | `True` | If True, will show a download button for chatbot messages that contain media. Defaults to True. |
| `group_consecutive_messages` | `bool` | `True` | If True, will display consecutive messages from the same role in the same bubble. If False, will display each message in a separate bubble. Defaults to True. |
| `allow_tags` | `list[str] \| bool` | `True` | If a list of tags is provided, these tags will be preserved in the output chatbot messages, even if `sanitize_html` is `True`. For example, if this list is ["thinking"], the tags `<thinking>` and `</thinking>` will not be removed. If True, all custom tags (non-standard HTML tags) will be preserved. If False, no tags will be preserved. Default value is 'True'. |
| `reasoning_tags` | `list[tuple[str, str]] \| None` | `None` | If provided, a list of tuples of (open_tag, close_tag) strings. Any text between these tags will be extracted and displayed in a separate collapsible message with metadata={"title": "Reasoning"}. For example, [("<thinking>", "</thinking>")] will extract content between <thinking> and </thinking> tags. Each thinking block will be displayed as a separate collapsible message before the main response. If None (default), no automatic extraction is performed. |
| `like_user_message` | `bool` | `False` | If True, will show like/dislike buttons for user messages as well. Defaults to False. |
### Shortcuts

| Class | Interface String Shortcut | Initialization |
|-------|--------------------------|----------------|
| `gradio.Chatbot` | `"chatbot"` | Uses default values |
### Examples

**Displaying Thoughts/Tool Usage**

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,

```python
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:

You can also specify metadata with a plain python dictionary,

```python
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 as the `content` of a message. Here’s an example:

```py
import gradio as gr

def load():
    return [
        {"role": "user", "content": "Can you show me some media?"},
        {"role": "assistant", "content": "Here's an audio clip:"},
        {"role": "assistant", "content": gr.Audio("https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/audio/audio_sample.wav")},
        {"role": "assistant", "content": "And here's a video:"},
        {"role": "assistant", "content": gr.Video("https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/videos/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

**chatbot_simple**

[See demo on Hugging Face Spaces](https://huggingface.co/spaces/gradio/chatbot_simple)

```python
import gradio as gr
import random
import time

with gr.Blocks() as demo:
    chatbot = gr.Chatbot()
    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()
```

**chatbot_streaming**

[See demo on Hugging Face Spaces](https://huggingface.co/spaces/gradio/chatbot_streaming)

```python
import gradio as gr
import random
import time

with gr.Blocks() as demo:
    chatbot = gr.Chatbot()
    msg = gr.Textbox()
    clear = gr.Button("Clear")

    def user(user_message, history: list):
        return "", history + [{"role": "user", "content": user_message}]

    def bot(history: list):
        bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
        history.append({"role": "assistant", "content": ""})
        for character in bot_message:
            history[-1]['content'] += character
            time.sleep(0.05)
            yield history

    msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
        bot, chatbot, chatbot
    )
    clear.click(lambda: None, None, chatbot, queue=False)

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

**chatbot_with_tools**

[See demo on Hugging Face Spaces](https://huggingface.co/spaces/gradio/chatbot_with_tools)

```python
import gradio as gr
from gradio import ChatMessage
import time

def generate_response(history):
    history.append(
        ChatMessage(
            role="user", content="What is the weather in San Francisco right now?"
        )
    )
    yield history
    time.sleep(0.25)
    history.append(
        ChatMessage(
            role="assistant",
            content="In order to find the current weather in San Francisco, I will need to use my weather tool.",
        )
    )
    yield history
    time.sleep(0.25)

    history.append(
        ChatMessage(
            role="assistant",
            content="API Error when connecting to weather service.",
            metadata={"title": "💥 Error using tool 'Weather'"},
        )
    )
    yield history
    time.sleep(0.25)

    history.append(
        ChatMessage(
            role="assistant",
            content="I will try again",
        )
    )
    yield history
    time.sleep(0.25)

    history.append(
        ChatMessage(
            role="assistant",
            content="Weather 72 degrees Fahrenheit with 20% chance of rain.",
            metadata={"title": "🛠️ Used tool 'Weather'"},
        )
    )
    yield history
    time.sleep(0.25)

    history.append(
        ChatMessage(
            role="assistant",
            content="Now that the API succeeded I can complete my task.",
        )
    )
    yield history
    time.sleep(0.25)

    history.append(
        ChatMessage(
            role="assistant",
            content="It's a sunny day in San Francisco with a current temperature of 72 degrees Fahrenheit and a 20% chance of rain. Enjoy the weather!",
        )
    )
    yield history

def like(evt: gr.LikeData):
    print("User liked the response")
    print(evt.index, evt.liked, evt.value)

with gr.Blocks() as demo:
    chatbot = gr.Chatbot(height=500, buttons=["copy"])
    button = gr.Button("Get San Francisco Weather")
    button.click(generate_response, chatbot, chatbot)
    chatbot.like(like)

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

**chatbot_core_components**

[See demo on Hugging Face Spaces](https://huggingface.co/spaces/gradio/chatbot_core_components)

```python

import gradio as gr
import os
import plotly.express as px  
import random

# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, video, & model3d). Plus shows support for streaming text.

txt = """
Absolutely! The mycorrhizal network, often referred to as the "Wood Wide Web," is a symbiotic association between fungi and the roots of most plant species. Here’s a deeper dive into how it works and its implications:

### How It Works

1. **Symbiosis**: Mycorrhizal fungi attach to plant roots, extending far into the soil. The plant provides the fungi with carbohydrates produced via photosynthesis. In return, the fungi help the plant absorb water and essential nutrients like phosphorus and nitrogen from the soil.

2. **Network Formation**: The fungal hyphae (thread-like structures) connect individual plants, creating an extensive underground network. This network can link many plants together, sometimes spanning entire forests.

3. **Communication**: Trees and plants use this network to communicate and share resources. For example, a tree under attack by pests can send chemical signals through the mycorrhizal network to warn neighboring trees. These trees can then produce defensive chemicals to prepare for the impending threat.

### Benefits and Functions

1. **Resource Sharing**: The network allows for the redistribution of resources among plants. For instance, a large, established tree might share excess nutrients and water with smaller, younger trees, promoting overall forest health.

2. **Defense Mechanism**: The ability to share information about pests and diseases enhances the resilience of plant communities. This early warning system helps plants activate their defenses before they are directly affected.

3. **Support for Seedlings**: Young seedlings, which have limited root systems, benefit immensely from the mycorrhizal network. They receive nutrients and water from larger plants, increasing their chances of survival and growth.

### Ecological Impact

1. **Biodiversity**: The mycorrhizal network supports biodiversity by fostering a cooperative environment. Plants of different species can coexist and thrive because of the shared resources and information.

2. **Forest Health**: The network enhances the overall health of forests. By enabling efficient nutrient cycling and supporting plant defenses, it contributes to the stability and longevity of forest ecosystems.

3. **Climate Change Mitigation**: Healthy forests act as significant carbon sinks, absorbing carbon dioxide from the atmosphere. The mycorrhizal network plays a critical role in maintaining forest health and, consequently, in mitigating climate change.

### Research and Discoveries

1. **Suzanne Simard's Work**: Ecologist Suzanne Simard’s research has been pivotal in uncovering the complexities of the mycorrhizal network. She demonstrated that trees of different species can share resources and that "mother trees" (large, older trees) play a crucial role in nurturing younger plants.

2. **Implications for Conservation**: Understanding the mycorrhizal network has significant implications for conservation efforts. It highlights the importance of preserving not just individual trees but entire ecosystems, including the fungal networks that sustain them.

### Practical Applications

1. **Agriculture**: Farmers and horticulturists are exploring the use of mycorrhizal fungi to improve crop yields and soil health. By incorporating these fungi into agricultural practices, they can reduce the need for chemical fertilizers and enhance plant resilience.

2. **Reforestation**: In reforestation projects, introducing mycorrhizal fungi can accelerate the recovery of degraded lands. The fungi help establish healthy plant communities, ensuring the success of newly planted trees.

The "Wood Wide Web" exemplifies the intricate and often hidden connections that sustain life on Earth. It’s a reminder of the profound interdependence within natural systems and the importance of preserving these delicate relationships.
"""

def random_plot():
    df = px.data.iris()
    fig = px.scatter(
        df,
        x="sepal_width",
        y="sepal_length",
        color="species",
        size="petal_length",
        hover_data=["petal_width"],
    )
    return fig

color_map = {
    "harmful": "crimson",
    "neutral": "gray",
    "beneficial": "green",
}

def html_src(harm_level):
    return f"""
<div style="display: flex; gap: 5px;">
  <div style="background-color: {color_map[harm_level]}; padding: 2px; border-radius: 5px;">
  {harm_level}
  </div>
</div>
"""

def print_like_dislike(x: gr.LikeData):
    print(x.index, x.value, x.liked)

def random_bokeh_plot():
    from bokeh.models import ColumnDataSource, Whisker
    from bokeh.plotting import figure
    from bokeh.sampledata.autompg2 import autompg2 as df
    from bokeh.transform import factor_cmap, jitter

    classes = sorted(df["class"].unique())

    p = figure(
        height=400,
        x_range=classes,
        background_fill_color="#efefef",
        title="Car class vs HWY mpg with quintile ranges",
    )
    p.xgrid.grid_line_color = None

    g = df.groupby("class")
    upper = g.hwy.quantile(0.80)
    lower = g.hwy.quantile(0.20)
    source = ColumnDataSource(data=dict(base=classes, upper=upper, lower=lower))

    error = Whisker(
        base="base",
        upper="upper",
        lower="lower",
        source=source,
        level="annotation",
        line_width=2,
    )
    error.upper_head.size = 20
    error.lower_head.size = 20
    p.add_layout(error)

    p.circle(
        jitter("class", 0.3, range=p.x_range),
        "hwy",
        source=df,
        alpha=0.5,
        size=13,
        line_color="white",
        color=factor_cmap("class", "Light6", classes),
    )
    return p

# get_file(), get_image(), get_model3d(), get_video() return file paths to sample media included with Gradio
from gradio.media import get_file, get_image, get_model3d, get_video

def random_matplotlib_plot():
    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt

    countries = ["USA", "Canada", "Mexico", "UK"]
    months = ["January", "February", "March", "April", "May"]
    m = months.index("January")
    r = 3.2
    start_day = 30 * m
    final_day = 30 * (m + 1)
    x = np.arange(start_day, final_day + 1)
    pop_count = {"USA": 350, "Canada": 40, "Mexico": 300, "UK": 120}
    df = pd.DataFrame({"day": x})
    for country in countries:
        df[country] = x ** (r) * (pop_count[country] + 1)

    fig = plt.figure()
    plt.plot(df["day"], df[countries].to_numpy())
    plt.title("Outbreak in " + "January")
    plt.ylabel("Cases")
    plt.xlabel("Days since Day 0")
    plt.legend(countries)
    return fig

def add_message(history, message):
    for x in message["files"]:
        history.append({"role": "user", "content": {"path": x}})
    if message["text"] is not None:
        history.append({"role": "user", "content": message["text"]})
    return history, gr.MultimodalTextbox(value=None, interactive=False)

def bot(history, response_type):
    msg = {"role": "assistant", "content": ""}
    if response_type == "plot":
        content = gr.Plot(random_plot())
    elif response_type == "bokeh_plot":
        content = gr.Plot(random_bokeh_plot())
    elif response_type == "matplotlib_plot":
        content =  gr.Plot(random_matplotlib_plot())
    elif response_type == "gallery":
        content = gr.Gallery(
            [get_image("avatar.png"), get_image("avatar.png")]
        )
    elif response_type == "dataframe":
        content = gr.Dataframe(
            interactive=True,
            headers=["One", "Two", "Three"],
            col_count=(3, "fixed"),
            row_count=(3, "fixed"),
            value=[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
            label="Dataframe",
        )
    elif response_type == "image":
       content = gr.Image(get_image("avatar.png"))
    elif response_type == "video":
       content = gr.Video(get_video("world.mp4"))
    elif response_type == "audio":
        content = gr.Audio(os.path.join("files", "audio.wav"))
    elif response_type == "audio_file":
        content = {"path": os.path.join("files", "audio.wav"), "alt_text": "description"}
    elif response_type == "image_file":
        content = {"path": get_image("avatar.png"), "alt_text": "description"}
    elif response_type == "video_file":
        content = {"path": get_video("world.mp4"), "alt_text": "description"}
    elif response_type == "txt_file":
        content = {"path": get_file("sample.txt"), "alt_text": "description"}
    elif response_type == "model3d_file":
        content = {"path": get_model3d("Duck.glb"), "alt_text": "description"}
    elif response_type == "html":
        content = gr.HTML(
            html_src(random.choice(["harmful", "neutral", "beneficial"]))
        )
    elif response_type == "model3d":
        content = gr.Model3D(get_model3d("Duck.glb"))
    else:
        content = txt
    msg["content"] = content 
    history.append(msg)
    return history

fig = random_plot()

with gr.Blocks(fill_height=True) as demo:
    chatbot = gr.Chatbot(
        elem_id="chatbot",
        scale=1,
        buttons=["copy"],
        avatar_images=(
            None,
            get_image("avatar.png"),
        ),
    )
    response_type = gr.Radio(
        [
            "audio_file",
            "image_file",
            "video_file",
            "txt_file",
            "model3d_file",
            "plot",
            "matplotlib_plot",
            "bokeh_plot",
            "image",
            "text",
            "gallery",
            "dataframe",
            "video",
            "audio",
            "html",
            "model3d",
        ],
        value="text",
        label="Response Type",
    )

    chat_input = gr.MultimodalTextbox(
        interactive=True,
        placeholder="Enter message or upload file...",
        show_label=False,
    )

    chat_msg = chat_input.submit(
        add_message, [chatbot, chat_input], [chatbot, chat_input]
    )
    bot_msg = chat_msg.then(
        bot, [chatbot, response_type], chatbot, api_name="bot_response"
    )
    bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])

    chatbot.like(print_like_dislike, None, None)

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:

- `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 https://www.gradio.app/main/docs/gradio/eventdata for more details.
- `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.
- `Chatbot.retry(fn, ...)`: This listener is triggered when the user clicks the retry button in the chatbot message.
- `Chatbot.undo(fn, ...)`: This listener is triggered when the user clicks the undo button in the chatbot message.
- `Chatbot.example_select(fn, ...)`: This listener is triggered when the user clicks on an example from within the Chatbot. This event has SelectData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See SelectData documentation on how to use this event data.
- `Chatbot.option_select(fn, ...)`: This listener is triggered when the user clicks on an option from within the Chatbot. This event has SelectData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See SelectData documentation on how to use this event data.
- `Chatbot.clear(fn, ...)`: This listener is triggered when the user clears the Chatbot using the clear button for the component.
- `Chatbot.copy(fn, ...)`: This listener is triggered when the user copies content from the Chatbot. Uses event data gradio.CopyData to carry information about the copied content. See EventData documentation on how to use this event data
- `Chatbot.edit(fn, ...)`: This listener is triggered when the user edits the Chatbot (e.g. image) using the built-in editor.

#### Event Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `fn` | `Callable \| None \| Literal['decorator']` | `"decorator"` | the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component. |
| `inputs` | `Component \| BlockContext \| list[Component \| BlockContext] \| Set[Component \| BlockContext] \| None` | `None` | List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. |
| `outputs` | `Component \| BlockContext \| list[Component \| BlockContext] \| Set[Component \| BlockContext] \| None` | `None` | List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. |
| `api_name` | `str \| None` | `None` | defines how the endpoint appears in the API docs. Can be a string or None. If set to a string, the endpoint will be exposed in the API docs with the given name. If None (default), the name of the function will be used as the API endpoint. |
| `api_description` | `str \| None \| Literal[False]` | `None` | Description of the API endpoint. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given description. If None, the function's docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs. |
| `scroll_to_output` | `bool` | `False` | If True, will scroll to output component on completion |
| `show_progress` | `Literal['full', 'minimal', 'hidden']` | `"full"` | how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all |
| `show_progress_on` | `Component \| list[Component] \| None` | `None` | Component or list of components to show the progress animation on. If None, will show the progress animation on all of the output components. |
| `queue` | `bool` | `True` | If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app. |
| `batch` | `bool` | `False` | If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component. |
| `max_batch_size` | `int` | `4` | Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) |
| `preprocess` | `bool` | `True` | If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component). |
| `postprocess` | `bool` | `True` | If False, will not run postprocessing of component data before returning 'fn' output to the browser. |
| `cancels` | `dict[str, Any] \| list[dict[str, Any]] \| None` | `None` | A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish. |
| `trigger_mode` | `Literal['once', 'multiple', 'always_last'] \| None` | `None` | If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete. |
| `js` | `str \| Literal[True] \| None` | `None` | Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components. |
| `concurrency_limit` | `int \| None \| Literal['default']` | `"default"` | If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default). |
| `concurrency_id` | `str \| None` | `None` | If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit. |
| `api_visibility` | `Literal['public', 'private', 'undocumented']` | `"public"` | controls the visibility and accessibility of this endpoint. Can be "public" (shown in API docs and callable by clients), "private" (hidden from API docs and not callable by clients), or "undocumented" (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to "private". |
| `time_limit` | `int \| None` | `None` |  |
| `stream_every` | `float` | `0.5` |  |
| `key` | `int \| str \| tuple[int \| str, ...] \| None` | `None` | A unique key for this event listener to be used in @gr.render(). If set, this value identifies an event as identical across re-renders when the key is identical. |
| `validator` | `Callable \| None` | `None` | Optional validation function to run before the main function. If provided, this function will be executed first with queue=False, and only if it completes successfully will the main function be called. The validator receives the same inputs as the main function and should return a `gr.validate()` for each input value. |
### Helper Classes

### ChatMessage

```python
gradio.ChatMessage(···)
```

#### Description

A dataclass that represents a message in the Chatbot component (with type="messages"). The only required field is `content`. The value of `gr.Chatbot` is a list of these dataclasses.

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `content` | `MessageContent \| list[MessageContent]` | `` | The content of the message. Can be a string, a file dict, a gradio component, or a list of these types to group these messages together. |
| `role` | `Literal['user', 'assistant', 'system']` | `"assistant"` | The role of the message, which determines the alignment of the message in the chatbot. Can be "user", "assistant", or "system". Defaults to "assistant". |
| `metadata` | `MetadataDict` | `_HAS_DEFAULT_FACTORY_CLASS()` | The metadata of the message, which is used to display intermediate thoughts / tool usage. Should be a dictionary with the following keys: "title" (required to display the thought), and optionally: "id" and "parent_id" (to nest thoughts), "duration" (to display the duration of the thought), "status" (to display the status of the thought). |
| `options` | `list[OptionDict]` | `_HAS_DEFAULT_FACTORY_CLASS()` | The options of the message. A list of Option objects, which are dictionaries with the following keys: "label" (the text to display in the option), and optionally "value" (the value to return when the option is selected if different from the label). |
### MetadataDict

A typed dictionary to represent metadata for a message in the Chatbot component. An instance of this dictionary is used for the `metadata` field in a ChatMessage when the chat message should be displayed as a thought.

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `title` | `str` | `` | The title of the 'thought' message. Only required field. |
| `id` | `int \| str` | `` | The ID of the message. Only used for nested thoughts. Nested thoughts can be nested by setting the parent_id to the id of the parent thought. |
| `parent_id` | `int \| str` | `` | The ID of the parent message. Only used for nested thoughts. |
| `log` | `str` | `` | A string message to display next to the thought title in a subdued font. |
| `duration` | `float` | `` | The duration of the message in seconds. Appears next to the thought title in a subdued font inside a parentheses. |
| `status` | `Literal['pending', 'done']` | `` | if set to `'pending'`, a spinner appears next to the thought title and the accordion is initialized open.  If `status` is `'done'`, the thought accordion is initialized closed. If `status` is not provided, the thought accordion is initialized open and no spinner is displayed. |
### OptionDict

A typed dictionary to represent an option in a ChatMessage. A list of these dictionaries is used for the `options` field in a ChatMessage.

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `value` | `str` | `` | The value to return when the option is selected. |
| `label` | `str` | `` | The text to display in the option, if different from the value. |
- [Chatbot Specific Events](https://www.gradio.app/guides/chatbot-specific-events/)
- [Conversational Chatbot](https://www.gradio.app/guides/conversational-chatbot/)
- [Creating A Chatbot Fast](https://www.gradio.app/guides/creating-a-chatbot-fast/)
- [Creating A Custom Chatbot With Blocks](https://www.gradio.app/guides/creating-a-custom-chatbot-with-blocks/)
- [Agents And Tool Usage](https://www.gradio.app/guides/agents-and-tool-usage/)
