ai-flash-card / src / app / api / flashcard-generator / route.ts
route.ts
Raw
import OpenAI from 'openai';

// Initialize OpenAI client
const openai = new OpenAI({
    apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY!,
});

// In-memory store for generated questions (would be better to use a database in production)
const generatedQuestions = new Set<string>();

export async function POST(req: Request) {
    try {
        const { prompt } = await req.json();

        if (!prompt) {
            return new Response('Prompt is required', { status: 400 });
        }

        // Generate the question
        const questionPrompt = `
        You are a master of a flashcard app and you want to generate a question based on the following text.
        1. Randomly select a part of the text (end, beginning or middle), try to focus on names, dates and concepts.
        2. Generate a question/concept based on the selected part.
        3. Ensure the question is specific to the content and no more than 50 characters long.
        Example: What is the capital of France?
        **Text:**
        '${prompt}'
        `;

        let questionText = '';
        let attempts = 0;
        const maxAttempts = 10; // Limit the number of attempts to avoid infinite loops

        while (attempts < maxAttempts) {
            const questionResponse = await openai.chat.completions.create({
                model: 'gpt-3.5-turbo',
                messages: [{ role: 'user', content: questionPrompt }],
            });

            questionText = questionResponse.choices[0].message?.content?.trim() || '';

            if (questionText && !generatedQuestions.has(questionText)) {
                generatedQuestions.add(questionText);
                break;
            }

            attempts++;
        }

        if (attempts === maxAttempts) {
            return new Response('Failed to generate a unique question', { status: 500 });
        }

        // Generate the answer
        const answerPrompt = `
            Based on the following question, generate a concise answer:
            Example: Question: "What is the capital of France?" Answer: "Paris"
            **Question:**
            '${questionText}'
            **Text:**
            '${prompt}'
            Output should be less than 60 characters and should be conscise.
        `;

        const answerResponse = await openai.chat.completions.create({
            model: 'gpt-3.5-turbo',
            messages: [{ role: 'user', content: answerPrompt }],
        });

        const answerText = answerResponse.choices[0].message?.content?.trim() || '';

        // Create a structured response
        const finalResult = {
            question: questionText,
            answer: answerText
        };

        return new Response(JSON.stringify(finalResult), {
            headers: { 'Content-Type': 'application/json' },
        });

    } catch (error) {
        console.error('Error in API route:', error);
        return new Response('Internal Server Error', { status: 500 });
    }
}