Call Tools in Multiple Steps

Learn how to call tools with multiple steps using the AI TOOLKIT and Node

1 min readnodetool useagentView source

Models call tools to gather information or perform actions that are not directly available to the model. When tool results are available, the model can use them to generate another response. You can enable multi-step tool calls in generateText by defining stopping conditions with stopWhen. This allows you to define the conditions for which your agent should stop when the model generates a tool call. import { generateText, tool, stepCountIs } from 'ai-toolkit'; import { z } from 'zod'; const { text, steps } = await generateText({ model: 'openai/gpt-4.1', stopWhen: stepCountIs(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: string }) => ({ location, temperature: 72 + Math.floor(Math.random() * 21) - 10, }), }), }, prompt: 'What is the weather in San Francisco?', });

ts
  1. 1import { generateText, tool, stepCountIs } from 'ai-toolkit';
  2. 2import { z } from 'zod';
  3. 3const { text, steps } = await generateText({
  4. 4model: 'openai/gpt-4.1',
  5. 5stopWhen: stepCountIs(5),
  6. 6tools: {
  7. 7weather: tool({
  8. 8description: 'Get the weather in a location',
  9. 9inputSchema: z.object({
  10. 10location: z.string().describe('The location to get the weather for'),
  11. 11}),
  12. 12execute: async ({ location }: { location: string }) => ({
  13. 13location,
  14. 14temperature: 72 + Math.floor(Math.random() * 21) - 10,
  15. 15}),
  16. 16}),
  17. 17},
  18. 18prompt: 'What is the weather in San Francisco?',
  19. 19});

Run it locally

$ npm install ai