import axios from "axios"; import { useEffect, useRef, useState } from "react"; import { getAssistantById, getPromptGeneratorOfAssistant, useChatStore, useMessageStore, useConnectionStore } from "@/store"; import { CreatorRole } from "@/types"; import { generateUUID } from "@/utils"; import Icon from "../Icon"; import Header from "./Header"; import MessageView from "./MessageView"; import MessageTextarea from "./MessageTextarea"; const ChatView = () => { const connectionStore = useConnectionStore(); const chatStore = useChatStore(); const messageStore = useMessageStore(); const [isRequesting, setIsRequesting] = useState(false); const chatViewRef = useRef(null); const currentChat = chatStore.currentChat; const messageList = messageStore.messageList.filter((message) => message.chatId === currentChat?.id); useEffect(() => { setTimeout(() => { if (!chatViewRef.current) { return; } chatViewRef.current.scrollTop = chatViewRef.current.scrollHeight; }); }, [currentChat, isRequesting]); const sendMessageToCurrentChat = async () => { if (!currentChat || !chatViewRef.current) { return; } if (isRequesting) { return; } setIsRequesting(true); const messageList = messageStore.getState().messageList.filter((message) => message.chatId === currentChat.id); let prompt = ""; if (connectionStore.currentConnectionCtx?.database) { const tables = await connectionStore.getOrFetchDatabaseSchema(connectionStore.currentConnectionCtx?.database); const promptGenerator = getPromptGeneratorOfAssistant(getAssistantById(currentChat.assistantId)!); prompt = promptGenerator(tables.map((table) => table.structure).join("/n")); } const { data } = await axios.post("/api/chat", { messages: [ { role: CreatorRole.System, content: prompt, }, ...messageList.map((message) => ({ role: message.creatorRole, content: message.content, })), ], }); messageStore.addMessage({ id: generateUUID(), chatId: currentChat.id, creatorId: currentChat.assistantId, creatorRole: CreatorRole.Assistant, createdAt: Date.now(), content: data, }); setIsRequesting(false); }; return (
{messageList.length === 0 ? <> : messageList.map((message) => )} {isRequesting && (
Requesting...
)}
); }; export default ChatView;