import { NextRequest, NextResponse } from 'next/server'; import { GoogleGenerativeAI } from '@google/generative-ai'; export async function POST(request: NextRequest) { try { const { question, answer, role, difficulty } = await request.json(); const headerApiKey = request.headers.get('x-gemini-api-key'); const apiKey = headerApiKey || process.env.GEMINI_API_KEY; if (!apiKey) { return NextResponse.json( { error: 'GEMINI_API_KEY is not configured. Please add it in Settings or .env.local file.' }, { status: 500 } ); } const genAI = new GoogleGenerativeAI(apiKey); const model = genAI.getGenerativeModel({ model: 'gemini-2.0-flash' }); const prompt = `You are an expert interview evaluator for a ${role} position (${difficulty} level). QUESTION: "${question}" CANDIDATE'S ANSWER: "${answer}" Evaluate the candidate's answer thoroughly. Return ONLY a valid JSON object (no markdown, no code blocks) with these exact fields: { "score": , "relevance": , "clarity": , "technicalAccuracy": , "confidence": , "strengths": [], "weaknesses": [], "suggestions": [], "sampleAnswer": "" } Be fair but rigorous. Provide constructive, actionable feedback. The sample answer should demonstrate what an excellent response looks like.`; const result = await model.generateContent(prompt); const responseText = result.response.text(); // Parse JSON from the response const jsonMatch = responseText.match(/\{[\s\S]*\}/); if (!jsonMatch) { throw new Error('Failed to parse evaluation from AI response'); } const evaluation = JSON.parse(jsonMatch[0]); return NextResponse.json({ evaluation }); } catch (error) { console.error('Error evaluating answer:', error); return NextResponse.json( { error: 'Failed to evaluate answer. Please try again.' }, { status: 500 } ); } }