The weather tool
A tool is a function the model is allowed to call. The Vercel AI SDK needs a small bundle for each tool: a description the model reads, a Zod schema for the parameters, and an execute function that runs on the server. We will start with a mocked weather tool so you can focus on the shape, not on sign-up flows for third party APIs.
import { tool } from 'ai';
import { z } from 'zod';
export const getWeather = tool({
description:
'Get the current weather for a given city. Returns temperature, condition, and humidity.',
parameters: z.object({
city: z.string().describe("The city name, e.g. 'Tokyo' or 'Paris'"),
}),
execute: async ({ city }) => {
const MOCK: Record<string, { tempC: number; condition: string }> = {
tokyo: { tempC: 18, condition: 'Partly Cloudy' },
paris: { tempC: 12, condition: 'Light Rain' },
london: { tempC: 10, condition: 'Overcast' },
};
const key = city.trim().toLowerCase();
const data = MOCK[key] ?? { tempC: 21, condition: 'Clear' };
return { city, temperatureC: data.tempC, condition: data.condition };
},
});
export const agentTools = { get_weather: getWeather };The description sells the tool to the model. The Zod schema validates arguments before execute runs. The execute function only runs when arguments pass validation.
import { streamText, convertToModelMessages } from 'ai';
import { createOpenRouter } from '@openrouter/ai-sdk-provider';
import { agentTools } from '@/lib/agent-tools';
import { SYSTEM_PROMPT } from '@/lib/utils';
export async function POST(req: Request) {
const { messages } = await req.json();
const openrouter = createOpenRouter({
apiKey: process.env.OPENROUTER_API_KEY ?? '',
});
const result = streamText({
model: openrouter.chat(process.env.OPENROUTER_MODEL ?? 'google/gemma-3-12b-it'),
system: SYSTEM_PROMPT,
messages: convertToModelMessages(messages),
tools: agentTools,
});
return result.toUIMessageStreamResponse();
}Pass the tools object to streamText. The SDK advertises them to the model, parses tool calls the model emits, runs execute, and streams results back into the UI message parts.
Quiz: Quiz
Loading practice…