TodayAI

GuidesAgents

用 Vercel AI SDK 完成 Tool Calling

按 AI SDK Core Tool Calling:用 tool() 定义 schema 与 execute,在 generateText 里启用多步 stopWhen,完成天气查询一类闭环。

基于 Vercel AI SDK 整理 · 官方资料 ↗

Tool Calling 让模型在需要时请求执行你定义的函数。工具包含 description、inputSchema,以及可选的 execute。

这篇按官方示例:定义 weather 工具,用 generateText + stopWhen 跑通「调用工具 → 拿结果 → 继续生成」的多步闭环。

定义一个 Tool

用 tool() 帮助推断 execute 参数类型。inputSchema 可用 Zod。

官方 weather tool + generateText

typescript
import { z } from 'zod';
import { generateText, tool, isStepCount } from 'ai';

const result = await generateText({
  model: 'xai/grok-4.5',
  tools: {
    weather: tool({
      description: 'Get the weather in a location',
      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,
      }),
    }),
  },
  stopWhen: isStepCount(5),
  prompt: 'What is the weather in San Francisco?',
});

一次调用里发生了什么

  • 模型可能生成普通文本,或生成 tool call
  • 若提供了 execute,SDK 在服务端执行并得到 tool result
  • 需要模型基于结果再回答时,用 stopWhen 打开多步循环

默认单次生成在发出 tool call 后就结束该步。stopWhen: isStepCount(5) 表示最多继续若干步,直到没有新的 tool call 或达到上限。

用 stopWhen 做多步

典型两步:第一步模型决定调 weather;第二步把 tool result 送回模型,生成面向用户的回答。

内置条件还包括 hasToolCall(...names)。也可组合多个条件。strict: true 可在支持的 provider 上强制参数符合 schema。

检查 toolCalls 与最终文本

查看结果字段

typescript
console.log(result.text);
console.log(result.toolCalls);
console.log(result.toolResults);
console.log(result.steps.length);

若 execute 省略,你可以把 tool call 转发到客户端或队列自行执行,再把结果塞回后续消息。

容易踩的坑

只有 tool call,没有最终自然语言回答

设置 stopWhen(如 isStepCount),让 SDK 在 tool result 之后继续生成。

参数总是不对

给 inputSchema 字段写 describe;必要时开 strict,并检查 Zod schema 是否过宽。

敏感操作被自动执行

使用官方 toolApproval 流程,对高风险工具要求用户批准后再 execute。

官方资料

Vercel AI SDK

Tool Calling