Stop Conditions: Keep the Loop Under Control
An agent loop runs until the model replies without asking for a tool, and nothing in that rule promises the moment will ever come. This lesson is about the code that makes sure every run ends anyway: a limit on the number of steps, a check for a run that repeats itself, and a named reason for every ending, so the program that started the run always knows what it got back.
How a run fails to end
The basic loop calls the model, runs every tool call in the reply, sends the results back and calls the model again. It stops only when a reply asks for no tool, or, with a final-answer tool, when the model hands over a valid result. Both depend on a decision of the model. When the model does not make that decision, the loop keeps going, and each turn costs another model call and makes the transcript longer.
In practice this happens in a few recognisable ways. Each one leaves its own trace in the transcript, and that trace is what the code around the model can detect.
| What goes wrong | What the transcript shows | What catches it |
|---|---|---|
| The model keeps looking | A new search after every result: other words, another page, one more order, and never an answer | A step limit |
| The model repeats a failed call | The same tool with the same arguments, the same error each time | A repeated-call check |
| The model never hands over a result | Plain text replies, or questions back, but no call to the final-answer tool | A step limit, after a reminder |
None of these is a crash. Every single step looks reasonable on its own: a search is a sensible thing to try, and an apology in plain text is a polite reply. The problem only shows across steps, which is why it has to be caught by code that watches the whole run, not by the model inside any one reply.
True or false?
A run that never ends usually raises an exception somewhere, so ordinary error handling will stop it.
False. Every call in such a run can succeed. The model keeps asking for tools, the tools keep answering, and nothing fails; only a check that counts or compares steps notices.
A model can keep a run going even when every tool it calls works correctly.
True. Searching again after a useful result is a choice of the model, not a fault of the tool. A working tool does not make the model decide it has enough.
The step limit
The simplest bound is a maximum number of model calls in one run. Each call is one step: the model reads the transcript and decides what to do next, whether that is one tool call, several, or a final answer. The loop counts the steps, and when the count reaches the limit it stops calling the model and ends the run itself.
Writing the loop as a for loop over a range makes the limit part of the structure: there is no path through the code that calls the model more often than the range allows.
MAX_STEPS = 10
for step in range(1, MAX_STEPS + 1):
reply = client.chat.completions.create(
model=MODEL, messages=messages, tools=TOOLS
)
# ... run the tool calls, or return the result ...
# Reached only when every step was used without a result.
return RunResult("step_limit", steps=MAX_STEPS)Why not tell the model in the system prompt to stop after ten steps? Because the model does not run the loop. It sees a transcript and produces one reply; it has no counter, and it may lose track of how many steps it has taken or simply decide one more search is worth it. A sentence in the prompt can encourage a short run. Only the loop can guarantee one, because the loop is the only place where the next model call is made or not made.
The number itself is a design choice, not a standard. Set it from the task: count how many steps a hard but normal task takes, and leave some room above it. A limit far too high lets a stuck run waste many calls before it ends; a limit too low cuts off runs that were about to succeed. As a reference point, the OpenAI Agents SDK counts the same thing (one model invocation per turn) and uses a default of 10 turns, which is that library's choice.
True or false?
A line in the system prompt such as "never use more than ten steps" bounds the run.
False. The model can ignore or miscount it. The run is bounded only when the code that makes the model calls refuses to make an eleventh.
A step is counted per model call, even when that one reply asks for three tool calls.
True. The limit counts the decisions of the model. A reply with three tool calls is one decision, and the three results go back in the next call.
Repeated calls
A step limit ends every run eventually, but a stuck run uses all of its steps before it ends. Some stuck runs can be recognised much earlier, by one clear sign: the model asks for the same tool with the same arguments that it already asked for in this run. The result is already in the transcript. Calling again returns the same thing, so a repeat is a strong sign that the model is going round in a circle, often after a call that failed. A second look can still be deliberate, which is why how many repeats to allow is a choice.
| Step | Tool call | Result | What the loop does |
|---|---|---|---|
| 1 | get_order(order_id="A-1042") | No order with that id | runs it |
| 2 | search_orders(email="sam@example.com") | Orders A-1024, A-0987 | runs it |
| 3 | get_order(order_id="A-1042") | Not run: already made in step 1 | warns the model |
| 4 | get_order(order_id="A-1042") | Not run | ends the run as stuck |
To detect a repeat, the loop remembers every call it has run, each as a key made of the tool name and its arguments, and checks each new call against them. The arguments arrive as a JSON string written by the model, so comparing the raw strings is not enough: the same arguments can come with different spacing or a different key order. Parse the string, then write it back out with the keys sorted, and two calls that mean the same thing get the same key. Arguments that are not valid JSON keep their raw string as the key.
import json
def call_key(call) -> tuple[str, str]:
try:
args = json.loads(call.function.arguments)
text = json.dumps(args, sort_keys=True)
except json.JSONDecodeError:
text = call.function.arguments
return (call.function.name, text)When a repeat appears, the loop has two responses, and they work well together:
- Tell the model. Instead of running the tool again, answer the call with a tool result that says what happened: this exact call was already made, its result is earlier in the conversation, so try something different or hand over what you have. Every tool call in a reply still gets a tool message with its
tool_call_id, so the conversation stays valid. Often this one message is enough to get the model out of the circle. - End the run. If the model repeats a call again after the warning, it is not going to recover, and the remaining steps would only be spent the same way. The loop ends the run as stuck.
How many repeats to allow before ending is your decision; there is no standard number. Warning on the first repeat and ending on the second, as in the table above, gives the model one chance to change course without letting it spend the rest of the run on it.
True or false?
Two calls with the arguments `{"id": 7, "lang": "en"}` and `{"lang":"en","id":7}` should count as a repeat.
True. They mean the same thing. Parsing both and dumping them with sorted keys gives one key, while a comparison of the raw strings would miss the repeat.
When the loop detects a repeat and decides to warn the model, it can skip the tool message for that call.
False. Every tool call needs a tool message with its id. The warning is that message: it answers the call in place of running the tool again.
Every ending has a name
With these checks in place, a run can end in a small number of ways, and the loop knows which one happened at the moment it happens. Giving each way a name turns that knowledge into data the rest of the program can read:
- Call the model
- Run tool calls
- done result handed over
- cut_off reply hit its length cap
- stuck same call again
- step_limit no steps left
- Call the model to Run tool calls: tool calls
- Run tool calls to Call the model: results, steps left
- Run tool calls to done: valid final answer
- Call the model to cut_off: finish_reason length
- Run tool calls to stuck: repeat after warning
- Run tool calls to step_limit: limit reached
Three of these names belong to the run, and the program defines them itself: done when the final-answer call passes validation, step_limit when the loop has used every step, and stuck when the repeated-call check gives up. No API sends them; they exist because the loop decided to stop for that reason.
The fourth name, cut_off, comes from a single reply instead of from the run. Every Chat Completions reply carries a finish_reason that says why the model stopped writing. The value length means it stopped because it reached the token cap of the request. That cap is set with max_completion_tokens, and it also counts tokens the reader never sees, such as reasoning.
A cut-off reply is not an error. The API returns it like any other reply, so the code has to check for it. Its text may stop mid-sentence, and a tool call in it may hold incomplete JSON. The loop must therefore not run its tool calls or treat its text as an answer. The run can end as cut_off, or the program can first try the call once more with a higher cap.
| Value | Meaning | What the loop does |
|---|---|---|
| tool_calls | The model called one or more tools | Runs them and continues |
| stop | A natural stop point (or a stop sequence) | Without a final-answer call: reminds the model, which costs a step |
| length | The token cap of the request was reached | Ends the run as cut_off |
| content_filter | Content was left out after a filter flagged it | Should end the run with a reason of its own |
| function_call | Deprecated, replaced by tool_calls | Not expected from current requests |
Note that stop does not mean the task is done. It only says the reply ended naturally. A run is done when the program has a result it validated, and nothing less. A loop that reads finish_reason should also expect values beyond the three it uses most (tool_calls, stop and length), and give any other value a name of its own instead of carrying on as if nothing happened.
True or false?
A reply with `finish_reason` set to `stop` means the agent has finished its task.
False. It means only that this reply ended at a natural point. The task is finished when the program holds a validated result, for example from the final-answer tool.
A reply cut off at its length cap arrives as a normal reply, not as an exception.
True. The API returns it with `finish_reason` set to `length`. Unless the code checks that field, it will happily use a half-written reply.
Ending without a result
Three of the four endings have no result. What the run returns in that case decides whether the caller can do the right thing. The tempting shortcut is to return whatever the model said last, or the last tool result, as if it were the answer. That turns an unfinished run into a confident-looking reply: a customer told that a refund was approved because the last text in the transcript mentioned refunds.
The honest return value says plainly that the run did not finish, and why. A small result type does this: the stop reason, the result only when there is one, and the number of steps used.
from dataclasses import dataclass
from typing import Literal
StopReason = Literal["done", "step_limit", "stuck", "cut_off"]
@dataclass
class RunResult:
reason: StopReason
result: dict | None = None
steps: int = 0
@property
def finished(self) -> bool:
return self.reason == "done"The loop now returns a RunResult on every path. Each check that ends the run returns at the point where it decides, with its own reason:
def run_agent(messages: list[dict], max_steps: int = 10) -> RunResult:
seen: set[tuple[str, str]] = set()
repeats = 0
for step in range(1, max_steps + 1):
reply = client.chat.completions.create(
model=MODEL, messages=messages, tools=TOOLS
)
choice = reply.choices[0]
if choice.finish_reason == "length":
return RunResult("cut_off", steps=step)
message = choice.message
messages.append(message.model_dump(exclude_none=True))
if not message.tool_calls:
messages.append({"role": "user", "content": REMINDER})
continue
for call in message.tool_calls:
key = call_key(call)
if key in seen:
repeats += 1
if repeats > 1:
return RunResult("stuck", steps=step)
content = REPEAT_WARNING
else:
seen.add(key)
content, result = execute(call)
if result is not None:
return RunResult("done", result=result, steps=step)
messages.append(
{"role": "tool", "tool_call_id": call.id, "content": content}
)
return RunResult("step_limit", steps=max_steps)Here execute runs a tool from the registry, or validates the arguments of the final-answer call; it returns the content for the tool message, plus the result when a final answer passed validation. REMINDER asks the model to hand over its result with the final-answer tool, and REPEAT_WARNING is the message for a repeated call. The reminder uses a step like any other call, so a model that keeps replying in plain text still meets the limit.
The caller now acts on the reason instead of guessing:
outcome = run_agent(messages)
if outcome.finished:
save(outcome.result)
else:
print(f"Unfinished: {outcome.reason} after {outcome.steps} steps")Different reasons suggest different next moves. A cut_off run may succeed with a higher token cap. A step_limit run may need a narrower task or a larger limit, and a stuck run usually points to a tool or an instruction that leaves the model with no way forward, worth reading in the transcript. In every case the unfinished task is reported as unfinished: it can wait for someone to look at it, but it is never saved as if it were an answer.
True or false?
When a run reaches its step limit, returning the last text of the model as the answer is a safe fallback.
False. That text was written mid-task and was never validated. Presenting it as the answer hides the fact that the run did not finish.
An unfinished run that returns its stop reason gives the caller enough to choose what to do next.
True. The reason separates a reply that ran out of tokens from a run that ran out of steps or went in circles, and each of those calls for a different response.