gradio-app / gradio

Build and share delightful machine learning apps, all in Python. 🌟 Star to support our work!
http://www.gradio.app
Apache License 2.0
30.56k stars 2.27k forks source link

Make placeholder a variable in ChatInterface class #8566

Closed ThomasCosyn closed 1 week ago

ThomasCosyn commented 1 week ago

Here is the code with the modification.

` class ChatInterface(Blocks): """ 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:
    import gradio as gr

    def echo(message, history):
        return message

    demo = gr.ChatInterface(fn=echo, examples=["hello", "hola", "merhaba"], title="Echo Bot")
    demo.launch()
Demos: chatinterface_multimodal, chatinterface_random_response, chatinterface_streaming_echo
Guides: creating-a-chatbot-fast, sharing-your-app
"""

def __init__(
    self,
    fn: Callable,
    *,
    multimodal: bool = False,
    chatbot: Chatbot | None = None,
    textbox: Textbox | MultimodalTextbox | None = None,
    additional_inputs: str | Component | list[str | Component] | None = None,
    additional_inputs_accordion_name: str | None = None,
    additional_inputs_accordion: str | Accordion | None = None,
    examples: list[str] | list[dict[str, str | list]] | list[list] | None = None,
    cache_examples: bool | Literal["lazy"] | None = None,
    examples_per_page: int = 10,
    title: str | None = None,
    description: str | None = None,
    theme: Theme | str | None = None,
    css: str | None = None,
    js: str | None = None,
    head: str | None = None,
    analytics_enabled: bool | None = None,
    submit_btn: str | None | Button = "Submit",
    stop_btn: str | None | Button = "Stop",
    retry_btn: str | None | Button = "🔄  Retry",
    undo_btn: str | None | Button = "↩️ Undo",
    clear_btn: str | None | Button = "🗑️  Clear",
    autofocus: bool = True,
    concurrency_limit: int | None | Literal["default"] = "default",
    fill_height: bool = True,
    delete_cache: tuple[int, int] | None = None,
    placeholder: str = "Type a message...",
):
    """
    Parameters:
        fn: The function to wrap the chat interface around. Should accept two parameters: a string input message and list of two-element lists of the form [[user_message, bot_message], ...] representing the chat history, and return a string response. See the Chatbot documentation for more information on the chat history format.
        multimodal: 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.
        chatbot: 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: 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: An instance or list of instances of gradio components (or their string shortcuts) to use as additional inputs to the chatbot. If components are not already rendered in a surrounding Blocks, then the components will be displayed under the chatbot, in an accordion.
        additional_inputs_accordion_name: Deprecated. Will be removed in a future version of Gradio. Use the `additional_inputs_accordion` parameter instead.
        additional_inputs_accordion: 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.
        examples: Sample inputs for the function; if provided, appear below the chatbot and can be clicked to populate the chatbot input. Should be a list of strings if `multimodal` is False, and a list of dictionaries (with keys `text` and `files`) if `multimodal` is True.
        cache_examples: 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.
        examples_per_page: If examples are provided, how many to display per page.
        title: 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: a description for the interface; if provided, appears above the chatbot and beneath the title in regular font. Accepts Markdown and HTML content.
        theme: Theme to use, loaded from gradio.themes.
        css: Custom css as a string or path to a css file. This css will be included in the demo webpage.
        js: Custom js as a string or path to a js file. The custom js should be in the form of a single js function. This function will automatically be executed when the page loads. For more flexibility, use the head parameter to insert js inside <script> tags.
        head: Custom html to insert into the head of the demo webpage. This can be used to add custom meta tags, multiple scripts, stylesheets, etc. to the page.
        analytics_enabled: Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable if defined, or default to True.
        submit_btn: Text to display on the submit button. If None, no button will be displayed. If a Button object, that button will be used.
        stop_btn: Text to display on the stop button, which replaces the submit_btn when the submit_btn or retry_btn is clicked and response is streaming. Clicking on the stop_btn will halt the chatbot response. If set to None, stop button functionality does not appear in the chatbot. If a Button object, that button will be used as the stop button.
        retry_btn: Text to display on the retry button. If None, no button will be displayed. If a Button object, that button will be used.
        undo_btn: Text to display on the delete last button. If None, no button will be displayed. If a Button object, that button will be used.
        clear_btn: Text to display on the clear button. If None, no button will be displayed. If a Button object, that button will be used.
        autofocus: If True, autofocuses to the textbox when the page loads.
        concurrency_limit: 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).
        fill_height: If True, the chat interface will expand to the height of window.
        delete_cache: 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.
        placeholder: Placeholder text to display in the textbox. Defaults to "Type a message...".
    """
    super().__init__(
        analytics_enabled=analytics_enabled,
        mode="chat_interface",
        css=css,
        title=title or "Gradio",
        theme=theme,
        js=js,
        head=head,
        fill_height=fill_height,
        delete_cache=delete_cache,
    )
    self.multimodal = multimodal
    self.concurrency_limit = concurrency_limit
    self.fn = fn
    self.is_async = inspect.iscoroutinefunction(
        self.fn
    ) or inspect.isasyncgenfunction(self.fn)
    self.is_generator = inspect.isgeneratorfunction(
        self.fn
    ) or inspect.isasyncgenfunction(self.fn)
    self.buttons: list[Button | None] = []

    self.examples = examples
    self.cache_examples = cache_examples

    if additional_inputs:
        if not isinstance(additional_inputs, list):
            additional_inputs = [additional_inputs]
        self.additional_inputs = [
            get_component_instance(i)
            for i in additional_inputs  # type: ignore
        ]
    else:
        self.additional_inputs = []
    if additional_inputs_accordion_name is not None:
        print(
            "The `additional_inputs_accordion_name` parameter is deprecated and will be removed in a future version of Gradio. Use the `additional_inputs_accordion` parameter instead."
        )
        self.additional_inputs_accordion_params = {
            "label": additional_inputs_accordion_name
        }
    if additional_inputs_accordion is None:
        self.additional_inputs_accordion_params = {
            "label": "Additional Inputs",
            "open": False,
        }
    elif isinstance(additional_inputs_accordion, str):
        self.additional_inputs_accordion_params = {
            "label": additional_inputs_accordion
        }
    elif isinstance(additional_inputs_accordion, Accordion):
        self.additional_inputs_accordion_params = (
            additional_inputs_accordion.recover_kwargs(
                additional_inputs_accordion.get_config()
            )
        )
    else:
        raise ValueError(
            f"The `additional_inputs_accordion` parameter must be a string or gr.Accordion, not {type(additional_inputs_accordion)}"
        )

    with self:
        if title:
            Markdown(
                f"<h1 style='text-align: center; margin-bottom: 1rem'>{self.title}</h1>"
            )
        if description:
            Markdown(description)

        if chatbot:
            self.chatbot = chatbot.render()
        else:
            self.chatbot = Chatbot(
                label="Chatbot", scale=1, height=200 if fill_height else None
            )

        with Row():
            for btn in [retry_btn, undo_btn, clear_btn]:
                if btn is not None:
                    if isinstance(btn, Button):
                        btn.render()
                    elif isinstance(btn, str):
                        btn = Button(
                            btn, variant="secondary", size="sm", min_width=60
                        )
                    else:
                        raise ValueError(
                            f"All the _btn parameters must be a gr.Button, string, or None, not {type(btn)}"
                        )
                self.buttons.append(btn)  # type: ignore

        with Group():
            with Row():
                if textbox:
                    if self.multimodal:
                        submit_btn = None
                    else:
                        textbox.container = False
                    textbox.show_label = False
                    textbox_ = textbox.render()
                    if not isinstance(textbox_, (Textbox, MultimodalTextbox)):
                        raise TypeError(
                            f"Expected a gr.Textbox or gr.MultimodalTextbox component, but got {type(textbox_)}"
                        )
                    self.textbox = textbox_
                elif self.multimodal:
                    submit_btn = None
                    self.textbox = MultimodalTextbox(
                        show_label=False,
                        label="Message",
                        placeholder=placeholder,
                        scale=7,
                        autofocus=autofocus,
                    )
                else:
                    self.textbox = Textbox(
                        container=False,
                        show_label=False,
                        label="Message",
                        placeholder=placeholder,
                        scale=7,
                        autofocus=autofocus,
                    )
                    ...
                    `

Works fine for me !

abidlabs commented 1 week ago

Hi @ThomasCosyn you can already achieve this by passing in a gr.Textbox instance with the placeholder supplied into the textbox argument of gr.ChatInterfce, see here: https://www.gradio.app/guides/creating-a-chatbot-fast#customizing-your-chatbot