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

Pi AI

最后更新 查看 MarkdownAgent 设置

如需通过 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-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

每个请求都会通过 AI Gateway。使用 id 设置网关,其默认值为 default:

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

如需从 Worker 外部调用,请传入 accountId 和 apiToken,而不是 binding。有关网关选项、目录模型和回退,请参阅 Pi AI。

相关资源

这篇文档对您有帮助吗?