This code defines an API route in a Next.js application...

August 30, 2025 at 08:09 PM

import { NextRequest, NextResponse } from 'next/server'; import { GoogleGenerativeAI } from '@google/generative-ai'; const genAI = new GoogleGenerativeAI(process.env.GOOGLE_AI_API_KEY || ''); export async function POST(request: NextRequest) { let description = ''; try { const body = await request.json(); description = body.description; if (!description || description.trim().length === 0) { return NextResponse.json( { error: 'Description is required' }, { status: 400 } ); } // Try Google AI first if API key is configured if (process.env.GOOGLE_AI_API_KEY && process.env.GOOGLE_AI_API_KEY !== 'your_google_ai_api_key_here') { try { const model = genAI.getGenerativeModel({ model: 'gemini-1.5-flash' }); const systemPrompt = `You are an expert career-writing assistant. Generate a 2–5 sentence resume profile summary that acts as a professional introduction. Begin with the candidate's role and years of experience, highlight key skills and industry expertise, and emphasize quantifiable achievements. Use keywords from the target job description and end with a clear value proposition. The tone must be professional, concise, and recruiter-ready. Write in third person without pronouns. Output only the summary.`; const prompt = `${systemPrompt} Candidate's background information: "${description}" Generate the professional profile summary:`; const result = await model.generateContentStream(prompt); const encoder = new TextEncoder(); const stream = new ReadableStream({ async start(controller) { let fullText = ''; for await (const chunk of result.stream) { const chunkText = chunk.text(); fullText += chunkText; controller.enqueue(encoder.encode(`data: ${JSON.stringify({ text: chunkText, fullText })}\n\n`)); } controller.enqueue(encoder.encode(`data: ${JSON.stringify({ done: true, wordCount: fullText.split(' ').length })}\n\n`)); controller.close(); } }); return new Response(stream, { headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' } }); } catch (aiError) { console.error('Google AI error:', aiError); // Fall through to mock generation } } // Fallback mock generation const mockSummary = `Experienced professional with expertise in ${description.toLowerCase()}. Proven track record of delivering results through innovative solutions and strategic thinking. Committed to driving organizational success through collaborative leadership and continuous improvement.`; return NextResponse.json({ summary: mockSummary, wordCount: mockSummary.split(' ').length }); } catch (error) { console.error('API error:', error); return NextResponse.json( { error: 'Failed to generate profile summary' }, { status: 500 } ); } }

This code defines an API route in a Next.js application that processes incoming HTTP POST requests to generate a professional resume profile summary, leveraging Google Generative AI if configured, and falling back to a mock implementation if AI fails or isn't configured.

Key Functional Steps:

  1. Dependencies and Initialization:

    • It imports NextRequest and NextResponse for handling requests and responses within Next.js API routes.
    • It imports GoogleGenerativeAI from @google/generative-ai and initializes it using an API key provided via the process.env.GOOGLE_AI_API_KEY environment variable.
  2. Handling POST Requests:

    • The POST function is defined as the main handler for incoming POST requests.
    • The request body is parsed as JSON to extract a description field.
  3. Validation:

    • Checks if the description is provided and is not empty. If invalid, it responds with a 400 status and an error message.
  4. Generative AI Integration:

    • If a valid GOOGLE_AI_API_KEY is configured, it attempts to generate a professional summary using Google Generative AI.
    • A specific AI model (gemini-1.5-flash) is used, and a detailed "system prompt" is crafted to instruct the AI to generate a well-formatted resume profile summary.
    • The body of the request (i.e., description passed by the user) is included in the prompt to tailor the AI-generated text.
  5. AI Content Streaming:

    • The AI response is streamed and sent back to the client in chunks using a ReadableStream. It tracks the full text and provides updates as the stream generates content.
    • Once completed, it also sends a "done" message with the total word count of the generated text.
  6. Fallback to Mock Generation:

    • If:
      • Google AI is not configured.
      • The API key is invalid.
      • An error occurs during AI processing.
    • It falls back to a hardcoded mock summary generated using the given description.
  7. Error Handling:

    • Handles any unexpected errors or exceptions during the process and returns a 500 status with an appropriate error message.

Behavior:

  • If AI is Enabled and Successful:

    • Generates and streams a professional resume profile summary based on the user's description.
  • If AI Fails or is Disabled:

    • Provides a simple, predefined "mock" summary using the description as input.

Example Inputs and Responses:

Input:

{ "description": "5 years of experience as a software developer specialized in React and Node.js" }

Output (AI Mode, Streamed Response):

data: { "text": "Software developer with 5 years of experience..." }
data: { "text": "... delivering modern web applications..." }
...
data: { "done": true, "wordCount": 42 }

Output (Fallback Mock Mode):

{
  "summary": "Experienced professional with expertise in 5 years of experience as a software developer specialized in react and node.js. Proven track record of delivering results through innovative solutions and strategic thinking. Committed to driving organizational success through collaborative leadership and continuous improvement.",
  "wordCount": 34
}

Purpose:

This function acts as a job-seeking assistant, helping users generate professional summaries based on their background information. It attempts to use advanced AI models for high-quality results but ensures fallback behavior to avoid disruptions.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node