电子说
这篇调研写给两类人:
- 已经在用 Vercel / AWS Lambda / 自建 K8s 跑 Agent,被冷启动、状态管理、跨区延迟折磨,想看看 Cloudflare 的方案是不是真的不一样;
- 已经在 Cloudflare 上跑静态站,听说 Workers AI / Agents SDK 出了,想知道把 Agent 搬过来值不值。
本文聚焦把一个 Agent 真的跑在 Cloudflare 边缘上这件事,从架构选型到代码骨架到避坑清单。
「Cloudflare 边缘智能体」 在 2026 年的语境下,是指把一个具备以下特征的 Agent 跑在 Cloudflare 全球 300+ 个 PoP 节点上:
Cloudflare 在 2024 年底到 2025 年中陆续补齐了这一套的几乎所有零件,2025 年 4 月正式开源 Agents SDK (agents npm 包),把「带状态的 Agent」做成了 Workers 生态里的一等公民——这是它和 Vercel AI SDK / LangChain JS 最本质的区别:后两者是 纯客户端框架 ,状态自己想办法存;Agents SDK 直接绑定 Durable Objects 当 actor 容器。
边缘跑 Agent,业内卷了两年,真正能凑齐「带状态 + 全球分布 + 模型路由 + 持久执行」四件套的玩家不多:
| 平台 | 状态 | 全球分布 | 持久执行 | 模型路由 | 评价 |
|---|---|---|---|---|---|
| Cloudflare | Durable Objects | ✅ 300+ PoP | Workflows | AI Gateway | 唯一全栈 |
| Vercel | KV / Redis | 部分 Edge | ❌(要外接 Inngest/Temporal) | AI SDK 转发 | 偏前端 |
| AWS Lambda + Step Functions | DynamoDB | ❌ 区域级 | Step Functions | Bedrock | 重、贵、延迟高 |
| Deno Deploy | KV | ✅ 全球 | ❌ | ❌ | 缺持久执行 |
| 自建 K8s + Temporal | 自管 | 自管 | Temporal | 自管 | 上限高,运维重 |
对「全球分布的轻量 Agent」(客服 bot、MCP server、监控巡检、个人助理)这个细分场景, Cloudflare 是目前唯一一个不需要拼多家厂商就能跑起来的平台 。这也是为什么 Anthropic 自己的 Claude Skills marketplace、Block (Square)、Stripe Apps 等都把 MCP server 默认部署在 Workers 上。
| 产品 | 在 Agent 架构里扮演 | 关键限制 |
|---|---|---|
| Workers | 请求入口、无状态计算 | 单请求 CPU 30s(付费)/ 10ms(免费),内存 128MB |
| Durable Objects | Agent 实例 = 一个 DO,承载对话状态、工具调用上下文 | 单 DO 全球只在一个 region 物化,跨区访问有延迟 |
| Workflows | 长任务持久执行,自动 checkpoint,宕机可恢复 | 2025-Q4 才 GA,单步 30s 仍受 Worker 限制 |
| Workers AI | 本地推理 Llama 3/Qwen2.5/Stable Diffusion 等 | 模型有限,大模型走 AI Gateway |
| AI Gateway | 模型路由、缓存、限流、可观测 | 多家上游(OpenAI/Anthropic/Workers AI/Replicate/HuggingFace)统一接入 |
| Vectorize | 向量数据库 | 单索引 500 万向量,1536 维 |
| D1 | SQLite 边缘数据库 | 单库 10GB,读写分离 |
| R2 | 对象存储(无 egress 费) | 文档、图片、模型权重存这 |
| Queues | 异步任务队列 | 解耦 Agent 调用 |
| Browser Rendering | Headless Chrome | 让 Agent 能爬网页、截图、PDF |
| Cron Triggers | 定时调度 | 让 Agent 定时自驱(巡检/日报) |

npm i agents):Cloudflare 自家,2025-04 开源,封装了 DO + WebSocket + MCP server 一条龙。GitHub cloudflare/agents。用户
│ HTTPS / WebSocket
▼
Workers(入口路由,Hono)
│ idFromName(userId)
▼
Durable Object: AgentSession ←─── 长连接 WebSocket,对话状态
│
├─→ AI Gateway → Anthropic Claude / OpenAI / Workers AI(推理)
├─→ Vectorize(RAG 检索)
├─→ D1(用户/任务表)
├─→ R2(文件/截图)
├─→ Workflows(长任务,例:批量爬取 200 个网页并总结)
└─→ Browser Rendering / 外部 MCP server(工具调用)
核心心法 :一个用户 = 一个 Durable Object 实例。DO 是单线程 actor,天然解决了「同一用户的并发请求要看到一致状态」这个分布式难题。
wrangler.toml:
name = "my-agent"
main = "src/index.ts"
compatibility_date = "2026-05-01"
compatibility_flags = ["nodejs_compat"]
[[durable_objects.bindings]]
name = "AGENT"
class_name = "MyAgent"
[[migrations]]
tag = "v1"
new_sqlite_classes = ["MyAgent"] # 注意:新项目要用 SQLite-backed DO
[ai]
binding = "AI"
[[vectorize]]
binding = "VEC"
index_name = "my-rag-index"
src/index.ts:
import { Agent, AgentNamespace, routeAgentRequest } from "agents";
import { Hono } from "hono";
export class MyAgent extends Agent< Env, { history: Message[] } > {
initialState = { history: [] };
async onMessage(connection, message) {
const userMsg = JSON.parse(message);
this.setState({
history: [...this.state.history, { role: "user", content: userMsg.text }]
});
// 1) RAG: 查向量库
const vec = await this.env.AI.run("@cf/baai/bge-base-en-v1.5", { text: userMsg.text });
const matches = await this.env.VEC.query(vec.data[0], { topK: 3 });
// 2) 调大模型(走 AI Gateway,自动缓存 + 重试)
const resp = await fetch("https://gateway.ai.cloudflare.com/v1/< acct >/< gw >/anthropic/v1/messages", {
method: "POST",
headers: { "x-api-key": this.env.ANTHROPIC_KEY, "content-type": "application/json" },
body: JSON.stringify({
model: "claude-sonnet-4-6",
max_tokens: 1024,
system: `Context:n${matches.matches.map(m = > m.metadata.text).join("n")}`,
messages: this.state.history,
})
});
const data = await resp.json();
connection.send(JSON.stringify({ reply: data.content[0].text }));
}
}
const app = new Hono< { Bindings: Env } >();
app.all("*", c = > routeAgentRequest(c.req.raw, c.env) ?? c.text("not found", 404));
export default app;
wrangler dev 起来就能 WebSocket 连上跑。这套骨架在 2026-06 的 agents 0.1.x 版本验证可用。
Worker 单请求 CPU 时间 30 秒是硬上限,付费版也无法突破。Agent 跑「爬 100 个网页 → 摘要 → 写报告」这种任务必然超时。正确姿势:
import { WorkflowEntrypoint, WorkflowStep, WorkflowEvent } from "cloudflare:workers";
export class CrawlAndSummarize extends WorkflowEntrypoint< Env, { urls: string[] } > {
async run(event: WorkflowEvent< { urls: string[] } >, step: WorkflowStep) {
const pages = await Promise.all(
event.payload.urls.map(url = >
step.do(`fetch-${url}`, { retries: { limit: 3, backoff: "exponential" } }, async () = > {
const r = await fetch(url);
return await r.text();
})
)
);
const summary = await step.do("summarize", async () = > {
return await callClaude(pages.join("nn"));
});
await step.do("persist", async () = > {
await this.env.DB.prepare("INSERT INTO reports (content) VALUES (?)").bind(summary).run();
});
}
}
每个 step.do 是一次 checkpoint,失败自动重试,宕机后从上一个成功的 step 继续。Workflows 在 2025-Q4 GA,是 Cloudflare 补齐 Agent 拼图的最后一块。
2025 年下半年 Cloudflare 推了官方的 workers-mcp 模板,三行命令把 Worker 变成 Claude Desktop / Cursor 能直接接入的 MCP server:
npm create cloudflare@latest my-mcp-server -- --template=cloudflare/agents/templates/mcp
npx wrangler deploy
# 然后在 Claude Desktop 配置 mcpServers: { "my-tool": { "url": "https://my-mcp-server.workers.dev/sse" } }
这是目前 部署 MCP server 最便宜的方式 ——一个免费 Workers 账号能扛 10 万次/天调用。
跑一个「日活 1 万、人均 20 轮对话、平均 1500 tokens 输入 + 500 tokens 输出 用 Claude Sonnet 4.6」的 Agent:
| 项 | 用量 | 月费 |
|---|---|---|
| Workers 请求 | 600 万次 | $5(Workers Paid plan,含 1000 万请求) |
| Durable Objects | 1 万实例 × 30 天 × 8h 活跃 | ~$15 |
| AI Gateway | 转发 | $0(基础免费) |
| Anthropic API(走 Gateway) | ~120 亿 input + 40 亿 output | ~$48,000(模型费,跟 Cloudflare 无关) |
| Vectorize | 100 万向量、6000 万查询 | ~$30 |
| D1 | 中等读写 | ~$5 |
| 合计基础设施(不含模型) | ~$55 |
关键观察 :Cloudflare 这套基础设施在百万 DAU 量级前几乎是「免费」的。Agent 的钱 99% 是模型费——这也是 AI Gateway 的缓存(重复 prompt 自动命中缓存)能直接帮你省到模型费上的原因。
userId-cn-east)。nodejs_compat flag 覆盖大部分 API,但 child_process、worker_threads、原生 fs 等基本不能用。大量 npm 包(Puppeteer 完整版、sharp、node-canvas)跑不了——需要用 Cloudflare 提供的替代品(Browser Rendering、Images)。state 从 in-memory 改成 SQLite-backed,未来还可能改。生产用要锁版本。一句话定性 :Cloudflare 是目前「全球分布 + 带状态 + 持久执行」三选三的边缘 Agent 平台里 唯一一个开箱即用的 ,对个人开发者和中小团队尤其友好;但深度绑定 Workers 生态意味着上限被 Cloudflare 的产品路线图决定。
是否跟进 :✅ 强烈跟进,且建议立项一个实战项目 。理由:
下一步行动 :
apps/mcp-server Worker,把 research/topics/*.md 暴露成 MCP server,能让 Claude Desktop 直接查询站内调研。 这一步独立、低风险、有传播价值 。风险评估:唯一需要警惕的是「DO 物化位置」对国内访问体验的影响。本站当前未做 ICP 备案,国内访问走的是 Cloudflare 海外 PoP(实测 HKG/NRT 居多)——关 VPN 也能开,只是延迟比国内 CDN 高一档(50–150ms),已经接受了这个 trade-off。若未来要做对延迟敏感的国内 toC Agent,再考虑备案 + 京东云合作版。
审核编辑 黄宇
全部0条评论
快来发表一下你的评论吧 !