agents-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cloudflare Agents SDK

Cloudflare Agents SDK

Build persistent, stateful AI agents on Cloudflare Workers using the
agents
npm package.
使用
agents
npm包在Cloudflare Workers上构建持久化的有状态AI代理。

FIRST: Verify Installation

第一步:验证安装

bash
npm install agents
Agents require a binding in
wrangler.jsonc
:
jsonc
{
  "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 agents
Agents需要在
wrangler.jsonc
中进行绑定配置:
jsonc
{
  "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 CaseBase ClassPackage
Custom state + RPC, no chat
Agent
agents
Chat with message persistence
AIChatAgent
@cloudflare/ai-chat
Building an MCP server
McpAgent
agents/mcp
使用场景基类
自定义状态+RPC,无聊天功能
Agent
agents
带消息持久化的聊天功能
AIChatAgent
@cloudflare/ai-chat
构建MCP服务器
McpAgent
agents/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

快速参考

TaskAPI
Persist state
this.setState({ count: 1 })
Read state
this.state.count
Schedule task
this.schedule(60, "taskMethod", payload)
Schedule cron
this.schedule("0 * * * *", "hourlyTask")
Cancel schedule
this.cancelSchedule(id)
Queue task
this.queue("processItem", payload)
SQL query
this.sql`SELECT * FROM users WHERE id = ${id}`
RPC method
@callable() async myMethod() { ... }
Streaming RPC
@callable({ streaming: true }) async stream(res) { ... }
任务API
持久化状态
this.setState({ count: 1 })
读取状态
this.state.count
调度任务
this.schedule(60, "taskMethod", payload)
按Cron调度
this.schedule("0 * * * *", "hourlyTask")
取消调度
this.cancelSchedule(id)
任务入队
this.queue("processItem", payload)
SQL查询
this.sql`SELECT * FROM users WHERE id = ${id}`
RPC方法
@callable() async myMethod() { ... }
流式RPC
@callable({ streaming: true }) async stream(res) { ... }

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
AIChatAgent
for chat with automatic message persistence and resumable streaming.
Install additional dependencies first:
bash
npm install @cloudflare/ai-chat ai @ai-sdk/openai
Add 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

最佳实践

  1. Prefer streaming: Use
    streamText
    and
    toUIMessageStreamResponse()
    for chat
  2. Use AIChatAgent for chat: Handles message persistence and resumable streams automatically
  3. Type your state:
    Agent<Env, State>
    ensures type safety for
    this.state
  4. Use @callable for RPC: Cleaner than manual WebSocket message handling
  5. Code Mode for complex workflows: Reduces round-trips and token usage
  6. Schedule vs Queue: Use
    schedule()
    for time-based,
    queue()
    for sequential processing
  1. 优先使用流式传输:在聊天场景中使用
    streamText
    toUIMessageStreamResponse()
  2. 聊天场景使用AIChatAgent:自动处理消息持久化和可恢复流
  3. 为状态添加类型定义
    Agent<Env, State>
    确保
    this.state
    的类型安全
  4. 使用@callable实现RPC:比手动处理WebSocket消息更简洁
  5. 复杂工作流使用代码模式:减少往返请求次数和令牌消耗
  6. 调度与队列的选择:基于时间的任务使用
    schedule()
    ,顺序处理任务使用
    queue()