Sub topic 9
Knowing when to stop
This chapter assumes you have read the agent loop chapter and can follow a Python for loop over model replies and tool results.
Why the loop needs an exit
The model has no built-in sense that the work is finished. Each call produces one reply. The harness decides whether to call again. Without clear exit rules, an agent can run for hours, spend tokens, and repeat the same failing action.
The normal exit: a reply with no tool calls
In most designs, the model signals completion by replying with text and no tool calls. The harness treats that text as the final answer and returns it.
This exit depends on the model's judgment. The model may stop early and claim success without checking. It may also keep calling tools after the work is done. The harness therefore needs its own limits as well.
Limits the harness enforces
| Limit | What it prevents | Typical response when hit |
|---|---|---|
| Step limit | Endless loops | Return a "stopped" status and the partial work |
| Repeat detection | The same failing call tried over and over | Stop, or tell the model to try something else |
| Time budget | A slow tool or a long session | Cancel the tool, then stop |
| Token or cost budget | Runaway spending and a full context window | Compact history or stop |
| User interrupt | Work heading the wrong way | Stop immediately and keep the transcript |
A loop with stop conditions
The function below returns a status, so the caller can tell a finished task from an abandoned one. The demo model at the bottom asks for the same tool call forever, so repeat detection ends the run.
import json
def run_agent(task, call_model, tools, max_steps=20, max_repeats=3):
messages = [{"role": "user", "content": task}]
seen = {}
for step in range(max_steps):
reply = call_model(messages)
messages.append({"role": "assistant", "content": reply["text"],
"tool_calls": reply["tool_calls"]})
if not reply["tool_calls"]:
return {"status": "done", "answer": reply["text"], "steps": step + 1}
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 {"status": "stuck", "steps": step + 1}
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 {"status": "step_limit", "steps": max_steps}
def looping_model(messages):
return {"text": "", "tool_calls": [
{"id": "1", "name": "echo", "arguments": {"text": "hi"}}]}
print(run_agent("demo", looping_model, {"echo": lambda text: text}))This prints {'status': 'stuck', 'steps': 4}. The fourth identical call goes over max_repeats, so the loop stops.
Common errors
- Choosing a limit that is too low. A limit of 5 steps cuts off ordinary tasks that read, edit, and test. Pick a value from observed traces, and make it configurable.
- Failing silently at the limit. If the harness returns an empty string, the user cannot tell what happened. Return a status and the work so far.
- Counting only identical calls. A model can vary one argument slightly and still be stuck. Also watch for repeated error messages.
- Trusting "done" without evidence. A claim of success is only text. For code tasks, have the harness run the tests before it accepts the stop.
Exercise
A model replies with text and no tool calls, but the text says "I fixed the bug" and the tests were never run. Name one stop condition the harness could add, and say where in the loop it would run.
Show answer
Add a verification check at the "no tool calls" exit. Before returning "done", the harness runs the test command. If the tests fail, it appends the failure output as a new message and continues the loop instead of returning. The step limit still bounds how many retries are possible.