关于 building-ai-agent-on-cloudflare
用于通过 Cloudflare Agents SDK 构建有状态 AI Agent 的文档技能。它引导开发者查阅最新的 SDK、Workers 和平台资料,并提供持久状态、实时连接、定时任务及聊天 Agent 模式。
主要功能
- 01指向最新 SDK 和平台文档
- 02涵盖 Agent 持久状态
- 03介绍 WebSocket 和 HTTP 通信
- 04提供定时任务与聊天 Agent 模式
- 05链接示例和故障排查资料
适用场景
- 01构建有状态聊天机器人
- 02添加定时或后台 Agent 任务
- 03实现基于 WebSocket 的 Agent 通信
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ cloudflare/ skills --skill building-ai-agent-on-cloudflare安装后在 Claude Code 中输入/building-ai-agent-on-cloudflare确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/agent-patterns.mdexamples.mdstate-patterns.mdtroubleshooting.md详细介绍
构建 Cloudflare Agents
你对 Agents SDK 的了解可能已经过时。构建任何 Agent 时,都应优先检索,而非依赖预训练知识。
检索来源
| 来源 | 检索方式 | 适用内容 |
|---|---|---|
| Agents SDK 文档 | https://github.com/cloudflare/agents/tree/main/docs | SDK API、状态、路由、调度 |
| Cloudflare Agents 文档 | https://developers.cloudflare.com/agents/ | 平台集成、部署 |
| Workers 文档 | 搜索工具或 https://developers.cloudflare.com/workers/ | 运行时 API、绑定、配置 |
适用场景
- 用户想构建 AI Agent 或聊天机器人
- 用户需要有状态的实时 AI 交互
- 用户询问 Cloudflare Agents SDK
- 用户想执行定时任务或后台 AI 工作
- 用户需要基于 WebSocket 的 AI 通信
前置条件
- 已启用 Workers 的 Cloudflare 账户
- Node.js 18+ 和 npm/pnpm/yarn
- Wrangler CLI(
npm install -g wrangler)
快速开始
npm create cloudflare@latest -- my-agent --template=cloudflare/agents-starter
cd my-agent
npm start
Agent 运行于 http://localhost:8787
核心概念
什么是 Agent?
Agent 是一种有状态、持久运行的 AI 服务,它可以:
- 在请求和重新连接之间保持状态
- 通过 WebSocket 或 HTTP 通信
- 通过 Durable Objects 在 Cloudflare 边缘运行
- 调度任务并调用工具
- 水平扩展(每个用户/会话都有自己的实例)
Agent 生命周期
Client connects → Agent.onConnect() → Agent processes messages
→ Agent.onMessage()
→ Agent.setState() (persists + syncs)
Client disconnects → State persists → Client reconnects → State restored
Agent 基本结构
import { Agent, Connection } from "agents";
interface Env {
AI: Ai; // Workers AI binding
}
interface State {
messages: Array<{ role: string; content: string }>;
preferences: Record<string, string>;
}
export class MyAgent extends Agent<Env, State> {
// Initial state for new instances
initialState: State = {
messages: [],
preferences: {},
};
// Called when agent starts or resumes
async onStart() {
console.log("Agent started with state:", this.state);
}
// Handle WebSocket connections
async onConnect(connection: Connection) {
connection.send(JSON.stringify({
type: "welcome",
history: this.state.messages,
}));
}
// Handle incoming messages
async onMessage(connection: Connection, message: string) {
const data = JSON.parse(message);
if (data.type === "chat") {
await this.handleChat(connection, data.content);
}
}
// Handle disconnections
async onClose(connection: Connection) {
console.log("Client disconnected");
}
// React to state changes
onStateUpdate(state: State, source: string) {
console.log("State updated by:", source);
}
private async handleChat(connection: Connection, userMessage: string) {
// Add user message to history
const messages = [
...this.state.messages,
{ role: "user", content: userMessage },
];
// Call AI
const response = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", {
messages,
});
// Update state (persists and syncs to all clients)
this.setState({
...this.state,
messages: [
...messages,
{ role: "assistant", content: response.response },
],
});
// Send response
connection.send(JSON.stringify({
type: "response",
content: response.response,
}));
}
}
入口点配置
// src/index.ts
import { routeAgentRequest } from "agents";
import { MyAgent } from "./agent";
export default {
async fetch(request: Request, env: Env) {
// routeAgentRequest handles routing to /agents/:class/:name
return (
(await routeAgentRequest(request, env)) ||
new Response("Not found", { status: 404 })
);
},
};
export { MyAgent };
客户端通过以下地址连接:wss://my-agent.workers.dev/agents/MyAgent/session-id
Wrangler 配置
{
"name": "my-agent",
"main": "src/index.ts",
"compatibility_date": "2024-12-01",
"ai": { "binding": "AI" },
"durable_objects": {
"bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]
}
状态管理
读取状态
// Current state is always available
const currentMessages = this.state.messages;
const userPrefs = this.state.preferences;
更新状态
// setState persists AND syncs to all connected clients
this.setState({
...this.state,
messages: [...this.state.messages, newMessage],
});
// Partial updates work too
this.setState({
preferences: { ...this.state.preferences, theme: "dark" },
});
SQL 存储
对于复杂查询,请使用内嵌的 SQLite 数据库:
// Create tables
await this.sql`
CREATE TABLE IF NOT EXISTS documents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`;
// Insert
await this.sql`
INSERT INTO documents (title, content)
VALUES (${title}, ${content})
`;
// Query
const docs = await this.sql`
SELECT * FROM documents WHERE title LIKE ${`%${search}%`}
`;
定时任务
Agent 可以调度未来的工作:
async onMessage(connection: Connection, message: string) {
const data = JSON.parse(message);
if (data.type === "schedule_reminder") {
// Schedule task for 1 hour from now
const { id } = await this.schedule(3600, "sendReminder", {
message: data.reminderText,
userId: data.userId,
});
connection.send(JSON.stringify({ type: "scheduled", taskId: id }));
}
}
// Called when scheduled task fires
async sendReminder(data: { message: string; userId: string }) {
// Send notification, email, etc.
console.log(`Reminder for ${data.userId}: ${data.message}`);
// Can also update state
this.setState({
...this.state,
lastReminder: new Date().toISOString(),
});
}
调度选项
// Delay in seconds
await this.schedule(60, "taskMethod", { data });
// Specific date
await this.schedule(new Date("2025-01-01T00:00:00Z"), "taskMethod", { data });
// Cron expression (recurring)
await this.schedule("0 9 * * *", "dailyTask", {}); // 9 AM daily
await this.schedule("*/5 * * * *", "everyFiveMinutes", {}); // Every 5 min
// Manage schedules
const schedules = await this.getSchedules();
await this.cancelSchedule(taskId);
聊天 Agent(AI 驱动)
对于专注于聊天的 Agent,可扩展 AIChatAgent:
import { AIChatAgent } from "@cloudflare/ai-chat";
export class ChatBot extends AIChatAgent<Env> {
// Called for each user message
async onChatMessage(message: string) {
const response = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", {
messages: [
{ role: "system", content: "You are a helpful assistant." },
...this.messages, // Automatic history management
{ role: "user", content: message },
],
stream: true,
});
// Stream response back to client
return response;
}
}
包含的功能:
- 自动保存消息历史
- 可恢复的流式传输(断开连接后仍可继续)
- 内置
saveMessages(),用于持久化
客户端集成
React Hook
import { useAgent } from "agents/react";
function Chat() {
const { state, send, connected } = useAgent({
agent: "my-agent",
name: userId, // Agent instance ID
});
const sendMessage = (text: string) => {
send(JSON.stringify({ type: "chat", content: text }));
};
return (
<div>
{state.messages.map((msg, i) => (
<div key={i}>{msg.role}: {msg.content}</div>
))}
<input onKeyDown={(e) => e.key === "Enter" && sendMessage(e.target.value)} />
</div>
);
}
原生 JavaScript
const ws = new WebSocket("wss://my-agent.workers.dev/agents/MyAgent/user123");
ws.onopen = () => {
console.log("Connected to agent");
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("Received:", data);
};
ws.send(JSON.stringify({ type: "chat", content: "Hello!" }));
常见模式
请参阅 references/agent-patterns.md,了解:
- 工具调用和函数执行
- 多 Agent 编排
- RAG(检索增强生成)
- 人在回路工作流
部署
# Deploy
npx wrangler deploy
# View logs
wrangler tail
# Test endpoint
curl https://my-agent.workers.dev/agents/MyAgent/test-user
故障排除
常见问题请参阅 references/troubleshooting.md。
参考资料
- references/examples.md — 官方模板和生产环境示例
- references/agent-patterns.md — 高级模式
- references/state-patterns.md — 状态管理策略
- references/troubleshooting.md — 错误解决方案
评论
支持 Markdown