chatbot-template/app/(chat)/api/chat/route.ts

104 lines
2.7 KiB
TypeScript
Raw Normal View History

import { convertToCoreMessages, Message, streamText } from 'ai';
import { z } from 'zod';
2024-10-11 18:00:22 +05:30
import { customModel } from '@/ai';
import { auth } from '@/app/(auth)/auth';
import { deleteChatById, getChatById, saveChat } from '@/db/queries';
import { Model, models } from '@/lib/model';
2024-10-11 18:00:22 +05:30
export async function POST(request: Request) {
const {
id,
messages,
model,
}: { id: string; messages: Array<Message>; model: Model['name'] } =
2024-10-11 18:00:22 +05:30
await request.json();
const session = await auth();
if (!session) {
return new Response('Unauthorized', { status: 401 });
}
if (!models.find((m) => m.name === model)) {
return new Response('Model not found', { status: 404 });
2024-10-11 18:00:22 +05:30
}
const coreMessages = convertToCoreMessages(messages);
const result = await streamText({
model: customModel(model),
2024-10-11 18:00:22 +05:30
system:
'you are a friendly assistant! keep your responses concise and helpful.',
2024-10-11 18:00:22 +05:30
messages: coreMessages,
maxSteps: 5,
tools: {
getWeather: {
description: 'Get the current weather at a location',
2024-10-11 18:00:22 +05:30
parameters: z.object({
latitude: z.number(),
longitude: z.number(),
}),
execute: async ({ latitude, longitude }) => {
const response = await fetch(
`https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current=temperature_2m&hourly=temperature_2m&daily=sunrise,sunset&timezone=auto`
2024-10-11 18:00:22 +05:30
);
const weatherData = await response.json();
return weatherData;
},
},
},
onFinish: async ({ responseMessages }) => {
if (session.user && session.user.id) {
try {
await saveChat({
id,
messages: [...coreMessages, ...responseMessages],
userId: session.user.id,
});
} catch (error) {
console.error('Failed to save chat');
2024-10-11 18:00:22 +05:30
}
}
},
experimental_telemetry: {
isEnabled: true,
functionId: 'stream-text',
2024-10-11 18:00:22 +05:30
},
});
return result.toDataStreamResponse({});
}
export async function DELETE(request: Request) {
const { searchParams } = new URL(request.url);
const id = searchParams.get('id');
2024-10-11 18:00:22 +05:30
if (!id) {
return new Response('Not Found', { status: 404 });
2024-10-11 18:00:22 +05:30
}
const session = await auth();
if (!session || !session.user) {
return new Response('Unauthorized', { status: 401 });
2024-10-11 18:00:22 +05:30
}
try {
const chat = await getChatById({ id });
if (chat.userId !== session.user.id) {
return new Response('Unauthorized', { status: 401 });
2024-10-11 18:00:22 +05:30
}
await deleteChatById({ id });
return new Response('Chat deleted', { status: 200 });
2024-10-11 18:00:22 +05:30
} catch (error) {
return new Response('An error occurred while processing your request', {
2024-10-11 18:00:22 +05:30
status: 500,
});
}
}