随着 Vercel AI SDK 6 的发布,构建 AI Agent 变得前所未有的简单和规范。新的 ToolLoopAgent 类为我们提供了一种结构化的方式来封装 LLM 配置、工具(Tools)和行为。
如果你正在寻找一种方法来复用模型配置、统一 Agent 行为,或者希望在 Next.js/Node.js 项目中获得极致的 TypeScript 类型安全,那么这篇教程就是为你准备的。
本文将带你深入了解如何使用 ToolLoopAgent 构建一个具备多步推理能力的 AI Agent。
为什么选择 ToolLoopAgent?
在开发 AI 应用时,我们经常面临以下痛点:
- 配置重复:在不同的 API 路由中重复编写相同的 prompt 和模型参数。
- 状态管理复杂:手动处理“工具调用 -> 执行工具 -> 再次调用 LLM”的循环(Agent Loop)非常繁琐。
- 类型缺失:很难保证前端组件和后端 Agent 之间的消息类型一致。
ToolLoopAgent 完美解决了这些问题。它内置了自动循环机制,允许 LLM 连续多次调用工具以完成复杂任务。
1. 环境准备
确保你的项目中已经安装了 ai 和 zod:
Bash
npm install ai zod
2. 快速上手:定义你的第一个 Agent
我们首先创建一个基础的 Agent。ToolLoopAgent 允许你在一个地方统一定义模型和系统指令。
TypeScript
import { ToolLoopAgent } from 'ai';
// 定义一个通用的 Agent
const myAgent = new ToolLoopAgent({
// 指定模型,例如 Anthropic Claude 或 OpenAI GPT
model: "anthropic/claude-sonnet-4.5",
// 系统指令:赋予 Agent 角色
instructions: 'You are a helpful assistant.',
});
这个 myAgent 实例现在可以在你应用的任何地方被复用。
3. 赋予能力:添加工具 (Tools)
Agent 的核心在于使用工具。我们可以通过 tools 属性并结合 zod 来定义工具的输入结构。
以下是一个拥有“代码执行”能力的 Agent 示例:
TypeScript
import { ToolLoopAgent, tool } from 'ai';
import { z } from 'zod';
const codeAgent = new ToolLoopAgent({
model: "anthropic/claude-sonnet-4.5",
instructions: 'You are an expert software engineer.',
tools: {
runCode: tool({
description: 'Execute Python code',
inputSchema: z.object({
code: z.string().describe('The python code to execute'),
}),
execute: async ({ code }) => {
// 在这里编写实际的执行逻辑
console.log('Executing:', code);
return { output: 'Code executed successfully' };
},
}),
},
});
4. 掌控流程:循环控制 (Loop Control)
默认情况下,Agent 的运行步数可能有限制。对于需要多步推理(例如:搜索 -> 阅读 -> 总结)的任务,我们需要配置 stopWhen。
stepCountIs 帮助我们定义最大迭代次数:
TypeScript
import { ToolLoopAgent, stepCountIs } from 'ai';
const researchAgent = new ToolLoopAgent({
model: "anthropic/claude-sonnet-4.5",
// 允许 Agent 最多运行 20 个步骤
// 每一轮(生成文本或调用工具)算作一个步骤
stopWhen: stepCountIs(20),
tools: {
// 假设这里有一些搜索工具
}
});
5. 结构化输出 (Structured Output)
如果你的应用需要 JSON 格式的输出(例如用于填充 UI 组件),可以使用 output 属性强制 Agent 返回特定结构的数据。
TypeScript
import { ToolLoopAgent, Output, stepCountIs } from 'ai';
import { z } from 'zod';
const analysisAgent = new ToolLoopAgent({
model: "anthropic/claude-sonnet-4.5",
// 定义输出 Schema
output: Output.object({
schema: z.object({
sentiment: z.enum(['positive', 'neutral', 'negative']),
summary: z.string(),
keyPoints: z.array(z.string()),
}),
}),
stopWhen: stepCountIs(10),
});
// 使用示例
async function runAnalysis() {
const { output } = await analysisAgent.generate({
prompt: 'Analyze customer feedback from the last quarter',
});
// output 将严格符合上面的 Zod Schema,且由 TS 自动推断类型
console.log(output.sentiment);
}
6. 实战集成:在 Next.js API 中使用
定义好 Agent 后,最常见的场景是在 API 路由中提供服务。ToolLoopAgent 提供了极简的集成方式。
方式一:流式传输给前端 (UI Streams)
这是构建 Chatbot 最常用的方式,能够直接对接 AI SDK 的前端 Hooks。
TypeScript
// app/api/chat/route.ts
import { createAgentUIStreamResponse } from 'ai';
import { myAgent } from '@/agents/my-agent'; // 假设你在这个文件定义了 agent
export async function POST(request: Request) {
const { messages } = await request.json();
return createAgentUIStreamResponse({
agent: myAgent,
uiMessages: messages, // 直接传入前端发送的消息历史
});
}
方式二:服务端生成文本
如果你只需要在服务端获取结果:
TypeScript
const result = await myAgent.generate({
prompt: 'What is the weather like in Tokyo?',
});
console.log(result.text);
7. 进阶技巧:类型安全与监控
端到端类型安全 (End-to-end Type Safety)
AI SDK 允许你推断 Agent 的消息类型,确保前端 useChat 与后端完全同步。
TypeScript
// agent.ts
import { ToolLoopAgent, InferAgentUIMessage } from 'ai';
export const myAgent = new ToolLoopAgent({ ... });
// 导出类型
export type MyAgentUIMessage = InferAgentUIMessage<typeof myAgent>;
在前端组件中:
TypeScript
// components/chat.tsx
'use client';
import { useChat } from '@ai-sdk/react';
import type { MyAgentUIMessage } from '@/agent.ts';
export function Chat() {
// 泛型支持,获得完整的类型提示
const { messages } = useChat<MyAgentUIMessage>();
// ...
}
步骤追踪 (Tracking)
通过 onStepFinish 回调,你可以轻松监控 Token 消耗或记录 Agent 的思考过程。
TypeScript
const agent = new ToolLoopAgent({
model: "anthropic/claude-sonnet-4.5",
onStepFinish: async ({ usage, finishReason, toolCalls }) => {
// 全局日志记录
console.log(`Step used ${usage.totalTokens} tokens`);
if (toolCalls) {
console.log('Tools used:', toolCalls.map(tc => tc.toolName));
}
},
});
总结
ToolLoopAgent 是 AI SDK 中一个非常强大的抽象。它不再要求开发者手动管理复杂的对话循环,而是将重心回归到 Prompt 设计、工具定义 和 数据结构 上。
通过本文,你应该已经掌握了:
- 如何实例化一个 Agent。
- 如何添加 Zod 定义的工具。
- 如何控制 Agent 的推理循环。
- 如何在 Next.js 中快速部署 Agent API。
快去尝试重构你的 AI 应用吧!