Skip to content

🏗️ 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 自动执行:

  1. 调用 weather 工具获取华氏温度
  2. 调用 convertFahrenheitToCelsius 转换为摄氏度
  3. 生成最终的文本响应

为什么使用 ToolLoopAgent?

优势说明
减少样板代码自动管理循环和消息数组
提高复用性定义一次,在整个应用中使用
简化维护统一的配置管理点
类型安全完整的 TypeScript 支持

前端面试知识库