quivr/frontend/app/chat/[chatId]/hooks/useChat.ts
Stepan Lebedev 600ff1ede0
feat(Unplug): chatting without brain streaming (#970)
* feat(Unplug): Adds new basic headless llm

* feat(Unplug): adds chatting without brain option when no streaming

* feat(Unplug): adds chatting without brain option when streaming
2023-08-18 10:32:22 +02:00

90 lines
2.6 KiB
TypeScript

/* eslint-disable max-lines */
import { AxiosError } from 'axios';
import { useParams } from 'next/navigation';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { getChatConfigFromLocalStorage } from '@/lib/api/chat/chat.local';
import { useChatApi } from '@/lib/api/chat/useChatApi';
import { useBrainContext } from '@/lib/context/BrainProvider/hooks/useBrainContext';
import { useChatContext } from '@/lib/context/ChatProvider/hooks/useChatContext';
import { useToast } from '@/lib/hooks';
import { useEventTracking } from '@/services/analytics/useEventTracking';
import { useQuestion } from './useQuestion';
import { ChatQuestion } from '../types';
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const useChat = () => {
const { track } = useEventTracking();
const params = useParams();
const [chatId, setChatId] = useState<string | undefined>(
params?.chatId as string | undefined
);
const [generatingAnswer, setGeneratingAnswer] = useState(false);
const { history } = useChatContext();
const { currentBrain } = useBrainContext();
const { publish } = useToast();
const { createChat } = useChatApi();
const { addStreamQuestion } = useQuestion();
const { t } = useTranslation(['chat']);
const addQuestion = async (question: string, callback?: () => void) => {
try {
setGeneratingAnswer(true);
let currentChatId = chatId;
//if chatId is not set, create a new chat. Chat name is from the first question
if (currentChatId === undefined) {
const chatName = question.split(' ').slice(0, 3).join(' ');
const chat = await createChat(chatName);
currentChatId = chat.chat_id;
setChatId(currentChatId);
}
void track('QUESTION_ASKED');
const chatConfig = getChatConfigFromLocalStorage(currentChatId);
const chatQuestion: ChatQuestion = {
model: chatConfig?.model,
question,
temperature: chatConfig?.temperature,
max_tokens: chatConfig?.maxTokens,
brain_id: currentBrain?.id,
};
await addStreamQuestion(currentChatId, chatQuestion);
callback?.();
} catch (error) {
console.error({ error });
if ((error as AxiosError).response?.status === 429) {
publish({
variant: 'danger',
text: t('limit_reached', { ns: 'chat' }),
});
return;
}
publish({
variant: 'danger',
text: t('error_occurred', { ns: 'chat' }),
});
} finally {
setGeneratingAnswer(false);
}
};
return {
history,
addQuestion,
generatingAnswer,
chatId,
};
};