# ChatInterface

```python
gradio.ChatInterface(fn, ···)
```

### Description

ChatInterface is Gradio's high-level abstraction for creating chatbot UIs, and allows you to create a web-based demo around a chatbot model in a few lines of code. Only one parameter is required: fn, which takes a function that governs the response of the chatbot based on the user input and chat history. Additional parameters can be used to control the appearance and behavior of the demo.

### Example Usage

**Basic Example**: A chatbot that echoes back the users’s message

```python
import gradio as gr

def echo(message, history):
    return message

demo = gr.ChatInterface(fn=echo, examples=["hello", "hola", "merhaba"], title="Echo Bot")
demo.launch()
```

**Custom Chatbot**: A `gr.ChatInterface` with a custom `gr.Chatbot` that includes a placeholder as well as upvote/downvote buttons. The upvote/downvote buttons are automatically added when a `.like()` event is attached to a `gr.Chatbot`. In order to attach event listeners to your custom chatbot, wrap the `gr.Chatbot` as well as the `gr.ChatInterface` inside of a `gr.Blocks` like this:

```py
import gradio as gr

def yes(message, history):
    return "yes"

def vote(data: gr.LikeData):
    if data.liked:
        print("You upvoted this response: " + data.value["value"])
    else:
        print("You downvoted this response: " + data.value["value"])

with gr.Blocks() as demo:
    chatbot = gr.Chatbot(placeholder="<strong>Your Personal Yes-Man</strong><br>Ask Me Anything")
    chatbot.like(vote, None, None)
    gr.ChatInterface(fn=yes, chatbot=chatbot)
    
demo.launch()
```

### Initialization

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `fn` | `Callable` | `` | the function to wrap the chat interface around. The function should accept two parameters: a `str` representing the input message and `list` of openai-style dictionaries: {"role": "user" \| "assistant", "content": `str` \| {"path": `str`} \| `gr.Component`} representing the chat history. The function should return/yield a `str` (for a simple message), a supported Gradio component (e.g. gr.Image to return an image), a `dict` (for a complete openai-style message response), or a `list` of such messages. |
| `multimodal` | `bool` | `False` | if True, the chat interface will use a `gr.MultimodalTextbox` component for the input, which allows for the uploading of multimedia files. If False, the chat interface will use a gr.Textbox component for the input. If this is True, the first argument of `fn` should accept not a `str` message but a `dict` message with keys "text" and "files" |
| `chatbot` | `Chatbot \| None` | `None` | an instance of the gr.Chatbot component to use for the chat interface, if you would like to customize the chatbot properties. If not provided, a default gr.Chatbot component will be created. |
| `textbox` | `Textbox \| MultimodalTextbox \| None` | `None` | an instance of the gr.Textbox or gr.MultimodalTextbox component to use for the chat interface, if you would like to customize the textbox properties. If not provided, a default gr.Textbox or gr.MultimodalTextbox component will be created. |
| `additional_inputs` | `str \| Component \| list[str \| Component] \| None` | `None` | an instance or list of instances of gradio components (or their string shortcuts) to use as additional inputs to the chatbot. If the components are not already rendered in a surrounding Blocks, then the components will be displayed under the chatbot, in an accordion. The values of these components will be passed into `fn` as arguments in order after the chat history. |
| `additional_inputs_accordion` | `str \| Accordion \| None` | `None` | if a string is provided, this is the label of the `gr.Accordion` to use to contain additional inputs. A `gr.Accordion` object can be provided as well to configure other properties of the container holding the additional inputs. Defaults to a `gr.Accordion(label="Additional Inputs", open=False)`. This parameter is only used if `additional_inputs` is provided. |
| `additional_outputs` | `Component \| list[Component] \| None` | `None` | an instance or list of instances of gradio components to use as additional outputs from the chat function. These must be components that are already defined in the same Blocks scope. If provided, the chat function should return additional values for these components. See $demo/chatinterface_artifacts. |
| `editable` | `bool` | `False` | if True, users can edit past messages to regenerate responses. |
| `examples` | `list[str] \| list[MultimodalValue] \| list[list] \| None` | `None` | sample inputs for the function; if provided, appear within the chatbot and can be clicked to populate the chatbot input. Should be a list of strings representing text-only examples, or a list of dictionaries (with keys `text` and `files`) representing multimodal examples. If `additional_inputs` are provided, the examples must be a list of lists, where the first element of each inner list is the string or dictionary example message and the remaining elements are the example values for the additional inputs -- in this case, the examples will appear under the chatbot. |
| `example_labels` | `list[str] \| None` | `None` | labels for the examples, to be displayed instead of the examples themselves. If provided, should be a list of strings with the same length as the examples list. Only applies when examples are displayed within the chatbot (i.e. when `additional_inputs` is not provided). |
| `example_icons` | `list[str] \| None` | `None` | icons for the examples, to be displayed above the examples. If provided, should be a list of string URLs or local paths with the same length as the examples list. Only applies when examples are displayed within the chatbot (i.e. when `additional_inputs` is not provided). |
| `run_examples_on_click` | `bool` | `True` | if True, clicking on an example will run the example through the chatbot fn and the response will be displayed in the chatbot. If False, clicking on an example will only populate the chatbot input with the example message. Has no effect if `cache_examples` is True |
| `cache_examples` | `bool \| None` | `None` | if True, caches examples in the server for fast runtime in examples. The default option in HuggingFace Spaces is True. The default option elsewhere is False.  Note that examples are cached separately from Gradio's queue() so certain features, such as gr.Progress(), gr.Info(), gr.Warning(), etc. will not be displayed in Gradio's UI for cached examples. |
| `cache_mode` | `Literal['eager', 'lazy'] \| None` | `None` | if "eager", all examples are cached at app launch. If "lazy", examples are cached for all users after the first use by any user of the app. If None, will use the GRADIO_CACHE_MODE environment variable if defined, or default to "eager". |
| `title` | `str \| I18nData \| None` | `None` | a title for the interface; if provided, appears above chatbot in large font. Also used as the tab title when opened in a browser window. |
| `description` | `str \| None` | `None` | a description for the interface; if provided, appears above the chatbot and beneath the title in regular font. Accepts Markdown and HTML content. |
| `flagging_mode` | `Literal['never', 'manual'] \| None` | `None` | one of "never", "manual". If "never", users will not see a button to flag an input and output. If "manual", users will see a button to flag. |
| `flagging_options` | `list[str] \| tuple[str, ...] \| None` | `('Like', 'Dislike')` | a list of strings representing the options that users can choose from when flagging a message. Defaults to ["Like", "Dislike"]. These two case-sensitive strings will render as "thumbs up" and "thumbs down" icon respectively next to each bot message, but any other strings appear under a separate flag icon. |
| `flagging_dir` | `str` | `".gradio/flagged"` | path to the the directory where flagged data is stored. If the directory does not exist, it will be created. |
| `analytics_enabled` | `bool \| None` | `None` | whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable if defined, or default to True. |
| `autofocus` | `bool` | `True` | if True, autofocuses to the textbox when the page loads. |
| `autoscroll` | `bool` | `True` | If True, will automatically scroll to the bottom of the chatbot when a new message appears, unless the user scrolls up. If False, will not scroll to the bottom of the chatbot automatically. |
| `submit_btn` | `str \| bool \| None` | `True` | If True, will show a submit button with a submit icon within the textbox. If a string, will use that string as the submit button text in place of the icon. If False, will not show a submit button. |
| `stop_btn` | `str \| bool \| None` | `True` | If True, will show a button with a stop icon during generator executions, to stop generating. If a string, will use that string as the submit button text in place of the stop icon. If False, will not show a stop button. |
| `concurrency_limit` | `int \| None \| Literal['default']` | `"default"` | if set, this is the maximum number of chatbot submissions that can be running simultaneously. Can be set to None to mean no limit (any number of chatbot submissions can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `.queue()`, which is 1 by default). |
| `delete_cache` | `tuple[int, int] \| None` | `None` | a tuple corresponding [frequency, age] both expressed in number of seconds. Every `frequency` seconds, the temporary files created by this Blocks instance will be deleted if more than `age` seconds have passed since the file was created. For example, setting this to (86400, 86400) will delete temporary files every day. The cache will be deleted entirely when the server restarts. If None, no cache deletion will occur. |
| `show_progress` | `Literal['full', 'minimal', 'hidden']` | `"minimal"` | 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 |
| `fill_height` | `bool` | `True` | if True, the chat interface will expand to the height of window. |
| `fill_width` | `bool` | `False` | Whether to horizontally expand to fill container fully. If False, centers and constrains app to a maximum width. |
| `api_name` | `str \| None` | `None` | defines how the chat 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, the name of the function will be used. |
| `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. |
| `api_visibility` | `Literal['public', 'private', 'undocumented']` | `"public"` | Controls the visibility of the chat endpoint. Can be "public" (shown in API docs and callable), "private" (hidden from API docs and not callable), or "undocumented" (hidden from API docs but callable). |
| `save_history` | `bool` | `False` | if True, will save the chat history to the browser's local storage and display previous conversations in a side panel. |
| `validator` | `Callable \| None` | `None` | a function that takes in the inputs and can optionally return a gr.validate() object for each input. |
### Demos

**chatinterface_random_response**

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

```python
import random
import gradio as gr

def random_response(message, history):
    return random.choice(["Yes", "No"])

demo = gr.ChatInterface(random_response, autofocus=False, api_name="chat")

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

**chatinterface_streaming_echo**

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

```python
import time
import gradio as gr

def slow_echo(message, history):
    for i in range(len(message)):
        time.sleep(0.05)
        yield "You typed: " + message[: i + 1]

demo = gr.ChatInterface(
    slow_echo,
    flagging_mode="manual",
    flagging_options=["Like", "Spam", "Inappropriate", "Other"],
    save_history=True,
)

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

**chatinterface_artifacts**

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

```python
import gradio as gr

python_code = """
def fib(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)
"""

js_code = """
function fib(n) {
    if (n <= 0) return 0;
    if (n === 1) return 1;
    return fib(n - 1) + fib(n - 2);
}
"""

def chat(message, history):
    if "python" in message.lower():
        return "Type Python or JavaScript to see the code.", gr.Code(language="python", value=python_code)
    elif "javascript" in message.lower():
        return "Type Python or JavaScript to see the code.", gr.Code(language="javascript", value=js_code)
    else:
        return "Please ask about Python or JavaScript.", None

with gr.Blocks() as demo:
    code = gr.Code(render=False)
    with gr.Row():
        with gr.Column():
            gr.Markdown("<center><h1>Write Python or JavaScript</h1></center>")
            gr.ChatInterface(
                chat,
                examples=["Python", "JavaScript"],
                additional_outputs=[code],
                api_name="chat",
            )
        with gr.Column():
            gr.Markdown("<center><h1>Code Artifacts</h1></center>")
            code.render()

demo.launch()
```

- [Creating A Chatbot Fast](https://www.gradio.app/guides/creating-a-chatbot-fast/)
- [Chatinterface Examples](https://www.gradio.app/guides/chatinterface-examples/)
- [Agents And Tool Usage](https://www.gradio.app/guides/agents-and-tool-usage/)
- [Chatbot Specific Events](https://www.gradio.app/guides/chatbot-specific-events/)
