fix(ai): implement two-stage loop detection to warn before hard-stopping (Fix 11)

This commit is contained in:
2026-05-16 12:59:16 -07:00
parent c06ab8650b
commit cdddaced30

View File

@@ -698,13 +698,29 @@ export async function POST(request: Request) {
for (const tc of resp.toolCalls) {
toolFingerprints.push(fingerprintToolCall(tc));
}
// Sliding window of 10 (was 8); threshold 3 stays the same
// Sliding window of 10 (was 8)
const window = toolFingerprints.slice(-10);
const counts = new Map<string, number>();
for (const fp of window) counts.set(fp, (counts.get(fp) ?? 0) + 1);
const repeated = [...counts.entries()].find(([, n]) => n >= 3);
if (repeated) {
loopBreakReason = `Repeated ${repeated[0]} ${repeated[1]}× in last 10 calls`;
// Find highest repeating tool call
let maxRepeats = 0;
let repeatedCmd = "";
for (const [fp, n] of counts.entries()) {
if (n > maxRepeats) {
maxRepeats = n;
repeatedCmd = fp.split("|")[0];
}
}
// Stage 1: Warning at 3 repeats
if (maxRepeats === 3) {
extraSystem += `\n\n[WARNING] You have called ${repeatedCmd} 3 times recently. Please wrap up this approach or try a completely different tool.`;
}
// Stage 2: Hard Break at 5 repeats
if (maxRepeats >= 5) {
loopBreakReason = `Repeated ${repeatedCmd} ${maxRepeats}× in last 10 calls`;
}
// Execute tool calls and add results. OpenAI-compatible APIs