|
| 1 | +import { NextRequest, NextResponse } from "next/server" |
| 2 | +import { createGoogleGenerativeAI } from "@ai-sdk/google" |
| 3 | +import { streamText } from "ai" |
| 4 | + |
| 5 | +import { db } from "@/lib/db" |
| 6 | +import { initializeDatabase } from "@/lib/init-db" |
| 7 | +import { |
| 8 | + buildSystemPrompt, |
| 9 | + createUserPrompt, |
| 10 | + TonePreset, |
| 11 | +} from "@/lib/prompts" |
| 12 | + |
| 13 | +// Force dynamic rendering |
| 14 | +export const dynamic = "force-dynamic" |
| 15 | +export const revalidate = 0 |
| 16 | + |
| 17 | +// Initialize the Google Generative AI provider |
| 18 | +const google = createGoogleGenerativeAI({ |
| 19 | + apiKey: process.env.GOOGLE_API_KEY!, |
| 20 | +}) |
| 21 | + |
| 22 | +export async function POST(request: NextRequest) { |
| 23 | + try { |
| 24 | + // Initialize database if needed |
| 25 | + await initializeDatabase() |
| 26 | + |
| 27 | + // Parse request body |
| 28 | + let articleId: string | null = null |
| 29 | + let tone: TonePreset | null = null |
| 30 | + |
| 31 | + try { |
| 32 | + const body = await request.json() |
| 33 | + articleId = body.articleId || null |
| 34 | + tone = body.tone || null |
| 35 | + |
| 36 | + if (!articleId) { |
| 37 | + return NextResponse.json( |
| 38 | + { |
| 39 | + success: false, |
| 40 | + error: "articleId is required", |
| 41 | + }, |
| 42 | + { status: 400 } |
| 43 | + ) |
| 44 | + } |
| 45 | + } catch (error) { |
| 46 | + return NextResponse.json( |
| 47 | + { |
| 48 | + success: false, |
| 49 | + error: "Invalid request body", |
| 50 | + }, |
| 51 | + { status: 400 } |
| 52 | + ) |
| 53 | + } |
| 54 | + |
| 55 | + // Fetch the article by ID |
| 56 | + const result = await db.execute( |
| 57 | + `SELECT * FROM news_articles WHERE id = ?`, |
| 58 | + [articleId] |
| 59 | + ) |
| 60 | + |
| 61 | + if (result.rows.length === 0) { |
| 62 | + return NextResponse.json( |
| 63 | + { |
| 64 | + success: false, |
| 65 | + error: "Article not found", |
| 66 | + }, |
| 67 | + { status: 404 } |
| 68 | + ) |
| 69 | + } |
| 70 | + |
| 71 | + const article = result.rows[0] |
| 72 | + |
| 73 | + console.log(`📰 Regenerating fact for article: ${articleId}`) |
| 74 | + console.log(`🎭 Tone: ${tone || "default"}`) |
| 75 | + |
| 76 | + // Create the prompt for generating a new fact with different angle |
| 77 | + const systemPrompt = buildSystemPrompt(tone) |
| 78 | + const userPrompt = createUserPrompt( |
| 79 | + article.title as string, |
| 80 | + article.content as string, |
| 81 | + undefined, // No matched topics for regenerate |
| 82 | + true // isRegenerate = true |
| 83 | + ) |
| 84 | + |
| 85 | + console.log(`🤖 System Prompt: "${systemPrompt.substring(0, 100)}..."`) |
| 86 | + console.log(`💬 User Prompt: "${userPrompt.substring(0, 100)}..."`) |
| 87 | + |
| 88 | + // Generate the streaming response using Gemini |
| 89 | + console.log(`🚀 Starting AI generation with Gemini...`) |
| 90 | + const aiResult = await streamText({ |
| 91 | + model: google("models/gemini-2.0-flash-lite"), |
| 92 | + system: systemPrompt, |
| 93 | + prompt: userPrompt, |
| 94 | + }) |
| 95 | + |
| 96 | + console.log(`✅ AI generation completed, creating streaming response...`) |
| 97 | + console.log( |
| 98 | + `📝 Expected JSON format: {"funFact": "...", "whyInteresting": "...", "sourceSnippet": "..."}` |
| 99 | + ) |
| 100 | + |
| 101 | + // Create response with metadata |
| 102 | + const response = aiResult.toTextStreamResponse() |
| 103 | + |
| 104 | + // Add custom headers with article metadata (sanitize for HTTP headers) |
| 105 | + response.headers.set( |
| 106 | + "X-Article-Source", |
| 107 | + (article.source as string).replace(/[^\x00-\x7F]/g, "") |
| 108 | + ) |
| 109 | + response.headers.set("X-Article-URL", article.url as string) |
| 110 | + response.headers.set( |
| 111 | + "X-Article-Title", |
| 112 | + (article.title as string).replace(/[^\x00-\x7F]/g, "") |
| 113 | + ) |
| 114 | + response.headers.set( |
| 115 | + "X-Article-Date", |
| 116 | + (article.published_at as string) || (article.created_at as string) |
| 117 | + ) |
| 118 | + response.headers.set("X-Article-ID", article.id as string) |
| 119 | + |
| 120 | + // Add cache control headers to prevent caching issues |
| 121 | + response.headers.set( |
| 122 | + "Cache-Control", |
| 123 | + "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0, s-maxage=0" |
| 124 | + ) |
| 125 | + response.headers.set("Pragma", "no-cache") |
| 126 | + response.headers.set("Expires", "0") |
| 127 | + response.headers.set("Surrogate-Control", "no-store") |
| 128 | + response.headers.set("CDN-Cache-Control", "no-store") |
| 129 | + response.headers.set("Vercel-CDN-Cache-Control", "no-store") |
| 130 | + response.headers.set("Cloudflare-CDN-Cache-Control", "no-store") |
| 131 | + |
| 132 | + // Add timestamp to prevent caching |
| 133 | + response.headers.set("X-Timestamp", Date.now().toString()) |
| 134 | + |
| 135 | + return response |
| 136 | + } catch (error) { |
| 137 | + console.error("Error regenerating fact:", error) |
| 138 | + return NextResponse.json( |
| 139 | + { |
| 140 | + success: false, |
| 141 | + error: |
| 142 | + error instanceof Error |
| 143 | + ? error.message |
| 144 | + : "Failed to regenerate fact", |
| 145 | + }, |
| 146 | + { status: 500 } |
| 147 | + ) |
| 148 | + } |
| 149 | +} |
| 150 | + |
0 commit comments