From 4d1a468e73a30c16cc74869eee798b10d6afcb34 Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Thu, 28 Nov 2024 15:34:50 -0500 Subject: [PATCH 01/26] artifacts --- demo/chatinterface_artifacts/run.py | 39 ++++++ gradio/chat_interface.py | 198 ++++++++++++++-------------- 2 files changed, 140 insertions(+), 97 deletions(-) create mode 100644 demo/chatinterface_artifacts/run.py diff --git a/demo/chatinterface_artifacts/run.py b/demo/chatinterface_artifacts/run.py new file mode 100644 index 0000000000000..791b9bc5af286 --- /dev/null +++ b/demo/chatinterface_artifacts/run.py @@ -0,0 +1,39 @@ +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("

Write Python or JavaScript

") + gr.ChatInterface(chat, examples=["Python", "JavaScript"], additional_outputs=[code], type="messages") + with gr.Column(): + gr.Markdown("

Code Artifacts

") + code.render() + +demo.launch() diff --git a/gradio/chat_interface.py b/gradio/chat_interface.py index 691ea88149502..b4cca48352465 100644 --- a/gradio/chat_interface.py +++ b/gradio/chat_interface.py @@ -39,7 +39,7 @@ from gradio.events import Dependency, SelectData from gradio.helpers import create_examples as Examples # noqa: N812 from gradio.helpers import special_args, update -from gradio.layouts import Accordion, Group, Row +from gradio.layouts import Accordion, Column, Group, Row from gradio.routes import Request from gradio.themes import ThemeClass as Theme @@ -74,6 +74,7 @@ def __init__( textbox: Textbox | MultimodalTextbox | None = None, additional_inputs: str | Component | list[str | Component] | None = None, additional_inputs_accordion: str | Accordion | None = None, + additional_outputs: Component | list[Component] | None = None, examples: list[str] | list[MultimodalValue] | list[list] | None = None, example_labels: list[str] | None = None, example_icons: list[str] | None = None, @@ -108,6 +109,7 @@ def __init__( 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 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: 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: 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. examples: 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: 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: 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). @@ -169,6 +171,7 @@ def __init__( get_component_instance(i) for i in utils.none_or_singleton_to_list(additional_inputs) ] + self.additional_outputs = utils.none_or_singleton_to_list(additional_outputs) if additional_inputs_accordion is None: self.additional_inputs_accordion_params = { "label": "Additional Inputs", @@ -203,108 +206,109 @@ def __init__( break with self: - if title: - Markdown( - f"

{self.title}

" - ) - if description: - Markdown(description) - if chatbot: - if self.type and self.type != chatbot.type: - warnings.warn( - "The type of the chatbot does not match the type of the chat interface. The type of the chat interface will be used." - "Recieved type of chatbot: {chatbot.type}, type of chat interface: {self.type}" + with Column(): + if title: + Markdown( + f"

{self.title}

" ) - chatbot.type = self.type - chatbot._setup_data_model() - self.chatbot = cast( - Chatbot, get_component_instance(chatbot, render=True) - ) - if self.chatbot.examples and self.examples_messages: - warnings.warn( - "The ChatInterface already has examples set. The examples provided in the chatbot will be ignored." + if description: + Markdown(description) + if chatbot: + if self.type and self.type != chatbot.type: + warnings.warn( + "The type of the chatbot does not match the type of the chat interface. The type of the chat interface will be used." + "Recieved type of chatbot: {chatbot.type}, type of chat interface: {self.type}" + ) + chatbot.type = self.type + chatbot._setup_data_model() + self.chatbot = cast( + Chatbot, get_component_instance(chatbot, render=True) + ) + if self.chatbot.examples and self.examples_messages: + warnings.warn( + "The ChatInterface already has examples set. The examples provided in the chatbot will be ignored." + ) + self.chatbot.examples = ( + self.examples_messages + if not self._additional_inputs_in_examples + else None + ) + self.chatbot._setup_examples() + else: + self.type = self.type or "tuples" + self.chatbot = Chatbot( + label="Chatbot", + scale=1, + height=400 if fill_height else None, + type=self.type, + autoscroll=autoscroll, + examples=self.examples_messages + if not self._additional_inputs_in_examples + else None, ) - self.chatbot.examples = ( - self.examples_messages - if not self._additional_inputs_in_examples - else None - ) - self.chatbot._setup_examples() - else: - self.type = self.type or "tuples" - self.chatbot = Chatbot( - label="Chatbot", - scale=1, - height=200 if fill_height else None, - type=self.type, - autoscroll=autoscroll, - examples=self.examples_messages - if not self._additional_inputs_in_examples - else None, - ) - with Group(): - with Row(): - if textbox: - textbox.show_label = False - textbox_ = get_component_instance(textbox, render=True) - if not isinstance(textbox_, (Textbox, MultimodalTextbox)): - raise TypeError( - f"Expected a gr.Textbox or gr.MultimodalTextbox component, but got {builtins.type(textbox_)}" + with Group(): + with Row(): + if textbox: + textbox.show_label = False + textbox_ = get_component_instance(textbox, render=True) + if not isinstance(textbox_, (Textbox, MultimodalTextbox)): + raise TypeError( + f"Expected a gr.Textbox or gr.MultimodalTextbox component, but got {builtins.type(textbox_)}" + ) + self.textbox = textbox_ + else: + textbox_component = ( + MultimodalTextbox if self.multimodal else Textbox + ) + self.textbox = textbox_component( + show_label=False, + label="Message", + placeholder="Type a message...", + scale=7, + autofocus=autofocus, + submit_btn=submit_btn, + stop_btn=stop_btn, ) - self.textbox = textbox_ - else: - textbox_component = ( - MultimodalTextbox if self.multimodal else Textbox - ) - self.textbox = textbox_component( - show_label=False, - label="Message", - placeholder="Type a message...", - scale=7, - autofocus=autofocus, - submit_btn=submit_btn, - stop_btn=stop_btn, - ) - # Hide the stop button at the beginning, and show it with the given value during the generator execution. - self.original_stop_btn = self.textbox.stop_btn - self.textbox.stop_btn = False - - self.fake_api_btn = Button("Fake API", visible=False) - self.fake_response_textbox = Textbox(label="Response", visible=False) - - if self.examples: - self.examples_handler = Examples( - examples=self.examples, - inputs=[self.textbox] + self.additional_inputs, - outputs=self.chatbot, - fn=self._examples_stream_fn - if self.is_generator - else self._examples_fn, - cache_examples=self.cache_examples, - cache_mode=self.cache_mode, - visible=self._additional_inputs_in_examples, - preprocess=self._additional_inputs_in_examples, - ) + # Hide the stop button at the beginning, and show it with the given value during the generator execution. + self.original_stop_btn = self.textbox.stop_btn + self.textbox.stop_btn = False + + self.fake_api_btn = Button("Fake API", visible=False) + self.fake_response_textbox = Textbox(label="Response", visible=False) + + if self.examples: + self.examples_handler = Examples( + examples=self.examples, + inputs=[self.textbox] + self.additional_inputs, + outputs=self.chatbot, + fn=self._examples_stream_fn + if self.is_generator + else self._examples_fn, + cache_examples=self.cache_examples, + cache_mode=self.cache_mode, + visible=self._additional_inputs_in_examples, + preprocess=self._additional_inputs_in_examples, + ) - any_unrendered_inputs = any( - not inp.is_rendered for inp in self.additional_inputs - ) - if self.additional_inputs and any_unrendered_inputs: - with Accordion(**self.additional_inputs_accordion_params): # type: ignore - for input_component in self.additional_inputs: - if not input_component.is_rendered: - input_component.render() - - self.saved_input = State() - self.chatbot_state = ( - State(self.chatbot.value) if self.chatbot.value else State([]) - ) - self.previous_input = State(value=[]) - self.show_progress = show_progress - self._setup_events() - self._setup_api() + any_unrendered_inputs = any( + not inp.is_rendered for inp in self.additional_inputs + ) + if self.additional_inputs and any_unrendered_inputs: + with Accordion(**self.additional_inputs_accordion_params): # type: ignore + for input_component in self.additional_inputs: + if not input_component.is_rendered: + input_component.render() + + self.saved_input = State() + self.chatbot_state = ( + State(self.chatbot.value) if self.chatbot.value else State([]) + ) + self.previous_input = State(value=[]) + self.show_progress = show_progress + self._setup_events() + self._setup_api() @staticmethod def _setup_example_messages( From fffe8bbbea3a16b09e99e426c6e592dc57d8c859 Mon Sep 17 00:00:00 2001 From: gradio-pr-bot Date: Thu, 28 Nov 2024 20:36:01 +0000 Subject: [PATCH 02/26] add changeset --- .changeset/lazy-symbols-behave.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/lazy-symbols-behave.md diff --git a/.changeset/lazy-symbols-behave.md b/.changeset/lazy-symbols-behave.md new file mode 100644 index 0000000000000..8c028281fd271 --- /dev/null +++ b/.changeset/lazy-symbols-behave.md @@ -0,0 +1,5 @@ +--- +"gradio": minor +--- + +feat:Additional outputs in `gr.ChatInterface` From b4e3868ca989088dd012df3c05c4034fa083bda2 Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Thu, 28 Nov 2024 15:40:32 -0500 Subject: [PATCH 03/26] chatinterface --- gradio/chat_interface.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradio/chat_interface.py b/gradio/chat_interface.py index b4cca48352465..b85e9499282f1 100644 --- a/gradio/chat_interface.py +++ b/gradio/chat_interface.py @@ -109,7 +109,7 @@ def __init__( 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 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: 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: 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. + additional_outputs: 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. examples: 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: 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: 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). From c34f43e353fbfb7db952661eda7510c777aca6d1 Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Thu, 28 Nov 2024 15:44:16 -0500 Subject: [PATCH 04/26] guide fixes --- guides/05_chatbots/01_creating-a-chatbot-fast.md | 2 +- guides/05_chatbots/02_chatinterface-examples.md | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/guides/05_chatbots/01_creating-a-chatbot-fast.md b/guides/05_chatbots/01_creating-a-chatbot-fast.md index 644c043243ed4..699c1a495300b 100644 --- a/guides/05_chatbots/01_creating-a-chatbot-fast.md +++ b/guides/05_chatbots/01_creating-a-chatbot-fast.md @@ -1,6 +1,6 @@ # How to Create a Chatbot with Gradio -Tags: NLP, LLM, CHATBOT +Tags: LLM, CHATBOT, NLP ## Introduction diff --git a/guides/05_chatbots/02_chatinterface-examples.md b/guides/05_chatbots/02_chatinterface-examples.md index e53780ce616bd..4de7f50eb6005 100644 --- a/guides/05_chatbots/02_chatinterface-examples.md +++ b/guides/05_chatbots/02_chatinterface-examples.md @@ -1,5 +1,7 @@ # Using Popular LLM libraries and APIs +Tags: LLM, CHATBOT, API + In this Guide, we go through several examples of how to use `gr.ChatInterface` with popular LLM libraries and API providers. We will cover the following libraries and API providers: @@ -37,7 +39,7 @@ Tip: For quick prototyping, the Date: Thu, 28 Nov 2024 15:49:49 -0500 Subject: [PATCH 05/26] example --- guides/05_chatbots/02_chatinterface-examples.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/guides/05_chatbots/02_chatinterface-examples.md b/guides/05_chatbots/02_chatinterface-examples.md index 4de7f50eb6005..1a7bd266aff88 100644 --- a/guides/05_chatbots/02_chatinterface-examples.md +++ b/guides/05_chatbots/02_chatinterface-examples.md @@ -49,7 +49,7 @@ The SambaNova Cloud API provides access to full-precision open-source models, su $code_llm_sambanova -Tip: For quick prototyping, the sambanova-gradio library makes it even easier to build chatbots on top of OpenAI models. +Tip: For quick prototyping, the sambanova-gradio library makes it even easier to build chatbots on top of SambaNova models. ## Hyperbolic @@ -57,7 +57,7 @@ The Hyperbolic AI API provides access to many open-source models, such as the Ll $code_llm_hyperbolic -Tip: For quick prototyping, the hyperbolic-gradio library makes it even easier to build chatbots on top of OpenAI models. +Tip: For quick prototyping, the hyperbolic-gradio library makes it even easier to build chatbots on top of Hyperbolic models. ## Anthropic's Claude From 4d7b5882ae9bb00b5d0b17d23d0a567ee329a7ec Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Fri, 29 Nov 2024 12:12:01 -0500 Subject: [PATCH 06/26] zerogpu --- gradio/chat_interface.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/gradio/chat_interface.py b/gradio/chat_interface.py index b85e9499282f1..02fe22fd72796 100644 --- a/gradio/chat_interface.py +++ b/gradio/chat_interface.py @@ -336,6 +336,8 @@ def _setup_example_messages( def _setup_events(self) -> None: submit_fn = self._stream_fn if self.is_generator else self._submit_fn + if hasattr(self.fn, "zerogpu"): + submit_fn.zerogpu = self.fn.zerogpu submit_triggers = [self.textbox.submit, self.chatbot.retry] submit_event = ( From 64f7d0def27fb86bdb93295424b30f6ec89adec6 Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Fri, 29 Nov 2024 12:12:38 -0500 Subject: [PATCH 07/26] Revert "zerogpu" This reverts commit 4d7b5882ae9bb00b5d0b17d23d0a567ee329a7ec. --- gradio/chat_interface.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/gradio/chat_interface.py b/gradio/chat_interface.py index 02fe22fd72796..b85e9499282f1 100644 --- a/gradio/chat_interface.py +++ b/gradio/chat_interface.py @@ -336,8 +336,6 @@ def _setup_example_messages( def _setup_events(self) -> None: submit_fn = self._stream_fn if self.is_generator else self._submit_fn - if hasattr(self.fn, "zerogpu"): - submit_fn.zerogpu = self.fn.zerogpu submit_triggers = [self.textbox.submit, self.chatbot.retry] submit_event = ( From c09a4462440e4c360cea0fec16a36cde4d7aa9a0 Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Fri, 29 Nov 2024 16:13:14 -0500 Subject: [PATCH 08/26] changes --- demo/chatinterface_artifacts/run.py | 7 ++++++- gradio/chat_interface.py | 32 ++++++++++++++++++++--------- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/demo/chatinterface_artifacts/run.py b/demo/chatinterface_artifacts/run.py index 791b9bc5af286..067a018b68e1f 100644 --- a/demo/chatinterface_artifacts/run.py +++ b/demo/chatinterface_artifacts/run.py @@ -31,7 +31,12 @@ def chat(message, history): with gr.Row(): with gr.Column(): gr.Markdown("

Write Python or JavaScript

") - gr.ChatInterface(chat, examples=["Python", "JavaScript"], additional_outputs=[code], type="messages") + gr.ChatInterface( + chat, + examples=["Python", "JavaScript"], + additional_outputs=[code], + type="messages" + ) with gr.Column(): gr.Markdown("

Code Artifacts

") code.render() diff --git a/gradio/chat_interface.py b/gradio/chat_interface.py index b85e9499282f1..08d28069324df 100644 --- a/gradio/chat_interface.py +++ b/gradio/chat_interface.py @@ -356,7 +356,7 @@ def _setup_events(self) -> None: .then( submit_fn, [self.saved_input, self.chatbot] + self.additional_inputs, - [self.chatbot], + [self.chatbot] + self.additional_outputs, show_api=False, concurrency_limit=cast( Union[int, Literal["default"], None], self.concurrency_limit @@ -660,13 +660,19 @@ def _append_history(self, history, message, first_response=True): async def _submit_fn( self, - message: str | MultimodalPostprocess, + message: str | MultimodalPostprocess | tuple, history_with_input: TupleFormat | list[MessageDict], request: Request, *args, - ) -> tuple[TupleFormat, TupleFormat] | tuple[list[MessageDict], list[MessageDict]]: + ) -> TupleFormat | list[MessageDict] | tuple[TupleFormat | list[MessageDict], ...]: + additional_outputs = () + if isinstance(message, tuple): + message_value, *additional_outputs = message + else: + message_value = message + message_serialized, history = self._process_msg_and_trim_history( - message, history_with_input + message_value, history_with_input ) inputs, _, _ = special_args( self.fn, inputs=[message_serialized, history, *args], request=request @@ -680,17 +686,23 @@ async def _submit_fn( ) self._append_history(history_with_input, response) - return history_with_input # type: ignore + return history_with_input if not additional_outputs else (history_with_input, *additional_outputs) async def _stream_fn( self, - message: str | MultimodalPostprocess, + message: str | MultimodalPostprocess | tuple, history_with_input: TupleFormat | list[MessageDict], request: Request, *args, ) -> AsyncGenerator: + additional_outputs = () + if isinstance(message, tuple): + message_value, *additional_outputs = message + else: + message_value = message + message_serialized, history = self._process_msg_and_trim_history( - message, history_with_input + message_value, history_with_input ) inputs, _, _ = special_args( self.fn, inputs=[message_serialized, history, *args], request=request @@ -706,12 +718,12 @@ async def _stream_fn( try: first_response = await utils.async_iteration(generator) self._append_history(history_with_input, first_response) - yield history_with_input + yield history_with_input if not additional_outputs else (history_with_input, *additional_outputs) except StopIteration: - yield history_with_input + yield history_with_input if not additional_outputs else (history_with_input, *additional_outputs) async for response in generator: self._append_history(history_with_input, response, first_response=False) - yield history_with_input + yield history_with_input if not additional_outputs else (history_with_input, *additional_outputs) def option_clicked( self, history: list[MessageDict], option: SelectData From db63a22f1ddda83e32c6467a310ca50f48bf4755 Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Fri, 29 Nov 2024 16:27:28 -0500 Subject: [PATCH 09/26] submit fn --- gradio/chat_interface.py | 34 ++++++++++++++-------------------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/gradio/chat_interface.py b/gradio/chat_interface.py index 08d28069324df..041b9dae85070 100644 --- a/gradio/chat_interface.py +++ b/gradio/chat_interface.py @@ -660,19 +660,13 @@ def _append_history(self, history, message, first_response=True): async def _submit_fn( self, - message: str | MultimodalPostprocess | tuple, + message: str | MultimodalPostprocess, history_with_input: TupleFormat | list[MessageDict], request: Request, *args, ) -> TupleFormat | list[MessageDict] | tuple[TupleFormat | list[MessageDict], ...]: - additional_outputs = () - if isinstance(message, tuple): - message_value, *additional_outputs = message - else: - message_value = message - message_serialized, history = self._process_msg_and_trim_history( - message_value, history_with_input + message, history_with_input ) inputs, _, _ = special_args( self.fn, inputs=[message_serialized, history, *args], request=request @@ -684,25 +678,25 @@ async def _submit_fn( response = await anyio.to_thread.run_sync( self.fn, *inputs, limiter=self.limiter ) + additional_outputs = None + if isinstance(response, tuple): + response, *additional_outputs = response + self._append_history(history_with_input, response) - return history_with_input if not additional_outputs else (history_with_input, *additional_outputs) + if additional_outputs: + return history_with_input, *additional_outputs + return history_with_input async def _stream_fn( self, - message: str | MultimodalPostprocess | tuple, + message: str | MultimodalPostprocess, history_with_input: TupleFormat | list[MessageDict], request: Request, *args, ) -> AsyncGenerator: - additional_outputs = () - if isinstance(message, tuple): - message_value, *additional_outputs = message - else: - message_value = message - message_serialized, history = self._process_msg_and_trim_history( - message_value, history_with_input + message, history_with_input ) inputs, _, _ = special_args( self.fn, inputs=[message_serialized, history, *args], request=request @@ -718,12 +712,12 @@ async def _stream_fn( try: first_response = await utils.async_iteration(generator) self._append_history(history_with_input, first_response) - yield history_with_input if not additional_outputs else (history_with_input, *additional_outputs) + yield history_with_input except StopIteration: - yield history_with_input if not additional_outputs else (history_with_input, *additional_outputs) + yield history_with_input async for response in generator: self._append_history(history_with_input, response, first_response=False) - yield history_with_input if not additional_outputs else (history_with_input, *additional_outputs) + yield history_with_input def option_clicked( self, history: list[MessageDict], option: SelectData From a5bcbba277c347b6e3801b92c52a8c9df2cda3e8 Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Fri, 29 Nov 2024 16:29:02 -0500 Subject: [PATCH 10/26] chat interface --- gradio/chat_interface.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/gradio/chat_interface.py b/gradio/chat_interface.py index 041b9dae85070..4bfd902494f57 100644 --- a/gradio/chat_interface.py +++ b/gradio/chat_interface.py @@ -694,7 +694,7 @@ async def _stream_fn( history_with_input: TupleFormat | list[MessageDict], request: Request, *args, - ) -> AsyncGenerator: + ) -> AsyncGenerator[TupleFormat | list[MessageDict] | tuple[TupleFormat | list[MessageDict], ...], None]: message_serialized, history = self._process_msg_and_trim_history( message, history_with_input ) @@ -709,15 +709,20 @@ async def _stream_fn( self.fn, *inputs, limiter=self.limiter ) generator = utils.SyncToAsyncIterator(generator, self.limiter) + try: first_response = await utils.async_iteration(generator) + if isinstance(first_response, tuple): + first_response, *additional_outputs = first_response self._append_history(history_with_input, first_response) - yield history_with_input + yield history_with_input if not additional_outputs else (history_with_input, *additional_outputs) except StopIteration: yield history_with_input async for response in generator: + if isinstance(response, tuple): + response, *additional_outputs = response self._append_history(history_with_input, response, first_response=False) - yield history_with_input + yield history_with_input if not additional_outputs else (history_with_input, *additional_outputs) def option_clicked( self, history: list[MessageDict], option: SelectData From 31cac4ca3e6d07d6d0b98e37139de5b0f94e21d8 Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Fri, 29 Nov 2024 16:31:17 -0500 Subject: [PATCH 11/26] changes --- gradio/chat_interface.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/gradio/chat_interface.py b/gradio/chat_interface.py index 4bfd902494f57..66cb9dda65f4f 100644 --- a/gradio/chat_interface.py +++ b/gradio/chat_interface.py @@ -394,7 +394,7 @@ def _setup_events(self) -> None: ).then( submit_fn, [self.saved_input, self.chatbot], - [self.chatbot], + [self.chatbot] + self.additional_outputs, show_api=False, concurrency_limit=cast( Union[int, Literal["default"], None], self.concurrency_limit @@ -427,7 +427,7 @@ def _setup_events(self) -> None: .then( submit_fn, [self.saved_input, self.chatbot] + self.additional_inputs, - [self.chatbot], + [self.chatbot] + self.additional_outputs, show_api=False, concurrency_limit=cast( Union[int, Literal["default"], None], self.concurrency_limit @@ -461,7 +461,7 @@ def _setup_events(self) -> None: ).then( submit_fn, [self.saved_input, self.chatbot], - [self.chatbot], + [self.chatbot] + self.additional_outputs, show_api=False, concurrency_limit=cast( Union[int, Literal["default"], None], self.concurrency_limit From 5d448ba8cac17d09613260dd1d648d431142d974 Mon Sep 17 00:00:00 2001 From: gradio-pr-bot Date: Fri, 29 Nov 2024 21:34:26 +0000 Subject: [PATCH 12/26] add changeset --- .changeset/lazy-symbols-behave.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/lazy-symbols-behave.md b/.changeset/lazy-symbols-behave.md index 8c028281fd271..a78a65eac331c 100644 --- a/.changeset/lazy-symbols-behave.md +++ b/.changeset/lazy-symbols-behave.md @@ -2,4 +2,4 @@ "gradio": minor --- -feat:Additional outputs in `gr.ChatInterface` +feat:Support `additional_outputs` in `gr.ChatInterface` From 1eb09dfa8b46261bcd659c52ad863ad4716c98ff Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Fri, 29 Nov 2024 16:34:43 -0500 Subject: [PATCH 13/26] notebook --- demo/chatinterface_artifacts/run.ipynb | 1 + 1 file changed, 1 insertion(+) create mode 100644 demo/chatinterface_artifacts/run.ipynb diff --git a/demo/chatinterface_artifacts/run.ipynb b/demo/chatinterface_artifacts/run.ipynb new file mode 100644 index 0000000000000..b2b2264126af4 --- /dev/null +++ b/demo/chatinterface_artifacts/run.ipynb @@ -0,0 +1 @@ +{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: chatinterface_artifacts"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "\n", "python_code = \"\"\"\n", "def fib(n):\n", " if n <= 0:\n", " return 0\n", " elif n == 1:\n", " return 1\n", " else:\n", " return fib(n-1) + fib(n-2)\n", "\"\"\"\n", "\n", "js_code = \"\"\"\n", "function fib(n) {\n", " if (n <= 0) return 0;\n", " if (n === 1) return 1;\n", " return fib(n - 1) + fib(n - 2);\n", "}\n", "\"\"\"\n", "\n", "def chat(message, history):\n", " if \"python\" in message.lower():\n", " return \"Type Python or JavaScript to see the code.\", gr.Code(language=\"python\", value=python_code)\n", " elif \"javascript\" in message.lower():\n", " return \"Type Python or JavaScript to see the code.\", gr.Code(language=\"javascript\", value=js_code)\n", " else:\n", " return \"Please ask about Python or JavaScript.\", None\n", "\n", "with gr.Blocks() as demo:\n", " code = gr.Code(render=False)\n", " with gr.Row():\n", " with gr.Column():\n", " gr.Markdown(\"

Write Python or JavaScript

\")\n", " gr.ChatInterface(\n", " chat,\n", " examples=[\"Python\", \"JavaScript\"],\n", " additional_outputs=[code],\n", " type=\"messages\"\n", " )\n", " with gr.Column():\n", " gr.Markdown(\"

Code Artifacts

\")\n", " code.render()\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5} \ No newline at end of file From 7d4f45ab91be5c723386be191d1908ebc84f055b Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Fri, 29 Nov 2024 16:42:31 -0500 Subject: [PATCH 14/26] lint --- gradio/chat_interface.py | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/gradio/chat_interface.py b/gradio/chat_interface.py index 66cb9dda65f4f..63dd6c0f7083f 100644 --- a/gradio/chat_interface.py +++ b/gradio/chat_interface.py @@ -276,7 +276,9 @@ def __init__( self.textbox.stop_btn = False self.fake_api_btn = Button("Fake API", visible=False) - self.fake_response_textbox = Textbox(label="Response", visible=False) + self.fake_response_textbox = Textbox( + label="Response", visible=False + ) if self.examples: self.examples_handler = Examples( @@ -694,7 +696,10 @@ async def _stream_fn( history_with_input: TupleFormat | list[MessageDict], request: Request, *args, - ) -> AsyncGenerator[TupleFormat | list[MessageDict] | tuple[TupleFormat | list[MessageDict], ...], None]: + ) -> AsyncGenerator[ + TupleFormat | list[MessageDict] | tuple[TupleFormat | list[MessageDict], ...], + None, + ]: message_serialized, history = self._process_msg_and_trim_history( message, history_with_input ) @@ -715,14 +720,22 @@ async def _stream_fn( if isinstance(first_response, tuple): first_response, *additional_outputs = first_response self._append_history(history_with_input, first_response) - yield history_with_input if not additional_outputs else (history_with_input, *additional_outputs) + yield ( + history_with_input + if not additional_outputs + else (history_with_input, *additional_outputs) + ) except StopIteration: yield history_with_input async for response in generator: if isinstance(response, tuple): response, *additional_outputs = response self._append_history(history_with_input, response, first_response=False) - yield history_with_input if not additional_outputs else (history_with_input, *additional_outputs) + yield ( + history_with_input + if not additional_outputs + else (history_with_input, *additional_outputs) + ) def option_clicked( self, history: list[MessageDict], option: SelectData From ffd25cace5942aa2ad1feba750486218897fb7c8 Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Fri, 29 Nov 2024 16:49:07 -0500 Subject: [PATCH 15/26] type --- gradio/chat_interface.py | 1 + 1 file changed, 1 insertion(+) diff --git a/gradio/chat_interface.py b/gradio/chat_interface.py index 63dd6c0f7083f..f616a38ae26f2 100644 --- a/gradio/chat_interface.py +++ b/gradio/chat_interface.py @@ -715,6 +715,7 @@ async def _stream_fn( ) generator = utils.SyncToAsyncIterator(generator, self.limiter) + additional_outputs = None try: first_response = await utils.async_iteration(generator) if isinstance(first_response, tuple): From 29b8d555033b35fa5bbdb5cfa2931285aa3a5e2d Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Mon, 2 Dec 2024 14:03:53 -0500 Subject: [PATCH 16/26] regex --- client/python/gradio_client/documentation.py | 8 ++++++++ gradio/chat_interface.py | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/client/python/gradio_client/documentation.py b/client/python/gradio_client/documentation.py index a3ab65493002e..0b237bece8a55 100644 --- a/client/python/gradio_client/documentation.py +++ b/client/python/gradio_client/documentation.py @@ -8,6 +8,7 @@ from collections import defaultdict from collections.abc import Callable from functools import lru_cache +import re classes_to_document = defaultdict(list) classes_inherit_documentation = {} @@ -157,6 +158,7 @@ def document_fn(fn: Callable, cls) -> tuple[str, list[dict], dict, str | None]: ) parameter = line[:colon_index] parameter_doc = line[colon_index + 2 :] + parameters[parameter] = parameter_doc elif mode == "return": returns.append(line) @@ -190,6 +192,12 @@ def document_fn(fn: Callable, cls) -> tuple[str, list[dict], dict, str | None]: parameter_doc["kwargs"] = True if "args" in parameter_doc["doc"]: parameter_doc["args"] = True + if parameter_doc["doc"] and "$demo/" in parameter_doc["doc"]: + parameter_doc["doc"] = re.sub( + r'\$demo/(\S+)', + lambda m: f'demo/{m.group(1)}', + parameter_doc["doc"] + ) parameter_docs.append(parameter_doc) if parameters: raise ValueError( diff --git a/gradio/chat_interface.py b/gradio/chat_interface.py index 38cd26241a73e..4c888a253d6d1 100644 --- a/gradio/chat_interface.py +++ b/gradio/chat_interface.py @@ -109,7 +109,7 @@ def __init__( 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 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: 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: 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. + additional_outputs: 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. examples: 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: 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: 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). From eb3ddd31c752a3bf805e9a89b4541a92969bbfdd Mon Sep 17 00:00:00 2001 From: gradio-pr-bot Date: Mon, 2 Dec 2024 19:04:44 +0000 Subject: [PATCH 17/26] add changeset --- .changeset/lazy-symbols-behave.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.changeset/lazy-symbols-behave.md b/.changeset/lazy-symbols-behave.md index a78a65eac331c..f4c24a150f8d6 100644 --- a/.changeset/lazy-symbols-behave.md +++ b/.changeset/lazy-symbols-behave.md @@ -1,5 +1,6 @@ --- "gradio": minor +"gradio_client": minor --- feat:Support `additional_outputs` in `gr.ChatInterface` From 89e7ac48e9c1abfe60c4328a697c06ecad143d85 Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Mon, 2 Dec 2024 14:08:19 -0500 Subject: [PATCH 18/26] fixes --- client/python/gradio_client/documentation.py | 8 ++++---- gradio/chat_interface.py | 4 +++- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/client/python/gradio_client/documentation.py b/client/python/gradio_client/documentation.py index 0b237bece8a55..e9d82a2f3cde3 100644 --- a/client/python/gradio_client/documentation.py +++ b/client/python/gradio_client/documentation.py @@ -4,11 +4,11 @@ import dataclasses import inspect +import re import warnings from collections import defaultdict from collections.abc import Callable from functools import lru_cache -import re classes_to_document = defaultdict(list) classes_inherit_documentation = {} @@ -158,7 +158,7 @@ def document_fn(fn: Callable, cls) -> tuple[str, list[dict], dict, str | None]: ) parameter = line[:colon_index] parameter_doc = line[colon_index + 2 :] - + parameters[parameter] = parameter_doc elif mode == "return": returns.append(line) @@ -194,9 +194,9 @@ def document_fn(fn: Callable, cls) -> tuple[str, list[dict], dict, str | None]: parameter_doc["args"] = True if parameter_doc["doc"] and "$demo/" in parameter_doc["doc"]: parameter_doc["doc"] = re.sub( - r'\$demo/(\S+)', + r"\$demo/(\S+)", lambda m: f'demo/{m.group(1)}', - parameter_doc["doc"] + parameter_doc["doc"], ) parameter_docs.append(parameter_doc) if parameters: diff --git a/gradio/chat_interface.py b/gradio/chat_interface.py index 4c888a253d6d1..acda449552f6c 100644 --- a/gradio/chat_interface.py +++ b/gradio/chat_interface.py @@ -240,7 +240,9 @@ def __init__( if textbox: textbox.show_label = False textbox_ = get_component_instance(textbox, render=True) - if not isinstance(textbox_, (Textbox, MultimodalTextbox)): + if not isinstance( + textbox_, (Textbox, MultimodalTextbox) + ): raise TypeError( f"Expected a gr.Textbox or gr.MultimodalTextbox component, but got {builtins.type(textbox_)}" ) From 8f81da7c4e1f26f74f8c070fa5a66d9af95072f3 Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Mon, 2 Dec 2024 14:08:52 -0500 Subject: [PATCH 19/26] line --- client/python/gradio_client/documentation.py | 1 - 1 file changed, 1 deletion(-) diff --git a/client/python/gradio_client/documentation.py b/client/python/gradio_client/documentation.py index e9d82a2f3cde3..4068e547e7710 100644 --- a/client/python/gradio_client/documentation.py +++ b/client/python/gradio_client/documentation.py @@ -158,7 +158,6 @@ def document_fn(fn: Callable, cls) -> tuple[str, list[dict], dict, str | None]: ) parameter = line[:colon_index] parameter_doc = line[colon_index + 2 :] - parameters[parameter] = parameter_doc elif mode == "return": returns.append(line) From 0faef73609116be16047a1495c87ebb315e9a82c Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Mon, 2 Dec 2024 14:13:22 -0500 Subject: [PATCH 20/26] fixes --- gradio/chat_interface.py | 143 ++++++++++++++++++++++----------------- 1 file changed, 80 insertions(+), 63 deletions(-) diff --git a/gradio/chat_interface.py b/gradio/chat_interface.py index acda449552f6c..4e80b65feacb2 100644 --- a/gradio/chat_interface.py +++ b/gradio/chat_interface.py @@ -125,7 +125,7 @@ def __init__( head_paths: Custom html code as a pathlib.Path to a html file or a list of such paths. This html files will be read, concatenated, and included in the head of the demo webpage. If the `head` parameter is also set, the html from `head` will be included first. analytics_enabled: whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable if defined, or default to True. autofocus: if True, autofocuses to the textbox when the page loads. - autoscroll: 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. + autoscroll: 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: 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: 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: 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). @@ -234,73 +234,90 @@ def __init__( warnings.warn( "The ChatInterface already has examples set. The examples provided in the chatbot will be ignored." ) - - with Group(): - with Row(): - if textbox: - textbox.show_label = False - textbox_ = get_component_instance(textbox, render=True) - if not isinstance( - textbox_, (Textbox, MultimodalTextbox) - ): - raise TypeError( - f"Expected a gr.Textbox or gr.MultimodalTextbox component, but got {builtins.type(textbox_)}" - ) - self.textbox = textbox_ - else: - textbox_component = ( - MultimodalTextbox if self.multimodal else Textbox - ) - self.textbox = textbox_component( - show_label=False, - label="Message", - placeholder="Type a message...", - scale=7, - autofocus=autofocus, - submit_btn=submit_btn, - stop_btn=stop_btn, + self.chatbot.examples = ( + self.examples_messages + if not self._additional_inputs_in_examples + else None + ) + self.chatbot._setup_examples() + else: + self.type = self.type or "tuples" + self.chatbot = Chatbot( + label="Chatbot", + scale=1, + height=200 if fill_height else None, + type=self.type, + autoscroll=autoscroll, + examples=self.examples_messages + if not self._additional_inputs_in_examples + else None, + ) + with Group(): + with Row(): + if textbox: + textbox.show_label = False + textbox_ = get_component_instance(textbox, render=True) + if not isinstance( + textbox_, (Textbox, MultimodalTextbox) + ): + raise TypeError( + f"Expected a gr.Textbox or gr.MultimodalTextbox component, but got {builtins.type(textbox_)}" ) + self.textbox = textbox_ + else: + textbox_component = ( + MultimodalTextbox if self.multimodal else Textbox + ) + self.textbox = textbox_component( + show_label=False, + label="Message", + placeholder="Type a message...", + scale=7, + autofocus=autofocus, + submit_btn=submit_btn, + stop_btn=stop_btn, + ) - # Hide the stop button at the beginning, and show it with the given value during the generator execution. - self.original_stop_btn = self.textbox.stop_btn - self.textbox.stop_btn = False - - self.fake_api_btn = Button("Fake API", visible=False) - self.fake_response_textbox = Textbox( - label="Response", visible=False - ) - - if self.examples: - self.examples_handler = Examples( - examples=self.examples, - inputs=[self.textbox] + self.additional_inputs, - outputs=self.chatbot, - fn=self._examples_stream_fn - if self.is_generator - else self._examples_fn, - cache_examples=self.cache_examples, - cache_mode=self.cache_mode, - visible=self._additional_inputs_in_examples, - preprocess=self._additional_inputs_in_examples, - ) + # Hide the stop button at the beginning, and show it with the given value during the generator execution. + self.original_stop_btn = self.textbox.stop_btn + self.textbox.stop_btn = False - any_unrendered_inputs = any( - not inp.is_rendered for inp in self.additional_inputs + self.fake_api_btn = Button("Fake API", visible=False) + self.fake_response_textbox = Textbox( + label="Response", visible=False ) - if self.additional_inputs and any_unrendered_inputs: - with Accordion(**self.additional_inputs_accordion_params): # type: ignore - for input_component in self.additional_inputs: - if not input_component.is_rendered: - input_component.render() - - self.saved_input = State() - self.chatbot_state = ( - State(self.chatbot.value) if self.chatbot.value else State([]) + + if self.examples: + self.examples_handler = Examples( + examples=self.examples, + inputs=[self.textbox] + self.additional_inputs, + outputs=self.chatbot, + fn=self._examples_stream_fn + if self.is_generator + else self._examples_fn, + cache_examples=self.cache_examples, + cache_mode=self.cache_mode, + visible=self._additional_inputs_in_examples, + preprocess=self._additional_inputs_in_examples, ) - self.previous_input = State(value=[]) - self.show_progress = show_progress - self._setup_events() - self._setup_api() + + any_unrendered_inputs = any( + not inp.is_rendered for inp in self.additional_inputs + ) + if self.additional_inputs and any_unrendered_inputs: + with Accordion(**self.additional_inputs_accordion_params): # type: ignore + for input_component in self.additional_inputs: + if not input_component.is_rendered: + input_component.render() + + self.saved_input = State() + self.chatbot_state = ( + State(self.chatbot.value) if self.chatbot.value else State([]) + ) + self.previous_input = State(value=[]) + self.show_progress = show_progress + self._setup_events() + self._setup_api() @staticmethod def _setup_example_messages( From df18abd51e4a9989d50f5345e107fdd8af212f69 Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Mon, 2 Dec 2024 14:13:41 -0500 Subject: [PATCH 21/26] formatting --- gradio/chat_interface.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/gradio/chat_interface.py b/gradio/chat_interface.py index 4e80b65feacb2..d6fe7b1af482e 100644 --- a/gradio/chat_interface.py +++ b/gradio/chat_interface.py @@ -257,9 +257,7 @@ def __init__( if textbox: textbox.show_label = False textbox_ = get_component_instance(textbox, render=True) - if not isinstance( - textbox_, (Textbox, MultimodalTextbox) - ): + if not isinstance(textbox_, (Textbox, MultimodalTextbox)): raise TypeError( f"Expected a gr.Textbox or gr.MultimodalTextbox component, but got {builtins.type(textbox_)}" ) From 0b0433fb96d7e674e23c16ba9ed5f369c9b71ae4 Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Mon, 2 Dec 2024 14:51:15 -0500 Subject: [PATCH 22/26] change --- client/python/gradio_client/documentation.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/client/python/gradio_client/documentation.py b/client/python/gradio_client/documentation.py index 4068e547e7710..0cdb141a57fea 100644 --- a/client/python/gradio_client/documentation.py +++ b/client/python/gradio_client/documentation.py @@ -177,6 +177,12 @@ def document_fn(fn: Callable, cls) -> tuple[str, list[dict], dict, str | None]: "annotation": param.annotation, "doc": parameters.get(param_name), } + if "$demo/" in parameter_doc["doc"]: + parameter_doc["doc"] = re.sub( + r"\$demo/(\w+)", + lambda m: f'demo/{m.group(1)}', + parameter_doc["doc"], + ) if param_name in parameters: del parameters[param_name] if param.default != inspect.Parameter.empty: @@ -191,12 +197,8 @@ def document_fn(fn: Callable, cls) -> tuple[str, list[dict], dict, str | None]: parameter_doc["kwargs"] = True if "args" in parameter_doc["doc"]: parameter_doc["args"] = True - if parameter_doc["doc"] and "$demo/" in parameter_doc["doc"]: - parameter_doc["doc"] = re.sub( - r"\$demo/(\S+)", - lambda m: f'demo/{m.group(1)}', - parameter_doc["doc"], - ) + print(parameter_doc["name"], "$demo" in parameter_doc["doc"]) + # if parameter_doc["doc"]: parameter_docs.append(parameter_doc) if parameters: raise ValueError( From dfc7bcb619b724f8f10f5c2534e590c5f96db18b Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Mon, 2 Dec 2024 14:51:25 -0500 Subject: [PATCH 23/26] change --- client/python/gradio_client/documentation.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/client/python/gradio_client/documentation.py b/client/python/gradio_client/documentation.py index 0cdb141a57fea..725dcdff23156 100644 --- a/client/python/gradio_client/documentation.py +++ b/client/python/gradio_client/documentation.py @@ -197,8 +197,6 @@ def document_fn(fn: Callable, cls) -> tuple[str, list[dict], dict, str | None]: parameter_doc["kwargs"] = True if "args" in parameter_doc["doc"]: parameter_doc["args"] = True - print(parameter_doc["name"], "$demo" in parameter_doc["doc"]) - # if parameter_doc["doc"]: parameter_docs.append(parameter_doc) if parameters: raise ValueError( From 93a063870f253eb509dd74791acc794be044a0bd Mon Sep 17 00:00:00 2001 From: Abubakar Abid Date: Mon, 2 Dec 2024 14:56:57 -0500 Subject: [PATCH 24/26] add guard --- client/python/gradio_client/documentation.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/python/gradio_client/documentation.py b/client/python/gradio_client/documentation.py index 725dcdff23156..96757d0a943ca 100644 --- a/client/python/gradio_client/documentation.py +++ b/client/python/gradio_client/documentation.py @@ -177,7 +177,7 @@ def document_fn(fn: Callable, cls) -> tuple[str, list[dict], dict, str | None]: "annotation": param.annotation, "doc": parameters.get(param_name), } - if "$demo/" in parameter_doc["doc"]: + if parameter_doc["doc"] and "$demo/" in parameter_doc["doc"]: parameter_doc["doc"] = re.sub( r"\$demo/(\w+)", lambda m: f'demo/{m.group(1)}', From fe603f9804f226e779558accad8f371860668bd1 Mon Sep 17 00:00:00 2001 From: aliabd Date: Mon, 2 Dec 2024 12:56:18 -0800 Subject: [PATCH 25/26] link to playground demo --- client/python/gradio_client/documentation.py | 7 ----- .../generate_jsons/src/docs/__init__.py | 26 +++++++++++++++++++ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/client/python/gradio_client/documentation.py b/client/python/gradio_client/documentation.py index 96757d0a943ca..a3ab65493002e 100644 --- a/client/python/gradio_client/documentation.py +++ b/client/python/gradio_client/documentation.py @@ -4,7 +4,6 @@ import dataclasses import inspect -import re import warnings from collections import defaultdict from collections.abc import Callable @@ -177,12 +176,6 @@ def document_fn(fn: Callable, cls) -> tuple[str, list[dict], dict, str | None]: "annotation": param.annotation, "doc": parameters.get(param_name), } - if parameter_doc["doc"] and "$demo/" in parameter_doc["doc"]: - parameter_doc["doc"] = re.sub( - r"\$demo/(\w+)", - lambda m: f'demo/{m.group(1)}', - parameter_doc["doc"], - ) if param_name in parameters: del parameters[param_name] if param.default != inspect.Parameter.empty: diff --git a/js/_website/generate_jsons/src/docs/__init__.py b/js/_website/generate_jsons/src/docs/__init__.py index 20eba0e649f67..fc1d6d9d88dfd 100644 --- a/js/_website/generate_jsons/src/docs/__init__.py +++ b/js/_website/generate_jsons/src/docs/__init__.py @@ -3,6 +3,9 @@ import os import re import requests +import base64 +import urllib.parse + from gradio_client.documentation import document_cls, generate_documentation @@ -97,11 +100,34 @@ def add_guides(): add_guides() +def generate_playground_link(demo_name): + playground_url = "https://gradio.app/playground?demo=Blank" + with open(os.path.join(DEMOS_DIR, demo_name, "run.py")) as f: + demo_code = f.read() + encoded_code = base64.b64encode(demo_code.encode('utf-8')).decode('utf-8') + encoded_code_url = urllib.parse.quote(encoded_code, safe='') + playground_url += "&code=" + encoded_code_url + if "requirements.txt" in os.listdir(os.path.join(DEMOS_DIR, demo_name)): + with open(os.path.join(DEMOS_DIR, demo_name, "requirements.txt")) as f: + requirements = f.read() + if requirements: + encoded_reqs = base64.b64encode(requirements.encode('utf-8')).decode('utf-8') + encoded_reqs_url = urllib.parse.quote(encoded_reqs, safe='') + playground_url += "&reqs=" + encoded_reqs_url + return f"demo/{demo_name}" + + def escape_parameters(parameters): new_parameters = [] for param in parameters: param = param.copy() # Manipulating the list item directly causes issues, so copy it first param["doc"] = html.escape(param["doc"]) if param["doc"] else param["doc"] + if param["doc"] and "$demo/" in param["doc"]: + param["doc"] = re.sub( + r"\$demo/(\w+)", + lambda m: generate_playground_link(m.group(1)), + param["doc"], + ) new_parameters.append(param) assert len(new_parameters) == len(parameters) return new_parameters From 591dcd0e324782bf8d635d63e21b26deaacdb0e4 Mon Sep 17 00:00:00 2001 From: gradio-pr-bot Date: Mon, 2 Dec 2024 20:57:17 +0000 Subject: [PATCH 26/26] add changeset --- .changeset/lazy-symbols-behave.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/lazy-symbols-behave.md b/.changeset/lazy-symbols-behave.md index f4c24a150f8d6..083d99d04bac7 100644 --- a/.changeset/lazy-symbols-behave.md +++ b/.changeset/lazy-symbols-behave.md @@ -1,6 +1,6 @@ --- "gradio": minor -"gradio_client": minor +"website": minor --- feat:Support `additional_outputs` in `gr.ChatInterface`