# 模式与用例
## 带工具的 AI 聊天
**服务端 (AIChatAgent):**
ts
import { AIChatAgent } from "agents";
import { openai } from "@ai-sdk/openai";
import { tool } from "ai";
import { z } from "zod";
export class ChatAgent extends AIChatAgent {
async onChatMessage(onFinish) {
return this.streamText({
model: openai("gpt-4"),
messages: this.messages, // 自动管理
tools: {
getWeather: tool({
description: "获取当前天气",
parameters: z.object({ city: z.string() }),
execute: async ({ city }) => `Weather in ${city}: Sunny, 72°F`
}),
searchDocs: tool({
description: "搜索文档",
parameters: z.object({ query: z.string() }),
execute: async ({ query }) => JSON.stringify(
this.sql`SELECT title, content FROM docs WHERE content LIKE ${'%' + query + '%'}`
)
})
},
onFinish,
});
}
}
**客户端 (React):**
tsx
import { useAgent } from "agents/react";
import { useAgentChat } from "agents/ai-react";
function ChatUI() {
const agent = useAgent({ agent: "ChatAgent" });
const { messages, input, handleInputChange, handleSubmit, isLoading } = useAgentChat({ agent });
return (
{messages.map(m =>
{m.role}: {m.content}
)}
);
}
## 人机协作 (客户端工具)
服务端定义工具,客户端执行:
ts
// 服务端
export class ChatAgent extends AIChatAgent {
async onChatMessage(onFinish) {
return this.streamText({
model: openai("gpt-4"),
messages: this.messages,
tools: {
confirmAction: tool({
description: "请求用户确认",
parameters: z.object({ action: z.string() }),
execute: "client", // 客户端执行
})
},
onFinish,
});
}
}
// 客户端
const { messages } = useAgentChat({
agent,
onToolCall: async (toolCall) => {
if (toolCall.toolName === "confirmAction") {
return { confirmed: window.confirm(`Confirm: ${toolCall.args.action}?`) };
}
}
});
## 任务队列与调度处理
ts
export class TaskAgent extends Agent {
onStart() {
this.schedule("*/5 * * * *", "processQueue", {}); // Eve