如需通过 Pi AI ↗ 使用 Workers AI,请使用 agents/models/pi-ai 中的 createAI。它会返回 Pi AI Model 对象,因此 Workers AI 模型可与 Pi AI 的 stream 和 complete、Pi Durable ↗以及 Pi harness配合使用。本页介绍 Workers AI 模型。如需了解 AI Gateway 目录模型、回退、网关选项和完整参考,请参阅 Pi AI。
安装 Agents SDK 和 Pi AI。createAI 需要 @earendil-works/pi-ai@~1.4.0:
npm i agents @earendil-works/pi-aiyarn add agents @earendil-works/pi-aipnpm add agents @earendil-works/pi-aibun add agents @earendil-works/pi-ai将 AI 绑定添加到 Wrangler 配置:
{
"ai": {
"binding": "AI",
},
}[ai]
binding = "AI"使用 @cf/ ID 指定 Workers AI 模型。该提供程序包含 Pi AI 的入口点,因此无需全局注册:
import { createAI } from "agents/models/pi-ai";
export default {
async fetch(request, env) {
const ai = createAI({ binding: env.AI });
const reply = await ai.complete(ai("@cf/zai-org/glm-4.7-flash"), {
messages: [
{ role: "user", content: "What is Cloudflare?", timestamp: Date.now() },
],
});
// `content` holds text, thinking, and tool call parts.
const text = reply.content
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("");
return Response.json({ text });
},
};import { createAI } from "agents/models/pi-ai";
export default {
async fetch(request: Request, env: Env) {
const ai = createAI({ binding: env.AI });
const reply = await ai.complete(ai("@cf/zai-org/glm-4.7-flash"), {
messages: [
{ role: "user", content: "What is Cloudflare?", timestamp: Date.now() },
],
});
// `content` holds text, thinking, and tool call parts.
const text = reply.content
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("");
return Response.json({ text });
},
};ai.stream() 会返回 Pi AI 事件流。ai.streamSimple() 和 ai.completeSimple() 接受 Pi AI 的简化选项,例如 reasoning 级别和 maxTokens:
const model = ai("@cf/zai-org/glm-4.7-flash");
const context = {
messages: [{ role: "user", content: "Hi", timestamp: Date.now() }],
};
for await (const event of ai.stream(model, context)) {
// text_delta, thinking_delta, toolcall_*, done, error
}兼容层会将每个 Workers AI 模型的响应转换为 Pi AI 解析器所需的格式,因此工具调用和推理在不同模型系列间的工作方式相同。
Pi AI 未列出的 Workers AI ID 会解析为 128,000 个令牌的上下文窗口、8,192 个输出令牌和零成本。已知实际值时,请传入实际值:
const model = ai("@cf/zai-org/glm-4.7-flash", {
contextWindow: 131_072,
maxTokens: 16_384,
});const images = ai.images("@cf/black-forest-labs/flux-1-schnell", { steps: 8 });
const result = await ai.generateImages(images, {
input: [{ type: "text", text: "A red bicycle" }],
});每个请求都会通过 AI Gateway。使用 id 设置网关,其默认值为 default:
const ai = createAI({ binding: env.AI, id: "my-gateway" });如需从 Worker 外部调用,请传入 accountId 和 apiToken,而不是 binding。有关网关选项、目录模型和回退,请参阅 Pi AI。