- Components
- Chatbot
New to Gradio? Start here: Getting Started
See the Release History
Chatbot
gradio.Chatbot(type="messages", ···)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 should be a string (rendered as markdown/html) or a Gradio component (useful for displaying files).
As an example:
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, type="messages")
demo.launch()For convenience, you can use the ChatMessage dataclass so that your text editor can give you autocomplete hints and typechecks.
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, type="messages")
demo.launch()Initialization
value: list[MessageDict | Message] | Callable | None
value: list[MessageDict | Message] | Callable | None= NoneDefault 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
label: str | I18nData | None= Nonethe 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
every: Timer | float | None= NoneContinously 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
inputs: Component | list[Component] | set[Component] | None= NoneComponents 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.
container: bool
container: bool= TrueIf True, will place the component in a container - providing some extra padding around the border.
scale: int | None
scale: int | None= Nonerelative 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
min_width: int= 160minimum 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']
visible: bool | Literal['hidden']= TrueIf 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
elem_id: str | None= NoneAn 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
elem_classes: list[str] | str | None= NoneAn 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
autoscroll: bool= TrueIf 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
render: bool= TrueIf 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
key: int | str | tuple[int | str, ...] | None= Nonein 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
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
height: int | str | None= 400The 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
resizable: bool= FalseIf True, the user of the Gradio app can resize the chatbot by dragging the bottom right corner.
max_height: int | str | None
max_height: int | str | None= NoneThe 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
min_height: int | str | None= NoneThe 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
editable: Literal['user', 'all'] | None= NoneAllows 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
latex_delimiters: list[dict[str, str | bool]] | None= NoneA 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.
rtl: bool
rtl: bool= FalseIf 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']] | None
buttons: list[Literal['share', 'copy', 'copy_all']] | None= NoneA list of buttons to show in the top right corner of the component. Valid options are "share", "copy", and "copy_all". 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. By default, "share" and "copy_all" buttons are shown.
watermark: str | None
watermark: str | None= NoneIf 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
avatar_images: tuple[str | Path | None, str | Path | None] | None= NoneTuple 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
sanitize_html: bool= TrueIf False, will disable HTML sanitization for chatbot messages. This is not recommended, as it can lead to security vulnerabilities.
render_markdown: bool
render_markdown: bool= TrueIf False, will disable Markdown rendering for chatbot messages.
feedback_options: list[str] | tuple[str, ...] | None
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
feedback_value: list[str | None] | None= NoneA 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
line_breaks: bool= TrueIf 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
layout: Literal['panel', 'bubble'] | None= NoneIf "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
placeholder: str | None= Nonea 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
examples: list[ExampleMessage] | None= NoneA 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: <class 'inspect._empty'>
allow_file_downloads: <class 'inspect._empty'>= TrueIf True, will show a download button for chatbot messages that contain media. Defaults to True.
group_consecutive_messages: bool
group_consecutive_messages: bool= TrueIf 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
allow_tags: list[str] | bool= TrueIf 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
reasoning_tags: list[tuple[str, str]] | None= NoneIf 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.
Shortcuts
| Class | Interface String Shortcut | Initialization |
|---|---|---|
| "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 historyWould be displayed as following:
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 historyUsing 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/gradio/media_assets/audio/audio_sample.wav")),
("Here's an video", 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
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 |
|---|---|
| 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 |
| Event listener for when the user selects or deselects the Chatbot. Uses event data gradio.SelectData to carry |
| 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. |
| This listener is triggered when the user clicks the retry button in the chatbot message. |
| This listener is triggered when the user clicks the undo button in the chatbot message. |
| 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. |
| 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. |
| This listener is triggered when the user clears the Chatbot using the clear button for the component. |
| 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 |
| This listener is triggered when the user edits the Chatbot (e.g. image) using the built-in editor. |
Event Parameters
fn: Callable | None | Literal['decorator']
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
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None= NoneList 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
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None= NoneList of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
api_name: str | None
api_name: str | None= Nonedefines 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]
api_description: str | None | Literal[False]= NoneDescription 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.
show_progress: Literal['full', 'minimal', 'hidden']
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
show_progress_on: Component | list[Component] | None= NoneComponent 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
queue: bool= TrueIf 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
batch: bool= FalseIf 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
max_batch_size: int= 4Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
preprocess: bool
preprocess: bool= TrueIf 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
postprocess: bool= TrueIf False, will not run postprocessing of component data before returning 'fn' output to the browser.
cancels: dict[str, Any] | list[dict[str, Any]] | None
cancels: dict[str, Any] | list[dict[str, Any]] | None= NoneA 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
trigger_mode: Literal['once', 'multiple', 'always_last'] | None= NoneIf "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
js: str | Literal[True] | None= NoneOptional 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']
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
concurrency_id: str | None= NoneIf 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']
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".
key: int | str | tuple[int | str, ...] | None
key: int | str | tuple[int | str, ...] | None= NoneA 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
validator: Callable | None= NoneOptional 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
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.
content: MessageContent | list[MessageContent]
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']
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
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]
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.
id: int | str
id: int | strThe 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.
duration: float
duration: floatThe duration of the message in seconds. Appears next to the thought title in a subdued font inside a parentheses.
status: Literal['pending', 'done']
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.