跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

Pi AI

最后更新 查看 MarkdownAgent 设置

要从 Pi AI ↗ 调用 AI Gateway,请使用 agents/models/pi-ai 中的 createAI。它可以通过你的网关调用模型目录中的模型、动态路由以及 Pi AI 自带的模型对象。本页介绍 AI Gateway 功能。完整参考请参阅 Pi AI。

安装

安装 Agents SDK 和 Pi AI。createAI 需要 @earendil-works/pi-ai@~1.4.0:

npm i agents @earendil-works/pi-ai

在 Worker 中,将 AI 绑定添加到 Wrangler 配置:

{
	"ai": {
		"binding": "AI",
	},
}
[ai]
binding = "AI"

调用目录模型

传递 Pi AI 的 AI Gateway 目录中的 <provider>/<id>。无需供应商密钥。AI Gateway 会通过 Unified Billing 对请求计费,或使用存储在网关上的密钥:

import { createAI } from "agents/models/pi-ai";

export default {
	async fetch(request, env) {
		const ai = createAI({ binding: env.AI, id: "my-gateway" });

		const reply = await ai.complete(ai("anthropic/claude-opus-5.5"), {
			messages: [
				{ role: "user", content: "Write a short story", timestamp: Date.now() },
			],
		});

		return Response.json(reply.content);
	},
};
import { createAI } from "agents/models/pi-ai";

export default {
	async fetch(request: Request, env: Env) {
		const ai = createAI({ binding: env.AI, id: "my-gateway" });

		const reply = await ai.complete(ai("anthropic/claude-opus-5.5"), {
			messages: [
				{ role: "user", content: "Write a short story", timestamp: Date.now() },
			],
		});

		return Response.json(reply.content);
	},
};

请使用目录中的 ID 拼写,例如 anthropic/claude-opus-5.5 或 openai/gpt-5.5。请求采用模型自己的格式(Anthropic Messages 或 OpenAI Responses),因此 Pi AI 自带的解析器可以读取答案,思考功能也会像使用供应商时一样正常工作。id 用于设置网关,默认值为 default。该网关上的动态路由格式为 dynamic/<route>,例如 ai("dynamic/support")。

调用 Pi AI 模型对象

传递 Pi AI 注册表中的任意模型。请求会发送到网关上的供应商原生提供程序端点,AI Gateway 会提供凭据:

import { getBuiltinModel } from "@earendil-works/pi-ai/providers/all";
import { createAI } from "agents/models/pi-ai";

const ai = createAI({ binding: env.AI, id: "my-gateway" });

const model = ai(getBuiltinModel("anthropic", "claude-opus-5-5"));

模型对象会保留供应商自己的 ID(例如 claude-opus-5-5)以及 Pi AI 为其提供的全部元数据。

回退到另一模型

如果主模型在生成任何输出前失败,fallback 会按顺序列出要尝试的模型。可以混用目录 ID、动态路由、Workers AI ID 和模型对象:

const model = ai("anthropic/claude-opus-5.5", {
	fallback: ["openai/gpt-5.5", "@cf/zai-org/glm-4.7-flash"],
});

设置网关选项

在 createAI、模型上或每次调用时设置缓存、日志记录、元数据、超时和重试:

const ai = createAI({
	binding: env.AI,
	id: "my-gateway",
	cacheTtl: 60,
	metadata: { app: "support-bot" },
});

const model = ai("openai/gpt-5.5", { byokAlias: "production" });

有关所有选项,请参阅缓存、标记和设置请求超时。

使用账户 ID 和 API token

要使用其他账户中的网关,或从 Worker 外部调用,请传递 accountId 和 apiToken,而不是 binding:

const ai = createAI({
	accountId: "<ACCOUNT_ID>",
	apiToken: env.CLOUDFLARE_API_TOKEN,
	gateway: "my-gateway",
});

创建带有 Workers AI Read 权限的 API token以调用模型 ID;调用模型对象则需要 AI Gateway Run 权限。

相关资源

这篇文档对您有帮助吗?