Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions app/api/chatgpt/route.ts
Original file line number Diff line number Diff line change
@@ -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 });
}
};
28 changes: 27 additions & 1 deletion components/forms/Answer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<z.infer<typeof AnswerSchema>>({
Expand Down Expand Up @@ -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 (
<div>
<div className="flex flex-col justify-between gap-5 sm:flex-row sm:items-center sm:gap-2">
Expand All @@ -71,7 +97,7 @@ const Answer = ({ question, questionId, authorId }: AnswerProps) => {

<Button
className="btn light-border-2 gap-1.5 rounded-md px-4 py-2.5 text-primary-500 shadow-none"
onClick={() => {}}
onClick={() => alert('Coming soon...')}
>
<Image
src="/assets/icons/stars.svg"
Expand Down