Skip to content
mentoor

Topic 2 of 5 · 4 min read

Stopping conditions that end runs cleanly

Goal: Write the stop conditions for a described agent so it ends on success, on a hard limit and on an unrecoverable error.

A loop that can only stop when the model feels finished will eventually run forever, so every agent needs one success stop and several hard stops that the model cannot talk its way past.

Check yourself · 1 of 3

Why should an agent loop have a hard turn limit even when the model is told to stop when done?

Choose one answer

Why it matters

A model decides to stop by replying without a tool call. That is a judgment, and judgments fail both ways. It may stop early and say "done" with the work half finished, or it may keep checking, re-reading and polishing. Your code owns the end of the run, just as it owns running the tools.

The stops to write

  1. Success: a done check you can verify. Prefer a final-answer tool, such as submit_result, whose arguments must pass validation. Better still, a real check: the tests pass, the file exists, the schema validates. Do not accept "I am done" in prose as the only signal.
  2. Turn limit. A fixed number of loop iterations. It is the last line of defence and should be set from real runs, not guessed.
  3. Repeated errors. If the same tool fails several times in a row, stop and report, or switch strategy. Retrying forever is not persistence.
  4. User interrupt. A cancel signal checked at the top of each turn and before each tool call, so a long run can be ended without killing the process.
  5. Unrecoverable error. Missing permission, an invalid API key or a deleted resource. Retrying cannot fix it, so end with a clear message.

Each stop should return a reason: done, turn_limit, repeated_error, cancelled, fatal. Callers and dashboards need to tell a success from a cutoff.

type StopReason = "done" | "turn_limit" | "repeated_error" | "cancelled" | "fatal";

for (let turn = 1; turn <= MAX_TURNS; turn++) {
  if (signal.aborted) return stop("cancelled");
  const reply = await model.call({ messages, tools });
  const done = reply.toolCalls.find(c => c.name === "submit_result");
  if (done && validate(done.input)) return stop("done", done.input);
  // run tools, count consecutive failures
  if (consecutiveFailures >= 3) return stop("repeated_error");
}
return stop("turn_limit");

Before and after

Weak: while (true) { ... if (!reply.toolCalls.length) break; }. It ends only when the model stops calling tools. A confused model that keeps calling search never ends, and a model that answers early ends with no check.

Fixed: a bounded for loop, a validated final-answer tool, a failure counter and an abort signal, as above.

What goes wrong

  • Trusting the model's "done". The agent claims the tests pass without running them.
  • A limit with no report. The run hits the cap and returns a half answer that looks like a finished one.
  • Retrying fatal errors. A 401 from the API retried ten times wastes ten turns and fixes nothing.
  • No cancel path. The only way to end a stuck run is to kill the process, losing its state.

Examples

A final-answer tool

{
  "name": "submit_result",
  "description": "Call once the migration script runs and the tests pass.",
  "input_schema": {
    "type": "object",
    "properties": {
      "summary": { "type": "string" },
      "tests_passed": { "type": "boolean" }
    },
    "required": ["summary", "tests_passed"]
  }
}

Your code accepts the call only when tests_passed is true and the last test run in the history agrees.

Which stop fits which failure

A support agent receives 403 from the refunds API on every call. That is fatal: permission will not appear on retry. Three timeouts from a search tool in a row is repeated_error: stop and report, or fall back to another source. A run that reached turn 25 of 25 with the task unfinished is turn_limit, and the caller should see that it is incomplete.

Key points

  • Your code owns the end of the run; the model's decision to stop is only one signal.
  • Prefer a final-answer tool or a real check (tests, schema) over a prose claim of being done.
  • Combine a success stop with a turn limit, a repeated-error stop, a cancel signal and a fatal-error exit.
  • Return a stop reason so callers can tell a finished run from a cutoff.
  • Do not retry errors that retrying cannot fix, such as authentication or permission failures.

Common mistakes

  • Relying on a no-tool-call reply as the only way the loop ends.
  • Setting a turn limit and returning whatever the last message was, with no stop reason.
  • Counting retries per turn instead of consecutive failures of the same tool.
  • Treating every error as retryable, including permission and authentication errors.

Check yourself · 2 of 3

Which signal is the most reliable proof that a coding agent has finished its task?

Choose one answer

Check yourself · 3 of 3

An agent calls a payments API and gets 401 Unauthorized on three turns in a row, retrying each time. What should the loop do?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic