mirror of
https://github.com/QuivrHQ/quivr.git
synced 2024-12-16 18:52:12 +03:00
a4a2d769b3
* feat: refetch brains list on when new brain is added * feat: update BrainConfig type * feat: update useSettingsTab add usebrainFormState and useSettings tab * feat: add <PrivateAccessConfirmationModal/> modal * feat: update translations * feat: handle brain status change to private * feat: validate chat access * test: fix failaing tests and remove deprecated
82 lines
1.9 KiB
TypeScript
82 lines
1.9 KiB
TypeScript
import { useTranslation } from "react-i18next";
|
|
|
|
import { useBrainContext } from "@/lib/context/BrainProvider/hooks/useBrainContext";
|
|
import { useFetch, useToast } from "@/lib/hooks";
|
|
|
|
import { useHandleStream } from "./useHandleStream";
|
|
import { ChatQuestion } from "../types";
|
|
|
|
interface UseChatService {
|
|
addStreamQuestion: (
|
|
chatId: string,
|
|
chatQuestion: ChatQuestion
|
|
) => Promise<void>;
|
|
}
|
|
|
|
export const useQuestion = (): UseChatService => {
|
|
const { fetchInstance } = useFetch();
|
|
const { currentBrain } = useBrainContext();
|
|
|
|
const { t } = useTranslation(["chat"]);
|
|
const { publish } = useToast();
|
|
const { handleStream } = useHandleStream();
|
|
|
|
const handleFetchError = async (response: Response) => {
|
|
if (response.status === 429) {
|
|
publish({
|
|
variant: "danger",
|
|
text: t("tooManyRequests", { ns: "chat" }),
|
|
});
|
|
|
|
return;
|
|
}
|
|
|
|
const errorMessage = (await response.json()) as { detail: string };
|
|
publish({
|
|
variant: "danger",
|
|
text: errorMessage.detail,
|
|
});
|
|
|
|
return;
|
|
};
|
|
|
|
const addStreamQuestion = async (
|
|
chatId: string,
|
|
chatQuestion: ChatQuestion
|
|
): Promise<void> => {
|
|
const headers = {
|
|
"Content-Type": "application/json",
|
|
Accept: "text/event-stream",
|
|
};
|
|
const body = JSON.stringify(chatQuestion);
|
|
|
|
try {
|
|
const response = await fetchInstance.post(
|
|
`/chat/${chatId}/question/stream?brain_id=${currentBrain?.id ?? ""}`,
|
|
body,
|
|
headers
|
|
);
|
|
if (!response.ok) {
|
|
void handleFetchError(response);
|
|
|
|
return;
|
|
}
|
|
|
|
if (response.body === null) {
|
|
throw new Error(t("resposeBodyNull", { ns: "chat" }));
|
|
}
|
|
|
|
await handleStream(response.body.getReader());
|
|
} catch (error) {
|
|
publish({
|
|
variant: "danger",
|
|
text: String(error),
|
|
});
|
|
}
|
|
};
|
|
|
|
return {
|
|
addStreamQuestion,
|
|
};
|
|
};
|