apix/app/api/grok/generate/route.ts
Khoa.vo 8741e3b89f
Some checks are pending
CI / build (18.x) (push) Waiting to run
CI / build (20.x) (push) Waiting to run
feat: Initial commit with multi-provider image generation
2026-01-05 13:50:35 +07:00

60 lines
2 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { GrokClient } from '@/lib/providers/grok-client';
export async function POST(req: NextRequest) {
try {
const { prompt, apiKey, cookies, imageCount = 1 } = await req.json();
if (!prompt) {
return NextResponse.json({ error: "Prompt is required" }, { status: 400 });
}
if (!apiKey && !cookies) {
return NextResponse.json(
{ error: "Grok API key or cookies required. Configure in Settings." },
{ status: 401 }
);
}
console.log(`[Grok API Route] Generating ${imageCount} image(s) for: "${prompt.substring(0, 30)}..."`);
const client = new GrokClient({ apiKey, cookies });
const results = await client.generate(prompt, imageCount);
// Download images as base64 for storage
const images = await Promise.all(
results.map(async (img) => {
let base64 = img.data;
if (!base64 && img.url && !img.url.startsWith('data:')) {
try {
base64 = await client.downloadAsBase64(img.url);
} catch (e) {
console.warn("[Grok API Route] Failed to download image:", e);
}
}
return {
data: base64 || '',
url: img.url,
prompt: img.prompt,
model: img.model,
aspectRatio: '1:1' // Grok default
};
})
);
const validImages = images.filter(img => img.data || img.url);
if (validImages.length === 0) {
throw new Error("No valid images generated");
}
return NextResponse.json({ images: validImages });
} catch (error: any) {
console.error("[Grok API Route] Error:", error);
return NextResponse.json(
{ error: error.message || "Grok generation failed" },
{ status: 500 }
);
}
}