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 */
import { useTranslation } from 'react-i18next';
import axios from "axios";
import { useTranslation } from "react-i18next";
import { useBrainContext } from '@/lib/context/BrainProvider/hooks/useBrainContext';
import { useChatContext } from '@/lib/context/ChatProvider/hooks/useChatContext';
import { useFetch } from '@/lib/hooks';
import { useBrainContext } from "@/lib/context/BrainProvider/hooks/useBrainContext";
import { useChatContext } from "@/lib/context/ChatProvider/hooks/useChatContext";
import { useFetch } from "@/lib/hooks";
import { useToast } from "@/lib/hooks/useToast";
import { ChatHistory, ChatQuestion } from '../types';
import { ChatHistory, ChatQuestion } from "../types";
interface UseChatService {
addStreamQuestion: (
@ -20,12 +22,13 @@ export const useQuestion = (): UseChatService => {
const { updateStreamingHistory } = useChatContext();
const { currentBrain } = useBrainContext();
const { t } = useTranslation(['chat']);
const { t } = useTranslation(["chat"]);
const { publish } = useToast();
const handleStream = async (
reader: ReadableStreamDefaultReader<Uint8Array>
): Promise<void> => {
const decoder = new TextDecoder('utf-8');
const decoder = new TextDecoder("utf-8");
const handleStreamRecursively = async () => {
const { done, value } = await reader.read();
@ -37,7 +40,7 @@ export const useQuestion = (): UseChatService => {
const dataStrings = decoder
.decode(value)
.trim()
.split('data: ')
.split("data: ")
.filter(Boolean);
dataStrings.forEach((data) => {
@ -45,7 +48,7 @@ export const useQuestion = (): UseChatService => {
const parsedData = JSON.parse(data) as ChatHistory;
updateStreamingHistory(parsedData);
} 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
): Promise<void> => {
const headers = {
'Content-Type': 'application/json',
Accept: 'text/event-stream',
"Content-Type": "application/json",
Accept: "text/event-stream",
};
const body = JSON.stringify(chatQuestion);
console.log('Calling API...');
console.log("Calling API...");
try {
const response = await fetchInstance.post(
`/chat/${chatId}/question/stream?brain_id=${currentBrain?.id ?? ''}`,
`/chat/${chatId}/question/stream?brain_id=${currentBrain?.id ?? ""}`,
body,
headers
);
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());
} 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",
"errorParsingData": "Error parsing data",
"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...",
"errorCallingAPI": "Error calling the API",
"ask": "Ask a question, or describe a task.",

View File

@ -21,6 +21,7 @@
"noCurrentBrain": "Sin cerebro seleccionado",
"receivedResponse": "Respuesta recibida. Iniciando gestión de stream...",
"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_create_brain": "@+: Crear un nuevo cerebro",
"shortcut_create_prompt": "#+: Crear una nueva instrucción personalizada",

View File

@ -21,6 +21,7 @@
"noCurrentBrain": "Pas de cerveau actuel",
"receivedResponse": "Réponse reçue. Commence à gérer le flux...",
"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_create_brain": "@+: Créer un nouveau cerveau",
"shortcut_create_prompt": "#+: Créer une nouvelle directive personnalisée",

View File

@ -21,6 +21,7 @@
"noCurrentBrain": "Nenhum cérebro selecionado",
"receivedResponse": "Resposta recebida. Iniciando o processamento do fluxo...",
"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_create_brain": "@+: Crie um novo cérebro",
"shortcut_create_prompt": "#+: Crie um novo prompt personalizado",

View File

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