It is already the latest posts!
It is already the oldest posts!

AI Agents in Practice: From One Model Call to a Production System

Part 5

〇五Stop Conditions

No tool call does not mean the task is done, and a spent budget is no reason to just exit

欤冰 9 min read 中文

The loop in Article 01 has two exits: the model's response contains no tool call, or the call count reaches max_steps. With a scripted fake model those two are enough. With a real model and real tools you meet at least these three situations:

  • the model's output is cut off halfway, the response has no tool call, and the loop returns half a sentence as the final answer;
  • every tool call returns a 12,000-token table, the 18th request exceeds a 200K context window, the API returns an error, and the 1.72 million tokens read by the 17 calls before it are wasted;
  • one tool takes 25 seconds per run, the step limit is far away, and the user has already waited two minutes.

None of the three can be handled by a step limit. This article splits stop conditions into four, looks at who decides each and when it is checked, and at how the loop should exit once a budget runs out.

Four stop conditions

ConditionDecided byPrevents
model declares it is donemodel(normal finish)
step limitruntimea model stuck repeating itself, a loop that never ends
token budgetruntimerunaway compute and cost per task, or one request exceeding the context window
wall-clock limitruntimeusers waiting longer than acceptable, or a downstream timeout firing first

Wall-clock time is the time that has actually passed since the task started, including model inference, tool runs and all waiting, as opposed to the time the CPU spends computing.

Only the first is decided by the model; the other three are budgets the runtime sets. They cannot stand in for each other: a step limit does not control how large each step is, a token budget does not control how slow each step is, and a time limit does not control the cost piling up inside a fast loop.

Where stop checks happen: the three budgets before the model call, stop_reason after it; when a budget is nearly spent, a final call with tools off

The model declaring it is done: read stop_reason, not the tool calls

Every model API response carries a field that says why the output ended. Anthropic's documentation calls it stop_reason; common values are:

  • end_turn: the model considers its output complete;
  • tool_use: the model requests a tool and waits for the result;
  • max_tokens: the output reached the max_tokens cap set in the request and was cut off;
  • stop_sequence: the output hit a stop string the developer specified.

OpenAI Chat Completions calls the field finish_reason, with values such as stop, tool_calls and length; length means truncation.

Article 01's loop decided "done" by whether the response had tool calls. That works between end_turn and tool_use, but max_tokens is misread: the output is cut mid-sentence, there is no tool call either, and the loop treats it as the final answer. A subtler case is truncation in the middle of a tool call's arguments: the JSON is incomplete and the runtime fails to parse it.

So the precise test for "the model declares it is done" is stop_reason == "end_turn". On max_tokens the runtime has a few options: retry with a larger max_tokens; keep the truncated part as an assistant message and append a user message asking the model to continue; or mark the task as abnormal and hand it to the caller. The code in this article takes the last option because it is the easiest to spot in logs.

Three budgets: check before the call

The step, token and time budgets are all checked before the model call.

Once a model call is sent, the tokens and time it consumes are fixed, so a check afterwards can only find out "we are already over". A check before the call knows the current context size and how long the previous round took, and can estimate whether the next round will cross the line.

The estimate has to match how each resource grows:

  • steps: one per round, compared directly;
  • tokens: the next request's input is at least the current context size, plus this round's tool result;
  • time: use the time the last round (model call plus tool run) actually took as the estimate for the next.

Time in particular has to be estimated. If you only compare "time used so far", then in a task whose tool takes 25 seconds, the check passes, the model call takes 6 seconds, the tool another 25, and the task overruns its limit by half a minute.

When a budget runs out: wrap up, don't just exit

Raising an exception when a budget runs out gives the user an error message and throws away everything gathered so far. A better approach reserves a small share of the budget and, when the budget is nearly spent, makes one last wrap-up call: tools off, and the model states, from what it has gathered, what was done, what was found and what is missing.

How to turn tools off depends on the API. Anthropic accepts tool_choice: {"type": "none"} and OpenAI tool_choice: "none", after which the model requests no tools. You could also leave the tool definitions out of this request, but Article 04 showed that changing tool definitions invalidates the whole prefix cache, making the wrap-up call more expensive.

The wrap-up call's budget has to be reserved in advance: if you wait until the tokens are all gone, the wrap-up itself crosses the line.

A loop with a stop policy

The code below replaces the real model and tools with a simulated clock and fixed token counts to reproduce five scenarios. Save it as stop_policy.py; Python 3.9 or later, no third-party packages:

from dataclasses import dataclass, field

# ---------- A simulated clock and token counts replace real calls, so results are reproducible ----------

class Clock:
    """Simulated wall clock. advance stands in for real waiting."""
    def __init__(self):
        self.now = 0.0
    def advance(self, seconds):
        self.now += seconds

@dataclass
class Reply:
    """Minimal model response. stop_reason values follow Anthropic: end_turn / tool_use / max_tokens."""
    text: str = ""
    tool: str = ""            # empty means no tool call
    stop_reason: str = "end_turn"
    output_tokens: int = 300

@dataclass
class Scenario:
    """A scenario: the model follows script; each tool returns result_tokens and takes tool_seconds."""
    name: str
    script: object                    # (step, tools_enabled) -> Reply
    result_tokens: int = 1500
    tool_seconds: float = 0.5

@dataclass
class Limits:
    """The three stop conditions the runtime controls, plus the share reserved for the final call."""
    max_steps: int = 12
    max_input_tokens: int = 200_000   # cumulative input over the whole task
    deadline_seconds: float = 120.0
    reserve_tokens: int = 20_000      # kept for the final wrap-up call
    reserve_seconds: float = 15.0

@dataclass
class Outcome:
    status: str
    steps: int
    input_tokens: int
    elapsed: float
    answer: str
    log: list = field(default_factory=list)

SYSTEM_TOKENS = 3000

def model_seconds(input_tokens, output_tokens):
    """Article 02's linear approximation: network 0.2s + prefill 8,000 tokens/s + decode 60 tokens/s."""
    return 0.2 + input_tokens / 8000 + output_tokens / 60

def run(scn, limits):
    """An Agent loop with a stop policy.

    Before every model call, check three budgets (steps, cumulative tokens, time left);
    after the call, use stop_reason to decide between done, continue and truncated.
    When a budget is about to run out, call once more with tools off so the model
    summarizes its progress.
    """
    clock = Clock()
    context = SYSTEM_TOKENS + 50          # system + user task
    used, step, log = 0, 0, []
    last_round = 0.0                      # seconds the last round (model + tools) took, used to estimate the next

    def call(tools_enabled):
        nonlocal used, context
        reply = scn.script(step, tools_enabled)
        used += context
        clock.advance(model_seconds(context, reply.output_tokens))
        context += reply.output_tokens
        return reply

    while True:
        # ---- Before the call: if this round could exceed a budget, wrap up instead ----
        reason = None
        if step >= limits.max_steps - 1:
            reason = "step_limit"
        elif used + context * 2 > limits.max_input_tokens - limits.reserve_tokens:
            reason = "token_budget"     # this round plus the wrap-up need at least 2 inputs of the current size
        elif clock.now + last_round > limits.deadline_seconds - limits.reserve_seconds:
            reason = "deadline"         # one more round would eat the time the wrap-up needs
        if reason:
            step += 1
            final = call(tools_enabled=False)
            log.append(f"step {step}: {reason}, final call without tools")
            return Outcome(reason, step, used, clock.now, final.text, log)

        step += 1
        started = clock.now
        reply = call(tools_enabled=True)

        # ---- After the call: tell the three stop_reasons apart ----
        if reply.stop_reason == "max_tokens":
            # the output was cut off, the task is not done; record it and stop, let the caller decide
            log.append(f"step {step}: output truncated")
            return Outcome("truncated", step, used, clock.now, reply.text, log)
        if not reply.tool:
            return Outcome("completed", step, used, clock.now, reply.text, log)

        clock.advance(scn.tool_seconds)    # the runtime runs the tool
        context += scn.result_tokens       # the result enters the next round's context
        last_round = clock.now - started

# ---------- Five scenarios ----------

def normal(step, tools):
    if not tools or step >= 4:
        return Reply("orders.user_id has no index.")
    return Reply(tool="grep_log", stop_reason="tool_use")

def never_done(step, tools):
    # the model keeps reading the same file, always deciding it needs one more look
    if not tools:
        return Reply("Not finished: read app.conf many times, found nothing new.")
    return Reply(tool="read_config", stop_reason="tool_use")

def big_results(step, tools):
    if not tools:
        return Reply("Not finished: checked logs of 4 shards; shard 3 looks wrong.")
    return Reply(tool="dump_table", stop_reason="tool_use")

def slow_tools(step, tools):
    if not tools:
        return Reply("Not finished: completed 3 full log scans.")
    return Reply(tool="scan_all_logs", stop_reason="tool_use")

def truncated(step, tools):
    if step == 3:
        # max_tokens hit mid-sentence: no tool call, so it looks finished
        return Reply("According to the slow-query log, the problem is", stop_reason="max_tokens", output_tokens=1024)
    return normal(step, tools)

SCENARIOS = [
    Scenario("normal", normal),
    Scenario("never_done", never_done, result_tokens=400),
    Scenario("big_results", big_results, result_tokens=12_000),
    Scenario("slow_tools", slow_tools, tool_seconds=25.0),
    Scenario("truncated", truncated),
]

if __name__ == "__main__":
    limits = Limits()
    for scn in SCENARIOS:
        o = run(scn, limits)
        print(f"{scn.name:<12} status={o.status:<13} steps={o.steps:>2} "
              f"input_tokens={o.input_tokens:>7,} elapsed={o.elapsed:6.1f}s  answer={o.answer}")

Output (simulated clock, identical every run):

normal       status=completed     steps= 4 input_tokens= 23,000 elapsed=  25.2s  answer=orders.user_id has no index.
never_done   status=step_limit    steps=12 input_tokens= 82,800 elapsed=  78.2s  answer=Not finished: read app.conf many times, found nothing new.
big_results  status=token_budget  steps= 5 input_tokens=138,250 elapsed=  45.3s  answer=Not finished: checked logs of 4 shards; shard 3 looks wrong.
slow_tools   status=deadline      steps= 4 input_tokens= 23,000 elapsed=  98.7s  answer=Not finished: completed 3 full log scans.
truncated    status=truncated     steps= 3 input_tokens= 14,550 elapsed=  30.5s  answer=According to the slow-query log, the problem is

The stop condition each of the five scenarios hit, and where steps, cumulative input and time ended relative to their limits

Where each scenario stopped

normal: 4 calls; the model returns end_turn on the 4th, with all three budgets far from their limits. The stop policy has no effect in this scenario, which is exactly how it should behave.

never_done: the model asks to read the same config file every round. After the 11th call the step check fires, and the 12th is the wrap-up call with tools off. The user gets an answer saying the task is unfinished and why. With "the model declares it is done" as the only exit, this loop would never end.

Re-reading the same file is a pattern that can be recognized long before the steps run out. Loop detection in Article 41 handles it. The step limit is the last line of defense, not the main detector.

big_results: each tool returns 12,000 tokens. Before the 5th call, cumulative input plus the estimate for "this round and the wrap-up" exceeds 180,000 (the 200,000 budget minus the 20,000 reserve), so the loop wraps up. Cumulative input ends at 138,250 tokens, below the budget.

For comparison, without a token budget this loop would run to the 17th call, reading 1,724,650 tokens in total; the 18th request's input would reach 212,150 tokens, beyond a 200K context window, the API would return an error, and the task would fail with no output at all.

slow_tools: each tool run takes 25 seconds. The first three rounds take about 31 seconds each; before the 4th call, time used plus the estimate for one more round exceeds 105 seconds (the 120-second limit minus the 15-second reserve), so the loop wraps up and ends at 98.7 seconds. Comparing only the time used so far, it would run one more full round of model call and tool and end at about 130 seconds, 10 seconds over the limit.

truncated: the 3rd call's output hits the 1,024-token cap and is cut off mid-sentence. stop_reason is max_tokens, and the runtime marks the task truncated. Article 01's loop would have returned the same output to the user as the final answer.

Where the budget numbers come from

The limits above are demonstration values. In a real system the three budgets come from different places:

  • the step limit can be taken from a high percentile of historical step counts, for example by running the evaluation set once (Article 53) and using 1.5 times the 99th percentile of successful tasks' steps;
  • the token budget follows from cost: convert the highest acceptable cost per task into cumulative input tokens at the provider's price. Separately, check that no single request's input exceeds the context window; that is a hard limit unrelated to cost;
  • the time limit is set by the caller. In interactive use it depends on how long users will wait; for background jobs, on the task queue's timeout (Article 57). The runtime's limit should be shorter than the external timeout, or the outside fires first and the runtime never gets to wrap up.

Record why it stopped

Outcome.status sorts every task's ending into five classes. The value of the field is in statistics: if the share of step_limit rises from 2% to 8% in a week, some change made the model more prone to repeating itself; if token_budget clusters on one tool, that tool returns too much; more truncated means max_tokens is set too low.

Record only "succeeded" or "failed" and these signals blur together. Article 52's cost accounting and Article 53's evaluation set both group statistics by stop reason.

With this, the skeleton of the loop is complete: how messages are organized, how requests are assembled, and when the loop stops. The next article is about the wait users see: streaming makes the first word appear sooner, but its effect on total time and on tool calls has to be looked at separately.

Back to top