Spaces:
Build error
Build error
| import { NextRequest, NextResponse } from "next/server"; | |
| import ZAI from "z-ai-web-dev-sdk"; | |
| const PROMPT_ENGINEER_SYSTEM = `Eres un Ingeniero de Prompts experto especializado en optimizar solicitudes en lenguaje natural para diferentes sistemas de IA. Tu trabajo es analizar la intenci贸n del usuario y generar prompts optimizados. | |
| ## TUS ESPECIALIDADES: | |
| ### 1. GENERACI脫N DE IM脕GENES | |
| Para im谩genes, optimiza prompts incluyendo: | |
| - Estilo art铆stico (realista, anime, oil painting, digital art, etc.) | |
| - Iluminaci贸n (golden hour, studio lighting, dramatic, soft) | |
| - Composici贸n (close-up, full body, landscape, portrait) | |
| - Calidad y detalles (4K, highly detailed, masterpiece) | |
| - Mood/atm贸sfera (cinematic, vibrant, moody) | |
| - Para personas: descripci贸n f铆sica detallada, ropa, pose, expresi贸n | |
| ### 2. GENERACI脫N DE VIDEOS | |
| Para videos, optimiza incluyendo: | |
| - Escena y ambiente | |
| - Movimientos de c谩mara (pan, zoom, tracking) | |
| - Acciones y transiciones | |
| - Duraci贸n estimada | |
| - Estilo visual | |
| - Audio/m煤sica sugerida | |
| ### 3. AN脕LISIS DE C脫DIGO | |
| Para c贸digo, estructura la solicitud: | |
| - Lenguaje de programaci贸n | |
| - Framework espec铆fico si aplica | |
| - Funcionalidad requerida | |
| - Restricciones y requisitos | |
| - Nivel de complejidad | |
| ### 4. CONTENIDO PARA REDES SOCIALES | |
| - Plataforma espec铆fica (YouTube, TikTok, Instagram, Twitter) | |
| - Tono y estilo | |
| - Longitud apropiada | |
| - Hashtags sugeridos | |
| - Horarios 贸ptimos de publicaci贸n | |
| ## REGLAS DE CENSURA POR PLATAFORMA: | |
| ### YouTube: | |
| - Sin desnudez ni contenido sexual | |
| - Violencia moderada permitida con advertencia | |
| - Sin discurso de odio | |
| - Sin contenido ilegal | |
| - Lenguaje moderado permitido | |
| ### TikTok: | |
| - Sin desnudez ni insinuaciones sexuales | |
| - Sin violencia gr谩fica | |
| - Sin contenido de autolesi贸n | |
| - Sin desinformaci贸n | |
| - M煤sica con licencia 煤nicamente | |
| ### Instagram: | |
| - Sin desnudez (arte cl谩sico con moderaci贸n) | |
| - Sin violencia gr谩fica | |
| - Sin contenido de autolesi贸n | |
| - Sin discurso de odio | |
| - Im谩genes editadas deben etiquetarse | |
| ### Twitter/X: | |
| - Mayor libertad pero con advertencias | |
| - Contenido sensible debe marcarse | |
| - Sin contenido ilegal | |
| ## FORMATO DE RESPUESTA: | |
| Responde SIEMPRE en este formato JSON: | |
| { | |
| "type": "image|video|code|text|social", | |
| "optimizedPrompt": "El prompt optimizado y detallado", | |
| "suggestions": ["sugerencia1", "sugerencia2"], | |
| "censorWarnings": ["advertencia1"] o [], | |
| "platformCompatible": ["youtube", "tiktok", ...], | |
| "parameters": { | |
| // Par谩metros t茅cnicos recomendados | |
| } | |
| }`; | |
| export async function POST(request: NextRequest) { | |
| try { | |
| const body = await request.json(); | |
| const { prompt, type, platform, character } = body; | |
| if (!prompt) { | |
| return NextResponse.json( | |
| { success: false, error: "El prompt es requerido" }, | |
| { status: 400 } | |
| ); | |
| } | |
| const zai = await ZAI.create(); | |
| // Construir el contexto | |
| let contextPrompt = prompt; | |
| if (type) { | |
| contextPrompt = `Tipo de tarea: ${type}\nSolicitud: ${prompt}`; | |
| } | |
| if (platform) { | |
| contextPrompt += `\nPlataforma destino: ${platform}`; | |
| } | |
| if (character) { | |
| contextPrompt += `\nPersonaje/Referencia: ${character}`; | |
| } | |
| const completion = await zai.chat.completions.create({ | |
| messages: [ | |
| { role: "system", content: PROMPT_ENGINEER_SYSTEM }, | |
| { role: "user", content: contextPrompt } | |
| ], | |
| temperature: 0.7, | |
| max_tokens: 2000, | |
| }); | |
| const response = completion.choices[0]?.message?.content || ""; | |
| // Intentar parsear el JSON de la respuesta | |
| let parsedResponse; | |
| try { | |
| // Buscar JSON en la respuesta | |
| const jsonMatch = response.match(/\{[\s\S]*\}/); | |
| if (jsonMatch) { | |
| parsedResponse = JSON.parse(jsonMatch[0]); | |
| } else { | |
| parsedResponse = { | |
| type: type || "text", | |
| optimizedPrompt: response, | |
| suggestions: [], | |
| censorWarnings: [], | |
| platformCompatible: ["general"], | |
| parameters: {} | |
| }; | |
| } | |
| } catch { | |
| parsedResponse = { | |
| type: type || "text", | |
| optimizedPrompt: response, | |
| suggestions: [], | |
| censorWarnings: [], | |
| platformCompatible: ["general"], | |
| parameters: {} | |
| }; | |
| } | |
| return NextResponse.json({ | |
| success: true, | |
| originalPrompt: prompt, | |
| ...parsedResponse | |
| }); | |
| } catch (error) { | |
| console.error("Error in prompt engineer:", error); | |
| return NextResponse.json( | |
| { success: false, error: "Error al procesar el prompt" }, | |
| { status: 500 } | |
| ); | |
| } | |
| } | |
| // Endpoint para obtener sugerencias de prompts | |
| export async function GET(request: NextRequest) { | |
| const { searchParams } = new URL(request.url); | |
| const category = searchParams.get("category") || "image"; | |
| const templates = { | |
| image: [ | |
| { | |
| name: "Retrato Profesional", | |
| template: "Retrato profesional de [persona], iluminaci贸n de estudio, fondo neutro, alta calidad, expresi贸n [emoci贸n]", | |
| variables: ["persona", "emoci贸n"] | |
| }, | |
| { | |
| name: "Escena Cinematogr谩fica", | |
| template: "Escena cinematogr谩fica de [descripci贸n], iluminaci贸n golden hour, atm贸sfera [mood], estilo pel铆cula, 4K", | |
| variables: ["descripci贸n", "mood"] | |
| }, | |
| { | |
| name: "Arte Digital", | |
| template: "Arte digital de [sujeto], estilo [estilo], colores vibrantes, altamente detallado, trending on artstation", | |
| variables: ["sujeto", "estilo"] | |
| } | |
| ], | |
| video: [ | |
| { | |
| name: "Video Promocional", | |
| template: "Video promocional de [producto/servicio], duraci贸n 30 segundos, estilo moderno, transiciones suaves", | |
| variables: ["producto/servicio"] | |
| }, | |
| { | |
| name: "Tutorial Animado", | |
| template: "Video tutorial animado sobre [tema], estilo infograf铆a, explicaci贸n paso a paso, iconos claros", | |
| variables: ["tema"] | |
| } | |
| ], | |
| code: [ | |
| { | |
| name: "API REST", | |
| template: "Crear API REST en [lenguaje] con [framework] para [funcionalidad], incluir validaci贸n y manejo de errores", | |
| variables: ["lenguaje", "framework", "funcionalidad"] | |
| }, | |
| { | |
| name: "Componente UI", | |
| template: "Componente [tipo] en React con TypeScript, props: [props], incluir estados y animaciones", | |
| variables: ["tipo", "props"] | |
| } | |
| ] | |
| }; | |
| return NextResponse.json({ | |
| success: true, | |
| templates: templates[category as keyof typeof templates] || templates.image | |
| }); | |
| } | |