使用 Vercel AI SDK 构建你的第一个智能体
一起构建一个 AI 智能体,学习如何通过 Vercel AI SDK 让 LLM 根据工具调用结果继续响应。
本页目录
上一个示例展示了 LLM 如何调用工具,在现实环境中执行操作。
但它们能做得更多:根据工具返回的信息继续作出反应。
这会形成一个强大的反馈循环,让 LLM 持续以现实世界的信息为依据。
包括 Anthropic 在内的大多数人,都把这种反馈循环称为智能体。
Vercel AI SDK 通过一个名为 steps 的概念,让实现过程非常简单。
我们将创建一个智能体,用来查询指定城市的当前天气。
滚动式代码讲解
首先创建一个 getWeather 工具。
先为工具提供描述和一些参数。
然后实现 execute 函数。
在这个例子中,先用桩实现,直接返回该城市气温为 25 度。
如果需要,也可以调用天气 API 获取真实天气。
import { tool } from "ai";import { z } from "zod";const getWeatherTool = tool({description:"Get the current weather in the specified city",parameters: z.object({city: z.string().describe("The city to get the weather for"),}),});
接下来把工具连接到一个名为 askAQuestion.
滚动式代码讲解
调用 streamText ,传入模型、提示词和 getWeather 工具。
然后遍历文本流,把文本打印到 stdout.
最后询问伦敦的天气。
import { streamText } from "ai";const askAQuestion = async (prompt: string) => {await streamText({model,prompt,tools: {getWeather: getWeatherTool,},});};
运行后,会发现一件有趣的事。
I'll help you check the current weather in London right away.
我们没有得到想要的信息,它只说:“我来帮你。”
为什么会这样?
调试 steps
使用上次相同的策略进行调试:查看 steps 返回的属性,它来自 streamText.
import { streamText } from "ai";const askAQuestion = async (prompt: string) => {const { steps } = await streamText({model,prompt,tools: {getWeather: getWeatherTool,},});console.dir(await steps, { depth: null });};await askAQuestion(`What's the weather in London?`);
因为这里使用 streamText ,所以必须 await 的结果 steps.
下面是 它输出的内容。
这大段 JSON 中有几件事情值得注意。
首先,它只有一个步骤;LLM 在这里仅执行了一步。
可以从 toolCalls and toolResults 属性中看到,它调用了一个工具并获得结果。
toolCalls: [{type: 'tool-call',toolCallId: 'toolu_011n3T6TJnwZLyR4G8h1ZcMz',toolName: 'getWeather',args: { city: 'London' }}],toolResults: [{type: 'tool-result',toolCallId: 'toolu_011n3T6TJnwZLyR4G8h1ZcMz',toolName: 'getWeather',args: { city: 'London' },result: 'The weather in London is 25°C and sunny.'}],
因此, LLM 调用了 getWeather 工具,把城市设为伦敦,并得到“伦敦天气为 25°C、晴朗”的结果。
但随后它决定停止。
看来 LLM 做了正确的事,调用了工具,却因为某种原因停止了。怎样才能让它执行多步?
想继续深入: 加入“面向真正工程师的 AI 编码”候补名单
maxSteps
默认情况下,AI SDK 只允许 LLM 执行一步。
如果希望允许更多步骤,可以传入 maxSteps to streamText.
这会强制循环在执行两步后停止。
运行后会得到非常不错的输出:
I'll help you check the current weather in London right away.It looks like London is experiencing a pleasant day with sunny conditions and a temperature of 25°C (which is about 77°F). It sounds like a great day to be outside and enjoy the nice weather!
可以看到,LLM 现在会根据工具提供的信息继续作出反应。
再次记录 steps,可以看到 执行了两个步骤。.
停止信号
如果允许超过两步会怎样?尝试把 maxSteps 提高到 10,看看结果。
结果是,我们得到了 几乎相同的结果。.
LLM 在两步后自行停止。
可以看到,第二步带有一个 finishReason of stop:
finishReason: 'stop'
这是因为 LLM 内置了任务完成后停止的机制。
这意味着循环有两种结束方式:LLM 自行停止,或达到 maxSteps.
把 maxSteps as Infinity 设置得过大并不好,因为 LLM 有时不会自行停止。
总结
总结一下,我们了解了如何使用 Vercel AI SDK 创建简单的智能体循环。
使用 maxSteps 可以让 LLM 执行多个步骤,并根据自己的工具结果继续行动。
借此可以构建以现实信息为依据、更加实用的 LLM 系统。