Your agent keeps calling the same tool. How do you stop it?
Question
A delivery support agent can call track_parcel. The carrier's API is down, so every call returns an error. In one chat the agent called track_parcel("PX-88") 40 times before the user gave up.
Each step sends the whole conversation again: 2,400 tokens at step 1, and 400 more at every step after that.
The agent loop is below. Why does it never stop? Add stop conditions, and say what the user should see when one fires.
def run(messages): while True: reply = model(messages, tools=[track_parcel]) if not reply.tool_calls: return reply.text for call in reply.tool_calls: messages.append(run_tool(call))
Show hints (3)
- "COUNT THE EXITS"
The loop ends only when the model stops asking for tools. What if it never does?
- "LIMITS IN CODE"
Give the loop exits that your code controls: a cap on steps, a token or cost budget, a time limit.
- "SAME CALL AGAIN"
The same tool with the same arguments and the same error each time is a strong signal. How many repeats would you allow? What if the arguments change slightly?
Show checked explanation
Only the model can end this loop, and it keeps retrying a failing tool. Add exits your code controls: a repeat limit, a token budget, a step limit and a timeout. When one fires, tell the user plainly and offer a person.
def run_agent(model, max_steps=10, max_repeats=3, token_budget=20_000): calls, spent = [], 0 for step in range(1, max_steps + 1): args, tokens = model(step) # tool arguments, or None for an answer spent += tokens if args is None: return f"answered at step {step}" calls.append(args) if calls.count(args) > max_repeats: return f"step {step}: same call {max_repeats + 1} times, hand off" if spent > token_budget: return f"step {step}: {spent} tokens, over budget, hand off" # run track_parcel(args) and add its result to the conversation return f"{max_steps} steps used, hand off" variants = ("PX-88", "px-88", "PX 88") # one parcel, written three ways print(run_agent(lambda step: ("PX-88", 2000 + 400 * step))) print(run_agent(lambda step: (variants[step % 3], 2000 + 400 * step)))
step 4: same call 4 times, hand off step 6: 20400 tokens, over budget, hand off
Code run on CPython 3.12 against the example above. Checked by an editor other than the author.
Walkthrough
The loop has one exit: a reply without tool calls. The model decides that. With a failing tool it often tries once more, and nothing in the code says no.
Cost grows faster than the number of steps, because every step resends the conversation. The 40-step chat used 408,000 tokens. Ten steps would have used 42,000.
Add exits that your code controls:
| run | what the model sends | what stops it |
|---|---|---|
| stuck | PX-88 every step | the 4th identical call, at step 4 |
| varied | px-88, PX 88, PX-88 in turn | the token budget, at step 6 (20,400 > 20,000) |
- Repeat limit. The same tool with the same arguments more than 3 times is almost always a loop. It is cheap and stops the common case early.
- Token or cost budget per task. It catches the same request written slightly differently.
- Step limit and timeout. The last backstop: a hard cap on model calls and on time for one task.
Fix what the tool returns. Send the failure back as an error result that says what went wrong and what to try: "carrier API down, try again in 10 minutes". A bare "failed" invites another try.
Retry in the tool, not in the model. Network retries with backoff belong inside track_parcel, a few attempts at most. The model should see one final error.
When a limit fires, tell the user what happened: "I can't reach the carrier right now." Offer a person or a later check. Log the reason, so you can find loops in your traces.
Common mistakes
- A line in the system prompt like "call each tool at most twice". That asks the model; it limits nothing. Keep the counter in code.
- Only a step limit of 100. It stops, but late: here 100 steps would cost 2,220,000 tokens, because each step costs more than the last.
- Relying on an exact-match repeat check alone.
PX-88,px-88andPX 88look different to it, so here it fires only at step 10. The budget stops the run at step 6. - Ending with an empty reply or a generic error. The user retries and starts the same loop again.
Follow-up questions
- "Some tasks really need 30 steps. Doesn't a limit break them?" Set limits per task type from your traces: the steps successful runs needed, plus a margin. Give long tasks a bigger budget and save progress, so a stopped run can resume. Alert when many runs hit a limit; that usually means a broken tool or prompt.
- "Two agents keep handing the task back and forth. Same fix?" Yes, but count for the whole task, not for each agent. Pass the step count and the remaining budget with every handoff, so A to B to A to B still uses up one budget.
What a strong answer covers
Sees that only the model can end the loop and adds exits in code: repeats, tokens, steps and time. Explains why cost grows faster than steps. Returns clear tool errors, retries inside the tool and ends with an honest message or a handoff.
Open in interactive practice deck →