diff --git a/app/api/chatgpt/route.ts b/app/api/chatgpt/route.ts new file mode 100644 index 0000000..7855bc9 --- /dev/null +++ b/app/api/chatgpt/route.ts @@ -0,0 +1,36 @@ +import { NextResponse } from 'next/server'; + +export const POST = async (request: Request) => { + const { question } = await request.json(); + + try { + const response = await fetch('https://api.openai.com/v1/chat/completions', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${process.env.OPEN_AI_API_KEY}`, + }, + body: JSON.stringify({ + model: 'gpt-3.5-turbo', + messages: [ + { + role: 'system', + content: 'You are a helpful assistant.', + }, + { + role: 'user', + content: `Tell me ${question}`, + }, + ], + }), + }); + + const data = await response.json(); + console.log('DATA: ', data); + const reply = data.choices[0].message.content; + + return NextResponse.json({ reply }); + } catch (error: any) { + return NextResponse.json({ error: error.message }); + } +}; diff --git a/components/forms/Answer.tsx b/components/forms/Answer.tsx index dffe40a..16bb9a8 100644 --- a/components/forms/Answer.tsx +++ b/components/forms/Answer.tsx @@ -29,6 +29,7 @@ const Answer = ({ question, questionId, authorId }: AnswerProps) => { const { mode } = useTheme(); const editorRef = useRef(null); const [isSubmitting, setIsSubmitting] = useState(false); + const [isSubmittingAI, setIsSubmittingAI] = useState(false); const router = useRouter(); const form = useForm>({ @@ -62,6 +63,31 @@ const Answer = ({ question, questionId, authorId }: AnswerProps) => { } } + const generateAIAnswer = async () => { + if (!authorId) return; + + setIsSubmittingAI(true); + + try { + const response = await fetch( + `${process.env.NEXT_PUBLIC_SERVER_URL}/api/chatgpt`, + { + method: 'POST', + body: JSON.stringify({ question }), + }, + ); + + const aiAnswer = await response.json(); + + alert(aiAnswer.reply); + } catch (error) { + console.log(error); + throw error; + } finally { + setIsSubmittingAI(false); + } + }; + return (
@@ -71,7 +97,7 @@ const Answer = ({ question, questionId, authorId }: AnswerProps) => {