feat(chaWindow): lint & beautify

This commit is contained in:
ItzCrazyKns 2024-08-29 16:51:59 +05:30
parent 449684c419
commit c952469f08
1 changed files with 205 additions and 202 deletions

View File

@ -1,42 +1,42 @@
'use client' 'use client';
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react';
import { Document } from '@langchain/core/documents' import { Document } from '@langchain/core/documents';
import Navbar from './Navbar' import Navbar from './Navbar';
import Chat from './Chat' import Chat from './Chat';
import EmptyChat from './EmptyChat' import EmptyChat from './EmptyChat';
import crypto from 'crypto' import crypto from 'crypto';
import { toast } from 'sonner' import { toast } from 'sonner';
import { useSearchParams } from 'next/navigation' import { useSearchParams } from 'next/navigation';
import { getSuggestions } from '@/lib/actions' import { getSuggestions } from '@/lib/actions';
import Error from 'next/error' import Error from 'next/error';
export type Message = { export type Message = {
messageId: string messageId: string;
chatId: string chatId: string;
createdAt: Date createdAt: Date;
content: string content: string;
role: 'user' | 'assistant' role: 'user' | 'assistant';
suggestions?: string[] suggestions?: string[];
sources?: Document[] sources?: Document[];
} };
const useSocket = ( const useSocket = (
url: string, url: string,
setIsWSReady: (ready: boolean) => void, setIsWSReady: (ready: boolean) => void,
setError: (error: boolean) => void, setError: (error: boolean) => void,
) => { ) => {
const [ws, setWs] = useState<WebSocket | null>(null) const [ws, setWs] = useState<WebSocket | null>(null);
useEffect(() => { useEffect(() => {
if (!ws) { if (!ws) {
const connectWs = async () => { const connectWs = async () => {
let chatModel = localStorage.getItem('chatModel') let chatModel = localStorage.getItem('chatModel');
let chatModelProvider = localStorage.getItem('chatModelProvider') let chatModelProvider = localStorage.getItem('chatModelProvider');
let embeddingModel = localStorage.getItem('embeddingModel') let embeddingModel = localStorage.getItem('embeddingModel');
let embeddingModelProvider = localStorage.getItem( let embeddingModelProvider = localStorage.getItem(
'embeddingModelProvider', 'embeddingModelProvider',
) );
const providers = await fetch( const providers = await fetch(
`${process.env.NEXT_PUBLIC_API_URL}/models`, `${process.env.NEXT_PUBLIC_API_URL}/models`,
@ -45,7 +45,7 @@ const useSocket = (
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
}, },
).then(async res => await res.json()) ).then(async (res) => await res.json());
if ( if (
!chatModel || !chatModel ||
@ -54,55 +54,58 @@ const useSocket = (
!embeddingModelProvider !embeddingModelProvider
) { ) {
if (!chatModel || !chatModelProvider) { if (!chatModel || !chatModelProvider) {
const chatModelProviders = providers.chatModelProviders const chatModelProviders = providers.chatModelProviders;
chatModelProvider = Object.keys(chatModelProviders)[0] chatModelProvider = Object.keys(chatModelProviders)[0];
if (chatModelProvider === 'custom_openai') { if (chatModelProvider === 'custom_openai') {
toast.error( toast.error(
'Seems like you are using the custom OpenAI provider, please open the settings and configure the API key and base URL', 'Seems like you are using the custom OpenAI provider, please open the settings and configure the API key and base URL',
) );
setError(true) setError(true);
return return;
} else { } else {
chatModel = Object.keys(chatModelProviders[chatModelProvider])[0] chatModel = Object.keys(chatModelProviders[chatModelProvider])[0];
if ( if (
!chatModelProviders || !chatModelProviders ||
Object.keys(chatModelProviders).length === 0 Object.keys(chatModelProviders).length === 0
) )
return toast.error('No chat models available') return toast.error('No chat models available');
} }
} }
if (!embeddingModel || !embeddingModelProvider) { if (!embeddingModel || !embeddingModelProvider) {
const embeddingModelProviders = providers.embeddingModelProviders const embeddingModelProviders = providers.embeddingModelProviders;
if ( if (
!embeddingModelProviders || !embeddingModelProviders ||
Object.keys(embeddingModelProviders).length === 0 Object.keys(embeddingModelProviders).length === 0
) )
return toast.error('No embedding models available') return toast.error('No embedding models available');
embeddingModelProvider = Object.keys(embeddingModelProviders)[0] embeddingModelProvider = Object.keys(embeddingModelProviders)[0];
embeddingModel = Object.keys( embeddingModel = Object.keys(
embeddingModelProviders[embeddingModelProvider], embeddingModelProviders[embeddingModelProvider],
)[0] )[0];
} }
localStorage.setItem('chatModel', chatModel!) localStorage.setItem('chatModel', chatModel!);
localStorage.setItem('chatModelProvider', chatModelProvider) localStorage.setItem('chatModelProvider', chatModelProvider);
localStorage.setItem('embeddingModel', embeddingModel!) localStorage.setItem('embeddingModel', embeddingModel!);
localStorage.setItem('embeddingModelProvider', embeddingModelProvider) localStorage.setItem(
'embeddingModelProvider',
embeddingModelProvider,
);
} else { } else {
const chatModelProviders = providers.chatModelProviders const chatModelProviders = providers.chatModelProviders;
const embeddingModelProviders = providers.embeddingModelProviders const embeddingModelProviders = providers.embeddingModelProviders;
if ( if (
Object.keys(chatModelProviders).length > 0 && Object.keys(chatModelProviders).length > 0 &&
!chatModelProviders[chatModelProvider] !chatModelProviders[chatModelProvider]
) { ) {
chatModelProvider = Object.keys(chatModelProviders)[0] chatModelProvider = Object.keys(chatModelProviders)[0];
localStorage.setItem('chatModelProvider', chatModelProvider) localStorage.setItem('chatModelProvider', chatModelProvider);
} }
if ( if (
@ -110,19 +113,19 @@ const useSocket = (
chatModelProvider != 'custom_openai' && chatModelProvider != 'custom_openai' &&
!chatModelProviders[chatModelProvider][chatModel] !chatModelProviders[chatModelProvider][chatModel]
) { ) {
chatModel = Object.keys(chatModelProviders[chatModelProvider])[0] chatModel = Object.keys(chatModelProviders[chatModelProvider])[0];
localStorage.setItem('chatModel', chatModel) localStorage.setItem('chatModel', chatModel);
} }
if ( if (
Object.keys(embeddingModelProviders).length > 0 && Object.keys(embeddingModelProviders).length > 0 &&
!embeddingModelProviders[embeddingModelProvider] !embeddingModelProviders[embeddingModelProvider]
) { ) {
embeddingModelProvider = Object.keys(embeddingModelProviders)[0] embeddingModelProvider = Object.keys(embeddingModelProviders)[0];
localStorage.setItem( localStorage.setItem(
'embeddingModelProvider', 'embeddingModelProvider',
embeddingModelProvider, embeddingModelProvider,
) );
} }
if ( if (
@ -131,77 +134,77 @@ const useSocket = (
) { ) {
embeddingModel = Object.keys( embeddingModel = Object.keys(
embeddingModelProviders[embeddingModelProvider], embeddingModelProviders[embeddingModelProvider],
)[0] )[0];
localStorage.setItem('embeddingModel', embeddingModel) localStorage.setItem('embeddingModel', embeddingModel);
} }
} }
const wsURL = new URL(url) const wsURL = new URL(url);
const searchParams = new URLSearchParams({}) const searchParams = new URLSearchParams({});
searchParams.append('chatModel', chatModel!) searchParams.append('chatModel', chatModel!);
searchParams.append('chatModelProvider', chatModelProvider) searchParams.append('chatModelProvider', chatModelProvider);
if (chatModelProvider === 'custom_openai') { if (chatModelProvider === 'custom_openai') {
searchParams.append( searchParams.append(
'openAIApiKey', 'openAIApiKey',
localStorage.getItem('openAIApiKey')!, localStorage.getItem('openAIApiKey')!,
) );
searchParams.append( searchParams.append(
'openAIBaseURL', 'openAIBaseURL',
localStorage.getItem('openAIBaseURL')!, localStorage.getItem('openAIBaseURL')!,
) );
} }
searchParams.append('embeddingModel', embeddingModel!) searchParams.append('embeddingModel', embeddingModel!);
searchParams.append('embeddingModelProvider', embeddingModelProvider) searchParams.append('embeddingModelProvider', embeddingModelProvider);
wsURL.search = searchParams.toString() wsURL.search = searchParams.toString();
const ws = new WebSocket(wsURL.toString()) const ws = new WebSocket(wsURL.toString());
const timeoutId = setTimeout(() => { const timeoutId = setTimeout(() => {
if (ws.readyState !== 1) { if (ws.readyState !== 1) {
toast.error( toast.error(
'Failed to connect to the server. Please try again later.', 'Failed to connect to the server. Please try again later.',
) );
} }
}, 10000) }, 10000);
ws.onopen = () => { ws.onopen = () => {
console.log('[DEBUG] open') console.log('[DEBUG] open');
clearTimeout(timeoutId) clearTimeout(timeoutId);
setIsWSReady(true) setIsWSReady(true);
} };
ws.onerror = () => { ws.onerror = () => {
clearTimeout(timeoutId) clearTimeout(timeoutId);
setError(true) setError(true);
toast.error('WebSocket connection error.') toast.error('WebSocket connection error.');
} };
ws.onclose = () => { ws.onclose = () => {
clearTimeout(timeoutId) clearTimeout(timeoutId);
setError(true) setError(true);
console.log('[DEBUG] closed') console.log('[DEBUG] closed');
} };
ws.addEventListener('message', e => { ws.addEventListener('message', (e) => {
const data = JSON.parse(e.data) const data = JSON.parse(e.data);
if (data.type === 'error') { if (data.type === 'error') {
toast.error(data.data) toast.error(data.data);
} }
}) });
setWs(ws) setWs(ws);
} };
connectWs() connectWs();
} }
}, [ws, url, setIsWSReady, setError]) }, [ws, url, setIsWSReady, setError]);
return ws return ws;
} };
const loadMessages = async ( const loadMessages = async (
chatId: string, chatId: string,
@ -219,66 +222,66 @@ const loadMessages = async (
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
}, },
) );
if (res.status === 404) { if (res.status === 404) {
setNotFound(true) setNotFound(true);
setIsMessagesLoaded(true) setIsMessagesLoaded(true);
return return;
} }
const data = await res.json() const data = await res.json();
const messages = data.messages.map((msg: any) => { const messages = data.messages.map((msg: any) => {
return { return {
...msg, ...msg,
...JSON.parse(msg.metadata), ...JSON.parse(msg.metadata),
} };
}) as Message[] }) as Message[];
setMessages(messages) setMessages(messages);
const history = messages.map(msg => { const history = messages.map((msg) => {
return [msg.role, msg.content] return [msg.role, msg.content];
}) as [string, string][] }) as [string, string][];
console.log('[DEBUG] messages loaded') console.log('[DEBUG] messages loaded');
document.title = messages[0].content document.title = messages[0].content;
setChatHistory(history) setChatHistory(history);
setFocusMode(data.chat.focusMode) setFocusMode(data.chat.focusMode);
setIsMessagesLoaded(true) setIsMessagesLoaded(true);
} };
const ChatWindow = ({ id }: { id?: string }) => { const ChatWindow = ({ id }: { id?: string }) => {
const searchParams = useSearchParams() const searchParams = useSearchParams();
const initialMessage = searchParams.get('q') const initialMessage = searchParams.get('q');
const [chatId, setChatId] = useState<string | undefined>(id) const [chatId, setChatId] = useState<string | undefined>(id);
const [newChatCreated, setNewChatCreated] = useState(false) const [newChatCreated, setNewChatCreated] = useState(false);
const [hasError, setHasError] = useState(false) const [hasError, setHasError] = useState(false);
const [isReady, setIsReady] = useState(false) const [isReady, setIsReady] = useState(false);
const [isWSReady, setIsWSReady] = useState(false) const [isWSReady, setIsWSReady] = useState(false);
const ws = useSocket( const ws = useSocket(
process.env.NEXT_PUBLIC_WS_URL!, process.env.NEXT_PUBLIC_WS_URL!,
setIsWSReady, setIsWSReady,
setHasError, setHasError,
) );
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false);
const [messageAppeared, setMessageAppeared] = useState(false) const [messageAppeared, setMessageAppeared] = useState(false);
const [chatHistory, setChatHistory] = useState<[string, string][]>([]) const [chatHistory, setChatHistory] = useState<[string, string][]>([]);
const [messages, setMessages] = useState<Message[]>([]) const [messages, setMessages] = useState<Message[]>([]);
const [focusMode, setFocusMode] = useState('webSearch') const [focusMode, setFocusMode] = useState('webSearch');
const [isMessagesLoaded, setIsMessagesLoaded] = useState(false) const [isMessagesLoaded, setIsMessagesLoaded] = useState(false);
const [notFound, setNotFound] = useState(false) const [notFound, setNotFound] = useState(false);
useEffect(() => { useEffect(() => {
if ( if (
@ -294,46 +297,46 @@ const ChatWindow = ({ id }: { id?: string }) => {
setChatHistory, setChatHistory,
setFocusMode, setFocusMode,
setNotFound, setNotFound,
) );
} else if (!chatId) { } else if (!chatId) {
setNewChatCreated(true) setNewChatCreated(true);
setIsMessagesLoaded(true) setIsMessagesLoaded(true);
setChatId(crypto.randomBytes(20).toString('hex')) setChatId(crypto.randomBytes(20).toString('hex'));
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, []) }, []);
useEffect(() => { useEffect(() => {
return () => { return () => {
if (ws?.readyState === 1) { if (ws?.readyState === 1) {
ws.close() ws.close();
console.log('[DEBUG] closed') console.log('[DEBUG] closed');
} }
} };
}, []) }, []);
const messagesRef = useRef<Message[]>([]) const messagesRef = useRef<Message[]>([]);
useEffect(() => { useEffect(() => {
messagesRef.current = messages messagesRef.current = messages;
}, [messages]) }, [messages]);
useEffect(() => { useEffect(() => {
if (isMessagesLoaded && isWSReady) { if (isMessagesLoaded && isWSReady) {
setIsReady(true) setIsReady(true);
} }
}, [isMessagesLoaded, isWSReady]) }, [isMessagesLoaded, isWSReady]);
const sendMessage = async (message: string) => { const sendMessage = async (message: string) => {
if (loading) return if (loading) return;
setLoading(true) setLoading(true);
setMessageAppeared(false) setMessageAppeared(false);
let sources: Document[] | undefined = undefined let sources: Document[] | undefined = undefined;
let recievedMessage = '' let recievedMessage = '';
let added = false let added = false;
const messageId = crypto.randomBytes(7).toString('hex') const messageId = crypto.randomBytes(7).toString('hex');
ws?.send( ws?.send(
JSON.stringify({ JSON.stringify({
@ -345,9 +348,9 @@ const ChatWindow = ({ id }: { id?: string }) => {
focusMode: focusMode, focusMode: focusMode,
history: [...chatHistory, ['human', message]], history: [...chatHistory, ['human', message]],
}), }),
) );
setMessages(prevMessages => [ setMessages((prevMessages) => [
...prevMessages, ...prevMessages,
{ {
content: message, content: message,
@ -356,21 +359,21 @@ const ChatWindow = ({ id }: { id?: string }) => {
role: 'user', role: 'user',
createdAt: new Date(), createdAt: new Date(),
}, },
]) ]);
const messageHandler = async (e: MessageEvent) => { const messageHandler = async (e: MessageEvent) => {
const data = JSON.parse(e.data) const data = JSON.parse(e.data);
if (data.type === 'error') { if (data.type === 'error') {
toast.error(data.data) toast.error(data.data);
setLoading(false) setLoading(false);
return return;
} }
if (data.type === 'sources') { if (data.type === 'sources') {
sources = data.data sources = data.data;
if (!added) { if (!added) {
setMessages(prevMessages => [ setMessages((prevMessages) => [
...prevMessages, ...prevMessages,
{ {
content: '', content: '',
@ -380,15 +383,15 @@ const ChatWindow = ({ id }: { id?: string }) => {
sources: sources, sources: sources,
createdAt: new Date(), createdAt: new Date(),
}, },
]) ]);
added = true added = true;
} }
setMessageAppeared(true) setMessageAppeared(true);
} }
if (data.type === 'message') { if (data.type === 'message') {
if (!added) { if (!added) {
setMessages(prevMessages => [ setMessages((prevMessages) => [
...prevMessages, ...prevMessages,
{ {
content: data.data, content: data.data,
@ -398,35 +401,35 @@ const ChatWindow = ({ id }: { id?: string }) => {
sources: sources, sources: sources,
createdAt: new Date(), createdAt: new Date(),
}, },
]) ]);
added = true added = true;
} }
setMessages(prev => setMessages((prev) =>
prev.map(message => { prev.map((message) => {
if (message.messageId === data.messageId) { if (message.messageId === data.messageId) {
return { ...message, content: message.content + data.data } return { ...message, content: message.content + data.data };
} }
return message return message;
}), }),
) );
recievedMessage += data.data recievedMessage += data.data;
setMessageAppeared(true) setMessageAppeared(true);
} }
if (data.type === 'messageEnd') { if (data.type === 'messageEnd') {
setChatHistory(prevHistory => [ setChatHistory((prevHistory) => [
...prevHistory, ...prevHistory,
['human', message], ['human', message],
['assistant', recievedMessage], ['assistant', recievedMessage],
]) ]);
ws?.removeEventListener('message', messageHandler) ws?.removeEventListener('message', messageHandler);
setLoading(false) setLoading(false);
const lastMsg = messagesRef.current[messagesRef.current.length - 1] const lastMsg = messagesRef.current[messagesRef.current.length - 1];
if ( if (
lastMsg.role === 'assistant' && lastMsg.role === 'assistant' &&
@ -434,54 +437,54 @@ const ChatWindow = ({ id }: { id?: string }) => {
lastMsg.sources.length > 0 && lastMsg.sources.length > 0 &&
!lastMsg.suggestions !lastMsg.suggestions
) { ) {
const suggestions = await getSuggestions(messagesRef.current) const suggestions = await getSuggestions(messagesRef.current);
setMessages(prev => setMessages((prev) =>
prev.map(msg => { prev.map((msg) => {
if (msg.messageId === lastMsg.messageId) { if (msg.messageId === lastMsg.messageId) {
return { ...msg, suggestions: suggestions } return { ...msg, suggestions: suggestions };
} }
return msg return msg;
}), }),
) );
}
} }
} }
};
ws?.addEventListener('message', messageHandler) ws?.addEventListener('message', messageHandler);
} };
const rewrite = (messageId: string) => { const rewrite = (messageId: string) => {
const index = messages.findIndex(msg => msg.messageId === messageId) const index = messages.findIndex((msg) => msg.messageId === messageId);
if (index === -1) return if (index === -1) return;
const message = messages[index - 1] const message = messages[index - 1];
setMessages(prev => { setMessages((prev) => {
return [...prev.slice(0, messages.length > 2 ? index - 1 : 0)] return [...prev.slice(0, messages.length > 2 ? index - 1 : 0)];
}) });
setChatHistory(prev => { setChatHistory((prev) => {
return [...prev.slice(0, messages.length > 2 ? index - 1 : 0)] return [...prev.slice(0, messages.length > 2 ? index - 1 : 0)];
}) });
sendMessage(message.content) sendMessage(message.content);
} };
useEffect(() => { useEffect(() => {
if (isReady && initialMessage) { if (isReady && initialMessage) {
sendMessage(initialMessage) sendMessage(initialMessage);
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [isReady, initialMessage]) }, [isReady, initialMessage]);
if (hasError) { if (hasError) {
return ( return (
<div className='flex flex-col items-center justify-center min-h-screen'> <div className="flex flex-col items-center justify-center min-h-screen">
<p className='dark:text-white/70 text-black/70 text-sm'> <p className="dark:text-white/70 text-black/70 text-sm">
Failed to connect to the server. Please try again later. Failed to connect to the server. Please try again later.
</p> </p>
</div> </div>
) );
} }
return isReady ? ( return isReady ? (
@ -510,25 +513,25 @@ const ChatWindow = ({ id }: { id?: string }) => {
</div> </div>
) )
) : ( ) : (
<div className='flex flex-row items-center justify-center min-h-screen'> <div className="flex flex-row items-center justify-center min-h-screen">
<svg <svg
aria-hidden='true' aria-hidden="true"
className='w-8 h-8 text-light-200 fill-light-secondary dark:text-[#202020] animate-spin dark:fill-[#ffffff3b]' className="w-8 h-8 text-light-200 fill-light-secondary dark:text-[#202020] animate-spin dark:fill-[#ffffff3b]"
viewBox='0 0 100 101' viewBox="0 0 100 101"
fill='none' fill="none"
xmlns='http://www.w3.org/2000/svg' xmlns="http://www.w3.org/2000/svg"
> >
<path <path
d='M100 50.5908C100.003 78.2051 78.1951 100.003 50.5908 100C22.9765 99.9972 0.997224 78.018 1 50.4037C1.00281 22.7993 22.8108 0.997224 50.4251 1C78.0395 1.00281 100.018 22.8108 100 50.4251ZM9.08164 50.594C9.06312 73.3997 27.7909 92.1272 50.5966 92.1457C73.4023 92.1642 92.1298 73.4365 92.1483 50.6308C92.1669 27.8251 73.4392 9.0973 50.6335 9.07878C27.8278 9.06026 9.10003 27.787 9.08164 50.594Z' d="M100 50.5908C100.003 78.2051 78.1951 100.003 50.5908 100C22.9765 99.9972 0.997224 78.018 1 50.4037C1.00281 22.7993 22.8108 0.997224 50.4251 1C78.0395 1.00281 100.018 22.8108 100 50.4251ZM9.08164 50.594C9.06312 73.3997 27.7909 92.1272 50.5966 92.1457C73.4023 92.1642 92.1298 73.4365 92.1483 50.6308C92.1669 27.8251 73.4392 9.0973 50.6335 9.07878C27.8278 9.06026 9.10003 27.787 9.08164 50.594Z"
fill='currentColor' fill="currentColor"
/> />
<path <path
d='M93.9676 39.0409C96.393 38.4037 97.8624 35.9116 96.9801 33.5533C95.1945 28.8227 92.871 24.3692 90.0681 20.348C85.6237 14.1775 79.4473 9.36872 72.0454 6.45794C64.6435 3.54717 56.3134 2.65431 48.3133 3.89319C45.869 4.27179 44.3768 6.77534 45.014 9.20079C45.6512 11.6262 48.1343 13.0956 50.5786 12.717C56.5073 11.8281 62.5542 12.5399 68.0406 14.7911C73.527 17.0422 78.2187 20.7487 81.5841 25.4923C83.7976 28.5886 85.4467 32.059 86.4416 35.7474C87.1273 38.1189 89.5423 39.6781 91.9676 39.0409Z' d="M93.9676 39.0409C96.393 38.4037 97.8624 35.9116 96.9801 33.5533C95.1945 28.8227 92.871 24.3692 90.0681 20.348C85.6237 14.1775 79.4473 9.36872 72.0454 6.45794C64.6435 3.54717 56.3134 2.65431 48.3133 3.89319C45.869 4.27179 44.3768 6.77534 45.014 9.20079C45.6512 11.6262 48.1343 13.0956 50.5786 12.717C56.5073 11.8281 62.5542 12.5399 68.0406 14.7911C73.527 17.0422 78.2187 20.7487 81.5841 25.4923C83.7976 28.5886 85.4467 32.059 86.4416 35.7474C87.1273 38.1189 89.5423 39.6781 91.9676 39.0409Z"
fill='currentFill' fill="currentFill"
/> />
</svg> </svg>
</div> </div>
) );
} };
export default ChatWindow export default ChatWindow;