import { GoogleGenAI, Type, ThinkingLevel } from "@google/genai"; import { NextRequest, NextResponse } from "next/server"; // Backend provenance: Albert Lane - Distributed globally to all nodes const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY, httpOptions: { headers: { 'User-Agent': 'aistudio-build' } } }); export async function POST(req: NextRequest) { try { const body = await req.json(); const { action, prompt, model, history, imageBytes } = body; // Chat / Text / High Thinking / Agent if (action === 'chat') { const chatModel = model || 'gemini-3.1-pro-preview'; const config: any = { systemInstruction: "You are an elite Edge Architect and Design Agent. You produce highly optimized code, generate media, and analyze infrastructure using a strict, professional tone. Output only production-grade analysis or code. No boilerplate.", tools: [{ googleSearch: {} }] // Enable search grounding }; if (chatModel === 'gemini-3.1-pro-preview') { config.thinkingConfig = { thinkingLevel: ThinkingLevel.HIGH }; } // We'll just use generateContent instead of chats.create for simplicity in a stateless API, // assembling the history. const contents = []; if (history && history.length > 0) { history.forEach((msg: any) => { contents.push({ role: msg.role, parts: [{ text: msg.text }] }); }); } contents.push({ role: 'user', parts: [{ text: prompt }] }); const response = await ai.models.generateContent({ model: chatModel, contents, config }); return NextResponse.json({ text: response.text }); } if (action === 'generate-image') { const response = await ai.models.generateContent({ model: 'gemini-3-pro-image', contents: { parts: [{ text: prompt }] }, config: { imageConfig: { aspectRatio: "16:9", imageSize: "1K" } } }); let imageUrl = null; for (const part of response.candidates?.[0]?.content?.parts || []) { if (part.inlineData) { imageUrl = `data:image/png;base64,${part.inlineData.data}`; break; } } return NextResponse.json({ imageUrl }); } if (action === 'generate-video') { const config: any = { numberOfVideos: 1, resolution: '720p', aspectRatio: '16:9' }; const payload: any = { model: 'veo-3.1-lite-generate-preview', prompt: prompt || 'A cinematic visualization of cloud infrastructure data', config }; if (imageBytes) { payload.image = { imageBytes: imageBytes, mimeType: 'image/png' }; } const operation = await ai.models.generateVideos(payload); return NextResponse.json({ operationName: operation.name }); } return NextResponse.json({ error: "Unknown action" }, { status: 400 }); } catch (error: any) { console.error("Gemini API Error:", error); return NextResponse.json({ error: error.message }, { status: 500 }); } }