import {
streamText,
convertToModelMessages,
tool,
UIMessage,
} from 'ai';
import Fastify from 'fastify';
import { z } from 'zod';
const fastify = Fastify({ logger: true });
fastify.post('/api/chat', async function (request, reply) {
const { messages } = request.body as { messages: UIMessage[] };
const result = streamText({
model: 'openai/gpt-4o',
messages: await convertToModelMessages(messages),
tools: {
getWeather: tool({
description: 'Get current weather for a city',
inputSchema: z.object({
city: z.string().describe('City name'),
}),
execute: async ({ city }) => {
const weatherData = {
city,
temperature: 72,
condition: 'Sunny',
humidity: 65,
};
return weatherData;
},
}),
searchWeb: tool({
description: 'Search the web for information',
inputSchema: z.object({
query: z.string(),
}),
execute: async ({ query }) => {
// Implement web search
return {
query,
results: [
{ title: 'Result 1', url: 'https://example.com/1' },
{ title: 'Result 2', url: 'https://example.com/2' },
],
};
},
}),
},
});
return reply.send(result.toUIMessageStreamResponse());
});
fastify.listen({ port: 8080 });