Gradio Agents & MCP 黑客马拉松
获奖者Gradio Agents & MCP 黑客马拉松
获奖者gradio.Examples(···)
examples: list[Any] | list[list[Any]] | str
可点击以填充特定组件的示例输入。应为嵌套列表,其中外部列表包含样本,每个内部列表包含与每个输入组件对应的输入。也可以提供示例目录的字符串路径,但它应位于运行 Gradio 应用的 Python 文件所在的目录中。如果存在多个输入组件并提供了目录,则目录中必须存在一个 log.csv 文件以链接相应的输入。
outputs: Component | list[Component] | None
= None
可选地,提供与示例输出对应的组件或组件列表。如果 `cache_examples` 不为 False,则此项为必填。
fn: Callable | None
= None
可选地,提供用于生成与示例对应的输出的函数。如果 `cache_examples` 不为 False,则此项为必填。如果 `run_on_click` 为 True,则也为必填。
cache_examples: bool | None
= None
如果为 True,则在服务器中缓存示例,以加快示例的运行时。如果为“lazy”,则示例会在首次使用后(由应用程序的任何用户使用)被缓存(供应用程序的所有用户使用)。如果为 None,将使用 GRADIO_CACHE_EXAMPLES 环境变量,该变量应为“true”或“false”。在 HuggingFace Spaces 中,此参数为 True(只要也提供了 `fn` 和 `outputs`)。否则默认选项为 False。请注意,示例是独立于 Gradio 的 queue() 缓存的,因此某些功能,例如 gr.Progress()、gr.Info()、gr.Warning() 等,不会在 Gradio UI 中显示已缓存示例。
cache_mode: Literal['eager', 'lazy'] | None
= None
如果为“lazy”,示例会在首次使用后被缓存。如果为“eager”,所有示例会在应用程序启动时被缓存。如果为 None,将使用 GRADIO_CACHE_MODE 环境变量(如果已定义),否则默认为“eager”。
run_on_click: bool
= False
如果 cache_examples 为 False,则单击示例时不会运行函数。将其设置为 True 以在单击示例时运行函数。如果 cache_examples 为 True,则此设置无效。
更新示例
在此演示中,我们展示了如何通过更新底层数据集的样本来更新示例。请注意,这仅在 cache_examples=False
时有效,因为更新底层数据集不会更新缓存。
import gradio as gr
def update_examples(country):
if country == "USA":
return gr.Dataset(samples=[["Chicago"], ["Little Rock"], ["San Francisco"]])
else:
return gr.Dataset(samples=[["Islamabad"], ["Karachi"], ["Lahore"]])
with gr.Blocks() as demo:
dropdown = gr.Dropdown(label="Country", choices=["USA", "Pakistan"], value="USA")
textbox = gr.Textbox()
examples = gr.Examples([["Chicago"], ["Little Rock"], ["San Francisco"]], textbox)
dropdown.change(update_examples, dropdown, examples.dataset)
demo.launch()
import gradio as gr
def calculator(num1, operation, num2):
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
return num1 / num2
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
num_1 = gr.Number(value=4)
operation = gr.Radio(["add", "subtract", "multiply", "divide"])
num_2 = gr.Number(value=0)
submit_btn = gr.Button(value="Calculate")
with gr.Column():
result = gr.Number()
submit_btn.click(
calculator, inputs=[num_1, operation, num_2], outputs=[result], api_name=False
)
examples = gr.Examples(
examples=[
[5, "add", 3],
[4, "divide", 2],
[-4, "multiply", 2.5],
[0, "subtract", 1.2],
],
inputs=[num_1, operation, num_2],
)
if __name__ == "__main__":
demo.launch(show_api=False)