diff --git a/app/[chapter]/[subchapter]/questions/[question]/page.tsx b/app/[chapter]/[subchapter]/questions/[question]/page.tsx index 7823ee0..5e006fe 100644 --- a/app/[chapter]/[subchapter]/questions/[question]/page.tsx +++ b/app/[chapter]/[subchapter]/questions/[question]/page.tsx @@ -3,6 +3,8 @@ import { content } from '@/content'; import Link from 'next/link'; import Question from '@/components/question/question'; import { useState } from 'react'; +import { Button } from '@/components/ui/button'; +import { useMutation, useQueryClient } from '@tanstack/react-query'; export default function SubchapterQuestionPage({ params: { @@ -32,6 +34,24 @@ export default function SubchapterQuestionPage({ const [showSolution, setShowSolution] = useState(false); + const explanationMutation = useMutation({ + mutationKey: ['explanation', questions[questionIndex]], + mutationFn: async () => { + const response = await fetch('api', { + method: 'POST', + body: JSON.stringify({ + question: questions[questionIndex], + }), + }); + + const data = await response.text(); + console.log(data); + return data; + }, + }); + + console.log(explanationMutation.isSuccess); + return ( <>
@@ -50,6 +70,25 @@ export default function SubchapterQuestionPage({ setShowSolution={setShowSolution} onAnswerCheck={() => setShowSolution(true)} /> + {explanationMutation.isSuccess ? ( +
+

Explanation

+

+ {explanationMutation.data} +

+
+ ) : ( + + )}
diff --git a/app/[chapter]/[subchapter]/questions/api/route.ts b/app/[chapter]/[subchapter]/questions/api/route.ts new file mode 100644 index 0000000..8ea9e16 --- /dev/null +++ b/app/[chapter]/[subchapter]/questions/api/route.ts @@ -0,0 +1,22 @@ +import OpenAI from 'openai'; + +const openai = new OpenAI(); + +export async function POST(request: Request) { + const body = await request.json(); + + const params: OpenAI.Chat.ChatCompletionCreateParams = { + messages: [ + { + role: 'system', + content: 'Please explain this question using natural language', + }, + { role: 'user', content: JSON.stringify(body.question) }, + ], + model: 'gpt-3.5-turbo', + }; + + const completion = await openai.chat.completions.create(params); + + return new Response(completion.choices[0].message.content); +} diff --git a/app/layout.tsx b/app/layout.tsx index cf3dca8..8207b31 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -4,7 +4,7 @@ import './globals.css'; import Navbar from '@/components/navbar'; import { Footer } from '@/components/footer'; import { content } from '@/content'; -import { CSPostHogProvider } from '@/components/providers'; +import { CSPostHogProvider, ReactQueryProvider } from '@/components/providers'; const inter = Inter({ subsets: ['latin'], @@ -40,13 +40,15 @@ export default function RootLayout({ return ( - - -
{children}
-