[ PROMPT_NODE_23914 ]
Agents SDK API 参考
[ SKILL_DOCUMENTATION ]
# API 参考
## 智能体类
### AIChatAgent
用于支持自动流式传输、消息历史记录、工具调用及可恢复流的 AI 聊天。
ts
import { AIChatAgent } from "agents";
import { openai } from "@ai-sdk/openai";
export class ChatAgent extends AIChatAgent {
async onChatMessage(onFinish) {
return this.streamText({
model: openai("gpt-4"),
messages: this.messages, // 自动管理消息历史
tools: {
getWeather: {
description: "获取天气",
parameters: z.object({ city: z.string() }),
execute: async ({ city }) => `Sunny, 72°F in ${city}`
}
},
onFinish, // 将响应持久化到 this.messages
});
}
}
### Agent (基类)
为自定义逻辑、WebSocket、电子邮件和 SQL 提供完全控制。
ts
import { Agent } from "agents";
export class MyAgent extends Agent {
// 下面是生命周期方法
}
**类型参数:** `Agent` - 环境绑定、智能体状态、连接状态
## 生命周期钩子
ts
onStart() { // 初始化/重启
this.sql`CREATE TABLE IF NOT EXISTS users (id TEXT, name TEXT)`;
}
async onRequest(req: Request) { // HTTP
const {pathname} = new URL(req.url);
if (pathname === "/users") return Response.json(this.sql`SELECT * FROM users`);
return new Response("Not found", {status: 404});
}
async onConnect(conn: Connection, ctx: ConnectionContext) { // WebSocket
conn.accept();
conn.setState({userId: ctx.request.headers.get("X-User-ID")});
conn.send(JSON.stringify({type: "connected", state: this.state}));
}
async onMessage(conn: Connection, msg: WSMessage) { // WS 消息
const m = JSON.parse(msg as string);
this.setState({messages: [...this.state.messages, m]});
this.connections.forEach(c => c.send(JSON.stringify(m)));
}
async onEmail(email: AgentEmail) { // 邮件路由
this.sql`INSERT INTO emails (from_addr,subject,body) VALUES (${email.from},${email.headers.get("subject")},${await email.text()})`;
}
## 状态、SQL、调度
ts
// 状态
this.setState({count: 42}); // 自动同步
this.setState({...this.state, count: this.state.count + 1});
// SQL (参数化查询防止注入)
this.sql`CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, name TEXT)`;
this.sql`INSERT INTO users (id,name) VALUES (${userId},${name})`;
const users = this.sql`SELECT * FROM users WHERE id = ${userId}`;
// 调度
await this.schedule(new Date("2026-12-25"