用户和客户端可以通过 WebSockets 直接连接到 Agent,允许与您的 Agent 进行长时间运行的双向通信。
要使 Agent 能够接受 WebSockets,请在您的 Agent 上定义 onConnect
和 onMessage
方法。
onConnect(connection: Connection, ctx: ConnectionContext)
在客户端建立新的 WebSocket 连接时被调用。原始的 HTTP 请求,包括请求头、cookies 和 URL 本身,都可以在ctx.request
上获取。onMessage(connection: Connection, message: WSMessage)
为每个传入的 WebSocket 消息调用。消息是ArrayBuffer | ArrayBufferView | string
之一,您可以使用connection.send()
向客户端发送消息。您可以通过检查connection.id
来区分客户端连接,它对每个连接的客户端都是唯一的。
以下是一个回显收到的任何消息的 Agent 示例:
import { Agent, Connection } from "agents";
export class ChatAgent extends Agent { async onConnect(connection, ctx) { // 连接被 SDK 自动接受。 // 您也可以在这里用 connection.close() 显式关闭连接 // 在 ctx.request 上访问 Request 以检查头部、cookies 和 URL }
async onMessage(connection, message) { // const response = await longRunningAITask(message) await connection.send(message); }}
import { Agent, Connection } from "agents";
export class ChatAgent extends Agent { async onConnect(connection: Connection, ctx: ConnectionContext) { // 连接被 SDK 自动接受。 // 您也可以在这里用 connection.close() 显式关闭连接 // 在 ctx.request 上访问 Request 以检查头部、cookies 和 URL }
async onMessage(connection: Connection, message: WSMessage) { // const response = await longRunningAITask(message) await connection.send(message); }}
Agent 框架包含一个有用的辅助包,用于从客户端应用程序直接连接到您的 Agent(或其他 Agents)。导入 agents/client
,创建 AgentClient
实例并使用它连接到您的 Agent 实例:
import { AgentClient } from "agents/client";
const connection = new AgentClient({ agent: "dialogue-agent", name: "insight-seeker",});
connection.addEventListener("message", (event) => { console.log("接收到:", event.data);});
connection.send( JSON.stringify({ type: "inquiry", content: "您看到了什么模式?", }),);
import { AgentClient } from "agents/client";
const connection = new AgentClient({ agent: "dialogue-agent", name: "insight-seeker",});
connection.addEventListener("message", (event) => { console.log("接收到:", event.data);});
connection.send( JSON.stringify({ type: "inquiry", content: "您看到了什么模式?", }),);
基于 React 的应用程序可以导入 agents/react
并使用 useAgent
hook 直接连接到 Agent 实例:
import { useAgent } from "agents/react";
function AgentInterface() { const connection = useAgent({ agent: "dialogue-agent", name: "insight-seeker", onMessage: (message) => { console.log("收到理解:", message.data); }, onOpen: () => console.log("连接已建立"), onClose: () => console.log("连接已关闭"), });
const inquire = () => { connection.send( JSON.stringify({ type: "inquiry", content: "您收集了哪些洞察?", }), ); };
return ( <div className="agent-interface"> <button onClick={inquire}>寻求理解</button> </div> );}
import { useAgent } from "agents/react";
function AgentInterface() { const connection = useAgent({ agent: "dialogue-agent", name: "insight-seeker", onMessage: (message) => { console.log("收到理解:", message.data); }, onOpen: () => console.log("连接已建立"), onClose: () => console.log("连接已关闭"), });
const inquire = () => { connection.send( JSON.stringify({ type: "inquiry", content: "您收集了哪些洞察?", }) ); };
return ( <div className="agent-interface"> <button onClick={inquire}>寻求理解</button> </div> );}
useAgent
hook 自动处理连接的生命周期,确保在组件挂载和卸载时正确初始化和清理。您还可以将 useAgent
与 useState
结合使用,自动在连接到您的 Agent 的所有客户端之间同步状态。
在您的 Agent 上定义 onError
和 onClose
方法以显式处理 WebSocket 客户端错误和关闭事件。记录错误、清理状态和/或发出指标:
import { Agent, Connection } from "agents";
export class ChatAgent extends Agent { // onConnect 和 onMessage 方法 // ...
// WebSocket 错误和断开连接(关闭)处理。 async onError(connection, error) { console.error(`WS 错误: ${error}`); } async onClose(connection, code, reason, wasClean) { console.log(`WS 关闭: ${code} - ${reason} - wasClean: ${wasClean}`); connection.close(); }}
import { Agent, Connection } from "agents";
export class ChatAgent extends Agent { // onConnect 和 onMessage 方法 // ...
// WebSocket 错误和断开连接(关闭)处理。 async onError(connection: Connection, error: unknown): Promise<void> { console.error(`WS 错误: ${error}`); } async onClose( connection: Connection, code: number, reason: string, wasClean: boolean, ): Promise<void> { console.log(`WS 关闭: ${code} - ${reason} - wasClean: ${wasClean}`); connection.close(); }}
- @2025 Cloudflare Ubitools
- Cf Repo