Sub topic 9
Knowing when to stop
This chapter assumes you have read the earlier chapters on tool calls and the agent loop. You should be comfortable with the loop that calls the model, runs the requested tools, appends the results, and calls the model again. Here you will look at how that loop ends, which ways it can end badly, and how to design the exits.
Why stopping is a design problem
The model does not decide to stop in any special way. Each call returns a reply, and a reply either contains tool calls or it does not. A reply with no tool calls is the model's signal that it is finished. The harness (the program that runs the loop) treats that as the normal exit.
Relying only on that exit is risky. The model can fail to produce a no-tool-call reply for many reasons:
- It keeps retrying a command that fails the same way each time.
- It alternates between two edits that undo each other.
- It keeps exploring a large codebase and never starts the change.
- A tool hangs, so the loop never reaches the next model call.
Each model call costs money and time, and each tool call may change files. A loop with no other exit can spend a budget, or damage a working tree, before anyone notices. So a production harness has several independent stop conditions, and each one covers a different failure.
The kinds of stop condition
A stop condition is any rule that ends the loop. They fall into a few groups.
| Condition | Who decides | What it protects against | Typical outcome |
|---|---|---|---|
| No tool calls in the reply | Model | Nothing. This is the normal finish. | Return the final text |
| Step limit | Harness | Endless loops, runaway cost | Return a "stopped" status |
| Wall-clock timeout | Harness | Slow tools, slow model calls | Return a "timed out" status |
| Token or cost budget | Harness | Spending more than planned | Stop, or compact and continue |
| Repeated identical calls | Harness | Stuck retry loops | Stop, or inject a warning |
| User interrupt or denied approval | User | Actions the user does not want | Stop, or ask for new direction |
| Explicit completion tool | Model, checked by harness | Ambiguous "I'm done" text | Verify, then return |
The first row is the only one the model controls. Every other row is a guard the harness enforces regardless of what the model says.
The step limit
A step is one model call plus the tool calls it triggers. The step limit is the count of those iterations. The loop from the Topic Spine already includes one: max_steps=20.
Choosing the number is a trade-off. A small limit, such as 5, stops loops quickly but cuts off legitimate tasks that need many reads before an edit. A large limit, such as 200, lets hard tasks finish but allows a stuck run to burn through many calls first. Many harnesses start in the range of 20 to 50 for interactive use and raise it for unattended jobs. Treat these as starting values to tune against real traces, not as fixed rules.
Two details matter in practice:
- Count model calls, not tool calls. One reply can request several tools in parallel. Counting model calls keeps the limit tied to the cost driver.
- Report the reason. Returning the string
"stopped: step limit reached"is better than returning nothing, but returning a structured status lets the caller decide what to do next, such as resuming with a higher limit.
Beyond step counting
A step limit treats every step as equal, but steps differ a lot. One step might read a 50-line file. Another might run a test suite for 25 seconds and return 5,000 characters. Extra guards catch what a step count cannot.
Wall-clock timeout. Check elapsed time at the top of each iteration. Also put a timeout on each tool, as the run_command example does with timeout=30. The loop-level timeout cannot interrupt a tool that is already running, so the two timeouts work together.
Budget check. The needs_compaction helper from the context chapter estimates token use. A related check can stop the loop when the cumulative tokens or cost of all calls passes a set amount. Running out of context window is different from running out of budget. Context pressure can often be fixed by compacting history, while a budget limit is a real stop.
Repeat detection. If the model issues the same tool call with the same arguments many times, it is almost certainly stuck. Hash the tool name and arguments and count occurrences. When the count passes a threshold, either stop or add a message telling the model that the call has already been made and has returned the same result.
A loop with several exits
The following code extends the minimal loop. It returns a dictionary with a stop field so the caller can tell the exits apart. It also takes tools as a parameter so the example runs on its own. The demo at the bottom uses a fake model that asks for the same call every time, so you can see the repeat guard fire without any API.
import json
import time
def run_agent(task, call_model, tools, max_steps=20, max_seconds=300, max_repeats=3):
messages = [{"role": "user", "content": task}]
started = time.monotonic()
seen = {}
for _ in range(max_steps):
if time.monotonic() - started > max_seconds:
return {"stop": "timeout", "messages": messages}
reply = call_model(messages)
messages.append({"role": "assistant", "content": reply["text"],
"tool_calls": reply["tool_calls"]})
if not reply["tool_calls"]:
return {"stop": "done", "answer": reply["text"], "messages": messages}
for call in reply["tool_calls"]:
key = (call["name"], json.dumps(call["arguments"], sort_keys=True))
seen[key] = seen.get(key, 0) + 1
if seen[key] > max_repeats:
return {"stop": "repeat", "call": call, "messages": messages}
try:
result = tools[call["name"]](**call["arguments"])
except Exception as e:
result = f"error: {e}"
messages.append({"role": "tool", "tool_call_id": call["id"],
"content": str(result)})
return {"stop": "step_limit", "messages": messages}
def stuck_model(messages):
# Always asks for the same call, like a model stuck in a retry loop.
return {"text": "", "tool_calls": [
{"id": "c1", "name": "echo", "arguments": {"text": "hi"}}]}
outcome = run_agent("say hi", stuck_model, {"echo": lambda text: text})
print(outcome["stop"])This prints repeat. The first three calls run, and the fourth trips the guard before it executes.
The guard returns in the middle of a batch of tool calls. The last assistant message therefore has tool calls with no matching tool results. Most provider APIs reject a conversation in that state. If you plan to resume the run, append a tool message for every unanswered call, for example "not executed: stopped by repeat guard", before the next model call.
Soft stops: warn before you cut off
A hard stop discards work in progress. A softer approach is to tell the model about the limit. When the run is near the step limit, for example at step 17 of 20, the harness can append a message such as "You have 3 steps left. Summarize what is done and what remains." The model can then wrap up cleanly.
The same idea works for repeat detection. Instead of ending the run on the third repeat, inject a message that says the call has returned the same result three times and suggests a different approach. If the model repeats the call again, then stop. This gives the model a chance to recover, which hard stops do not.
When "done" is not really done
The model can stop too early. A reply like "I've fixed the bug" with no tool calls ends the loop, but the model may never have run the tests. The harness has a few options:
- Verify before accepting. After a no-tool-call reply, the harness runs a check, such as the project's test command. If the check fails, it appends the output as a new message and continues the loop.
- Require a completion tool. Define a
finishtool whose arguments include a short summary. The harness treats only this call as the end. This avoids confusing a mid-task remark with a final answer. - Rely on instructions. The system prompt can tell the model to run tests before finishing. This costs nothing, but it is advice, not enforcement.
Verification gives the strongest guarantee, because it does not depend on what the model says about its own work. It also links to the next chapter's subject: test output is the feedback that decides whether the loop continues.
Common mistakes
- Only a step limit. A single slow tool can exceed any reasonable time budget before the step count matters.
- Silent exits. Returning an empty string on a limit hit makes a failure look like an answer.
- Counting tool calls instead of model calls. Parallel tool calls make the limit unpredictable.
- Hashing arguments unsorted. Two identical calls with keys in a different order look different. Use
sort_keys=True, as the example does. - Leaving unanswered tool calls in the history. This breaks the next API call if you resume.
Exercise
A run ends with stop reason "step_limit" after 20 steps. The trace shows the model alternated between editing utils.py and running a test that failed each time with a different error message. Would the repeat guard in this chapter have caught it? What would you add?
Show answer
No. The repeat guard keys on the same tool name with the same arguments. Here the edits and test outputs differ each time, so the call counts never pass the threshold. Add a guard on progress instead: for example, stop or warn when the same test command has failed N times in a row, or when the same file has been edited more than a set number of times. A soft warning near the step limit, telling the model to summarize its state, would also help.
Exercise
Your harness accepts any reply without tool calls as "done". The model writes "All tests pass now" without having run any tests. Name two ways to prevent accepting this, and say which is stronger.
Show answer
Run the test command in the harness after the reply and continue the loop with the output if it fails, or require a finish tool and check conditions when it is called. The harness-side verification is stronger, because it checks the actual state of the project and does not depend on the model's own claim. A system prompt instruction to run tests is weaker, because the model can ignore it.