本页面提供了 Agent SDK API 的概述,包括 Agent
类、内置于 Agents SDK 的方法和属性。
Agents SDK 公开了两个主要 API:
- 服务器端
Agent
类。Agent 封装了 Agent 的所有逻辑,包括客户端如何连接到它、如何存储状态、它公开的方法、如何调用 AI 模型以及任何错误处理。 - 客户端
AgentClient
类,允许您从客户端应用程序连接到 Agent 实例。客户端 API 还包括 React hooks,包括useAgent
和useAgentChat
,并允许您在每个唯一的 Agent(运行在服务器端)和您的客户端应用程序之间自动同步状态。
您还可以在 Agents API 参考中找到每个 API 的更具体使用示例。
import { Agent } from "agents";
class MyAgent extends Agent { // 在 Agent 上定义方法}
export default MyAgent;
import { Agent } from "agents";
class MyAgent extends Agent { // 在 Agent 上定义方法}
export default MyAgent;
一个 Agent 可以有许多(数百万个)实例:每个实例都是一个独立运行的独立微服务器。这允许 Agents 水平扩展:一个 Agent 可以与单个用户关联,或与数千个用户关联,这取决于您正在构建的 Agent。
Agent 的实例通过唯一标识符寻址:该标识符(ID)可以是用户 ID、电子邮件地址、GitHub 用户名、航班机票号码、发票 ID,或任何其他有助于唯一标识实例并代表谁行动的标识符。
编写 Agent 需要您定义一个扩展 Agents SDK 包中 Agent
类的类。Agent 封装了 Agent 的所有逻辑,包括客户端如何连接到它、如何存储状态、它公开的方法以及任何错误处理。
您还可以在 Agent 上定义自己的方法:从技术上讲,发布一个只公开您自己方法的 Agent 是有效的,并直接从 Worker 创建/获取 Agents。
您自己的方法可以通过 this.env
访问 Agent 的环境变量和绑定,通过 this.setState
访问状态,并通过 this.yourMethodName
调用 Agent 上的其他方法。
import { Agent } from "agents";
interface Env { // 在这里定义环境变量和绑定}
// 将 Env 作为 TypeScript 类型参数传递// 作为绑定连接到您的 Agent 或 Worker 的任何服务// 然后在 this.env.<BINDING_NAME> 上可用
// 用于创建可以维护状态、编排的 Agents 的核心类// 复杂的 AI 工作流、调度任务,并与用户和其他 Agents 交互。class MyAgent extends Agent<Env, State> { // 可选的初始状态定义 initialState = { counter: 0, messages: [], lastUpdated: null, };
// 当新的 Agent 实例启动或从休眠中唤醒时调用 async onStart() { console.log("Agent 已启动,状态:", this.state); }
// 处理来到此 Agent 实例的 HTTP 请求 // 返回 Response 对象 async onRequest(request: Request): Promise<Response> { return new Response("来自 Agent 的问候!"); }
// 当建立 WebSocket 连接时调用 // 通过 ctx.request 访问原始请求进行身份验证等 async onConnect(connection: Connection, ctx: ConnectionContext) { // 连接被 SDK 自动接受。 // 您也可以在这里用 connection.close() 显式关闭连接 // 在 ctx.request 上访问 Request 以检查头部、cookies 和 URL }
// 为在 WebSocket 连接上接收的每条消息调用 // 消息可以是 string、ArrayBuffer 或 ArrayBufferView async onMessage(connection: Connection, message: WSMessage) { // 处理传入消息 connection.send("已收到您的消息"); }
// 处理 WebSocket 连接错误 async onError(connection: Connection, error: unknown): Promise<void> { console.error(`连接错误:`, error); }
// 处理 WebSocket 连接关闭事件 async onClose( connection: Connection, code: number, reason: string, wasClean: boolean, ): Promise<void> { console.log(`连接已关闭: ${code} - ${reason}`); }
// 当 Agent 的状态从任何源更新时调用 // source 可以是 "server" 或客户端 Connection onStateUpdate(state: State, source: "server" | Connection) { console.log("状态已更新:", state, "来源:", source); }
// 您可以定义自己的自定义方法,由请求、 // WebSocket 消息或调度任务调用 async customProcessingMethod(data: any) { // 处理数据、更新状态、调度任务等 this.setState({ ...this.state, lastUpdated: new Date() }); }}
// 带有自定义方法的基本 Agent 实现import { Agent } from "agents";
class MyAgent extends Agent { initialState = { counter: 0, lastUpdated: null, };
async onRequest(request) { if (request.method === "POST") { await this.incrementCounter(); return new Response(JSON.stringify(this.state), { headers: { "Content-Type": "application/json" }, }); } return new Response(JSON.stringify(this.state), { headers: { "Content-Type": "application/json" }, }); }
async incrementCounter() { this.setState({ counter: this.state.counter + 1, lastUpdated: new Date(), }); }}
// 带有自定义方法的基本 Agent 实现import { Agent } from "agents";
interface MyState { counter: number; lastUpdated: Date | null;}
class MyAgent extends Agent<Env, MyState> { initialState = { counter: 0, lastUpdated: null, };
async onRequest(request: Request) { if (request.method === "POST") { await this.incrementCounter(); return new Response(JSON.stringify(this.state), { headers: { "Content-Type": "application/json" }, }); } return new Response(JSON.stringify(this.state), { headers: { "Content-Type": "application/json" }, }); }
async incrementCounter() { this.setState({ counter: this.state.counter + 1, lastUpdated: new Date(), }); }}
WebSocket API 允许您接受和管理与 Agent 的 WebSocket 连接。
表示与 Agent 的 WebSocket 连接。
// WebSocket 连接接口interface Connection<State = unknown> { // 此连接的唯一 ID id: string;
// 附加到此连接的客户端特定状态 state: State;
// 更新连接的状态 setState(state: State): void;
// 接受传入的 WebSocket 连接 accept(): void;
// 使用可选代码和原因关闭 WebSocket 连接 close(code?: number, reason?: string): void;
// 向客户端发送消息 // 可以是 string、ArrayBuffer 或 ArrayBufferView send(message: string | ArrayBuffer | ArrayBufferView): void;}
// Example of handling WebSocket messagesexport class YourAgent extends Agent { async onMessage(connection, message) { if (typeof message === "string") { try { // Parse JSON message const data = JSON.parse(message);
if (data.type === "update") { // Update connection-specific state connection.setState({ ...connection.state, lastActive: Date.now() });
// Update global Agent state this.setState({ ...this.state, connections: this.state.connections + 1, });
// Send response back to this client only connection.send( JSON.stringify({ type: "updated", status: "success", }), ); } } catch (e) { connection.send(JSON.stringify({ error: "Invalid message format" })); } } }}
// Example of handling WebSocket messagesexport class YourAgent extends Agent { async onMessage(connection: Connection, message: WSMessage) { if (typeof message === "string") { try { // Parse JSON message const data = JSON.parse(message);
if (data.type === "update") { // Update connection-specific state connection.setState({ ...connection.state, lastActive: Date.now() });
// Update global Agent state this.setState({ ...this.state, connections: this.state.connections + 1, });
// Send response back to this client only connection.send( JSON.stringify({ type: "updated", status: "success", }), ); } } catch (e) { connection.send(JSON.stringify({ error: "Invalid message format" })); } } }}
Types of messages that can be received from a WebSocket.
// Types of messages that can be received from WebSocketstype WSMessage = string | ArrayBuffer | ArrayBufferView;
Context information for a WebSocket connection.
// Context available during WebSocket connectioninterface ConnectionContext { // The original HTTP request that initiated the WebSocket connection request: Request;}
Methods and types for managing Agent state.
// State management in the Agent classclass Agent<Env, State = unknown> { // Initial state that will be set if no state exists yet initialState: State = {} as unknown as State;
// Current state of the Agent, persisted across restarts get state(): State;
// Update the Agent's state // Persists to storage and notifies all connected clients setState(state: State): void;
// Called when state is updated from any source // Override to react to state changes onStateUpdate(state: State, source: "server" | Connection): void;}
// Example of state management in an Agent
// Inside your Agent classexport class YourAgent extends Agent { async addMessage(sender, text) { // Update state with new message this.setState({ ...this.state, messages: [ ...this.state.messages, { sender, text, timestamp: Date.now() }, ].slice(-this.state.settings.maxHistoryLength), // Maintain max history });
// The onStateUpdate method will automatically be called // and all connected clients will receive the update }
// Override onStateUpdate to add custom behavior when state changes onStateUpdate(state, source) { console.log( `State updated by ${source === "server" ? "server" : "client"}`, );
// You could trigger additional actions based on state changes if (state.messages.length > 0) { const lastMessage = state.messages[state.messages.length - 1]; if (lastMessage.text.includes("@everyone")) { this.notifyAllParticipants(lastMessage); } } }}
// Example of state management in an Agentinterface ChatState { messages: Array<{ sender: string; text: string; timestamp: number }>; participants: string[]; settings: { allowAnonymous: boolean; maxHistoryLength: number; };}
interface Env { // Your bindings and environment variables}
// Inside your Agent classexport class YourAgent extends Agent<Env, ChatState> { async addMessage(sender: string, text: string) { // Update state with new message this.setState({ ...this.state, messages: [ ...this.state.messages, { sender, text, timestamp: Date.now() }, ].slice(-this.state.settings.maxHistoryLength), // Maintain max history });
// The onStateUpdate method will automatically be called // and all connected clients will receive the update }
// Override onStateUpdate to add custom behavior when state changes onStateUpdate(state: ChatState, source: "server" | Connection) { console.log( `State updated by ${source === "server" ? "server" : "client"}`, );
// You could trigger additional actions based on state changes if (state.messages.length > 0) { const lastMessage = state.messages[state.messages.length - 1]; if (lastMessage.text.includes("@everyone")) { this.notifyAllParticipants(lastMessage); } } }}
Schedule tasks to run at a specified time in the future.
// Scheduling API for running tasks in the futureclass Agent<Env, State = unknown> { // Schedule a task to run in the future // when: seconds from now, specific Date, or cron expression // callback: method name on the Agent to call // payload: data to pass to the callback // Returns a Schedule object with the task ID async schedule<T = any>( when: Date | string | number, callback: keyof this, payload?: T, ): Promise<Schedule<T>>;
// Get a scheduled task by ID // Returns undefined if the task doesn't exist async getSchedule<T = any>(id: string): Promise<Schedule<T> | undefined>;
// Get all scheduled tasks matching the criteria // Returns an array of Schedule objects getSchedules<T = any>(criteria?: { description?: string; id?: string; type?: "scheduled" | "delayed" | "cron"; timeRange?: { start?: Date; end?: Date }; }): Schedule<T>[];
// Cancel a scheduled task by ID // Returns true if the task was cancelled, false otherwise async cancelSchedule(id: string): Promise<boolean>;}
// Example of scheduling in an Agent
export class YourAgent extends Agent { // Schedule a one-time reminder in 2 hours async scheduleReminder(userId, message) { const twoHoursFromNow = new Date(Date.now() + 2 * 60 * 60 * 1000);
const schedule = await this.schedule(twoHoursFromNow, "sendReminder", { userId, message, channel: "email", });
console.log(`Scheduled reminder with ID: ${schedule.id}`); return schedule.id; }
// Schedule a recurring daily task using cron async scheduleDailyReport() { // Run at 08:00 AM every day const schedule = await this.schedule( "0 8 * * *", // Cron expression: minute hour day month weekday "generateDailyReport", { reportType: "daily-summary" }, );
console.log(`Scheduled daily report with ID: ${schedule.id}`); return schedule.id; }
// Method that will be called when the scheduled task runs async sendReminder(data) { console.log(`Sending reminder to ${data.userId}: ${data.message}`); // Add code to send the actual notification }}
// Example of scheduling in an Agentinterface ReminderData { userId: string; message: string; channel: string;}
export class YourAgent extends Agent { // Schedule a one-time reminder in 2 hours async scheduleReminder(userId: string, message: string) { const twoHoursFromNow = new Date(Date.now() + 2 * 60 * 60 * 1000);
const schedule = await this.schedule<ReminderData>( twoHoursFromNow, "sendReminder", { userId, message, channel: "email" }, );
console.log(`Scheduled reminder with ID: ${schedule.id}`); return schedule.id; }
// Schedule a recurring daily task using cron async scheduleDailyReport() { // Run at 08:00 AM every day const schedule = await this.schedule( "0 8 * * *", // Cron expression: minute hour day month weekday "generateDailyReport", { reportType: "daily-summary" }, );
console.log(`Scheduled daily report with ID: ${schedule.id}`); return schedule.id; }
// Method that will be called when the scheduled task runs async sendReminder(data: ReminderData) { console.log(`Sending reminder to ${data.userId}: ${data.message}`); // Add code to send the actual notification }}
Represents a scheduled task.
// Represents a scheduled tasktype Schedule<T = any> = { // Unique identifier for the schedule id: string; // Name of the method to be called callback: string; // Data to be passed to the callback payload: T;} & ( | { // One-time execution at a specific time type: "scheduled"; // Timestamp when the task should execute time: number; } | { // Delayed execution after a certain time type: "delayed"; // Timestamp when the task should execute time: number; // Number of seconds to delay execution delayInSeconds: number; } | { // Recurring execution based on cron expression type: "cron"; // Timestamp for the next execution time: number; // Cron expression defining the schedule cron: string; });
export class YourAgent extends Agent { // Example of managing scheduled tasks async viewAndManageSchedules() { // Get all scheduled tasks const allSchedules = this.getSchedules(); console.log(`Total scheduled tasks: ${allSchedules.length}`);
// Get tasks scheduled for a specific time range const upcomingSchedules = this.getSchedules({ timeRange: { start: new Date(), end: new Date(Date.now() + 24 * 60 * 60 * 1000), // Next 24 hours }, });
// Get a specific task by ID const taskId = "task-123"; const specificTask = await this.getSchedule(taskId);
if (specificTask) { console.log( `Found task: ${specificTask.callback} at ${new Date(specificTask.time)}`, );
// Cancel a scheduled task const cancelled = await this.cancelSchedule(taskId); console.log(`Task cancelled: ${cancelled}`); } }}
export class YourAgent extends Agent { // Example of managing scheduled tasks async viewAndManageSchedules() { // Get all scheduled tasks const allSchedules = this.getSchedules(); console.log(`Total scheduled tasks: ${allSchedules.length}`);
// Get tasks scheduled for a specific time range const upcomingSchedules = this.getSchedules({ timeRange: { start: new Date(), end: new Date(Date.now() + 24 * 60 * 60 * 1000), // Next 24 hours }, });
// Get a specific task by ID const taskId = "task-123"; const specificTask = await this.getSchedule(taskId);
if (specificTask) { console.log( `Found task: ${specificTask.callback} at ${new Date(specificTask.time)}`, );
// Cancel a scheduled task const cancelled = await this.cancelSchedule(taskId); console.log(`Task cancelled: ${cancelled}`); } }}
Each Agent instance has an embedded SQLite database that can be accessed using the this.sql
method within any method on your Agent
class.
Execute SQL queries against the Agent's built-in SQLite database using the this.sql
method within any method on your Agent
class.
// SQL query API for the Agent's embedded databaseclass Agent<Env, State = unknown> { // Execute a SQL query with tagged template literals // Returns an array of rows matching the query sql<T = Record<string, string | number | boolean | null>>( strings: TemplateStringsArray, ...values: (string | number | boolean | null)[] ): T[];}
// Example of using SQL in an Agent
export class YourAgent extends Agent { async setupDatabase() { // Create a table if it doesn't exist this.sql` CREATE TABLE IF NOT EXISTS users ( id TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE, created_at INTEGER ) `; }
async createUser(id, name, email) { // Insert a new user this.sql` INSERT INTO users (id, name, email, created_at) VALUES (${id}, ${name}, ${email}, ${Date.now()}) `; }
async getUserById(id) { // Query a user by ID const users = this.sql` SELECT * FROM users WHERE id = ${id} `;
return users.length ? users[0] : null; }
async searchUsers(term) { // Search users with a wildcard return this.sql` SELECT * FROM users WHERE name LIKE ${"%" + term + "%"} OR email LIKE ${"%" + term + "%"} ORDER BY created_at DESC `; }}
// Example of using SQL in an Agentinterface User { id: string; name: string; email: string; created_at: number;}
export class YourAgent extends Agent { async setupDatabase() { // Create a table if it doesn't exist this.sql` CREATE TABLE IF NOT EXISTS users ( id TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE, created_at INTEGER ) `; }
async createUser(id: string, name: string, email: string) { // Insert a new user this.sql` INSERT INTO users (id, name, email, created_at) VALUES (${id}, ${name}, ${email}, ${Date.now()}) `; }
async getUserById(id: string): Promise<User | null> { // Query a user by ID const users = this.sql<User>` SELECT * FROM users WHERE id = ${id} `;
return users.length ? users[0] : null; }
async searchUsers(term: string): Promise<User[]> { // Search users with a wildcard return this.sql<User>` SELECT * FROM users WHERE name LIKE ${"%" + term + "%"} OR email LIKE ${"%" + term + "%"} ORDER BY created_at DESC `; }}
The Agents SDK provides a set of client APIs for interacting with Agents from client-side JavaScript code, including:
- React hooks, including
useAgent
anduseAgentChat
, for connecting to Agents from client applications. - Client-side state syncing that allows you to subscribe to state updates between the Agent and any connected client(s) when calling
this.setState
within your Agent's code. - The ability to call remote methods (Remote Procedure Calls; RPC) on the Agent from client-side JavaScript code using the
@callable
method decorator.
Client for connecting to an Agent from the browser.
import { AgentClient } from "agents/client";
// Options for creating an AgentClienttype AgentClientOptions = Omit<PartySocketOptions, "party" | "room"> & { // Name of the agent to connect to (class name in kebab-case) agent: string; // Name of the specific Agent instance (optional, defaults to "default") name?: string; // Other WebSocket options like host, protocol, etc.};
// WebSocket client for connecting to an Agentclass AgentClient extends PartySocket { static fetch(opts: PartyFetchOptions): Promise<Response>; constructor(opts: AgentClientOptions);}
// Example of using AgentClient in the browserimport { AgentClient } from "agents/client";
// Connect to an Agent instanceconst client = new AgentClient({ agent: "chat-agent", // Name of your Agent class in kebab-case name: "support-room-123", // Specific instance name host: window.location.host, // Using same host});
client.onopen = () => { console.log("Connected to agent"); // Send an initial message client.send(JSON.stringify({ type: "join", user: "user123" }));};
client.onmessage = (event) => { // Handle incoming messages const data = JSON.parse(event.data); console.log("Received:", data);
if (data.type === "state_update") { // Update local UI with new state updateUI(data.state); }};
client.onclose = () => console.log("Disconnected from agent");
// Send messages to the Agentfunction sendMessage(text) { client.send( JSON.stringify({ type: "message", text, timestamp: Date.now(), }), );}
// Example of using AgentClient in the browserimport { AgentClient } from "agents/client";
// Connect to an Agent instanceconst client = new AgentClient({ agent: "chat-agent", // Name of your Agent class in kebab-case name: "support-room-123", // Specific instance name host: window.location.host, // Using same host});
client.onopen = () => { console.log("Connected to agent"); // Send an initial message client.send(JSON.stringify({ type: "join", user: "user123" }));};
client.onmessage = (event) => { // Handle incoming messages const data = JSON.parse(event.data); console.log("Received:", data);
if (data.type === "state_update") { // Update local UI with new state updateUI(data.state); }};
client.onclose = () => console.log("Disconnected from agent");
// Send messages to the Agentfunction sendMessage(text) { client.send( JSON.stringify({ type: "message", text, timestamp: Date.now(), }), );}
Make an HTTP request to an Agent.
import { agentFetch } from "agents/client";
// Options for the agentFetch functiontype AgentClientFetchOptions = Omit<PartyFetchOptions, "party" | "room"> & { // Name of the agent to connect to agent: string; // Name of the specific Agent instance (optional) name?: string;};
// Make an HTTP request to an Agentfunction agentFetch( opts: AgentClientFetchOptions, init?: RequestInit,): Promise<Response>;
// Example of using agentFetch in the browserimport { agentFetch } from "agents/client";
// Function to get data from an Agentasync function fetchAgentData() { try { const response = await agentFetch( { agent: "task-manager", name: "user-123-tasks", }, { method: "GET", headers: { Authorization: `Bearer ${userToken}`, }, }, );
if (!response.ok) { throw new Error(`Error: ${response.status}`); }
const data = await response.json(); return data; } catch (error) { console.error("Failed to fetch from agent:", error); }}
// Example of using agentFetch in the browserimport { agentFetch } from "agents/client";
// Function to get data from an Agentasync function fetchAgentData() { try { const response = await agentFetch( { agent: "task-manager", name: "user-123-tasks", }, { method: "GET", headers: { Authorization: `Bearer ${userToken}`, }, }, );
if (!response.ok) { throw new Error(`Error: ${response.status}`); }
const data = await response.json(); return data; } catch (error) { console.error("Failed to fetch from agent:", error); }}
The Agents SDK provides a React API for simplifying connection and routing to Agents from front-end frameworks, including React Router (Remix), Next.js, and Astro.
React hook for connecting to an Agent.
import { useAgent } from "agents/react";
// Options for the useAgent hooktype UseAgentOptions<State = unknown> = Omit< Parameters<typeof usePartySocket>[0], "party" | "room"> & { // Name of the agent to connect to agent: string; // Name of the specific Agent instance (optional) name?: string; // Called when the Agent's state is updated onStateUpdate?: (state: State, source: "server" | "client") => void;};
// React hook for connecting to an Agent// Returns a WebSocket connection with setState methodfunction useAgent<State = unknown>( options: UseAgentOptions<State>,): PartySocket & { // Update the Agent's state setState: (state: State) => void;};
The Agents SDK exposes an AIChatAgent
class that extends the Agent
class and exposes an onChatMessage
method that simplifies building interactive chat agents.
You can combine this with the useAgentChat
React hook from the agents/ai-react
package to manage chat state and messages between a user and your Agent(s).
Extension of the Agent
class with built-in chat capabilities.
import { AIChatAgent } from "agents/ai-chat-agent";import { Message, StreamTextOnFinishCallback, ToolSet } from "ai";
// Base class for chat-specific agentsclass AIChatAgent<Env = unknown, State = unknown> extends Agent<Env, State> { // Array of chat messages for the current conversation messages: Message[];
// Handle incoming chat messages and generate a response // onFinish is called when the response is complete async onChatMessage( onFinish: StreamTextOnFinishCallback<ToolSet>, ): Promise<Response | undefined>;
// Persist messages within the Agent's local storage. async saveMessages(messages: Message[]): Promise<void>;}
// Example of extending AIChatAgentimport { AIChatAgent } from "agents/ai-chat-agent";import { Message } from "ai";
class CustomerSupportAgent extends AIChatAgent { // Override the onChatMessage method to customize behavior async onChatMessage(onFinish) { // Access the AI models using environment bindings const { openai } = this.env.AI;
// Get the current conversation history const chatHistory = this.messages;
// Generate a system prompt based on knowledge base const systemPrompt = await this.generateSystemPrompt();
// Generate a response stream const stream = await openai.chat({ model: "gpt-4o", messages: [{ role: "system", content: systemPrompt }, ...chatHistory], stream: true, });
// Return the streaming response return new Response(stream, { headers: { "Content-Type": "text/event-stream" }, }); }
// Helper method to generate a system prompt async generateSystemPrompt() { // Query knowledge base or use static prompt return `You are a helpful customer support agent. Respond to customer inquiries based on the following guidelines: - Be friendly and professional - If you don't know an answer, say so - Current company policies: ...`; }}
// Example of extending AIChatAgentimport { AIChatAgent } from "agents/ai-chat-agent";import { Message } from "ai";
interface Env { AI: any; // Your AI binding}
class CustomerSupportAgent extends AIChatAgent<Env> { // Override the onChatMessage method to customize behavior async onChatMessage(onFinish) { // Access the AI models using environment bindings const { openai } = this.env.AI;
// Get the current conversation history const chatHistory = this.messages;
// Generate a system prompt based on knowledge base const systemPrompt = await this.generateSystemPrompt();
// Generate a response stream const stream = await openai.chat({ model: "gpt-4o", messages: [{ role: "system", content: systemPrompt }, ...chatHistory], stream: true, });
// Return the streaming response return new Response(stream, { headers: { "Content-Type": "text/event-stream" }, }); }
// Helper method to generate a system prompt async generateSystemPrompt() { // Query knowledge base or use static prompt return `You are a helpful customer support agent. Respond to customer inquiries based on the following guidelines: - Be friendly and professional - If you don't know an answer, say so - Current company policies: ...`; }}
React hook for building AI chat interfaces using an Agent.
import { useAgentChat } from "agents/ai-react";import { useAgent } from "agents/react";import type { Message } from "ai";
// Options for the useAgentChat hooktype UseAgentChatOptions = Omit< Parameters<typeof useChat>[0] & { // Agent connection from useAgent agent: ReturnType<typeof useAgent>; }, "fetch">;
// React hook for building AI chat interfaces using an Agentfunction useAgentChat(options: UseAgentChatOptions): { // Current chat messages messages: Message[]; // Set messages and synchronize with the Agent setMessages: (messages: Message[]) => void; // Clear chat history on both client and Agent clearHistory: () => void; // Append a new message to the conversation append: ( message: Message, chatRequestOptions?: any, ) => Promise<string | null | undefined>; // Reload the last user message reload: (chatRequestOptions?: any) => Promise<string | null | undefined>; // Stop the AI response generation stop: () => void; // Current input text input: string; // Set the input text setInput: React.Dispatch<React.SetStateAction<string>>; // Handle input changes handleInputChange: ( e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, ) => void; // Submit the current input handleSubmit: ( event?: { preventDefault?: () => void }, chatRequestOptions?: any, ) => void; // Additional metadata metadata?: Object; // Whether a response is currently being generated isLoading: boolean; // Current status of the chat status: "submitted" | "streaming" | "ready" | "error"; // Tool data from the AI response data?: any[]; // Set tool data setData: ( data: any[] | undefined | ((data: any[] | undefined) => any[] | undefined), ) => void; // Unique ID for the chat id: string; // Add a tool result for a specific tool call addToolResult: ({ toolCallId, result, }: { toolCallId: string; result: any; }) => void; // Current error if any error: Error | undefined;};
// Example of using useAgentChat in a React componentimport { useAgentChat } from "agents/ai-react";import { useAgent } from "agents/react";import { useState } from "react";
function ChatInterface() { // Connect to the chat agent const agentConnection = useAgent({ agent: "customer-support", name: "session-12345", });
// Use the useAgentChat hook with the agent connection const { messages, input, handleInputChange, handleSubmit, isLoading, error, clearHistory, } = useAgentChat({ agent: agentConnection, initialMessages: [ { role: "system", content: "You're chatting with our AI assistant." }, { role: "assistant", content: "Hello! How can I help you today?" }, ], });
return ( <div className="chat-container"> <div className="message-history"> {messages.map((message, i) => ( <div key={i} className={`message ${message.role}`}> {message.role === "user" ? "👤" : "🤖"} {message.content} </div> ))}
{isLoading && <div className="loading">AI is typing...</div>} {error && <div className="error">Error: {error.message}</div>} </div>
<form onSubmit={handleSubmit} className="message-input"> <input value={input} onChange={handleInputChange} placeholder="Type your message..." disabled={isLoading} /> <button type="submit" disabled={isLoading || !input.trim()}> Send </button> <button type="button" onClick={clearHistory}> Clear Chat </button> </form> </div> );}
// Example of using useAgentChat in a React componentimport { useAgentChat } from "agents/ai-react";import { useAgent } from "agents/react";import { useState } from "react";
function ChatInterface() { // Connect to the chat agent const agentConnection = useAgent({ agent: "customer-support", name: "session-12345", });
// Use the useAgentChat hook with the agent connection const { messages, input, handleInputChange, handleSubmit, isLoading, error, clearHistory, } = useAgentChat({ agent: agentConnection, initialMessages: [ { role: "system", content: "You're chatting with our AI assistant." }, { role: "assistant", content: "Hello! How can I help you today?" }, ], });
return ( <div className="chat-container"> <div className="message-history"> {messages.map((message, i) => ( <div key={i} className={`message ${message.role}`}> {message.role === "user" ? "👤" : "🤖"} {message.content} </div> ))}
{isLoading && <div className="loading">AI is typing...</div>} {error && <div className="error">Error: {error.message}</div>} </div>
<form onSubmit={handleSubmit} className="message-input"> <input value={input} onChange={handleInputChange} placeholder="Type your message..." disabled={isLoading} /> <button type="submit" disabled={isLoading || !input.trim()}> Send </button> <button type="button" onClick={clearHistory}> Clear Chat </button> </form> </div> );}
- Build a chat Agent using the Agents SDK and deploy it to Workers.
- Learn more using WebSockets to build interactive Agents and stream data back from your Agent.
- Orchestrate asynchronous workflows from your Agent by combining the Agents SDK and Workflows.
- @2025 Cloudflare Ubitools
- Cf Repo