import {
streamText,
convertToModelMessages,
tool,
stepCountIs,
} from 'ai';
import { z } from 'zod';
export default defineEventHandler(async (event) => {
const { messages } = await readBody(event);
const result = streamText({
model: 'openai/gpt-4o',
messages: await convertToModelMessages(messages),
stopWhen: stepCountIs(10),
tools: {
getWeather: tool({
description: 'Get current weather for a city',
inputSchema: z.object({
city: z.string(),
}),
execute: async ({ city }) => {
// Fetch weather data
const data = await $fetch(
`https://api.weatherapi.com/v1/current.json`,
{
params: {
key: useRuntimeConfig().weatherApiKey,
q: city,
},
},
);
return {
temperature: data.current.temp_c,
condition: data.current.condition.text,
};
},
}),
},
});
return result.toUIMessageStreamResponse();
});