November 3, 2026 路 #48
AI agentsMediumOpen write-up
The agent that never stopped
The agent got stuck retrying a failing tool and ran all night. Which line needs a limit?
def run(task):
messages = [system_prompt(), user(task)]
while True:
reply = llm.chat(messages, tools=TOOLS)
if reply.final_answer:
return reply.final_answer
result = call_tool(reply.tool_call)
messages += [reply, tool_result(result)]Next puzzle in UTC
One try. The first answer sticks.
How to fix it
Nothing bounds the loop. A tool that keeps failing, or a model that keeps asking for it, costs money every iteration. Cap steps and spend, then fail loudly.
Agents end when the model decides it is done. When a tool keeps returning an error, the model often tries again, and again. Each turn also resends the growing history, so cost per step rises as the loop runs. Temperature does not guarantee termination.
Fix
MAX_STEPS = 20
MAX_TOKENS = 200_000
def run(task):
messages = [system_prompt(), user(task)]
used = 0
for _ in range(MAX_STEPS):
reply = llm.chat(messages, tools=TOOLS)
used += reply.usage.total_tokens
if reply.final_answer:
return reply.final_answer
if used > MAX_TOKENS:
break
messages += [reply, tool_result(call_tool(reply.tool_call))]
raise AgentBudgetExceeded(task)
Add a wall-clock timeout, alert on budget errors, and set a hard spend limit with the model provider as a last line of defense.