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

404 lines
11 KiB
TypeScript
Raw Normal View History

2024-10-30 16:01:24 +05:30
import {
convertToCoreMessages,
Message,
StreamData,
streamObject,
streamText,
} from 'ai';
import { z } from 'zod';
2024-10-11 18:00:22 +05:30
import { customModel } from '@/ai';
2024-10-30 16:01:24 +05:30
import { models } from '@/ai/models';
2024-11-12 13:32:55 +03:00
import { systemPrompt } from '@/ai/prompts';
import { auth } from '@/app/(auth)/auth';
2024-10-30 16:01:24 +05:30
import {
deleteChatById,
getChatById,
getDocumentById,
saveChat,
saveDocument,
2024-11-05 17:15:51 +03:00
saveMessages,
2024-10-30 16:01:24 +05:30
saveSuggestions,
} from '@/db/queries';
import { Suggestion } from '@/db/schema';
2024-11-05 17:15:51 +03:00
import {
generateUUID,
getMostRecentUserMessage,
sanitizeResponseMessages,
} from '@/lib/utils';
import { generateTitleFromUserMessage } from '../../actions';
2024-10-30 16:01:24 +05:30
export const maxDuration = 60;
type AllowedTools =
| 'createDocument'
| 'updateDocument'
| 'requestSuggestions'
| 'getWeather';
2024-11-07 02:40:29 +03:00
const blocksTools: AllowedTools[] = [
2024-10-30 16:01:24 +05:30
'createDocument',
'updateDocument',
'requestSuggestions',
];
const weatherTools: AllowedTools[] = ['getWeather'];
2024-10-11 18:00:22 +05:30
const allTools: AllowedTools[] = [...blocksTools, ...weatherTools];
2024-10-11 18:00:22 +05:30
export async function POST(request: Request) {
const {
id,
messages,
2024-10-30 16:01:24 +05:30
modelId,
}: { id: string; messages: Array<Message>; modelId: string } =
2024-10-11 18:00:22 +05:30
await request.json();
const session = await auth();
2024-11-05 17:15:51 +03:00
if (!session || !session.user || !session.user.id) {
return new Response('Unauthorized', { status: 401 });
}
2024-10-30 16:01:24 +05:30
const model = models.find((model) => model.id === modelId);
if (!model) {
return new Response('Model not found', { status: 404 });
2024-10-11 18:00:22 +05:30
}
const coreMessages = convertToCoreMessages(messages);
2024-11-05 17:15:51 +03:00
const userMessage = getMostRecentUserMessage(coreMessages);
if (!userMessage) {
return new Response('No user message found', { status: 400 });
}
const chat = await getChatById({ id });
if (!chat) {
const title = await generateTitleFromUserMessage({ message: userMessage });
await saveChat({ id, userId: session.user.id, title });
}
await saveMessages({
messages: [
{ ...userMessage, id: generateUUID(), createdAt: new Date(), chatId: id },
],
});
2024-10-30 16:01:24 +05:30
const streamingData = new StreamData();
2024-10-11 18:00:22 +05:30
const result = await streamText({
2024-10-30 16:01:24 +05:30
model: customModel(model.apiIdentifier),
system: systemPrompt,
2024-10-11 18:00:22 +05:30
messages: coreMessages,
maxSteps: 5,
experimental_activeTools: allTools,
2024-10-11 18:00:22 +05:30
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;
},
},
2024-10-30 16:01:24 +05:30
createDocument: {
description: 'Create a document for a writing activity',
parameters: z.object({
title: z.string(),
}),
execute: async ({ title }) => {
const id = generateUUID();
let draftText: string = '';
streamingData.append({
type: 'id',
content: id,
});
streamingData.append({
type: 'title',
content: title,
});
streamingData.append({
type: 'clear',
content: '',
});
const { fullStream } = await streamText({
model: customModel(model.apiIdentifier),
system:
'Write about the given topic. Markdown is supported. Use headings wherever appropriate.',
prompt: title,
});
for await (const delta of fullStream) {
const { type } = delta;
if (type === 'text-delta') {
const { textDelta } = delta;
draftText += textDelta;
streamingData.append({
type: 'text-delta',
content: textDelta,
});
}
}
streamingData.append({ type: 'finish', content: '' });
if (session.user && session.user.id) {
await saveDocument({
id,
title,
content: draftText,
userId: session.user.id,
});
}
return {
id,
title,
content: `A document was created and is now visible to the user.`,
};
},
},
updateDocument: {
description: 'Update a document with the given description',
parameters: z.object({
id: z.string().describe('The ID of the document to update'),
description: z
.string()
.describe('The description of changes that need to be made'),
}),
execute: async ({ id, description }) => {
const document = await getDocumentById({ id });
if (!document) {
return {
error: 'Document not found',
};
}
const { content: currentContent } = document;
let draftText: string = '';
streamingData.append({
type: 'clear',
content: document.title,
});
const { fullStream } = await streamText({
model: customModel(model.apiIdentifier),
system:
'You are a helpful writing assistant. Based on the description, please update the piece of writing.',
experimental_providerMetadata: {
openai: {
prediction: {
type: 'content',
content: currentContent,
},
},
},
2024-10-30 16:01:24 +05:30
messages: [
{
role: 'user',
content: description,
},
{ role: 'user', content: currentContent },
],
});
for await (const delta of fullStream) {
const { type } = delta;
if (type === 'text-delta') {
const { textDelta } = delta;
draftText += textDelta;
streamingData.append({
type: 'text-delta',
content: textDelta,
});
}
}
streamingData.append({ type: 'finish', content: '' });
if (session.user && session.user.id) {
await saveDocument({
id,
title: document.title,
content: draftText,
userId: session.user.id,
});
}
return {
id,
title: document.title,
content: 'The document has been updated successfully.',
};
},
},
requestSuggestions: {
description: 'Request suggestions for a document',
parameters: z.object({
documentId: z
.string()
.describe('The ID of the document to request edits'),
}),
execute: async ({ documentId }) => {
const document = await getDocumentById({ id: documentId });
if (!document || !document.content) {
return {
error: 'Document not found',
};
}
let suggestions: Array<
Omit<Suggestion, 'userId' | 'createdAt' | 'documentCreatedAt'>
> = [];
const { elementStream } = await streamObject({
model: customModel(model.apiIdentifier),
system:
'You are a help writing assistant. Given a piece of writing, please offer suggestions to improve the piece of writing and describe the change. It is very important for the edits to contain full sentences instead of just words. Max 5 suggestions.',
2024-10-30 16:01:24 +05:30
prompt: document.content,
output: 'array',
schema: z.object({
originalSentence: z.string().describe('The original sentence'),
suggestedSentence: z.string().describe('The suggested sentence'),
description: z
.string()
.describe('The description of the suggestion'),
}),
});
for await (const element of elementStream) {
const suggestion = {
originalText: element.originalSentence,
suggestedText: element.suggestedSentence,
description: element.description,
id: generateUUID(),
documentId: documentId,
isResolved: false,
};
streamingData.append({
type: 'suggestion',
content: suggestion,
});
suggestions.push(suggestion);
}
if (session.user && session.user.id) {
const userId = session.user.id;
await saveSuggestions({
suggestions: suggestions.map((suggestion) => ({
...suggestion,
userId,
createdAt: new Date(),
documentCreatedAt: document.createdAt,
})),
});
}
return {
id: documentId,
title: document.title,
message: 'Suggestions have been added to the document',
};
},
},
2024-10-11 18:00:22 +05:30
},
onFinish: async ({ responseMessages }) => {
if (session.user && session.user.id) {
try {
2024-10-30 16:01:24 +05:30
const responseMessagesWithoutIncompleteToolCalls =
sanitizeResponseMessages(responseMessages);
2024-11-05 17:15:51 +03:00
await saveMessages({
messages: responseMessagesWithoutIncompleteToolCalls.map(
(message) => {
const messageId = generateUUID();
if (message.role === 'assistant') {
streamingData.appendMessageAnnotation({
messageIdFromServer: messageId,
});
}
return {
id: messageId,
chatId: id,
role: message.role,
content: message.content,
createdAt: new Date(),
};
}
),
2024-10-11 18:00:22 +05:30
});
} catch (error) {
console.error('Failed to save chat');
2024-10-11 18:00:22 +05:30
}
}
2024-10-30 16:01:24 +05:30
streamingData.close();
2024-10-11 18:00:22 +05:30
},
experimental_telemetry: {
isEnabled: true,
functionId: 'stream-text',
2024-10-11 18:00:22 +05:30
},
});
2024-10-30 16:01:24 +05:30
return result.toDataStreamResponse({
data: streamingData,
});
2024-10-11 18:00:22 +05:30
}
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,
});
}
}