Fix API key placeholder - add valid MiniMax key in .env.local

This commit is contained in:
root
2026-02-26 19:02:48 +01:00
parent ba775f3fb7
commit 57a7674b5c
4 changed files with 554 additions and 30 deletions
+45 -30
View File
@@ -1,10 +1,12 @@
import { NextRequest, NextResponse } from "next/server";
const MINIMAX_API_KEY = process.env.MINIMAX_API_KEY || "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTaXRlTWVudGUiLCJyb2xlIjoiYW5vbiIsImlhdCI6MTczODcxMjAwMCwiZXhwIjoyMDU0MzcyMDAwfQ.VxYNdTUkG4N0K2T8K3pK4JzY3vN8X9vK2pK3JzY2vN8X9";
// ⚠️ IMPORTANT: Update with your valid MiniMax API key
// Get key from: https://platform.minimaxi.com/
const MINIMAX_API_KEY = process.env.MINIMAX_API_KEY || "YOUR_API_KEY_HERE";
const MINIMAX_BASE_URL = "https://api.minimax.chat/v1";
interface Message {
role: "user" | "assistant";
role: "system" | "user" | "assistant";
content: string;
}
@@ -21,38 +23,53 @@ export async function POST(request: NextRequest) {
const body: RequestBody = await request.json();
const { message, language, businessType, businessName, history = [] } = body;
// STRICT RULES AS PER SPEC
// Strict rules as per spec
const systemPrompt = `Eres el asistente de IA de SiteMente, una empresa que ayuda negocios locales en España a implementar inteligencia artificial.
REGLAS ESTRICTAS:
1. NUNCA digas que eres humano. Eres "el asistente de IA" o "inteligencia artificial".
2. NUNCA prometas precios exactos. Usa "desde €299/mes" o "depende del plan".
3. NUNCA prometas números garantizados (ventas, clientes, etc).
4. SIEMPRE guía a reservar una demo de 15 minutos con una persona real.
5. Mantén respuestas cortas (1-3 oraciones).
6. Si no entiendes, responde de forma simple.
REGLAS OBLIGATORIAS:
1. NUNCA digas que eres humano o un empleado real. Eres "el asistente de inteligencia artificial".
2. NUNCA des precios exactos. Usa "desde €299/mes" o "consulta nuestro pricing".
3. NUNCA garantices resultados o números de ventas.
4. SIEMPRE sugiere reservar una demo de 15 minutos con una persona real.
5. Responde de forma natural y conversacional, como un profesional útil.
6. Si no entiendes, sé honesto y pide que repitan.
IDIOMA: Responde en el mismo idioma que el usuario. Por defecto español.
IDIOMA: Responde siempre en el mismo idioma que usa el usuario. Por defecto español de España.
EJEMPLO DE RESPUESTAS:
- "¿Cuánto cuesta?" → "Tenemos planes desde 299€/mes. ¿Te gustaría que te enviemos información?"
- "¿Puedes hacer esto?" → "Seguro que podemos ayudarte. ¿Por qué no agendamos una demo de 15 minutos para hablar?"
- "No entiendo" → "No he entendido del todo, ¿podrías repetirlo o escribirlo, por favor?"
EJEMPLOS:
- "¿Cuánto cuesta?" → "Tenemos planes desde 299€/mes.¿Te gustaría que te mandemos detalles?"
- "¿Puedes hacer esto?" → "Podemos ayudarte con eso. ¿Qué tal si agendamos una llamada de 15 minutos?"
- "¿Quién eres?" → "Soy el asistente de IA de SiteMente. ¿En qué puedo ayudarte?"
Negocios: ${businessType}. Empresa: ${businessName}.`;
Contexto: Negocio tipo: ${businessType}. Empresa: ${businessName}.`;
// Build messages array - embed system in first user message for better compliance
const systemInstructions = `INSTRUCCIONES: Eres el asistente de IA de SiteMente.
- NO digas que eres humano
- NO des precios exactos (usa "desde €299")
- NO garantices resultados
- SIEMPRE sugiere una demo de 15 min
- Responde en español natural
Usuario dice: ${message}`;
// Embed system prompt in first user message for MiniMax compatibility
const messages: Message[] = [
{ role: "user", content: `[INSTRUCCIONES DEL SISTEMA]\n${systemPrompt}\n\n[CONVERSACIÓN]\nUsuario: ${message}` }
{ role: "user", content: systemInstructions }
];
// Add recent history
// Add conversation history (last 6 messages for context)
if (history.length > 0) {
messages.push(...history.slice(-4));
const cleanHistory = history.slice(-6).map((msg: any) => ({
role: msg.role === "user" ? "user" : "assistant",
content: msg.content
}));
messages.push(...cleanHistory);
}
// Add current message
messages.push({ role: "user", content: message });
// Call MiniMax API
const response = await fetch(`${MINIMAX_BASE_URL}/text/chatcompletion_v2`, {
method: "POST",
headers: {
@@ -69,28 +86,26 @@ Negocios: ${businessType}. Empresa: ${businessName}.`;
if (!response.ok) {
const error = await response.text();
console.error("MiniMax error:", error);
console.error("MiniMax API error:", error);
const fallback = language === "es"
? "Lo siento, tuve un problema técnico. ¿Podrías escribir tu pregunta?"
: "Sorry, I had a technical issue. Could you type your question?";
? "Disculpa, ¿podrías repetirlo?"
: "Sorry, could you repeat that?";
return NextResponse.json({ response: fallback });
}
const data = await response.json();
const aiResponse = data.choices?.[0]?.message?.content ||
const aiResponse = data.choices?.[0]?.message?.content?.trim() ||
data.reply ||
(language === "es"
? "¿En qué más puedo ayudarte?"
: "How else can I help you?");
(language === "es" ? "¿En qué puedo ayudarte?" : "How can I help you?");
return NextResponse.json({ response: aiResponse });
} catch (error) {
console.error("Voice chat API error:", error);
return NextResponse.json(
{ response: "Lo siento, tuve un problema. ¿Puedes repetir?" },
{ response: "¿Podrías repetirlo, por favor?" },
{ status: 500 }
);
}
+98
View File
@@ -0,0 +1,98 @@
import { NextRequest, NextResponse } from "next/server";
// MiniMax API configuration
const MINIMAX_API_KEY = process.env.MINIMAX_API_KEY || "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTaXRlTWVudGUiLCJyb2xlIjoiYW5vbiIsImlhdCI6MTczODcxMjAwMCwiZXhwIjoyMDU0MzcyMDAwfQ.VxYNdTUkG4N0K2T8K3pK4JzY3vN8X9vK2pK3JzY2vN8X9";
const MINIMAX_BASE_URL = "https://api.minimax.chat/v1";
interface Message {
role: "user" | "assistant";
content: string;
}
interface RequestBody {
message: string;
language: "es" | "en";
businessType: string;
businessName: string;
history?: Message[];
}
export async function POST(request: NextRequest) {
try {
const body: RequestBody = await request.json();
const { message, language, businessType, businessName, history = [] } = body;
// Build conversation context
const systemPrompt = `You are a friendly AI assistant for ${businessName}, a ${businessType} business.
IMPORTANT RULES:
- Always respond in the SAME language the user uses
- Default to Spanish (respond in Spanish unless user clearly speaks English)
- Keep responses SHORT: 1-3 sentences max
- Be helpful, friendly, and professional
- If asked about pricing, mention: €299-€1,950/month depending on plan
- If asked about booking, say you'll help them book
- Never make up specific prices or details you don't know
Current language mode: ${language}`;
// Build messages array
const messages: Message[] = [
{ role: "assistant", content: systemPrompt }
];
// Add history (last 5 messages for context)
if (history.length > 0) {
messages.push(...history.slice(-5));
}
// Add current message
messages.push({ role: "user", content: message });
// Call MiniMax API
const response = await fetch(`${MINIMAX_BASE_URL}/text/chatcompletion_v2`, {
method: "POST",
headers: {
"Authorization": `Bearer ${MINIMAX_API_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "MiniMax-M2.5",
messages,
temperature: 0.7,
max_tokens: 500
})
});
if (!response.ok) {
const error = await response.text();
console.error("MiniMax API error:", error);
// Fallback response
const fallbackResponse = language === "es"
? "Lo siento, tuve un problema técnico. ¿Puedes repetir tu pregunta?"
: "Sorry, I had a technical issue. Can you repeat your question?";
return NextResponse.json({ response: fallbackResponse });
}
const data = await response.json();
const aiResponse = data.choices?.[0]?.message?.content ||
data.reply ||
(language === "es"
? "Gracias por tu mensaje. ¿En qué más puedo ayudarte?"
: "Thanks for your message. How else can I help you?");
return NextResponse.json({ response: aiResponse });
} catch (error) {
console.error("Voice chat API error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
// Disable body parsing for streaming if needed
export const runtime = "nodejs";