|
| 1 | +import { NextRequest, NextResponse } from "next/server"; |
| 2 | +import { GoogleGenerativeAI } from "@google/generative-ai"; |
| 3 | +import { HistoryItem, HistoryPart } from "@/lib/types"; |
| 4 | + |
| 5 | +// Initialize the Google Gen AI client with your API key |
| 6 | +const GEMINI_API_KEY = process.env.GEMINI_API_KEY || ""; |
| 7 | +const genAI = new GoogleGenerativeAI(GEMINI_API_KEY); |
| 8 | + |
| 9 | +// Define the model ID for Gemini 2.0 Flash experimental |
| 10 | +const MODEL_ID = "gemini-2.0-flash-exp"; |
| 11 | + |
| 12 | +// Define interface for the formatted history item |
| 13 | +interface FormattedHistoryItem { |
| 14 | + role: "user" | "model"; |
| 15 | + parts: Array<{ |
| 16 | + text?: string; |
| 17 | + inlineData?: { data: string; mimeType: string }; |
| 18 | + }>; |
| 19 | +} |
| 20 | + |
| 21 | +export async function POST(req: NextRequest) { |
| 22 | + try { |
| 23 | + // Parse JSON request instead of FormData |
| 24 | + const requestData = await req.json(); |
| 25 | + const { prompt, image: inputImage, history } = requestData; |
| 26 | + |
| 27 | + if (!prompt) { |
| 28 | + return NextResponse.json( |
| 29 | + { error: "Prompt is required" }, |
| 30 | + { status: 400 } |
| 31 | + ); |
| 32 | + } |
| 33 | + |
| 34 | + // Get the model with the correct configuration |
| 35 | + const model = genAI.getGenerativeModel({ |
| 36 | + model: MODEL_ID, |
| 37 | + generationConfig: { |
| 38 | + temperature: 1, |
| 39 | + topP: 0.95, |
| 40 | + topK: 40, |
| 41 | + // @ts-expect-error - Gemini API JS is missing this type |
| 42 | + responseModalities: ["Text", "Image"], |
| 43 | + }, |
| 44 | + }); |
| 45 | + |
| 46 | + let result; |
| 47 | + |
| 48 | + try { |
| 49 | + // Convert history to the format expected by Gemini API |
| 50 | + const formattedHistory = |
| 51 | + history && history.length > 0 |
| 52 | + ? history |
| 53 | + .map((item: HistoryItem) => { |
| 54 | + return { |
| 55 | + role: item.role, |
| 56 | + parts: item.parts |
| 57 | + .map((part: HistoryPart) => { |
| 58 | + if (part.text) { |
| 59 | + return { text: part.text }; |
| 60 | + } |
| 61 | + if (part.image && item.role === "user") { |
| 62 | + const imgParts = part.image.split(","); |
| 63 | + if (imgParts.length > 1) { |
| 64 | + return { |
| 65 | + inlineData: { |
| 66 | + data: imgParts[1], |
| 67 | + mimeType: part.image.includes("image/png") |
| 68 | + ? "image/png" |
| 69 | + : "image/jpeg", |
| 70 | + }, |
| 71 | + }; |
| 72 | + } |
| 73 | + } |
| 74 | + return { text: "" }; |
| 75 | + }) |
| 76 | + .filter((part) => Object.keys(part).length > 0), // Remove empty parts |
| 77 | + }; |
| 78 | + }) |
| 79 | + .filter((item: FormattedHistoryItem) => item.parts.length > 0) // Remove items with no parts |
| 80 | + : []; |
| 81 | + |
| 82 | + // Create a chat session with the formatted history |
| 83 | + const chat = model.startChat({ |
| 84 | + history: formattedHistory, |
| 85 | + }); |
| 86 | + |
| 87 | + // Prepare the current message parts |
| 88 | + const messageParts = []; |
| 89 | + |
| 90 | + // Add the text prompt |
| 91 | + messageParts.push({ text: prompt }); |
| 92 | + |
| 93 | + // Add the image if provided |
| 94 | + if (inputImage) { |
| 95 | + // For image editing |
| 96 | + console.log("Processing image edit request"); |
| 97 | + |
| 98 | + // Check if the image is a valid data URL |
| 99 | + if (!inputImage.startsWith("data:")) { |
| 100 | + throw new Error("Invalid image data URL format"); |
| 101 | + } |
| 102 | + |
| 103 | + const imageParts = inputImage.split(","); |
| 104 | + if (imageParts.length < 2) { |
| 105 | + throw new Error("Invalid image data URL format"); |
| 106 | + } |
| 107 | + |
| 108 | + const base64Image = imageParts[1]; |
| 109 | + const mimeType = inputImage.includes("image/png") |
| 110 | + ? "image/png" |
| 111 | + : "image/jpeg"; |
| 112 | + console.log( |
| 113 | + "Base64 image length:", |
| 114 | + base64Image.length, |
| 115 | + "MIME type:", |
| 116 | + mimeType |
| 117 | + ); |
| 118 | + |
| 119 | + // Add the image to message parts |
| 120 | + messageParts.push({ |
| 121 | + inlineData: { |
| 122 | + data: base64Image, |
| 123 | + mimeType: mimeType, |
| 124 | + }, |
| 125 | + }); |
| 126 | + } |
| 127 | + |
| 128 | + // Send the message to the chat |
| 129 | + console.log("Sending message with", messageParts.length, "parts"); |
| 130 | + result = await chat.sendMessage(messageParts); |
| 131 | + } catch (error) { |
| 132 | + console.error("Error in chat.sendMessage:", error); |
| 133 | + throw error; |
| 134 | + } |
| 135 | + |
| 136 | + const response = result.response; |
| 137 | + |
| 138 | + let textResponse = null; |
| 139 | + let imageData = null; |
| 140 | + let mimeType = "image/png"; |
| 141 | + |
| 142 | + // Process the response |
| 143 | + if (response.candidates && response.candidates.length > 0) { |
| 144 | + const parts = response.candidates[0].content.parts; |
| 145 | + console.log("Number of parts in response:", parts.length); |
| 146 | + |
| 147 | + for (const part of parts) { |
| 148 | + if ("inlineData" in part && part.inlineData) { |
| 149 | + // Get the image data |
| 150 | + imageData = part.inlineData.data; |
| 151 | + mimeType = part.inlineData.mimeType || "image/png"; |
| 152 | + console.log( |
| 153 | + "Image data received, length:", |
| 154 | + imageData.length, |
| 155 | + "MIME type:", |
| 156 | + mimeType |
| 157 | + ); |
| 158 | + } else if ("text" in part && part.text) { |
| 159 | + // Store the text |
| 160 | + textResponse = part.text; |
| 161 | + console.log( |
| 162 | + "Text response received:", |
| 163 | + textResponse.substring(0, 50) + "..." |
| 164 | + ); |
| 165 | + } |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + // Return just the base64 image and description as JSON |
| 170 | + return NextResponse.json({ |
| 171 | + image: imageData ? `data:${mimeType};base64,${imageData}` : null, |
| 172 | + description: textResponse, |
| 173 | + }); |
| 174 | + } catch (error) { |
| 175 | + console.error("Error generating image:", error); |
| 176 | + return NextResponse.json( |
| 177 | + { |
| 178 | + error: "Failed to generate image", |
| 179 | + details: error instanceof Error ? error.message : String(error), |
| 180 | + }, |
| 181 | + { status: 500 } |
| 182 | + ); |
| 183 | + } |
| 184 | +} |
0 commit comments