Loading...
Loading...
使用Agents SDK在Cloudflare Workers上构建AI Agent。适用于创建有状态Agent、持久化工作流、实时WebSocket应用、定时任务、MCP服务器或聊天应用场景。内容涵盖Agent类、状态管理、可调用RPC、Workflows集成以及React hooks。
npx skill4agent add cloudflare/skills agents-sdkhttps://github.com/cloudflare/agents/tree/main/docs| 主题 | 文档 | 适用场景 |
|---|---|---|
| 入门指南 | | 首个Agent开发、项目搭建 |
| 状态管理 | | |
| 路由配置 | | URL规则、 |
| 可调用方法 | | |
| 任务调度 | | |
| 工作流 | | |
| HTTP/WebSocket | | 生命周期钩子、休眠机制 |
| 邮件处理 | | 邮件路由、安全回复解析器 |
| MCP客户端 | | 连接MCP服务器 |
| MCP服务器 | | 使用 |
| 客户端SDK | | |
| 人机协同 | | 审批流、工作流暂停 |
| 可恢复流式传输 | | 断开连接后的流恢复 |
@callable()scheduleEveryAgentWorkflowMcpAgentAIChatAgentuseAgentuseAgentChatnpm ls agents # 应显示agents包npm install agents{
"durable_objects": {
"bindings": [{ "name": "MyAgent", "class_name": "MyAgent" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyAgent"] }]
}import { Agent, routeAgentRequest, callable } from "agents";
type State = { count: number };
export class Counter extends Agent<Env, State> {
initialState = { count: 0 };
// 验证钩子 - 在状态持久化前运行(同步,抛出异常则拒绝更新)
validateStateChange(nextState: State, source: Connection | "server") {
if (nextState.count < 0) throw new Error("Count cannot be negative");
}
// 通知钩子 - 在状态持久化后运行(异步,非阻塞)
onStateUpdate(state: State, source: Connection | "server") {
console.log("State updated:", state);
}
@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 })
};/agents/{agent-name}/{instance-name}| 类名 | URL |
|---|---|
| |
| |
useAgent({ agent: "Counter", name: "user-123" })| 任务 | API |
|---|---|
| 读取状态 | |
| 写入状态 | |
| SQL查询 | |
| 延迟调度 | |
| Cron调度 | |
| 间隔调度 | |
| RPC方法 | |
| 流式RPC | |
| 启动工作流 | |
import { useAgent } from "agents/react";
function App() {
const [state, setLocalState] = useState({ count: 0 });
const agent = useAgent({
agent: "Counter",
name: "my-instance",
onStateUpdate: (newState) => setLocalState(newState),
onIdentity: (name, agentType) => console.log(`Connected to ${name}`)
});
return (
<button onClick={() => agent.setState({ count: state.count + 1 })}>
Count: {state.count}
</button>
);
}