explicit too many request in chat error (#1000)

This commit is contained in:
Zineb El Bachiri 2023-08-21 16:07:07 +02:00 committed by GitHub
parent 9aaedcff51
commit 20d5294795
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 140 additions and 125 deletions

View File

@ -1,12 +1,14 @@
/* eslint-disable max-lines */ /* eslint-disable max-lines */
import { useTranslation } from 'react-i18next'; import axios from "axios";
import { useTranslation } from "react-i18next";
import { useBrainContext } from '@/lib/context/BrainProvider/hooks/useBrainContext'; import { useBrainContext } from "@/lib/context/BrainProvider/hooks/useBrainContext";
import { useChatContext } from '@/lib/context/ChatProvider/hooks/useChatContext'; import { useChatContext } from "@/lib/context/ChatProvider/hooks/useChatContext";
import { useFetch } from '@/lib/hooks'; import { useFetch } from "@/lib/hooks";
import { useToast } from "@/lib/hooks/useToast";
import { ChatHistory, ChatQuestion } from '../types'; import { ChatHistory, ChatQuestion } from "../types";
interface UseChatService { interface UseChatService {
addStreamQuestion: ( addStreamQuestion: (
@ -20,12 +22,13 @@ export const useQuestion = (): UseChatService => {
const { updateStreamingHistory } = useChatContext(); const { updateStreamingHistory } = useChatContext();
const { currentBrain } = useBrainContext(); const { currentBrain } = useBrainContext();
const { t } = useTranslation(['chat']); const { t } = useTranslation(["chat"]);
const { publish } = useToast();
const handleStream = async ( const handleStream = async (
reader: ReadableStreamDefaultReader<Uint8Array> reader: ReadableStreamDefaultReader<Uint8Array>
): Promise<void> => { ): Promise<void> => {
const decoder = new TextDecoder('utf-8'); const decoder = new TextDecoder("utf-8");
const handleStreamRecursively = async () => { const handleStreamRecursively = async () => {
const { done, value } = await reader.read(); const { done, value } = await reader.read();
@ -37,7 +40,7 @@ export const useQuestion = (): UseChatService => {
const dataStrings = decoder const dataStrings = decoder
.decode(value) .decode(value)
.trim() .trim()
.split('data: ') .split("data: ")
.filter(Boolean); .filter(Boolean);
dataStrings.forEach((data) => { dataStrings.forEach((data) => {
@ -45,7 +48,7 @@ export const useQuestion = (): UseChatService => {
const parsedData = JSON.parse(data) as ChatHistory; const parsedData = JSON.parse(data) as ChatHistory;
updateStreamingHistory(parsedData); updateStreamingHistory(parsedData);
} catch (error) { } catch (error) {
console.error(t('errorParsingData', { ns: 'chat' }), error); console.error(t("errorParsingData", { ns: "chat" }), error);
} }
}); });
@ -60,26 +63,33 @@ export const useQuestion = (): UseChatService => {
chatQuestion: ChatQuestion chatQuestion: ChatQuestion
): Promise<void> => { ): Promise<void> => {
const headers = { const headers = {
'Content-Type': 'application/json', "Content-Type": "application/json",
Accept: 'text/event-stream', Accept: "text/event-stream",
}; };
const body = JSON.stringify(chatQuestion); const body = JSON.stringify(chatQuestion);
console.log('Calling API...'); console.log("Calling API...");
try { try {
const response = await fetchInstance.post( const response = await fetchInstance.post(
`/chat/${chatId}/question/stream?brain_id=${currentBrain?.id ?? ''}`, `/chat/${chatId}/question/stream?brain_id=${currentBrain?.id ?? ""}`,
body, body,
headers headers
); );
if (response.body === null) { if (response.body === null) {
throw new Error(t('resposeBodyNull', { ns: 'chat' })); throw new Error(t("resposeBodyNull", { ns: "chat" }));
} }
console.log(t('receivedResponse'), response); console.log(t("receivedResponse"), response);
await handleStream(response.body.getReader()); await handleStream(response.body.getReader());
} catch (error) { } catch (error) {
console.error(t('errorCallingAPI', { ns: 'chat' }), error); if (axios.isAxiosError(error) && error.response?.status === 429) {
publish({
variant: "danger",
text: t("tooManyRequests", { ns: "chat" }),
});
}
console.error(t("errorCallingAPI", { ns: "chat" }), error);
} }
}; };

View File

@ -9,6 +9,7 @@
"noCurrentBrain": "No current brain", "noCurrentBrain": "No current brain",
"errorParsingData": "Error parsing data", "errorParsingData": "Error parsing data",
"resposeBodyNull": "Responde body is null", "resposeBodyNull": "Responde body is null",
"tooManyRequests": "You have exceeded the number of requests per day. To continue chatting, please enter an OpenAI API key in your profile or in used brain.",
"receivedResponse": "Received response. Starting to handle stream...", "receivedResponse": "Received response. Starting to handle stream...",
"errorCallingAPI": "Error calling the API", "errorCallingAPI": "Error calling the API",
"ask": "Ask a question, or describe a task.", "ask": "Ask a question, or describe a task.",

View File

@ -21,6 +21,7 @@
"noCurrentBrain": "Sin cerebro seleccionado", "noCurrentBrain": "Sin cerebro seleccionado",
"receivedResponse": "Respuesta recibida. Iniciando gestión de stream...", "receivedResponse": "Respuesta recibida. Iniciando gestión de stream...",
"resposeBodyNull": "Cuerpo de respuesta vacío", "resposeBodyNull": "Cuerpo de respuesta vacío",
"tooManyRequests": "Has excedido el número de solicitudes por día. Para continuar chateando, por favor ingresa una clave de API de OpenAI en tu perfil o en el cerebro utilizado.",
"shortcut_choose_prompt": "#: Elegir una instrucción específica", "shortcut_choose_prompt": "#: Elegir una instrucción específica",
"shortcut_create_brain": "@+: Crear un nuevo cerebro", "shortcut_create_brain": "@+: Crear un nuevo cerebro",
"shortcut_create_prompt": "#+: Crear una nueva instrucción personalizada", "shortcut_create_prompt": "#+: Crear una nueva instrucción personalizada",

View File

@ -21,6 +21,7 @@
"noCurrentBrain": "Pas de cerveau actuel", "noCurrentBrain": "Pas de cerveau actuel",
"receivedResponse": "Réponse reçue. Commence à gérer le flux...", "receivedResponse": "Réponse reçue. Commence à gérer le flux...",
"resposeBodyNull": "Le corps de la réponse est nul", "resposeBodyNull": "Le corps de la réponse est nul",
"tooManyRequests": "Vous avez dépassé le nombre de requêtes par jour. Pour continuer à discuter, veuillez entrer une clé d'API OpenAI dans votre profil ou dans le cerveau utilisé.",
"shortcut_choose_prompt": "#: Choisir une directive spécifique", "shortcut_choose_prompt": "#: Choisir une directive spécifique",
"shortcut_create_brain": "@+: Créer un nouveau cerveau", "shortcut_create_brain": "@+: Créer un nouveau cerveau",
"shortcut_create_prompt": "#+: Créer une nouvelle directive personnalisée", "shortcut_create_prompt": "#+: Créer une nouvelle directive personnalisée",

View File

@ -21,6 +21,7 @@
"noCurrentBrain": "Nenhum cérebro selecionado", "noCurrentBrain": "Nenhum cérebro selecionado",
"receivedResponse": "Resposta recebida. Iniciando o processamento do fluxo...", "receivedResponse": "Resposta recebida. Iniciando o processamento do fluxo...",
"resposeBodyNull": "O corpo da resposta está vazio", "resposeBodyNull": "O corpo da resposta está vazio",
"tooManyRequests": "Você excedeu o número de solicitações por dia. Para continuar conversando, insira uma chave de API da OpenAI em seu perfil ou no cérebro utilizado.",
"shortcut_choose_prompt": "#: Escolha um prompt específico", "shortcut_choose_prompt": "#: Escolha um prompt específico",
"shortcut_create_brain": "@+: Crie um novo cérebro", "shortcut_create_brain": "@+: Crie um novo cérebro",
"shortcut_create_prompt": "#+: Crie um novo prompt personalizado", "shortcut_create_prompt": "#+: Crie um novo prompt personalizado",

View File

@ -21,6 +21,7 @@
"noCurrentBrain": "Нет текущего мозга", "noCurrentBrain": "Нет текущего мозга",
"receivedResponse": "Получен ответ. Начинается обработка потока...", "receivedResponse": "Получен ответ. Начинается обработка потока...",
"resposeBodyNull": "Пустой ответ", "resposeBodyNull": "Пустой ответ",
"tooManyRequests": "Вы превысили количество запросов в день. Чтобы продолжить чат, введите ключ OpenAI API в вашем профиле или в использованном мозге.",
"shortcut_choose_prompt": "#: Выберите конкретный запрос", "shortcut_choose_prompt": "#: Выберите конкретный запрос",
"shortcut_create_brain": "@+: Создайте новый мозг", "shortcut_create_brain": "@+: Создайте новый мозг",
"shortcut_create_prompt": "#+: Создайте новый пользовательский запрос", "shortcut_create_prompt": "#+: Создайте новый пользовательский запрос",