chatbot-template/app/(chat)/chat/[id]/page.tsx

109 lines
2.7 KiB
TypeScript
Raw Normal View History

2024-10-11 18:00:22 +05:30
import { CoreMessage, CoreToolMessage, Message, ToolInvocation } from "ai";
import { notFound } from "next/navigation";
2023-05-19 12:33:56 -04:00
2024-10-11 18:00:22 +05:30
import { auth } from "@/app/(auth)/auth";
import { Chat as PreviewChat } from "@/components/custom/chat";
import { getChatById } from "@/db/queries";
import { Chat } from "@/db/schema";
import { generateUUID } from "@/lib/utils";
2023-06-16 21:52:01 +04:00
2024-10-11 18:00:22 +05:30
function addToolMessageToChat({
toolMessage,
messages,
}: {
toolMessage: CoreToolMessage;
messages: Array<Message>;
}): Array<Message> {
return messages.map((message) => {
if (message.toolInvocations) {
return {
...message,
toolInvocations: message.toolInvocations.map((toolInvocation) => {
const toolResult = toolMessage.content.find(
(tool) => tool.toolCallId === toolInvocation.toolCallId,
);
2023-06-16 21:52:01 +04:00
2024-10-11 18:00:22 +05:30
if (toolResult) {
return {
...toolInvocation,
state: "result",
result: toolResult.result,
};
}
2024-10-11 18:00:22 +05:30
return toolInvocation;
}),
};
}
2024-10-11 18:00:22 +05:30
return message;
});
2023-05-19 12:33:56 -04:00
}
2024-10-11 18:00:22 +05:30
function convertToUIMessages(messages: Array<CoreMessage>): Array<Message> {
return messages.reduce((chatMessages: Array<Message>, message) => {
if (message.role === "tool") {
return addToolMessageToChat({
toolMessage: message as CoreToolMessage,
messages: chatMessages,
});
}
let textContent = "";
let toolInvocations: Array<ToolInvocation> = [];
if (typeof message.content === "string") {
textContent = message.content;
} else if (Array.isArray(message.content)) {
for (const content of message.content) {
if (content.type === "text") {
textContent += content.text;
} else if (content.type === "tool-call") {
toolInvocations.push({
state: "call",
toolCallId: content.toolCallId,
toolName: content.toolName,
args: content.args,
});
}
}
}
2023-06-16 21:52:01 +04:00
2024-10-11 18:00:22 +05:30
chatMessages.push({
id: generateUUID(),
role: message.role,
content: textContent,
toolInvocations,
});
return chatMessages;
}, []);
}
export default async function Page({ params }: { params: any }) {
const { id } = params;
const chatFromDb = await getChatById({ id });
if (!chatFromDb) {
notFound();
2023-06-16 21:52:01 +04:00
}
2024-10-11 18:00:22 +05:30
// type casting
const chat: Chat = {
...chatFromDb,
messages: convertToUIMessages(chatFromDb.messages as Array<CoreMessage>),
};
2023-06-16 21:52:01 +04:00
2024-10-11 18:00:22 +05:30
const session = await auth();
if (!session || !session.user) {
return notFound();
}
2023-05-19 12:33:56 -04:00
2024-10-11 18:00:22 +05:30
if (session.user.id !== chat.userId) {
return notFound();
2023-06-16 15:28:43 -04:00
}
2024-10-11 18:00:22 +05:30
return <PreviewChat id={chat.id} initialMessages={chat.messages} />;
2023-06-02 15:15:35 -04:00
}