Agent loop with no iteration limit
An agent or tool loop with no iteration limit.
Why it costs money
An agent loop keeps calling the model until the model says it is done. When a tool keeps failing, or the model keeps asking for one more search, nothing in the loop itself ends the run. Each iteration is a full paid call, and in most agents each call also carries the growing transcript.
A loop like this does not fail loudly. It runs until the process is killed, a timeout hits, or the account runs out of credit. A bound that exists but defaults to None or -1 has the same effect on every caller who does not override it.
Example
Flagged
import anthropic
client = anthropic.Anthropic()
def run_agent(task: str, tools: list) -> None:
messages = [{"role": "user", "content": task}]
while True:
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=2048,
tools=tools,
messages=messages,
)
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": execute_tools(response.content)})Fixed
import anthropic
client = anthropic.Anthropic()
MAX_STEPS = 15
def run_agent(task: str, tools: list):
messages = [{"role": "user", "content": task}]
for _ in range(MAX_STEPS):
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=2048,
tools=tools,
messages=messages,
)
if response.stop_reason != "tool_use":
return response
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": execute_tools(response.content)})
raise RuntimeError(f"Agent did not finish within {MAX_STEPS} steps")How to fix it
Give every agent loop a concrete maximum number of steps and an explicit stop condition, such as the model no longer requesting a tool. Raise or return a clear error when the limit is reached, so the caller knows the task did not finish.
If a limit is configurable, default it to a number rather than None or -1, and pair it with a token or dollar budget so a long run is stopped even when each step looks reasonable.
What the audit detects
- while True or while (true) loops whose body calls an LLM or agent and contains no break, return, raise or throw, exit, iteration counter or comparison.
- Agent limits such as max_iterations, max_turns or recursion limits whose default value is None, -1 or infinity, found by reading the default in the syntax tree, including typed parameters like max_iter: Optional[int] = None.
- Not flagged: loops that block on a queue or channel read (each iteration is triggered by an incoming message), recursion that counts down to a base case, limits set to a number, and optional parameters with no explicit default. Exits inside called functions are not traced.
Research
When Agents Do Not Stop: Uncovering Infinite Agentic Loops in LLM Agents. Static analysis detected infinite agentic loops with 91.9% precision on the paper's evaluation set, and treats a limit that defaults to a sentinel such as None or -1 as no limit.