import {
streamText,
convertToModelMessages,
tool,
UIMessage,
} from 'ai';
import express, { Request, Response } from 'express';
import { z } from 'zod';
const app = express();
app.use(express.json());
app.post('/api/chat', async (req: Request, res: Response) => {
const { messages }: { messages: UIMessage[] } = req.body;
const result = streamText({
model: 'openai/gpt-4o',
messages: await convertToModelMessages(messages),
tools: {
getWeather: tool({
description: 'Get current weather for a location',
inputSchema: z.object({
city: z.string(),
}),
execute: async ({ city }) => {
// Simulate weather API call
const weatherData = {
city,
temperature: 72,
condition: 'Sunny',
};
return weatherData;
},
}),
calculateSum: tool({
description: 'Add two numbers',
inputSchema: z.object({
a: z.number(),
b: z.number(),
}),
execute: async ({ a, b }) => {
return { result: a + b };
},
}),
},
});
result.pipeUIMessageStreamToResponse(res);
});
app.listen(8080);