fix(ai): implement two-stage loop detection to warn before hard-stopping (Fix 11)
This commit is contained in:
@@ -698,13 +698,29 @@ export async function POST(request: Request) {
|
|||||||
for (const tc of resp.toolCalls) {
|
for (const tc of resp.toolCalls) {
|
||||||
toolFingerprints.push(fingerprintToolCall(tc));
|
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 window = toolFingerprints.slice(-10);
|
||||||
const counts = new Map<string, number>();
|
const counts = new Map<string, number>();
|
||||||
for (const fp of window) counts.set(fp, (counts.get(fp) ?? 0) + 1);
|
for (const fp of window) counts.set(fp, (counts.get(fp) ?? 0) + 1);
|
||||||
const repeated = [...counts.entries()].find(([, n]) => n >= 3);
|
|
||||||
if (repeated) {
|
// Find highest repeating tool call
|
||||||
loopBreakReason = `Repeated ${repeated[0]} ${repeated[1]}× in last 10 calls`;
|
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
|
// Execute tool calls and add results. OpenAI-compatible APIs
|
||||||
|
|||||||
Reference in New Issue
Block a user