fix(ai): verbessere MiniMax Fehlerbehandlung und Bildgenerierung (Balance & Base64 Support)

This commit is contained in:
Jannik committed 2026-10-25 21:44:10 +01:00
1 parent 5a1513f047
commit 8e774593c8
1 file changed
+115 -28
+115 -28
View File
@@ -155,9 +155,10 @@ export async function chatText(envArg, messages, opts = {}) {
async function callMiniMaxChat(env, messages, opts) {
const apiKey = env.MINIMAX_API_KEY || env.AI_API_KEY;
const model = env.MINIMAX_MODEL || env.AI_MODEL || 'MiniMax-M3';
const baseUrl = (env.AI_BASE_URL || 'https://api.minimax.io/v1').replace(/\/+$/, '');
// Reasoning models (like MiniMax-M3) emit thinking tokens first; allow sufficient completion tokens
const maxTokens = Math.max((opts.maxTokens ?? 300) * 3, 600);
const res = await fetch('https://api.minimax.io/v1/chat/completions', {
const res = await fetch(`${baseUrl}/chat/completions`, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
@@ -171,10 +172,33 @@ async function callMiniMaxChat(env, messages, opts) {
}),
});
if (!res.ok) {
const t = await res.text().catch(() => '');
throw new Error(`MiniMax chat ${res.status}: ${t.slice(0, 300)}`);
const raw = await res.text().catch(() => '');
let detail = raw.slice(0, 300);
try {
const parsed = JSON.parse(raw);
if (parsed?.error?.message) {
detail = parsed.error.message;
if (parsed.error.type === 'insufficient_balance_error' || raw.includes('1008')) {
detail = `Guthaben aufgebraucht (Code 1008: insufficient balance). Dein MiniMax-Konto hat kein Guthaben mehr oder das Kontingent für Modell "${model}" ist erschöpft. Bitte auf platform.minimax.io prüfen.`;
}
} else if (parsed?.base_resp?.status_msg) {
detail = parsed.base_resp.status_msg;
}
} catch {}
throw new Error(`MiniMax chat ${res.status}: ${detail}`);
}
const data = await res.json();
const data = await res.json().catch(() => null);
if (!data) throw new Error('MiniMax chat: empty response');
if (data.base_resp && data.base_resp.status_code !== 0) {
const code = data.base_resp.status_code;
const msg = data.base_resp.status_msg || 'Unbekannter API-Fehler';
if (code === 1008) {
throw new Error(`MiniMax Guthaben aufgebraucht (Code 1008).`);
}
throw new Error(`MiniMax API-Fehler (Code ${code}): ${msg}`);
}
const content = data?.choices?.[0]?.message?.content;
if (!content) throw new Error('MiniMax chat: empty response');
const clean = stripThinking(content);
@@ -286,27 +310,37 @@ async function sendOpenAICompat(baseUrl, apiKey, model, messages, opts, extraHea
// ---------------- Image Generation ----------------
export async function genImage(envArg, prompt, aspectRatio = '1:1') {
const config = await getEffectiveAIConfig(envArg);
if (!config.hasKey) {
throw new Error(`Kein API-Key für Bildgenerierung (Provider: ${config.provider}) hinterlegt.`);
}
const env = {
...getEnv(envArg),
AI_PROVIDER: config.provider,
AI_API_KEY: config.apiKey,
MINIMAX_API_KEY: config.apiKey,
OPENAI_API_KEY: config.apiKey,
};
const rawEnv = getEnv(envArg);
const provider = config.provider;
const minimaxKey = provider === 'minimax' ? config.apiKey : (rawEnv.MINIMAX_API_KEY || '');
const openaiKey = provider === 'openai' ? config.apiKey : (rawEnv.OPENAI_API_KEY || '');
const env = {
...rawEnv,
AI_PROVIDER: config.provider,
AI_API_KEY: config.apiKey,
MINIMAX_API_KEY: minimaxKey,
OPENAI_API_KEY: openaiKey,
AI_BASE_URL: config.baseUrl,
};
try {
if (provider === 'minimax' || env.MINIMAX_API_KEY) {
return await genMiniMaxImage(env, prompt, aspectRatio);
} else if (provider === 'openai' && (env.OPENAI_API_KEY || env.AI_API_KEY)) {
if (provider === 'minimax' || minimaxKey) {
try {
return await genMiniMaxImage(env, prompt, aspectRatio);
} catch (mmErr) {
// If MiniMax failed due to insufficient balance and an OpenAI key is configured, fallback to OpenAI
if (openaiKey && (mmErr.message.includes('1008') || mmErr.message.includes('Guthaben'))) {
console.warn('MiniMax Bildguthaben erschöpft, wechsle auf OpenAI Fallback...');
return await genOpenAIImage(env, prompt);
}
throw mmErr;
}
} else if (provider === 'openai' || openaiKey) {
return await genOpenAIImage(env, prompt);
} else {
throw new Error(`Bildgenerierung wird für Provider "${provider}" aktuell nicht unterstützt (nur MiniMax und OpenAI).`);
throw new Error(`Bildgenerierung wird für Provider "${provider}" aktuell nicht direkt unterstützt (nur MiniMax und OpenAI). Bitte in den Einstellungen einen OpenAI- oder MiniMax-Key hinterlegen.`);
}
} catch (err) {
console.error(`AI image generation failed:`, err.message);
@@ -316,7 +350,12 @@ export async function genImage(envArg, prompt, aspectRatio = '1:1') {
async function genMiniMaxImage(env, prompt, aspectRatio = '1:1') {
const apiKey = env.MINIMAX_API_KEY || env.AI_API_KEY;
const res = await fetch('https://api.minimax.io/v1/image_generation', {
if (!apiKey) {
throw new Error('Kein MiniMax API-Key für Bildgenerierung hinterlegt.');
}
const baseUrl = (env.AI_BASE_URL || 'https://api.minimax.io/v1').replace(/\/+$/, '');
const res = await fetch(`${baseUrl}/image_generation`, {
method: 'POST',
headers: {
Authorization: `Bearer ${apiKey}`,
@@ -331,15 +370,63 @@ async function genMiniMaxImage(env, prompt, aspectRatio = '1:1') {
prompt_optimizer: true,
}),
});
if (!res.ok) {
const t = await res.text().catch(() => '');
throw new Error(`MiniMax image ${res.status}: ${t.slice(0, 300)}`);
}
const data = await res.json();
const url = data?.data?.image_urls?.[0] || data?.image_urls?.[0];
if (!url) throw new Error('MiniMax image: no url in response');
return await saveImageFromUrl(url);
if (!res.ok) {
const raw = await res.text().catch(() => '');
let detail = raw.slice(0, 300);
try {
const parsed = JSON.parse(raw);
if (parsed?.error?.message) {
detail = parsed.error.message;
if (parsed.error.type === 'insufficient_balance_error' || raw.includes('1008')) {
detail = 'Guthaben aufgebraucht (Code 1008: insufficient balance). MiniMax Coding/Token-Pläne beinhalten keine Bildgenerierung – image-01 erfordert separates Prepaid-Guthaben auf platform.minimax.io.';
}
} else if (parsed?.base_resp?.status_msg) {
detail = parsed.base_resp.status_msg;
}
} catch {}
throw new Error(`MiniMax HTTP ${res.status}: ${detail}`);
}
const data = await res.json().catch(() => null);
if (!data) throw new Error('MiniMax image: Leere JSON-Antwort');
// MiniMax application-level status check (base_resp)
if (data.base_resp && data.base_resp.status_code !== 0) {
const code = data.base_resp.status_code;
const msg = data.base_resp.status_msg || 'Unbekannter API-Fehler';
if (code === 1008) {
throw new Error(`MiniMax Guthaben aufgebraucht (Code 1008: insufficient balance). Hinweis: MiniMax Coding/Token-Pläne beinhalten keine Bildgenerierung. Das Bildmodell image-01 erfordert separates Prepaid-Guthaben auf platform.minimax.io. Alternativ ein Profilbild manuell hochladen.`);
} else if (code === 1004 || code === 2049) {
throw new Error(`MiniMax API-Key ungültig oder abgelaufen (Code ${code}: ${msg}).`);
} else if (code === 1000 || code === 1013) {
throw new Error(`MiniMax Sicherheitsfilter: Prompt wurde abgelehnt (Code ${code}: ${msg}).`);
} else if (code === 2056) {
throw new Error(`MiniMax Nutzungslimit erreicht (Code ${code}: ${msg}).`);
}
throw new Error(`MiniMax API-Fehler (Code ${code}): ${msg}`);
}
// Check for generation failure in metadata
if (data.metadata?.failed_count && Number(data.metadata.failed_count) > 0 && !data.data?.image_urls?.length && !data.data?.image_base64?.length) {
throw new Error(`MiniMax Bildgenerierung fehlgeschlagen (failed_count: ${data.metadata.failed_count})`);
}
// URL result
const url = data.data?.image_urls?.[0] || data.image_urls?.[0] || data.data?.[0]?.url;
if (url) {
return await saveImageFromUrl(url);
}
// Base64 result
const b64 = data.data?.image_base64?.[0] || data.image_base64?.[0] || data.data?.[0]?.b64_json;
if (b64) {
const buf = Buffer.from(b64, 'base64');
return saveImageBuffer(buf, 'image/jpeg');
}
console.error('Unerwartete MiniMax Bild-Antwort:', JSON.stringify(data));
throw new Error(`MiniMax Bild: Keine Bild-URL oder Base64 in der Antwort erhalten. Antwort: ${JSON.stringify(data).slice(0, 200)}`);
}
async function genOpenAIImage(env, prompt) {