2023-06-06 19:11:36 +03:00
|
|
|
import { useEffect, useState } from "react";
|
2023-06-03 21:09:00 +03:00
|
|
|
|
|
|
|
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))
|
|
|
|
}
|
|
|
|
})()
|
|
|
|
}, [])
|
|
|
|
|
2023-06-03 21:09:00 +03:00
|
|
|
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))
|
2023-06-03 21:09:00 +03:00
|
|
|
setQuestion("");
|
|
|
|
setIsPending(false);
|
|
|
|
};
|
|
|
|
|
2023-06-06 19:11:36 +03:00
|
|
|
const resetHistory = () => {
|
|
|
|
localStorage.setItem('history', JSON.stringify([]))
|
|
|
|
setHistory([])
|
|
|
|
}
|
|
|
|
|
2023-06-03 21:09:00 +03:00
|
|
|
return {
|
|
|
|
isPending,
|
|
|
|
history,
|
|
|
|
question,
|
|
|
|
setQuestion,
|
2023-06-06 19:11:36 +03:00
|
|
|
resetHistory,
|
2023-06-03 21:09:00 +03:00
|
|
|
askQuestion,
|
|
|
|
};
|
|
|
|
};
|