Vercel AI SDK tool calling example

Authors
  • avatar
    Name
    Hamza Rahman
Published on
-
2 mins read

Use Vercel AI SDK tools when the model should call a JavaScript function during text generation.

This example gives the model a getWeather tool.

Install

npm install ai @ai-sdk/openai zod

Set your API key:

export OPENAI_API_KEY="your_api_key_here"

Code

import { openai } from '@ai-sdk/openai'
import { generateText, stepCountIs, tool } from 'ai'
import { z } from 'zod'
const result = await generateText({
model: openai('gpt-5.5'),
tools: {
getWeather: tool({
description: 'Get the weather for a city.',
inputSchema: z.object({
city: z.string().describe('The city to get weather for.'),
}),
execute: async ({ city }) => {
return {
city,
forecast: city.toLowerCase() === 'karachi' ? 'hot and humid' : 'sunny',
}
},
}),
},
stopWhen: stepCountIs(5),
prompt: 'What is the weather in Karachi?',
})
console.log(result.text)

Important parts

  • tool() defines the callable function.
  • inputSchema tells the model which arguments are valid.
  • execute runs your real JavaScript code.
  • stopWhen: stepCountIs(5) allows the model to take tool-use steps and then finish.

When to use it

Use this for app helpers where the model needs live data or computed values:

  • Weather or location lookup
  • Product availability
  • Database search
  • Price calculators
  • Internal admin actions

References