Gradio 代理 & MCP 黑客马拉松

获奖者
Gradio logo

Gradio 新手?从这里开始:开始使用

查看 发布历史

客户端 1.0 发布!

我们很高兴推出 Gradio 客户端的首次重大发布。凭借客户端**符合人体工程学**、**透明**和**可移植**的设计,将任何 Gradio 应用程序转化为生产级端点变得更加容易。

符合人体工程学的 API 💆


从 Gradio 应用中流式传输(5 行代码)


使用 submit 方法获取可迭代的任务。


在 Python 中

from gradio_client import Client

client = Client("gradio/llm_stream")

for result in client.submit("What's the best UI framework in Python?"):
    print(result)

在 TypeScript 中

import { Client } from "@gradio/client";

const client = await Client.connect("gradio/llm_stream")
const job = client.submit("/predict", {"text": "What's the best UI framework in Python?"})

for await (const msg of job) console.log(msg.data)

使用与应用程序相同的关键字参数


在下面的示例中,上游应用程序有一个函数,其参数名为 `message`、`system_prompt` 和 `tokens`。我们可以看到客户端的 `predict` 调用使用了相同的参数。

在 Python 中

from gradio_client import Client

client = Client("http://127.0.0.1:7860/")
result = client.predict(
		message="Hello!!",
		system_prompt="You are helpful AI.",
		tokens=10,
		api_name="/chat"
)
print(result)

在 TypeScript 中

import { Client } from "@gradio/client";

const client = await Client.connect("http://127.0.0.1:7860/");
const result = await client.predict("/chat", { 		
		message: "Hello!!", 		
		system_prompt: "Hello!!", 		
		tokens: 10, 
});

console.log(result.data);

更好的错误消息


如果上游应用程序出现问题,只要原始应用程序的 `launch()` 函数中 `show_error=True`,或者它是 `gr.Error` 异常,客户端就会抛出相同的异常。

透明设计 🪟

您在 UI 中可以执行的任何操作,都可以通过客户端完成

  • 🔐身份验证
  • 🛑 任务取消
  • ℹ️ 访问队列位置和 API
  • 📕 查看 API 信息

这里有一个示例,展示了如何显示待处理任务的队列位置
from gradio_client import Client

client = Client("gradio/diffusion_model")

job = client.submit("A cute cat")
while not job.done():
    status = job.status()
    print(f"Current in position {status.rank} out of {status.queue_size}")

可移植设计 ⛺️


客户端几乎可以在任何 Python 和 JavaScript 环境(Node、Deno、浏览器、Service Workers)中运行。
这里有一个使用 gevent 从 Flask 服务器调用客户端的示例
from gevent import monkey
monkey.patch_all()

from gradio_client import Client
from flask import Flask, send_file
import time

app = Flask(__name__)

imageclient = Client("gradio/diffusion_model")

@app.route("/gen")
def gen():
      result = imageclient.predict(
                "A cute cat",
                api_name="/predict"
              )
      return send_file(result)

if __name__ == "__main__":
      app.run(host="0.0.0.0", port=5000)

v1.0 迁移指南和重大更改


Python

  • Client 类的 `serialize` 参数已移除,不再生效。
  • Client 的 `upload_files` 参数已移除。
  • 所有文件路径必须封装在 `handle_file` 方法中。例如,`caption = client.predict(handle_file('./dog.jpg'))`。
  • output_dir 参数已移除。它未在 `download_files` 参数中指定。

JavaScript


客户端已完全重新设计。它已从函数重构为类。现在可以通过 await `connect` 方法来构造一个实例。
const app = await Client.connect("gradio/whisper")

app 变量具有与 Python 类相同的方法(submitpredictview_apiduplicate)。