fix(prompt): erhoehe Token-Limits fuer Reasoning-Modelle und fuege robusten JSON-Parser hinzu

This commit is contained in:
Jannik committed 2026-10-25 22:06:37 +01:00
1 parent 7be853cef0
commit 94e15b2f3e
1 file changed
+88 -9
+88 -9
View File
@@ -162,7 +162,7 @@ async function callMiniMaxChat(env, messages, opts) {
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 maxTokens = Math.max((opts.maxTokens ?? 300) * 4, 3000);
const res = await fetch(`${baseUrl}/chat/completions`, {
method: 'POST',
headers: {
@@ -469,6 +469,91 @@ async function saveImageFromUrl(url) {
return saveImageBuffer(buf, type);
}
function parseJsonSafe(raw) {
let cleaned = String(raw || '').replace(/```json/gi, '').replace(/```/g, '').trim();
const sIdx = cleaned.indexOf('{');
if (sIdx === -1) throw new Error('Kein JSON in der Modell-Antwort gefunden');
cleaned = cleaned.substring(sIdx);
const eIdx = cleaned.lastIndexOf('}');
if (eIdx !== -1) {
cleaned = cleaned.substring(0, eIdx + 1);
}
// 1. Direct parse
try {
return JSON.parse(cleaned);
} catch (err) {
// 2. Auto-repair cut-off JSON
try {
let repaired = cleaned;
let inString = false;
let escaped = false;
for (let i = 0; i < repaired.length; i++) {
const ch = repaired[i];
if (escaped) {
escaped = false;
} else if (ch === '\\') {
escaped = true;
} else if (ch === '"') {
inString = !inString;
}
}
if (inString) repaired += '"';
let openBraces = 0;
let openBrackets = 0;
inString = false;
escaped = false;
for (let i = 0; i < repaired.length; i++) {
const ch = repaired[i];
if (escaped) {
escaped = false;
} else if (ch === '\\') {
escaped = true;
} else if (ch === '"') {
inString = !inString;
} else if (!inString) {
if (ch === '{') openBraces++;
else if (ch === '}') openBraces--;
else if (ch === '[') openBrackets++;
else if (ch === ']') openBrackets--;
}
}
while (openBrackets > 0) { repaired += ']'; openBrackets--; }
while (openBraces > 0) { repaired += '}'; openBraces--; }
return JSON.parse(repaired);
} catch {}
// 3. Fallback: regex extraction of fields
const extractField = (key) => {
const match = cleaned.match(new RegExp(`"${key}"\\s*:\\s*"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)`, 'i'));
return match ? match[1].replace(/\\"/g, '"').replace(/\\n/g, '\n') : '';
};
const name = extractField('name');
const bio = extractField('bio');
const personality = extractField('personality');
const system_prompt = extractField('system_prompt');
const avatar_prompt = extractField('avatar_prompt');
const change_summary = extractField('change_summary');
const gender = extractField('gender');
let hobbies = [];
const hm = cleaned.match(/"hobbies"\s*:\s*\[([\s\S]*?)(\]|$)/);
if (hm) {
hobbies = (hm[1].match(/"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"/g) || []).map((s) => s.slice(1, -1));
}
if (name || bio || personality || system_prompt) {
return { name, bio, personality, system_prompt, avatar_prompt, change_summary, gender, hobbies };
}
throw err;
}
}
// ---------------- Prompt Enhancement Helper ----------------
export async function enhanceCharacterPrompt(envArg, data = {}) {
const {
@@ -533,15 +618,9 @@ Gib jetzt das optimierte JSON-Objekt zurück:`;
const raw = await chatText(envArg, [
{ role: 'system', content: systemInstruction },
{ role: 'user', content: userPrompt },
], { temperature: 0.7, maxTokens: 900 });
], { temperature: 0.7, maxTokens: 2000 });
let cleaned = raw.replace(/\`\`\`json/gi, '').replace(/\`\`\`/g, '').trim();
const sIdx = cleaned.indexOf('{');
const eIdx = cleaned.lastIndexOf('}');
if (sIdx !== -1 && eIdx !== -1) {
cleaned = cleaned.substring(sIdx, eIdx + 1);
}
const parsed = JSON.parse(cleaned);
const parsed = parseJsonSafe(raw);
const validGenders = ['female', 'male', 'trans_female', 'trans_male', 'nonbinary', 'unspecified'];
const resolvedGender = validGenders.includes(parsed.gender) ? parsed.gender : (validGenders.includes(gender) ? gender : 'unspecified');