quivr/frontend/app/chat/hooks/useQuestion.ts

61 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-06-06 19:11:36 +03:00
import { useEffect, useState } from "react";
import { useSupabase } from "@/app/supabase-provider";
import { useBrainConfig } from "@/lib/context/BrainConfigProvider/hooks/useBrainConfig";
import { useAxios } from "@/lib/useAxios";
import { redirect } from "next/navigation";
export const useQuestion = () => {
const [question, setQuestion] = useState("");
const [history, setHistory] = useState<Array<[string, string]>>([]);
const [isPending, setIsPending] = useState(false);
const { session } = useSupabase();
const { axiosInstance } = useAxios();
const {
config: { maxTokens, model, temperature },
} = useBrainConfig();
if (session === null) {
redirect("/login");
}
2023-06-06 19:11:36 +03:00
useEffect(()=>{
// Check if history exists in local storage. If it does, fetch it and set it as history
(async ()=>{
const localHistory = await localStorage.getItem('history')
if(localHistory){
setHistory(JSON.parse(localHistory))
}
})()
}, [])
const askQuestion = async () => {
setHistory((hist) => [...hist, ["user", question]]);
setIsPending(true);
const response = await axiosInstance.post(`/chat/`, {
model,
question,
history,
temperature,
max_tokens: maxTokens,
});
setHistory(response.data.history);
2023-06-06 19:11:36 +03:00
localStorage.setItem('history', JSON.stringify(response.data.history))
setQuestion("");
setIsPending(false);
};
2023-06-06 19:11:36 +03:00
const resetHistory = () => {
localStorage.setItem('history', JSON.stringify([]))
setHistory([])
}
return {
isPending,
history,
question,
setQuestion,
2023-06-06 19:11:36 +03:00
resetHistory,
askQuestion,
};
};