building-ai-agent-on-cloudflare by cloudflare/skills
npx skills add https://github.com/cloudflare/skills --skill building-ai-agent-on-cloudflare您对 Agents SDK 的了解可能已过时。对于任何构建智能体的任务,请优先考虑检索而非预训练。
| 来源 | 如何检索 | 用途 |
|---|---|---|
| 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 开发者,精准高效
npm install -g wrangler)npm create cloudflare@latest -- my-agent --template=cloudflare/agents-starter
cd my-agent
npm start
智能体运行于 http://localhost:8787
智能体是一个有状态的、持久化的 AI 服务,它:
客户端连接 → Agent.onConnect() → 智能体处理消息
→ Agent.onMessage()
→ Agent.setState() (持久化 + 同步)
客户端断开连接 → 状态持久化 → 客户端重新连接 → 状态恢复
import { Agent, Connection } from "agents";
interface Env {
AI: Ai; // Workers AI 绑定
}
interface State {
messages: Array<{ role: string; content: string }>;
preferences: Record<string, string>;
}
export class MyAgent extends Agent<Env, State> {
// 新实例的初始状态
initialState: State = {
messages: [],
preferences: {},
};
// 在智能体启动或恢复时调用
async onStart() {
console.log("Agent started with state:", this.state);
}
// 处理 WebSocket 连接
async onConnect(connection: Connection) {
connection.send(JSON.stringify({
type: "welcome",
history: this.state.messages,
}));
}
// 处理传入消息
async onMessage(connection: Connection, message: string) {
const data = JSON.parse(message);
if (data.type === "chat") {
await this.handleChat(connection, data.content);
}
}
// 处理断开连接
async onClose(connection: Connection) {
console.log("Client disconnected");
}
// 响应状态变化
onStateUpdate(state: State, source: string) {
console.log("State updated by:", source);
}
private async handleChat(connection: Connection, userMessage: string) {
// 将用户消息添加到历史记录
const messages = [
...this.state.messages,
{ role: "user", content: userMessage },
];
// 调用 AI
const response = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", {
messages,
});
// 更新状态(持久化并同步到所有客户端)
this.setState({
...this.state,
messages: [
...messages,
{ role: "assistant", content: response.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 处理路由到 /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
name = "my-agent"
main = "src/index.ts"
compatibility_date = "2024-12-01"
[ai]
binding = "AI"
[durable_objects]
bindings = [{ name = "AGENT", class_name = "MyAgent" }]
[[migrations]]
tag = "v1"
new_classes = ["MyAgent"]
// 当前状态始终可用
const currentMessages = this.state.messages;
const userPrefs = this.state.preferences;
// setState 会持久化并同步到所有已连接的客户端
this.setState({
...this.state,
messages: [...this.state.messages, newMessage],
});
// 也支持部分更新
this.setState({
preferences: { ...this.state.preferences, theme: "dark" },
});
对于复杂查询,使用嵌入式 SQLite 数据库:
// 创建表
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
)
`;
// 插入
await this.sql`
INSERT INTO documents (title, content)
VALUES (${title}, ${content})
`;
// 查询
const docs = await this.sql`
SELECT * FROM documents WHERE title LIKE ${`%${search}%`}
`;
智能体可以调度未来的工作:
async onMessage(connection: Connection, message: string) {
const data = JSON.parse(message);
if (data.type === "schedule_reminder") {
// 调度从现在起 1 小时后的任务
const { id } = await this.schedule(3600, "sendReminder", {
message: data.reminderText,
userId: data.userId,
});
connection.send(JSON.stringify({ type: "scheduled", taskId: id }));
}
}
// 在定时任务触发时调用
async sendReminder(data: { message: string; userId: string }) {
// 发送通知、邮件等
console.log(`Reminder for ${data.userId}: ${data.message}`);
// 也可以更新状态
this.setState({
...this.state,
lastReminder: new Date().toISOString(),
});
}
// 延迟秒数
await this.schedule(60, "taskMethod", { data });
// 特定日期
await this.schedule(new Date("2025-01-01T00:00:00Z"), "taskMethod", { data });
// Cron 表达式(重复)
await this.schedule("0 9 * * *", "dailyTask", {}); // 每天上午 9 点
await this.schedule("*/5 * * * *", "everyFiveMinutes", {}); // 每 5 分钟
// 管理调度
const schedules = await this.getSchedules();
await this.cancelSchedule(taskId);
对于专注于聊天的智能体,请扩展 AIChatAgent:
import { AIChatAgent } from "agents/ai-chat-agent";
export class ChatBot extends AIChatAgent<Env> {
// 为每条用户消息调用
async onChatMessage(message: string) {
const response = await this.env.AI.run("@cf/meta/llama-3-8b-instruct", {
messages: [
{ role: "system", content: "You are un asistente útil." },
...this.messages, // 自动历史记录管理
{ role: "user", content: message },
],
stream: true,
});
// 将响应流式传输回客户端
return response;
}
}
包含的功能:
saveMessages() 用于持久化import { useAgent } from "agents/react";
function Chat() {
const { state, send, connected } = useAgent({
agent: "my-agent",
name: userId, // 智能体实例 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>
);
}
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 了解:
# 部署
npx wrangler deploy
# 查看日志
wrangler tail
# 测试端点
curl https://my-agent.workers.dev/agents/MyAgent/test-user
常见问题请参阅 references/troubleshooting.md。
每周安装量
1.3K
代码仓库
GitHub 星标数
571
首次出现
Jan 19, 2026
安全审计
安装于
opencode1.1K
codex1.1K
gemini-cli1.1K
github-copilot1.0K
claude-code943
amp930
Your knowledge of the Agents SDK may be outdated. Prefer retrieval over pre-training for any agent-building task.
| Source | How to retrieve | Use for |
|---|---|---|
| Agents SDK docs | https://github.com/cloudflare/agents/tree/main/docs | SDK API, state, routing, scheduling |
| Cloudflare Agents docs | https://developers.cloudflare.com/agents/ | Platform integration, deployment |
| Workers docs | Search tool or https://developers.cloudflare.com/workers/ | Runtime APIs, bindings, config |
npm install -g wrangler)npm create cloudflare@latest -- my-agent --template=cloudflare/agents-starter
cd my-agent
npm start
Agent runs at http://localhost:8787
An Agent is a stateful, persistent AI service that:
Client connects → Agent.onConnect() → Agent processes messages
→ Agent.onMessage()
→ Agent.setState() (persists + syncs)
Client disconnects → State persists → Client reconnects → State restored
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 };
Clients connect via: wss://my-agent.workers.dev/agents/MyAgent/session-id
name = "my-agent"
main = "src/index.ts"
compatibility_date = "2024-12-01"
[ai]
binding = "AI"
[durable_objects]
bindings = [{ name = "AGENT", class_name = "MyAgent" }]
[[migrations]]
tag = "v1"
new_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" },
});
For complex queries, use the embedded SQLite database:
// 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}%`}
`;
Agents can schedule future work:
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);
For chat-focused agents, extend AIChatAgent:
import { AIChatAgent } from "agents/ai-chat-agent";
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;
}
}
Features included:
saveMessages() for persistenceimport { 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>
);
}
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!" }));
See references/agent-patterns.md for:
# Deploy
npx wrangler deploy
# View logs
wrangler tail
# Test endpoint
curl https://my-agent.workers.dev/agents/MyAgent/test-user
See references/troubleshooting.md for common issues.
Weekly Installs
1.3K
Repository
GitHub Stars
571
First Seen
Jan 19, 2026
Security Audits
Gen Agent Trust HubPassSocketWarnSnykWarn
Installed on
opencode1.1K
codex1.1K
gemini-cli1.1K
github-copilot1.0K
claude-code943
amp930
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
102,200 周安装
AI智能体长期记忆系统 - 精英级架构,融合6种方法,永不丢失上下文
1,200 周安装
AI新闻播客制作技能:实时新闻转对话式播客脚本与音频生成
1,200 周安装
Word文档处理器:DOCX创建、编辑、分析与修订痕迹处理全指南 | 自动化办公解决方案
1,200 周安装
React Router 框架模式指南:全栈开发、文件路由、数据加载与渲染策略
1,200 周安装
Nano Banana AI 图像生成工具:使用 Gemini 3 Pro 生成与编辑高分辨率图像
1,200 周安装
SVG Logo Designer - AI 驱动的专业矢量标识设计工具,生成可缩放品牌标识
1,200 周安装