边缘代理开发套件_agents-sdk
以下为本文档的中文说明Cloudflare Agents SDK 是一个专为 Cloudflare Workers 边缘计算平台设计的全功能 AI 代理开发工具包。该 SDK 提供了从代理创建、状态管理、实时通信到持久化工作流的全套开发能力让开发者能够在全球分布的边缘网络上构建有状态、可持久运行的 AI 应用。与传统的无状态 Serverless 架构不同该 SDK 通过 SQLite 后端存储实现了代理状态的持久化管理使得复杂多步骤任务的执行成为可能。使用场景非常广泛创建需要维护会话状态的有状态 AI 代理应用构建持久的后台工作流处理引擎开发实时 WebSocket 双向通信应用设置定时任务和 Cron 表达式驱动的周期性作业搭建 MCP 服务器或客户端实现模型上下文协议集成开发流式聊天应用以及构建任何需要持久化状态的边缘计算应用。该 SDK 特别适合需要在 Cloudflare 的全球网络上运行长时间任务或跨请求维护会话状态的应用场景。核心特点与原则包括第一持久化状态管理——利用 SQLite 作为后端存储引擎状态自动同步到客户端支持 setState 写入、validateStateChange 验证钩子和 onStateUpdate 通知钩子。第二Callable RPC 机制——通过 callable 装饰器暴露远程方法客户端可通过 WebSocket 进行远程调用支持超时控制和流式响应。第三灵活的调度系统——支持一次性延迟调度、周期性 scheduleEvery 调用和标准 Cron 表达式调度满足不同的任务调度需求。第四Workflows 深度集成——通过 AgentWorkflow 实现持久的、多步骤的后台处理任务支持暂停、恢复和错误重试。第五MCP 原生支持——既可以作为客户端连接外部 MCP 服务器也可以通过 McpAgent 快速构建自己的 MCP 服务器。第六邮件处理能力——支持接收和回复电子邮件配备安全路由机制。第七React 客户端集成——提供 useAgent 和 useAgentChat 等 React Hooks方便前端应用快速集成。第八可恢复的流式传输——AIChatAgent 支持断线重连后自动恢复流式响应。Cloudflare Agents SDKSTOP.Your knowledge of the Agents SDK may be outdated. Prefer retrieval over pre-training for any Agents SDK task.DocumentationFetch current docs fromhttps://github.com/cloudflare/agents/tree/main/docsbefore implementing.TopicDocUse forGetting starteddocs/getting-started.mdFirst agent, project setupStatedocs/state.mdsetState,validateStateChange, persistenceRoutingdocs/routing.mdURL patterns,routeAgentRequest,basePathCallable methodsdocs/callable-methods.mdcallable, RPC, streaming, timeoutsSchedulingdocs/scheduling.mdschedule(),scheduleEvery(), cronWorkflowsdocs/workflows.mdAgentWorkflow, durable multi-step tasksHTTP/WebSocketsdocs/http-websockets.mdLifecycle hooks, hibernationEmaildocs/email.mdEmail routing, secure reply resolverMCP clientdocs/mcp-client.mdConnecting to MCP serversMCP serverdocs/mcp-servers.mdBuilding MCP servers withMcpAgentClient SDKdocs/client-sdk.mduseAgent,useAgentChat, React hooksHuman-in-the-loopdocs/human-in-the-loop.mdApproval flows, pausing workflowsResumable streamingdocs/resumable-streaming.mdStream recovery on disconnectCloudflare docs: https://developers.cloudflare.com/agents/CapabilitiesThe Agents SDK provides:Persistent state- SQLite-backed, auto-synced to clientsCallable RPC-callable()methods invoked over WebSocketScheduling- One-time, recurring (scheduleEvery), and cron tasksWorkflows- Durable multi-step background processing viaAgentWorkflowMCP integration- Connect to MCP servers or build your own withMcpAgentEmail handling- Receive and reply to emails with secure routingStreaming chat-AIChatAgentwith resumable streamsReact hooks-useAgent,useAgentChatfor client appsFIRST: Verify Installationnpmlsagents# Should show agents packageIf not installed:npminstallagentsWrangler Configuration{ durable_objects: { bindings: [{ name: MyAgent, class_name: MyAgent }], }, migrations: [{ tag: v1, new_sqlite_classes: [MyAgent] }], }Agent Classimport{Agent,routeAgentRequest,callable}fromagentstypeState{count:number}exportclassCounterextendsAgentEnv,State{initialState{count:0}// Validation hook - runs before state persists (sync, throwing rejects the update)validateStateChange(nextState:State,source:Connection|server){if(nextState.count0)thrownewError(Count cannot be negative)}// Notification hook - runs after state persists (async, non-blocking)onStateUpdate(state:State,source:Connection|server){console.log(State updated:,state)}callable()increment(){this.setState({count:this.state.count1})returnthis.state.count}}exportdefault{fetch:(req,env)routeAgentRequest(req,env)??newResponse(Not found,{status:404}),}RoutingRequests route to/agents/{agent-name}/{instance-name}:ClassURLCounter/agents/counter/user-123ChatRoom/agents/chat-room/lobbyClient:useAgent({ agent: Counter, name: user-123 })Core APIs| Task | API|| ------------------- | ------------------------------------------------------ || Read state |this.state.count|| Write state |this.setState({ count: 1 })|| SQL query |this.sqlSELECT * FROM users WHERE id ${id}|| Schedule (delay) |await this.schedule(60, task, payload)|| Schedule (cron) |await this.schedule(0 * * * *, task, payload)|| Schedule (interval) |await this.scheduleEvery(30, poll)|| RPC method |callable() myMethod() { ... }|| Streaming RPC |callable({ streaming: true }) stream(res) { ... }|| Start workflow |await this.runWorkflow(ProcessingWorkflow, params)|React Clientimport { 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 }Referencesreferences/workflows.md- Durable Workflows integrationreferences/callable.md- RPC methods, streaming, timeoutsreferences/state-scheduling.md- State persistence, schedulingreferences/streaming-chat.md- AIChatAgent, resumable streamsreferences/mcp.md- MCP server integrationreferences/email.md- Email routing and handlingreferences/codemode.md- Code Mode (experimental)3e:[“ , ,,L40”,null,{“content”:“$41”,“frontMatter”:{“name”:“agents-sdk”,“description”:“Build AI agents on Cloudflare Workers using the Agents SDK. Load when creating stateful agents, durable workflows, real-time WebSocket apps, scheduled tasks, MCP servers, or chat applications. Covers Agent class, state management, callable RPC, Workflows integration, and React hooks.”}}]3f:[“KaTeX parse error: Expected }, got EOF at end of input: …,children:[[”,“div”,null,{“className”:“flex items-center justify-between border-b border-border bg-muted/30 px-4 py-2.5”,“children”:[[“KaTeX parse error: Expected }, got EOF at end of input: …,children:[”,“span”,null,{“className”:“truncate text-xs font-medium text-muted-foreground”,“children”:“同仓库更多 Skills”}]}],[“KaTeX parse error: Expected EOF, got } at position 88: …ldren:同仓库}]]}̲],[”,“div”,null,{“className”:“p-4 sm:p-5”,“children”:[[“ , h 2 , n u l l , i d : r e l a t e d − s k i l l s − h e a d i n g , c l a s s N a m e : t e x t − 2 x l f o n t − s e m i b o l d t r a c k i n g − n o r m a l t e x t − f o r e g r o u n d , c h i l d r e n : 同仓库更多 S k i l l s ] , [ ,h2,null,{id:related-skills-heading,className:text-2xl font-semibold tracking-normal text-foreground,children:同仓库更多 Skills}],[,h2,null,id:related−skills−heading,className:text−2xlfont−semiboldtracking−normaltext−foreground,children:同仓库更多Skills],[”,“div”,null,{“className”:“mt-4 grid gap-3 sm:grid-cols-2”,“children”:[“L 42 , L42,L42,L43”]}]]}]]}]44:I[206516,[“/_next/static/chunks/051aanbhrv4br.js”,“/_next/static/chunks/0mizr60h7ayzt.js”,“/_next/static/chunks/0v9lm1dmbdoo-.js”,“/_next/static/chunks/0rxr1j1j3j-.r.js”,“/_next/static/chunks/02ftybezfvqjd.js”,“/_next/static/chunks/0.v9ksvnnj8ia.js”,“/_next/static/chunks/0bn6id96nx3k.js,“/_next/static/chunks/13ybnhn37c.tc.js”,“/_next/static/chunks/0_fnrdtruz8uf.js”,“/_next/static/chunks/0r6l15utt1mwb.js”,“/_next/static/chunks/0dm9a5into854.js”,/_next/static/chunks/07k6hqoibtcn.js”,“/next/static/chunks/0b4cao.4y…j.js”,“/_next/static/chunks/02i-n28z7kjd0.js”],“default”]

相关新闻