🏗️ ToolLoopAgent 类
ToolLoopAgent 类是 AI SDK 构建 Agent 的推荐方法,它封装了 LLM 配置、工具和行为,自动处理 Agent 循环。
基础示例
typescript
import { ToolLoopAgent, tool } from 'ai';
import { z } from 'zod';
const weatherAgent = new ToolLoopAgent({
model: "anthropic/claude-sonnet-4.5",
tools: {
weather: tool({
description: 'Get the weather in a location (in Fahrenheit)',
inputSchema: z.object({
location: z.string().describe('The location to get the weather for'),
}),
execute: async ({ location }) => ({
location,
temperature: 72 + Math.floor(Math.random() * 21) - 10,
}),
}),
convertFahrenheitToCelsius: tool({
description: 'Convert temperature from Fahrenheit to Celsius',
inputSchema: z.object({
temperature: z.number().describe('Temperature in Fahrenheit'),
}),
execute: async ({ temperature }) => {
const celsius = Math.round((temperature - 32) * (5 / 9));
return { celsius };
},
}),
},
});
const result = await weatherAgent.generate({
prompt: 'What is the weather in San Francisco in celsius?',
});
console.log(result.text); // Agent 的最终回答
console.log(result.steps); // Agent 执行的步骤Agent 自动执行:
- 调用
weather工具获取华氏温度 - 调用
convertFahrenheitToCelsius转换为摄氏度 - 生成最终的文本响应
为什么使用 ToolLoopAgent?
| 优势 | 说明 |
|---|---|
| 减少样板代码 | 自动管理循环和消息数组 |
| 提高复用性 | 定义一次,在整个应用中使用 |
| 简化维护 | 统一的配置管理点 |
| 类型安全 | 完整的 TypeScript 支持 |