""" This file defines a useful high-level abstraction to build Gradio chatbots: ChatInterface. """ from __future__ import annotations import inspect import re import traceback from typing import AsyncGenerator, Callable, Literal, Union, cast import anyio from gradio.blocks import Blocks from gradio.components import ( Button, Chatbot, Component, Markdown, MultimodalTextbox, State, Textbox, get_component_instance, ) from gradio.events import Dependency, on from gradio.helpers import create_examples as Examples # noqa: N812 from gradio.helpers import special_args from gradio.layouts import Accordion, Group, Row from gradio.routes import Request from gradio.themes import ThemeClass as Theme from gradio.utils import SyncToAsyncIterator, async_iteration, async_lambda from gradio_client.documentation import document from langchain_experimental.tools.python.tool import PythonREPLTool from utils.output_parser import parse_code_action def replace_image_path(markdown_text): pattern = r"!\[.*?\]\((.*?)\)" # 替换图片链接并添加"file/"前缀 modified_text = re.sub(pattern, r"![\g<1>](file/\g<1>)", markdown_text) return modified_text def execute_code(code_str: str, tool: PythonREPLTool): """Execute python code and return the execution result. Args: code_str (str): The code to be executed. tool (PythonREPLTool): Python AST REPL tool. Returns: str: Code execution result. """ try: result = tool.invoke(code_str) result = str(result) return result except: return traceback.format_exc() def extract_code(response): """Extract code from the chatbot response. Args: response (str): The chatbot response. Returns: str: Extracted code. """ try: code = response.split("```")[-2] code = code.replace("python", "") except: code = None return code @document() class MyChatInterface(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, mode: str = "prompt", code_start_token: str = "<|execute_start|>\n```python\n", code_end_token: str = "```\n<|execute_end|>", tool_call_token: str = "<|tool_call|>", ): """ 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