mirror of
https://github.com/QuivrHQ/quivr.git
synced 2024-12-14 17:03:29 +03:00
✨ explicit too many request in chat error (#1000)
This commit is contained in:
parent
9aaedcff51
commit
20d5294795
@ -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);
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -1,36 +1,37 @@
|
||||
{
|
||||
"title": "Chat with {{brain}}",
|
||||
"brain":"brain",
|
||||
"keyboard_shortcuts": "Keyboard shortcuts",
|
||||
"brains":"brains",
|
||||
"subtitle": "Talk to a language model about your uploaded data",
|
||||
"limit_reached": "You have reached the limit of requests, please try again later",
|
||||
"error_occurred": "Error occurred while getting answer",
|
||||
"noCurrentBrain": "No current brain",
|
||||
"errorParsingData": "Error parsing data",
|
||||
"resposeBodyNull": "Responde body is null",
|
||||
"receivedResponse": "Received response. Starting to handle stream...",
|
||||
"errorCallingAPI": "Error calling the API",
|
||||
"ask": "Ask a question, or describe a task.",
|
||||
"begin_conversation_placeholder": "Begin conversation here...",
|
||||
"thinking": "Thinking...",
|
||||
"chat": "Chat",
|
||||
"errorFetching": "Error occurred while fetching your chats",
|
||||
"chatDeleted": "Chat sucessfully deleted. Id: {{id}}",
|
||||
"errorDeleting": "Error deleting chat: {{error}}",
|
||||
"chatNameUpdated": "Chat name updated",
|
||||
"shortcut_select_brain": "@: Select a brain to talk",
|
||||
"shortcut_select_file": "/: Select a file to talk to",
|
||||
"shortcut_choose_prompt": "#: Choose a specific prompt",
|
||||
"shortcut_create_brain": "@+: Create a new brain",
|
||||
"shortcut_feed_brain": "/+: Feed a brain with knowledge",
|
||||
"shortcut_create_prompt": "#+: Create a new custom prompt",
|
||||
"shortcut_manage_brains": "CMDB: Manage your brains",
|
||||
"shortcut_go_to_user_page": "CMDU: Go to user page",
|
||||
"shortcut_go_to_shortcuts": "CMDK: Go to shortcuts",
|
||||
"chat_title_intro": "Chat with your",
|
||||
"empty_brain_title_prefix": "Upload files in a",
|
||||
"empty_brain_title_suffix": "and chat with them",
|
||||
"actions_bar_placeholder": "Ask a question to @brains or /files and choose your #prompt",
|
||||
"missing_brain": "Please select a brain to chat with"
|
||||
}
|
||||
"title": "Chat with {{brain}}",
|
||||
"brain": "brain",
|
||||
"keyboard_shortcuts": "Keyboard shortcuts",
|
||||
"brains": "brains",
|
||||
"subtitle": "Talk to a language model about your uploaded data",
|
||||
"limit_reached": "You have reached the limit of requests, please try again later",
|
||||
"error_occurred": "Error occurred while getting answer",
|
||||
"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.",
|
||||
"begin_conversation_placeholder": "Begin conversation here...",
|
||||
"thinking": "Thinking...",
|
||||
"chat": "Chat",
|
||||
"errorFetching": "Error occurred while fetching your chats",
|
||||
"chatDeleted": "Chat sucessfully deleted. Id: {{id}}",
|
||||
"errorDeleting": "Error deleting chat: {{error}}",
|
||||
"chatNameUpdated": "Chat name updated",
|
||||
"shortcut_select_brain": "@: Select a brain to talk",
|
||||
"shortcut_select_file": "/: Select a file to talk to",
|
||||
"shortcut_choose_prompt": "#: Choose a specific prompt",
|
||||
"shortcut_create_brain": "@+: Create a new brain",
|
||||
"shortcut_feed_brain": "/+: Feed a brain with knowledge",
|
||||
"shortcut_create_prompt": "#+: Create a new custom prompt",
|
||||
"shortcut_manage_brains": "CMDB: Manage your brains",
|
||||
"shortcut_go_to_user_page": "CMDU: Go to user page",
|
||||
"shortcut_go_to_shortcuts": "CMDK: Go to shortcuts",
|
||||
"chat_title_intro": "Chat with your",
|
||||
"empty_brain_title_prefix": "Upload files in a",
|
||||
"empty_brain_title_suffix": "and chat with them",
|
||||
"actions_bar_placeholder": "Ask a question to @brains or /files and choose your #prompt",
|
||||
"missing_brain": "Please select a brain to chat with"
|
||||
}
|
||||
|
@ -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",
|
||||
@ -34,4 +35,4 @@
|
||||
"thinking": "Pensando...",
|
||||
"title": "Conversa con {{brain}}",
|
||||
"missing_brain": "No hay cerebro seleccionado"
|
||||
}
|
||||
}
|
||||
|
@ -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",
|
||||
@ -34,4 +35,4 @@
|
||||
"thinking": "Réflexion...",
|
||||
"title": "Discuter avec {{brain}}",
|
||||
"missing_brain": "Veuillez selectionner un cerveau pour discuter"
|
||||
}
|
||||
}
|
||||
|
@ -1,37 +1,38 @@
|
||||
{
|
||||
"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.",
|
||||
"begin_conversation_placeholder": "Inicie a conversa aqui...",
|
||||
"brain": "cérebro",
|
||||
"brains": "cérebros",
|
||||
"chat": "Conversa",
|
||||
"chat_title_intro": "Conversa com",
|
||||
"chatDeleted": "Conversa excluída com sucesso. Id: {{id}}",
|
||||
"chatNameUpdated": "Nome da conversa atualizado",
|
||||
"empty_brain_title_intro": "Converse com o seu",
|
||||
"empty_brain_title_prefix": "Carregue arquivos em um",
|
||||
"empty_brain_title_suffix": "e converse com eles",
|
||||
"error_occurred": "Ocorreu um erro ao obter a resposta",
|
||||
"errorCallingAPI": "Erro ao chamar a API",
|
||||
"errorDeleting": "Erro ao excluir a conversa: {{error}}",
|
||||
"errorFetching": "Ocorreu um erro ao buscar suas conversas",
|
||||
"errorParsingData": "Erro ao analisar os dados",
|
||||
"keyboard_shortcuts": "Atalhos do teclado",
|
||||
"limit_reached": "Você atingiu o limite de solicitações, por favor, tente novamente mais tarde",
|
||||
"noCurrentBrain": "Nenhum cérebro selecionado",
|
||||
"receivedResponse": "Resposta recebida. Iniciando o processamento do fluxo...",
|
||||
"resposeBodyNull": "O corpo da resposta está vazio",
|
||||
"shortcut_choose_prompt": "#: Escolha um prompt específico",
|
||||
"shortcut_create_brain": "@+: Crie um novo cérebro",
|
||||
"shortcut_create_prompt": "#+: Crie um novo prompt personalizado",
|
||||
"shortcut_feed_brain": "/+: Alimente um cérebro com conhecimento",
|
||||
"shortcut_go_to_shortcuts": "CMDA: Acesse os atalhos",
|
||||
"shortcut_go_to_user_page": "CMDU: Acesse a página do usuário",
|
||||
"shortcut_manage_brains": "CMGC: Gerencie seus cérebros",
|
||||
"shortcut_select_brain": "@: Selecione um cérebro para conversar",
|
||||
"shortcut_select_file": "/: Selecione um arquivo para conversar",
|
||||
"subtitle": "Converse com um modelo de linguagem sobre seus dados enviados",
|
||||
"thinking": "Pensando...",
|
||||
"title": "Converse com {{brain}}",
|
||||
"missing_brain": "Cérebro não encontrado"
|
||||
}
|
||||
"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.",
|
||||
"begin_conversation_placeholder": "Inicie a conversa aqui...",
|
||||
"brain": "cérebro",
|
||||
"brains": "cérebros",
|
||||
"chat": "Conversa",
|
||||
"chat_title_intro": "Conversa com",
|
||||
"chatDeleted": "Conversa excluída com sucesso. Id: {{id}}",
|
||||
"chatNameUpdated": "Nome da conversa atualizado",
|
||||
"empty_brain_title_intro": "Converse com o seu",
|
||||
"empty_brain_title_prefix": "Carregue arquivos em um",
|
||||
"empty_brain_title_suffix": "e converse com eles",
|
||||
"error_occurred": "Ocorreu um erro ao obter a resposta",
|
||||
"errorCallingAPI": "Erro ao chamar a API",
|
||||
"errorDeleting": "Erro ao excluir a conversa: {{error}}",
|
||||
"errorFetching": "Ocorreu um erro ao buscar suas conversas",
|
||||
"errorParsingData": "Erro ao analisar os dados",
|
||||
"keyboard_shortcuts": "Atalhos do teclado",
|
||||
"limit_reached": "Você atingiu o limite de solicitações, por favor, tente novamente mais tarde",
|
||||
"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",
|
||||
"shortcut_feed_brain": "/+: Alimente um cérebro com conhecimento",
|
||||
"shortcut_go_to_shortcuts": "CMDA: Acesse os atalhos",
|
||||
"shortcut_go_to_user_page": "CMDU: Acesse a página do usuário",
|
||||
"shortcut_manage_brains": "CMGC: Gerencie seus cérebros",
|
||||
"shortcut_select_brain": "@: Selecione um cérebro para conversar",
|
||||
"shortcut_select_file": "/: Selecione um arquivo para conversar",
|
||||
"subtitle": "Converse com um modelo de linguagem sobre seus dados enviados",
|
||||
"thinking": "Pensando...",
|
||||
"title": "Converse com {{brain}}",
|
||||
"missing_brain": "Cérebro não encontrado"
|
||||
}
|
||||
|
@ -1,37 +1,38 @@
|
||||
{
|
||||
"actions_bar_placeholder": "Задайте вопрос @brains или /files и выберите ваш #prompt",
|
||||
"ask": "Задайте вопрос или опишите задачу.",
|
||||
"begin_conversation_placeholder": "Начните беседу здесь...",
|
||||
"brain": "мозг",
|
||||
"brains": "мозги",
|
||||
"chat": "Чат",
|
||||
"chat_title_intro": "Чат с",
|
||||
"chatDeleted": "Чат успешно удален. Id: {{id}}",
|
||||
"chatNameUpdated": "Имя чата обновлено",
|
||||
"empty_brain_title_intro": "Чат с вашими",
|
||||
"empty_brain_title_prefix": "Загрузите файлы в",
|
||||
"empty_brain_title_suffix": "и общайтесь с ними",
|
||||
"error_occurred": "Произошла ошибка при получении ответа",
|
||||
"errorCallingAPI": "Ошибка вызова API",
|
||||
"errorDeleting": "Ошибка при удалении чата: {{error}}",
|
||||
"errorFetching": "Произошла ошибка при получении ваших чатов",
|
||||
"errorParsingData": "Ошибка при разборе данных",
|
||||
"keyboard_shortcuts": "Сочетания клавиш",
|
||||
"limit_reached": "Вы достигли лимита запросов, пожалуйста, попробуйте позже",
|
||||
"noCurrentBrain": "Нет текущего мозга",
|
||||
"receivedResponse": "Получен ответ. Начинается обработка потока...",
|
||||
"resposeBodyNull": "Пустой ответ",
|
||||
"shortcut_choose_prompt": "#: Выберите конкретный запрос",
|
||||
"shortcut_create_brain": "@+: Создайте новый мозг",
|
||||
"shortcut_create_prompt": "#+: Создайте новый пользовательский запрос",
|
||||
"shortcut_feed_brain": "/+: Подайте мозгу знаний",
|
||||
"shortcut_go_to_shortcuts": "CMDK: Перейти к ярлыкам",
|
||||
"shortcut_go_to_user_page": "CMDU: Перейти на страницу пользователя",
|
||||
"shortcut_manage_brains": "CMDB: Управление вашими мозгами",
|
||||
"shortcut_select_brain": "@: Выберите мозг для общения",
|
||||
"shortcut_select_file": "/: Выберите файл для общения",
|
||||
"subtitle": "Общайтесь с языковой моделью о ваших загруженных данных",
|
||||
"thinking": "Думаю...",
|
||||
"title": "Чат с {{brain}}",
|
||||
"missing_brain": "Мозг не найден"
|
||||
}
|
||||
"actions_bar_placeholder": "Задайте вопрос @brains или /files и выберите ваш #prompt",
|
||||
"ask": "Задайте вопрос или опишите задачу.",
|
||||
"begin_conversation_placeholder": "Начните беседу здесь...",
|
||||
"brain": "мозг",
|
||||
"brains": "мозги",
|
||||
"chat": "Чат",
|
||||
"chat_title_intro": "Чат с",
|
||||
"chatDeleted": "Чат успешно удален. Id: {{id}}",
|
||||
"chatNameUpdated": "Имя чата обновлено",
|
||||
"empty_brain_title_intro": "Чат с вашими",
|
||||
"empty_brain_title_prefix": "Загрузите файлы в",
|
||||
"empty_brain_title_suffix": "и общайтесь с ними",
|
||||
"error_occurred": "Произошла ошибка при получении ответа",
|
||||
"errorCallingAPI": "Ошибка вызова API",
|
||||
"errorDeleting": "Ошибка при удалении чата: {{error}}",
|
||||
"errorFetching": "Произошла ошибка при получении ваших чатов",
|
||||
"errorParsingData": "Ошибка при разборе данных",
|
||||
"keyboard_shortcuts": "Сочетания клавиш",
|
||||
"limit_reached": "Вы достигли лимита запросов, пожалуйста, попробуйте позже",
|
||||
"noCurrentBrain": "Нет текущего мозга",
|
||||
"receivedResponse": "Получен ответ. Начинается обработка потока...",
|
||||
"resposeBodyNull": "Пустой ответ",
|
||||
"tooManyRequests": "Вы превысили количество запросов в день. Чтобы продолжить чат, введите ключ OpenAI API в вашем профиле или в использованном мозге.",
|
||||
"shortcut_choose_prompt": "#: Выберите конкретный запрос",
|
||||
"shortcut_create_brain": "@+: Создайте новый мозг",
|
||||
"shortcut_create_prompt": "#+: Создайте новый пользовательский запрос",
|
||||
"shortcut_feed_brain": "/+: Подайте мозгу знаний",
|
||||
"shortcut_go_to_shortcuts": "CMDK: Перейти к ярлыкам",
|
||||
"shortcut_go_to_user_page": "CMDU: Перейти на страницу пользователя",
|
||||
"shortcut_manage_brains": "CMDB: Управление вашими мозгами",
|
||||
"shortcut_select_brain": "@: Выберите мозг для общения",
|
||||
"shortcut_select_file": "/: Выберите файл для общения",
|
||||
"subtitle": "Общайтесь с языковой моделью о ваших загруженных данных",
|
||||
"thinking": "Думаю...",
|
||||
"title": "Чат с {{brain}}",
|
||||
"missing_brain": "Мозг не найден"
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user