Vercel AI SDK tool calling example
- Authors
- 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 zodSet 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.inputSchematells the model which arguments are valid.executeruns 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
Related articles
LangChain JS agent with a custom tool
Create a small LangChain JavaScript agent with one custom tool using createAgent, tool, and Zod.
OpenAI function calling JavaScript example
Minimal OpenAI function calling example in JavaScript using a local tool and the Responses API.
Force an LLM to return JSON in JavaScript
Return schema-shaped JSON from an LLM in JavaScript using OpenAI structured outputs instead of fragile JSON parsing.

