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

@ -1,36 +1,37 @@
{ {
"title": "Chat with {{brain}}", "title": "Chat with {{brain}}",
"brain":"brain", "brain": "brain",
"keyboard_shortcuts": "Keyboard shortcuts", "keyboard_shortcuts": "Keyboard shortcuts",
"brains":"brains", "brains": "brains",
"subtitle": "Talk to a language model about your uploaded data", "subtitle": "Talk to a language model about your uploaded data",
"limit_reached": "You have reached the limit of requests, please try again later", "limit_reached": "You have reached the limit of requests, please try again later",
"error_occurred": "Error occurred while getting answer", "error_occurred": "Error occurred while getting answer",
"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",
"receivedResponse": "Received response. Starting to handle stream...", "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.",
"errorCallingAPI": "Error calling the API", "receivedResponse": "Received response. Starting to handle stream...",
"ask": "Ask a question, or describe a task.", "errorCallingAPI": "Error calling the API",
"begin_conversation_placeholder": "Begin conversation here...", "ask": "Ask a question, or describe a task.",
"thinking": "Thinking...", "begin_conversation_placeholder": "Begin conversation here...",
"chat": "Chat", "thinking": "Thinking...",
"errorFetching": "Error occurred while fetching your chats", "chat": "Chat",
"chatDeleted": "Chat sucessfully deleted. Id: {{id}}", "errorFetching": "Error occurred while fetching your chats",
"errorDeleting": "Error deleting chat: {{error}}", "chatDeleted": "Chat sucessfully deleted. Id: {{id}}",
"chatNameUpdated": "Chat name updated", "errorDeleting": "Error deleting chat: {{error}}",
"shortcut_select_brain": "@: Select a brain to talk", "chatNameUpdated": "Chat name updated",
"shortcut_select_file": "/: Select a file to talk to", "shortcut_select_brain": "@: Select a brain to talk",
"shortcut_choose_prompt": "#: Choose a specific prompt", "shortcut_select_file": "/: Select a file to talk to",
"shortcut_create_brain": "@+: Create a new brain", "shortcut_choose_prompt": "#: Choose a specific prompt",
"shortcut_feed_brain": "/+: Feed a brain with knowledge", "shortcut_create_brain": "@+: Create a new brain",
"shortcut_create_prompt": "#+: Create a new custom prompt", "shortcut_feed_brain": "/+: Feed a brain with knowledge",
"shortcut_manage_brains": "CMDB: Manage your brains", "shortcut_create_prompt": "#+: Create a new custom prompt",
"shortcut_go_to_user_page": "CMDU: Go to user page", "shortcut_manage_brains": "CMDB: Manage your brains",
"shortcut_go_to_shortcuts": "CMDK: Go to shortcuts", "shortcut_go_to_user_page": "CMDU: Go to user page",
"chat_title_intro": "Chat with your", "shortcut_go_to_shortcuts": "CMDK: Go to shortcuts",
"empty_brain_title_prefix": "Upload files in a", "chat_title_intro": "Chat with your",
"empty_brain_title_suffix": "and chat with them", "empty_brain_title_prefix": "Upload files in a",
"actions_bar_placeholder": "Ask a question to @brains or /files and choose your #prompt", "empty_brain_title_suffix": "and chat with them",
"missing_brain": "Please select a brain to chat with" "actions_bar_placeholder": "Ask a question to @brains or /files and choose your #prompt",
} "missing_brain": "Please select a brain to chat with"
}

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",
@ -34,4 +35,4 @@
"thinking": "Pensando...", "thinking": "Pensando...",
"title": "Conversa con {{brain}}", "title": "Conversa con {{brain}}",
"missing_brain": "No hay cerebro seleccionado" "missing_brain": "No hay cerebro seleccionado"
} }

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",
@ -34,4 +35,4 @@
"thinking": "Réflexion...", "thinking": "Réflexion...",
"title": "Discuter avec {{brain}}", "title": "Discuter avec {{brain}}",
"missing_brain": "Veuillez selectionner un cerveau pour discuter" "missing_brain": "Veuillez selectionner un cerveau pour discuter"
} }

View File

@ -1,37 +1,38 @@
{ {
"actions_bar_placeholder": "Faça uma pergunta para @cérebros ou /arquivos e escolha o seu #prompt", "actions_bar_placeholder": "Faça uma pergunta para @cérebros ou /arquivos e escolha o seu #prompt",
"ask": "Faça uma pergunta ou descreva uma tarefa.", "ask": "Faça uma pergunta ou descreva uma tarefa.",
"begin_conversation_placeholder": "Inicie a conversa aqui...", "begin_conversation_placeholder": "Inicie a conversa aqui...",
"brain": "cérebro", "brain": "cérebro",
"brains": "cérebros", "brains": "cérebros",
"chat": "Conversa", "chat": "Conversa",
"chat_title_intro": "Conversa com", "chat_title_intro": "Conversa com",
"chatDeleted": "Conversa excluída com sucesso. Id: {{id}}", "chatDeleted": "Conversa excluída com sucesso. Id: {{id}}",
"chatNameUpdated": "Nome da conversa atualizado", "chatNameUpdated": "Nome da conversa atualizado",
"empty_brain_title_intro": "Converse com o seu", "empty_brain_title_intro": "Converse com o seu",
"empty_brain_title_prefix": "Carregue arquivos em um", "empty_brain_title_prefix": "Carregue arquivos em um",
"empty_brain_title_suffix": "e converse com eles", "empty_brain_title_suffix": "e converse com eles",
"error_occurred": "Ocorreu um erro ao obter a resposta", "error_occurred": "Ocorreu um erro ao obter a resposta",
"errorCallingAPI": "Erro ao chamar a API", "errorCallingAPI": "Erro ao chamar a API",
"errorDeleting": "Erro ao excluir a conversa: {{error}}", "errorDeleting": "Erro ao excluir a conversa: {{error}}",
"errorFetching": "Ocorreu um erro ao buscar suas conversas", "errorFetching": "Ocorreu um erro ao buscar suas conversas",
"errorParsingData": "Erro ao analisar os dados", "errorParsingData": "Erro ao analisar os dados",
"keyboard_shortcuts": "Atalhos do teclado", "keyboard_shortcuts": "Atalhos do teclado",
"limit_reached": "Você atingiu o limite de solicitações, por favor, tente novamente mais tarde", "limit_reached": "Você atingiu o limite de solicitações, por favor, tente novamente mais tarde",
"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",
"shortcut_choose_prompt": "#: Escolha um prompt específico", "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_create_brain": "@+: Crie um novo cérebro", "shortcut_choose_prompt": "#: Escolha um prompt específico",
"shortcut_create_prompt": "#+: Crie um novo prompt personalizado", "shortcut_create_brain": "@+: Crie um novo cérebro",
"shortcut_feed_brain": "/+: Alimente um cérebro com conhecimento", "shortcut_create_prompt": "#+: Crie um novo prompt personalizado",
"shortcut_go_to_shortcuts": "CMDA: Acesse os atalhos", "shortcut_feed_brain": "/+: Alimente um cérebro com conhecimento",
"shortcut_go_to_user_page": "CMDU: Acesse a página do usuário", "shortcut_go_to_shortcuts": "CMDA: Acesse os atalhos",
"shortcut_manage_brains": "CMGC: Gerencie seus cérebros", "shortcut_go_to_user_page": "CMDU: Acesse a página do usuário",
"shortcut_select_brain": "@: Selecione um cérebro para conversar", "shortcut_manage_brains": "CMGC: Gerencie seus cérebros",
"shortcut_select_file": "/: Selecione um arquivo para conversar", "shortcut_select_brain": "@: Selecione um cérebro para conversar",
"subtitle": "Converse com um modelo de linguagem sobre seus dados enviados", "shortcut_select_file": "/: Selecione um arquivo para conversar",
"thinking": "Pensando...", "subtitle": "Converse com um modelo de linguagem sobre seus dados enviados",
"title": "Converse com {{brain}}", "thinking": "Pensando...",
"missing_brain": "Cérebro não encontrado" "title": "Converse com {{brain}}",
} "missing_brain": "Cérebro não encontrado"
}

View File

@ -1,37 +1,38 @@
{ {
"actions_bar_placeholder": "Задайте вопрос @brains или /files и выберите ваш #prompt", "actions_bar_placeholder": "Задайте вопрос @brains или /files и выберите ваш #prompt",
"ask": "Задайте вопрос или опишите задачу.", "ask": "Задайте вопрос или опишите задачу.",
"begin_conversation_placeholder": "Начните беседу здесь...", "begin_conversation_placeholder": "Начните беседу здесь...",
"brain": "мозг", "brain": "мозг",
"brains": "мозги", "brains": "мозги",
"chat": "Чат", "chat": "Чат",
"chat_title_intro": "Чат с", "chat_title_intro": "Чат с",
"chatDeleted": "Чат успешно удален. Id: {{id}}", "chatDeleted": "Чат успешно удален. Id: {{id}}",
"chatNameUpdated": "Имя чата обновлено", "chatNameUpdated": "Имя чата обновлено",
"empty_brain_title_intro": "Чат с вашими", "empty_brain_title_intro": "Чат с вашими",
"empty_brain_title_prefix": "Загрузите файлы в", "empty_brain_title_prefix": "Загрузите файлы в",
"empty_brain_title_suffix": "и общайтесь с ними", "empty_brain_title_suffix": "и общайтесь с ними",
"error_occurred": "Произошла ошибка при получении ответа", "error_occurred": "Произошла ошибка при получении ответа",
"errorCallingAPI": "Ошибка вызова API", "errorCallingAPI": "Ошибка вызова API",
"errorDeleting": "Ошибка при удалении чата: {{error}}", "errorDeleting": "Ошибка при удалении чата: {{error}}",
"errorFetching": "Произошла ошибка при получении ваших чатов", "errorFetching": "Произошла ошибка при получении ваших чатов",
"errorParsingData": "Ошибка при разборе данных", "errorParsingData": "Ошибка при разборе данных",
"keyboard_shortcuts": "Сочетания клавиш", "keyboard_shortcuts": "Сочетания клавиш",
"limit_reached": "Вы достигли лимита запросов, пожалуйста, попробуйте позже", "limit_reached": "Вы достигли лимита запросов, пожалуйста, попробуйте позже",
"noCurrentBrain": "Нет текущего мозга", "noCurrentBrain": "Нет текущего мозга",
"receivedResponse": "Получен ответ. Начинается обработка потока...", "receivedResponse": "Получен ответ. Начинается обработка потока...",
"resposeBodyNull": "Пустой ответ", "resposeBodyNull": "Пустой ответ",
"shortcut_choose_prompt": "#: Выберите конкретный запрос", "tooManyRequests": "Вы превысили количество запросов в день. Чтобы продолжить чат, введите ключ OpenAI API в вашем профиле или в использованном мозге.",
"shortcut_create_brain": "@+: Создайте новый мозг", "shortcut_choose_prompt": "#: Выберите конкретный запрос",
"shortcut_create_prompt": "#+: Создайте новый пользовательский запрос", "shortcut_create_brain": "@+: Создайте новый мозг",
"shortcut_feed_brain": "/+: Подайте мозгу знаний", "shortcut_create_prompt": "#+: Создайте новый пользовательский запрос",
"shortcut_go_to_shortcuts": "CMDK: Перейти к ярлыкам", "shortcut_feed_brain": "/+: Подайте мозгу знаний",
"shortcut_go_to_user_page": "CMDU: Перейти на страницу пользователя", "shortcut_go_to_shortcuts": "CMDK: Перейти к ярлыкам",
"shortcut_manage_brains": "CMDB: Управление вашими мозгами", "shortcut_go_to_user_page": "CMDU: Перейти на страницу пользователя",
"shortcut_select_brain": "@: Выберите мозг для общения", "shortcut_manage_brains": "CMDB: Управление вашими мозгами",
"shortcut_select_file": "/: Выберите файл для общения", "shortcut_select_brain": "@: Выберите мозг для общения",
"subtitle": "Общайтесь с языковой моделью о ваших загруженных данных", "shortcut_select_file": "/: Выберите файл для общения",
"thinking": "Думаю...", "subtitle": "Общайтесь с языковой моделью о ваших загруженных данных",
"title": "Чат с {{brain}}", "thinking": "Думаю...",
"missing_brain": "Мозг не найден" "title": "Чат с {{brain}}",
} "missing_brain": "Мозг не найден"
}