// Tolerate models that wrap JSON in prose or code fences. export function extractJson(text: string): string { const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/); if (fenced) return fenced[1]; const start = text.indexOf('{'); const end = text.lastIndexOf('}'); if (start !== -1 && end !== -1) return text.slice(start, end + 1); return text; } // Best-effort repair of JSON cut off mid-output (e.g. hit the token ceiling): // close an open string, drop a dangling trailing fragment, then balance the // remaining open { and [. export function repairTruncatedJson(input: string): string { let inStr = false; let esc = false; const stack: string[] = []; for (let i = 0; i < input.length; i++) { const ch = input[i]; if (inStr) { if (esc) esc = false; else if (ch === '\\') esc = true; else if (ch === '"') inStr = false; continue; } if (ch === '"') inStr = true; else if (ch === '{' || ch === '[') stack.push(ch); else if (ch === '}' || ch === ']') stack.pop(); } let out = input; if (inStr) out += '"'; // Drop a trailing incomplete property like `"price":` or a dangling comma. out = out.replace(/[\s,]*("[^"]*"\s*:\s*)?$/u, ''); out = out.replace(/[\s,]+$/u, ''); for (let i = stack.length - 1; i >= 0; i--) { out += stack[i] === '{' ? '}' : ']'; } return out; } // Parse a model reply tolerantly: strip fences/prose via extractJson, then try // the raw candidate and a truncation-repaired version. Returns the parsed object // (or null if still unparseable) so callers never crash on malformed output. export function parseLenientJson>(text: string): T | null { const candidate = extractJson(text); for (const a of [candidate, repairTruncatedJson(candidate)]) { try { const obj = JSON.parse(a); if (obj && typeof obj === 'object') return obj as T; } catch { /* try next */ } } return null; }