A repeated tool call is not automatically a loop. An agent may call get_job_status several times because the job is still running. The warning sign appears when the call, the meaningful result, and the task state stay the same, with no deadline or expected change that justifies another request.
The practical rule is to put a detector in the runtime, before the next tool executes. Normalize the tool name and arguments, compare the result that matters, and record some evidence of progress. When the same combination returns without progress, pause the run with an explicit reason. When it is polling, the scheduler should own the interval, deadline, and terminal state instead of leaving the model to decide on its own.
This is a spoke of how to prevent an AI agent from looping forever. That article covers the broad stop policy. This one answers the narrower question: how do you recognize repetition before the run spends its entire budget, and how do you avoid blocking a job that can still advance?
Short answer
- Compare the tool name and normalized arguments, not only the tool name.
- Compare the result or state version that can change the next decision.
- Pause when the same call returns the same evidence without observable progress.
- Treat polling as a separate contract with a runtime-owned deadline, next time, and terminal state.
- Return
no_progressorpoll_deadline_exceededto the caller. Do not hide the stop inside a prompt.
Why is counting calls not enough?
A simple counter flags almost every agent that is doing useful work. Searching for three documents, reading two files, or checking five orders can repeat the same tool with different arguments. The name search appears several times, but the task moved forward.
The JavaScript Agents SDK documents the runner loop: the runtime calls the model, executes tools when they appear, and returns to the model until it gets a final output or reaches maxTurns. The page also documents a default of 10 turns and MaxTurnsExceededError when the ceiling is reached unless the limit is changed. That ceiling is a safety barrier, not a progress detector.
The Microsoft Agent Framework recommends bounding autonomous loops because a completion condition can fail, a model can stall, and an evaluator can be probabilistic. That supports a hard limit. It does not tell you which repeated action is useless in your domain. That part needs execution evidence.
A local detector should answer three questions:
- Is the call structurally the same?
- Is the meaningful result the same?
- Has any part of the task state changed since the last attempt?
If the answer is “yes, yes, and no” several times in a row, you have a better signal than a global counter. You still do not have universal proof. A repeated read may be deliberate verification, and an API may return the same result before changing later. The detector should therefore pause or request a decision, not pretend it knows the model’s intent.
How do you build a stable tool fingerprint?
Compare the call structure, not the textual representation in the transcript. JSON object key order should not make two equal calls look different. Volatile fields such as requestId and timestamps also do not represent a change in intent.
A minimal fingerprint contains the tool name and normalized arguments. To increase confidence, keep a fingerprint of the result that affects the next step. Do not put the whole prompt in the key. It is unnecessary and can leak sensitive data into logs or metrics.
The following is an offline fixture. It does not call an LLM or a real tool. progressKey must come from the domain: a job version, processed-item count, diff hash, or another fact the application can observe.
import assert from "node:assert/strict";
function stableJson(value) {
if (Array.isArray(value)) {
return `[${value.map(stableJson).join(",")}]`;
}
if (value && typeof value === "object") {
return `{${Object.keys(value).sort().map((key) =>
`${JSON.stringify(key)}:${stableJson(value[key])}`,
).join(",")}}`;
}
return JSON.stringify(value);
}
function fingerprint(step) {
return stableJson({ tool: step.tool, args: step.args });
}
function resultFingerprint(step) {
return stableJson({ tool: step.tool, result: step.result });
}
function inspectStep(step, previous, options = { repeatLimit: 3 }) {
const call = fingerprint(step);
const result = resultFingerprint(step);
const sameObservation = call === previous.call && result === previous.result;
const stateChanged = step.progressKey !== undefined
&& step.progressKey !== previous.progressKey;
const repeats = sameObservation && !stateChanged
? previous.repeats + 1
: 0;
if (stateChanged) {
return { action: "continue", reason: "progress", call, result, repeats: 0 };
}
if (repeats >= options.repeatLimit) {
return { action: "pause", reason: "no_progress", call, result, repeats };
}
return { action: "continue", reason: "observe", call, result, repeats };
}
const first = {
tool: "read_status",
args: { jobId: "job-7", verbose: false },
result: { status: "running" },
progressKey: "version-4",
};
let state = {
call: fingerprint(first),
result: resultFingerprint(first),
progressKey: first.progressKey,
repeats: 0,
};
for (let i = 0; i < 3; i += 1) {
const decision = inspectStep(first, state);
assert.equal(decision.action, i === 2 ? "pause" : "continue");
state = { ...state, ...decision, progressKey: first.progressKey };
}
const changed = inspectStep({ ...first, progressKey: "version-5" }, state);
assert.deepEqual(changed, {
action: "continue",
reason: "progress",
call: state.call,
result: state.result,
repeats: 0,
});
console.log("no-progress detector fixture passed");
Run it with Node.js:
node repeated-tool-guard.mjs
In the fixture, repeatLimit: 3 is a test parameter. Do not treat it as a universal recommendation. A read may be cheap and safe; a write may need to pause on the first repetition. The policy must know the operation’s risk and contract.
When is repetition legitimate polling?
Polling is an expected way to repeat a query when external state can change over time. The problem starts when the model controls the repetition without a limit. The same running response can consume many turns, and the runtime may not know whether the next request will wait, change the interval, or simply call again.
Separate polling from a free-form agent loop. The tool or runtime should declare something like this:
| Field | Responsibility |
|---|---|
jobId |
identifies the job being checked |
status |
distinguishes running, completed, and failed |
nextPollAt |
says when the next query may happen |
deadline |
ends the shared wait budget |
progressKey |
shows whether an observable fact changed |
While status is running, the scheduler can schedule another query until deadline. The model does not need to emit the same tool on every turn. If the deadline arrives without a terminal state, return poll_deadline_exceeded and let the caller decide whether to wait longer, requeue the job, or ask for intervention.
Do not use the name get_status as a free pass. A read can be legitimate for a few cycles and become waste later. The limit belongs to the run and the job, with a shared clock. A retry created inside the tool must not reset the run’s counter.
The Gemini CLI loop-detection implementation is a useful public reference for one important distinction: compare call arguments and account for semantic equivalence rather than comparing only the tool name. Your product may need different rules. Treat the code as something to inspect, not as a universal policy.
What should the runtime do when the detector fires?
Do not call the same tool again before changing the condition that caused the repetition. The runtime can take three paths:
- Pause: record
no_progress, the fingerprint, the last evidence, and the next allowed decision. - Request a strategy change: return a short message with the repeated call and require another tool, another argument, or an explanation of the blocker. This is a controlled new attempt, not permission to repeat automatically.
- Escalate: if the tool has external side effects, the state is unknown, or the detector cannot decide safely, send the run to a person or a reconciliation queue.
The article about tracing AI agent tool calls with OpenTelemetry explains where to record the run, tool, attempt, and summarized result. A trace helps you investigate the first repeated step. It should not be the only control: the guard belongs in the dispatcher before the next execution.
Do not turn every error into no_progress. A 401 may need credential renewal, a 400 may need corrected arguments, and a timeout after a write may require verifying whether the tool call had an effect before retrying. The stop reason should state which decision is blocked.
If the failure is only a timeout test, use an injectable clock and a fixture that separates waiting from effects, as in testing an AI agent tool timeout without waiting or duplicating effects. Timeout, no-progress repetition, and unknown effect are different diagnoses even when they occur in the same run.
How do you test without depending on the model?
Build small deterministic trajectories. The test does not need to prove that a model would choose a tool. It needs to prove that the runtime recognizes the pattern and does not execute a forbidden call.
| Scenario | Evidence | Expected decision |
|---|---|---|
| Same name, different arguments | intent changed | continue |
| Same name and arguments, different result | new evidence exists | continue and update state |
| Same name, arguments, and result, state unchanged | no progress observed | pause after the limit |
get_status with running |
job may still advance | schedule through the scheduler until the deadline |
get_status after the deadline |
waiting budget is gone | return poll_deadline_exceeded |
| Same write after a timeout | external effect is ambiguous | verify the effect before retrying |
| A, B, A, B cycle | calls oscillate | pause or request intervention |
Test normalization too. Payloads with keys in a different order should produce the same fingerprint. Remove a volatile field before comparison if it does not represent an intent change. Do not remove the field that identifies the resource or version that can actually change the result.
In production, count the attempt when the dispatcher admits the call, not after it finishes. If the process dies, an in-memory counter disappears. For a durable run, persist the guard state with the run, without confusing that record with a receipt from the external system.
Method and limits
I checked the current OpenAI Agents SDK documentation, Microsoft Agent Framework documentation, and a public Gemini CLI loop-detection implementation on November 19, 2026. I also compared public results and practitioner discussions, but used those discussions only for language and symptoms. I did not run the detector against a model provider or production tool; the fixture is local and deterministic.
AI assistance helped organize the research, review the prose, create the localized versions, and check example consistency. It did not provide a false-positive measurement. When I need to extend a debugging session with less repeated context, I use RemoteCode, a tool I built; that mention is editorial and is not evidence for the detector’s behavior.
Conclusion
An agent is stuck when it keeps consuming steps without adding useful evidence, not simply because it called a tool more than once. Compare the normalized call, meaningful result, and observable state. If all three stay the same, pause with a reason the runtime can record.
Polling deserves a different contract. The scheduler owns the next time, deadline, and terminal state. That lets a slow job finish while a no-progress repetition cannot quietly spend the rest of the budget behind a transcript that only looks active.
Sources consulted
- OpenAI Agents SDK, Running Agents, accessed November 19, 2026.
- Microsoft Agent Framework, Agent looping, accessed November 19, 2026.
- Google Gemini CLI, loopDetectionService.ts, accessed November 19, 2026.