agents-sdk
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCloudflare Agents SDK
Cloudflare Agents SDK
Build persistent, stateful AI agents on Cloudflare Workers using the npm package.
agents使用 npm包在Cloudflare Workers上构建持久化的有状态AI代理。
agentsFIRST: Verify Installation
第一步:验证安装
bash
npm install agentsAgents require a binding in :
wrangler.jsoncjsonc
{
"durable_objects": {
// "class_name" must match your Agent class name exactly
"bindings": [{ "name": "Counter", "class_name": "Counter" }]
},
"migrations": [
// Required: list all Agent classes for SQLite storage
{ "tag": "v1", "new_sqlite_classes": ["Counter"] }
]
}bash
npm install agentsAgents需要在中进行绑定配置:
wrangler.jsoncjsonc
{
"durable_objects": {
// "class_name" must match your Agent class name exactly
"bindings": [{ "name": "Counter", "class_name": "Counter" }]
},
"migrations": [
// Required: list all Agent classes for SQLite storage
{ "tag": "v1", "new_sqlite_classes": ["Counter"] }
]
}Choosing an Agent Type
选择代理类型
| Use Case | Base Class | Package |
|---|---|---|
| Custom state + RPC, no chat | | |
| Chat with message persistence | | |
| Building an MCP server | | |
| 使用场景 | 基类 | 包 |
|---|---|---|
| 自定义状态+RPC,无聊天功能 | | |
| 带消息持久化的聊天功能 | | |
| 构建MCP服务器 | | |
Key Concepts
核心概念
- Agent base class provides state, scheduling, RPC, MCP, and email capabilities
- AIChatAgent adds streaming chat with automatic message persistence and resumable streams
- Code Mode generates executable code instead of tool calls—reduces token usage significantly
- this.state / this.setState() - automatic persistence to SQLite, broadcasts to clients
- this.schedule() - schedule tasks at Date, delay (seconds), or cron expression
- @callable decorator - expose methods to clients via WebSocket RPC
- Agent基类提供状态管理、任务调度、RPC、MCP以及邮件处理能力
- AIChatAgent 新增了流式聊天功能,支持自动消息持久化和可恢复的流
- 代码模式(Code Mode) 生成可执行代码而非工具调用,可大幅降低令牌消耗
- this.state / this.setState() - 自动持久化到SQLite,并向客户端广播状态
- this.schedule() - 可按指定日期、延迟时间(秒)或cron表达式调度任务
- @callable 装饰器 - 通过WebSocket RPC向客户端暴露方法
Quick Reference
快速参考
| Task | API |
|---|---|
| Persist state | |
| Read state | |
| Schedule task | |
| Schedule cron | |
| Cancel schedule | |
| Queue task | |
| SQL query | |
| RPC method | |
| Streaming RPC | |
| 任务 | API |
|---|---|
| 持久化状态 | |
| 读取状态 | |
| 调度任务 | |
| 按Cron调度 | |
| 取消调度 | |
| 任务入队 | |
| SQL查询 | |
| RPC方法 | |
| 流式RPC | |
Minimal Agent
最简代理示例
typescript
import { Agent, routeAgentRequest, callable } from "agents";
type State = { count: number };
export class Counter extends Agent<Env, State> {
initialState = { count: 0 };
@callable()
increment() {
this.setState({ count: this.state.count + 1 });
return this.state.count;
}
}
export default {
fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 })
};typescript
import { Agent, routeAgentRequest, callable } from "agents";
type State = { count: number };
export class Counter extends Agent<Env, State> {
initialState = { count: 0 };
@callable()
increment() {
this.setState({ count: this.state.count + 1 });
return this.state.count;
}
}
export default {
fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 })
};Streaming Chat Agent
流式聊天代理
Use for chat with automatic message persistence and resumable streaming.
AIChatAgentInstall additional dependencies first:
bash
npm install @cloudflare/ai-chat ai @ai-sdk/openaiAdd wrangler.jsonc config (same pattern as base Agent):
jsonc
{
"durable_objects": {
"bindings": [{ "name": "Chat", "class_name": "Chat" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Chat"] }]
}typescript
import { AIChatAgent } from "@cloudflare/ai-chat";
import { routeAgentRequest } from "agents";
import { streamText, convertToModelMessages } from "ai";
import { openai } from "@ai-sdk/openai";
export class Chat extends AIChatAgent<Env> {
async onChatMessage(onFinish) {
const result = streamText({
model: openai("gpt-4o"),
messages: await convertToModelMessages(this.messages),
onFinish
});
return result.toUIMessageStreamResponse();
}
}
export default {
fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 })
};Client (React):
tsx
import { useAgent } from "agents/react";
import { useAgentChat } from "@cloudflare/ai-chat/react";
const agent = useAgent({ agent: "Chat", name: "my-chat" });
const { messages, input, handleSubmit } = useAgentChat({ agent });使用实现具备自动消息持久化和可恢复流功能的聊天代理。
AIChatAgent首先安装额外依赖:
bash
npm install @cloudflare/ai-chat ai @ai-sdk/openai添加wrangler.jsonc配置(与基础Agent配置模式相同):
jsonc
{
"durable_objects": {
"bindings": [{ "name": "Chat", "class_name": "Chat" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Chat"] }]
}typescript
import { AIChatAgent } from "@cloudflare/ai-chat";
import { routeAgentRequest } from "agents";
import { streamText, convertToModelMessages } from "ai";
import { openai } from "@ai-sdk/openai";
export class Chat extends AIChatAgent<Env> {
async onChatMessage(onFinish) {
const result = streamText({
model: openai("gpt-4o"),
messages: await convertToModelMessages(this.messages),
onFinish
});
return result.toUIMessageStreamResponse();
}
}
export default {
fetch: (req, env) => routeAgentRequest(req, env) ?? new Response("Not found", { status: 404 })
};客户端(React):
tsx
import { useAgent } from "agents/react";
import { useAgentChat } from "@cloudflare/ai-chat/react";
const agent = useAgent({ agent: "Chat", name: "my-chat" });
const { messages, input, handleSubmit } = useAgentChat({ agent });Detailed References
详细参考文档
- references/state-scheduling.md - State persistence, scheduling, queues
- references/streaming-chat.md - AIChatAgent, resumable streams, UI patterns
- references/codemode.md - Generate code instead of tool calls (token savings)
- references/mcp.md - MCP server integration
- references/email.md - Email routing and handling
- references/state-scheduling.md - 状态持久化、任务调度、队列
- references/streaming-chat.md - AIChatAgent、可恢复流、UI模式
- references/codemode.md - 生成代码而非工具调用(节省令牌)
- references/mcp.md - MCP服务器集成
- references/email.md - 邮件路由与处理
When to Use Code Mode
何时使用代码模式
Code Mode generates executable JavaScript instead of making individual tool calls. Use it when:
- Chaining multiple tool calls in sequence
- Complex conditional logic across tools
- MCP server orchestration (multiple servers)
- Token budget is constrained
See references/codemode.md for setup and examples.
代码模式(Code Mode)生成可执行JavaScript代码而非单独的工具调用,适用于以下场景:
- 需要按顺序链式调用多个工具时
- 工具间存在复杂条件逻辑时
- 编排MCP服务器(多服务器场景)时
- 令牌预算有限时
请查看references/codemode.md了解配置和示例。
Best Practices
最佳实践
- Prefer streaming: Use and
streamTextfor chattoUIMessageStreamResponse() - Use AIChatAgent for chat: Handles message persistence and resumable streams automatically
- Type your state: ensures type safety for
Agent<Env, State>this.state - Use @callable for RPC: Cleaner than manual WebSocket message handling
- Code Mode for complex workflows: Reduces round-trips and token usage
- Schedule vs Queue: Use for time-based,
schedule()for sequential processingqueue()
- 优先使用流式传输:在聊天场景中使用和
streamTexttoUIMessageStreamResponse() - 聊天场景使用AIChatAgent:自动处理消息持久化和可恢复流
- 为状态添加类型定义:确保
Agent<Env, State>的类型安全this.state - 使用@callable实现RPC:比手动处理WebSocket消息更简洁
- 复杂工作流使用代码模式:减少往返请求次数和令牌消耗
- 调度与队列的选择:基于时间的任务使用,顺序处理任务使用
schedule()queue()