Skip to content

Commit

Permalink
Add explanation feature using OpenAI and React-Query
Browse files Browse the repository at this point in the history
  • Loading branch information
markwitt1 committed Apr 26, 2024
1 parent 837d80a commit 5b55a08
Show file tree
Hide file tree
Showing 7 changed files with 353 additions and 9 deletions.
39 changes: 39 additions & 0 deletions app/[chapter]/[subchapter]/questions/[question]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down Expand Up @@ -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 (
<>
<div className='flex h-full w-full overflow-scroll'>
Expand All @@ -50,6 +70,25 @@ export default function SubchapterQuestionPage({
setShowSolution={setShowSolution}
onAnswerCheck={() => setShowSolution(true)}
/>
{explanationMutation.isSuccess ? (
<div className='mt-4 max-w-[50%]'>
<h2 className='text-xl font-bold text-gray-900'>Explanation</h2>
<p className='break-words text-gray-700'>
{explanationMutation.data}
</p>
</div>
) : (
<Button
onClick={
explanationMutation.isPending
? undefined
: () => explanationMutation.mutateAsync()
}
disabled={explanationMutation.isPending}
>
{explanationMutation.isPending ? 'Loading...' : 'Get explanation'}
</Button>
)}
</div>
</div>
</>
Expand Down
22 changes: 22 additions & 0 deletions app/[chapter]/[subchapter]/questions/api/route.ts
Original file line number Diff line number Diff line change
@@ -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);
}
18 changes: 10 additions & 8 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
Expand Down Expand Up @@ -40,13 +40,15 @@ export default function RootLayout({
return (
<html lang='en'>
<CSPostHogProvider>
<body
className={`h-screen min-h-screen bg-white text-primary antialiased ${inter.className}`}
>
<Navbar chapters={content.chapters} />
<main className='flex h-full w-full'>{children}</main>
<Footer />
</body>
<ReactQueryProvider>
<body
className={`h-screen min-h-screen bg-white text-primary antialiased ${inter.className}`}
>
<Navbar chapters={content.chapters} />
<main className='flex h-full w-full'>{children}</main>
<Footer />
</body>
</ReactQueryProvider>
</CSPostHogProvider>
</html>
);
Expand Down
8 changes: 8 additions & 0 deletions components/providers.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
'use client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import posthog from 'posthog-js';
import { PostHogProvider } from 'posthog-js/react';
import { ReactNode } from 'react';
Expand All @@ -11,3 +12,10 @@ if (typeof window !== 'undefined') {
export function CSPostHogProvider({ children }: { children: ReactNode }) {
return <PostHogProvider client={posthog}>{children}</PostHogProvider>;
}

const queryClient = new QueryClient();
export function ReactQueryProvider({ children }: { children: ReactNode }) {
return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
}
122 changes: 122 additions & 0 deletions components/ui/dialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
"use client"

import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"

import { cn } from "@/lib/utils"

const Dialog = DialogPrimitive.Root

const DialogTrigger = DialogPrimitive.Trigger

const DialogPortal = DialogPrimitive.Portal

const DialogClose = DialogPrimitive.Close

const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName

const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName

const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"

const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"

const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName

const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName

export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,19 @@
"type": "module",
"dependencies": {
"@radix-ui/react-accordion": "^1.1.2",
"@radix-ui/react-dialog": "^1.0.5",
"@radix-ui/react-dropdown-menu": "^2.0.6",
"@radix-ui/react-label": "^2.0.2",
"@radix-ui/react-slot": "^1.0.2",
"@supabase/ssr": "^0.3.0",
"@supabase/supabase-js": "^2.42.3",
"@tanstack/react-query": "^5.32.0",
"class-variance-authority": "^0.7.0",
"classnames": "^2.5.1",
"clsx": "^2.1.0",
"lucide-react": "^0.367.0",
"next": "14.1.3",
"openai": "^4.38.5",
"posthog-js": "^1.121.4",
"posthog-node": "^4.0.0",
"react": "^18.2.0",
Expand Down
Loading

0 comments on commit 5b55a08

Please sign in to comment.