CH 02 · The Agent Loop Pattern · 13/15
Read as one pageReal code: Gemini CLI spots a stuck loop
Gemini CLI, Google's open-source terminal agent, watches every tool call the model requests. The check below is the stuck-loop item from the list above, extended from one repeated call to a repeating cycle.
private checkToolCallLoop(toolCall: { name: string; args: object }): boolean {
const key = this.getToolCallKey(toolCall); // [1]
this.toolCallHistory.push(key);
// ... (4 lines: keep only the newest 25 keys)
const n = this.toolCallHistory.length;
const R = TOOL_CALL_LOOP_THRESHOLD; // 5
// Check for repeating patterns of cycle length k from 1 to 5
for (let k = 1; k <= 5; k++) { // [2]
const requiredLength = k * R;
if (n >= requiredLength) {
const cycle = this.toolCallHistory.slice(-k);
let isPatternMatch = true;
for (let i = 0; i < requiredLength; i++) {
const indexFromEnd = requiredLength - i;
const actualKey = this.toolCallHistory[n - indexFromEnd];
const expectedKey = cycle[i % k]; // [3]
if (actualKey !== expectedKey) {
isPatternMatch = false;
break;
}
}
if (isPatternMatch) {
return true; // [4]
}
}
}
return false;
}
Source: google-gemini/gemini-cli, packages/core/src/services/loopDetectionService.ts (Apache-2.0)
What to notice
- [1]
getToolCallKeyfingerprints a call: the tool name plusJSON.stringify(args), hashed with SHA-256. Two calls match only when both are identical. The skipped lines keep the newest 25 keys, five cycle lengths times five repeats. - [2]
kis the cycle length.k = 1catches the same call five times.k = 2catches A, B, A, B across ten calls. A check for the identical call in a row misses that second shape, and flipping between two actions is a common way agents get stuck. - [3] The window is the last
k * 5keys, andcycleis its lastk.cycle[i % k]is what positionimust be if that cycle repeats. One mismatch ends the test for thisk. - [4] A match returns
true.addAndCheckstoresRepeated tool call: ...with the arguments on the result. The log records the loop type and strike count; the arguments are sent to the model in the recovery message.
Five different files in a row do not match, because the arguments differ. On a match, core/client.ts gives the model one chance: _recoverFromLoop stops the reply and sends a message asking it to step back. A second detection yields LoopDetected, which the agent layer reports as the error "Loop detected, stopping execution." That error has fatal set to false, so it is not marked as the reason the whole agent halts, and this turn does not continue.
Read it yourself: in loopDetectionService.test.ts, read the tests for a cycle of length 2 and for alternating sequences that vary. Then answer from getToolCallKey: do {"path": "a", "limit": 10} and {"limit": 10, "path": "a"} hash the same? (JSON.stringify keeps key order.) After 30 turns on one prompt the service also asks a model, using LOOP_DETECTION_SYSTEM_PROMPT at the top of the file. What can that model catch that a hash cannot?
Finished this idea?
Your learning progress stays in this browser.