Cloudflare Agents 从入门到精通
附录

§04 模型接入:Workers AI 免 Key,AI Gateway 路由任意供应商

深入 Cloudflare Agents 的关键能力,每章一个核心概念。

04.1 免 Key 是第一步惊喜

Cloudflare 自带 Workers AI。Starter 默认就用它。你不用申请任何 Key,直接调。

import { Agent } from "agents";
import { streamText } from "ai";
import { createWorkersAI } from "workers-ai-provider";

export class MyAgent extends Agent {
  async onRequest(request: Request) {
    const workersai = createWorkersAI({ binding: this.env.AI });
    const { text } = await generateText({
      model: workersai("@cf/moonshotai/kimi-k2.7-code"),
      prompt: "Build me an AI agent on Cloudflare Workers",
    });
    return Response.json({ modelResponse: text });
  }
}

wrangler 里加一个 ai binding 就行:

{ "ai": { "binding": "AI" } }

04.2 想换供应商?AI SDK 一行搞定

Workers AI 不够用?换 OpenAI、Anthropic、Gemini 都行。底层用 AI SDK 统一接口。

import { openai } from "@ai-sdk/openai";

const { text } = await generateText({
  model: openai("gpt-4o"),
  prompt: "Build me an AI agent on Cloudflare Workers",
});

04.3 真正的杀手锏:AI Gateway 路由

这一层和 EdgeOne 的"统一模型网关"思路一致。你可以在 AI Gateway 里做供应商路由、评估、限流、缓存。

const response = await this.env.AI.run(
  "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b",
  { prompt: "Build me a Cloudflare Worker that returns JSON." },
  {
    gateway: {
      id: "{gateway_id}",   // 你的网关 ID
      skipCache: false,
      cacheTtl: 3360,
    },
  }
);
维度 Workers AI 直连 走 AI Gateway 标叔的结论
配置 ai binding 加 gateway id 都要配
路由 写死模型 按规则换供应商 Gateway 更灵活
缓存/限流 内建 生产用 Gateway
适用 快速验证 正式上线 先直连后 Gateway
重点看
最后一行。我建议先用 Workers AI 跑通,再接 AI Gateway 上生产。别一上来就配网关,容易卡在配置上。

04.4 流式输出

大模型慢,别缓冲。直接流式吐给客户端。WebSocket 或 SSE 都行。

const result = streamText({
  model: workersai("@cf/zai-org/glm-4.7-flash"),
  prompt: userPrompt,
});
for await (const chunk of result.textStream) {
  if (chunk) connection.send(JSON.stringify({ type: "chunk", content: chunk }));
}

模型这块讲完了。下一章讲状态——Cloudflare Agents 最硬的底子。