Sub topic 11
Knowing when to stop
An agent loop that can keep searching can also keep searching forever. This chapter covers the conditions that end a retrieval loop, how to set a step budget, and what to do when the budget runs out. It assumes you can read basic Python and have seen the agent loop from the previous chapters: the model calls a tool, you run it, you append the result, and you call the model again.
Why stopping needs design
Classic RAG always does exactly one retrieval, so it cannot loop. An agent has no such limit unless you add one. Three things go wrong without a stopping design:
- Runaway loops. The model repeats the same query, or keeps rephrasing a search whose answer is simply not in the corpus.
- Runaway cost. Each step sends the whole message history again, so cost grows faster than the step count.
- Premature answers. The model stops after one weak search and answers from guesswork.
Good stopping logic prevents all three. It ends the loop when the evidence is enough, and it also ends it when more searching will not help.
The stopping conditions
A loop can end for several reasons. Treat each one as a separate, named exit.
| Exit | Trigger | Who decides |
|---|---|---|
| Final answer | The model replies with no tool calls | The model |
| Step budget | The loop count reaches `MAX_STEPS` | Your code |
| Token or cost budget | Total tokens or spend passes a limit | Your code |
| Time budget | Wall-clock time passes a limit | Your code |
| Repetition | The same tool call appears again | Your code |
| Tool failure | A tool keeps returning errors | Your code |
The first exit is the happy path. The model decides it has enough and writes the answer. Every other exit is a guard that your code enforces regardless of what the model wants.
Setting a step budget
A step is one model call, which may contain several parallel tool calls. The budget caps the number of model calls, not the number of tool calls. Choose the number from the questions you expect:
- A single-fact lookup needs one or two steps.
- A comparison of two items needs about three: one search for each, then the answer.
- A multi-part question may need five to eight.
Start with a budget slightly above the number of steps your hardest realistic question needs. Then read your logs. If many runs hit the limit, either the budget is too low or the agent is wandering. Raising the number fixes only the first case.
The loop from the plan already uses a budget:
import json
MAX_STEPS = 5
def run_agent(question, call_model, tools_by_name, tool_specs):
# call_model(messages, tool_specs) is supplied by you and returns a dict:
# {"content": str, "tool_calls": [{"id": str, "name": str, "arguments": dict}]}
# An empty or missing "tool_calls" means the model has given its final answer.
messages = [
{"role": "system", "content": "Answer from the documentation. Search when you need facts, and cite passage ids."},
{"role": "user", "content": question},
]
for _ in range(MAX_STEPS):
reply = call_model(messages, tool_specs)
tool_calls = reply.get("tool_calls") or []
if not tool_calls:
return reply["content"]
messages.append({
"role": "assistant",
"content": reply.get("content", ""),
"tool_calls": tool_calls,
})
for call in tool_calls:
tool = tools_by_name.get(call["name"])
if tool is None:
result = {"error": f"unknown tool: {call['name']}"}
else:
result = tool(**call["arguments"])
messages.append({
"role": "tool",
"tool_call_id": call["id"],
"content": json.dumps(result),
})
# Budget spent: force a final answer with no tools offered.
messages.append({
"role": "user",
"content": "Step limit reached. Answer now with what you have found and say what is still missing.",
})
return call_model(messages, [])[“content”]Two details matter here. The for loop makes the budget a hard limit that the model cannot argue with. And the final call passes an empty tool list, so the model cannot request another search. Without that, some models answer with yet another tool call and your function returns nothing useful.
Failing gracefully at the limit
Hitting the budget is not an error to hide. It is information. The forced-answer message in the loop does two jobs. It tells the model to answer now, and it tells the model to state what is still missing. A good limit-hit answer reads like this: "The documentation covers the rate limit for the free plan, but I did not find the limit for the enterprise plan."
That honest partial answer is better than a confident guess and better than an error page. Log every limit hit, too. A rising rate of limit hits is an early sign that your retrieval quality dropped or that questions changed.
Guards beyond the step count
A step budget alone is a blunt tool. Add guards for the cases it misses.
Repetition
If the model sends the same query twice, a third attempt will not behave differently. Track the calls you have already run:
import json
def is_repeat(call, seen):
# Same tool and same arguments, ignoring key order.
key = (call["name"], json.dumps(call["arguments"], sort_keys=True))
if key in seen:
return True
seen.add(key)
return FalseWhen is_repeat returns True, do not run the tool. Return a tool result such as {"error": "You already ran this exact search. Try a different query or answer now."}. This nudges the model without ending the loop. If repeats continue, treat it as a guard trip and force the final answer.
Exact matching misses near-duplicates, such as "reset password" followed by "password reset". Normalizing case and word order catches a few more, but do not chase perfection. The step budget still backs you up.
Token and time budgets
Each step resends the full history. A loop of five steps with 3,000 tokens of results per step sends far more than 15,000 tokens in total, because earlier results are sent again on every later call. Track tokens as the loop runs, using the usage numbers that most providers return with each response, and stop when a limit is reached. A time budget protects the user from a loop that is technically within the step limit but slow. Check the clock at the top of each iteration.
Empty and failing results
If a search returns nothing, one rewrite is reasonable. Three empty searches in a row usually mean the answer is not in the corpus. Count consecutive empty results and treat a small number, such as two, as a signal to answer with "not found". The same applies to tool errors: a tool that fails twice with the same error will fail a third time.
Combining the guards
Put the guards in one place so the exits stay readable. This version extends the loop with repetition and time checks:
import json
import time
MAX_STEPS = 6
MAX_SECONDS = 30
MAX_EMPTY = 2
def run_guarded_agent(question, call_model, tools_by_name, tool_specs):
messages = [
{"role": "system", "content": "Answer from the documentation. Cite passage ids."},
{"role": "user", "content": question},
]
seen = set()
empty_in_a_row = 0
started = time.monotonic()
stop_reason = "step_limit"
for _ in range(MAX_STEPS):
if time.monotonic() - started > MAX_SECONDS:
stop_reason = "time_limit"
break
reply = call_model(messages, tool_specs)
tool_calls = reply.get("tool_calls") or []
if not tool_calls:
return {"answer": reply["content"], "stop_reason": "final_answer"}
messages.append({
"role": "assistant",
"content": reply.get("content", ""),
"tool_calls": tool_calls,
})
for call in tool_calls:
key = (call["name"], json.dumps(call["arguments"], sort_keys=True))
tool = tools_by_name.get(call["name"])
if key in seen:
result = {"error": "Exact search already run. Change the query or answer now."}
elif tool is None:
result = {"error": f"unknown tool: {call['name']}"}
else:
seen.add(key)
result = tool(**call["arguments"])
empty_in_a_row = empty_in_a_row + 1 if not result else 0
messages.append({
"role": "tool",
"tool_call_id": call["id"],
"content": json.dumps(result),
})
if empty_in_a_row >= MAX_EMPTY:
stop_reason = "no_evidence"
break
messages.append({
"role": "user",
"content": "Stop searching. Answer now with what you have found and say what is still missing.",
})
answer = call_model(messages, [])["content"]
return {"answer": answer, "stop_reason": stop_reason}The function returns a stop_reason next to the answer. That field costs nothing and pays off in evaluation, where you will want to count how often each exit fires.
Common mistakes
- Budget set too low. Questions that need three searches get cut off at two and produce partial answers that look like model failures.
- Offering tools on the forced final call. The model asks for another search and your code returns an empty or malformed answer.
- Counting tool calls instead of steps. Parallel calls inside one step then use up the budget too fast.
- Silent cutoffs. If the answer does not say it is incomplete, users trust a guess.
- Relying on the model to count. A line in the prompt such as "use at most three searches" is a request. Only code enforces a limit.
Exercises
Exercise
A loop has MAX_STEPS = 4. The model sends two parallel search calls in step 1, one search in step 2, and a final answer with no tool calls in step 3. How many steps were used, and did the budget trip?
Show answer
Three steps were used, because a step is one model call and the two parallel searches in step 1 count once. The budget did not trip. The loop exited through the final-answer path with stopreason "finalanswer".
Exercise
In the guarded loop, the model repeats the identical search three times and every result is non-empty. Which guard handles this, and what does the model see on the repeats?
Show answer
The repetition guard handles it. On the second and third attempts the tool does not run. The model receives a tool result with an error saying the exact search was already run and asking it to change the query or answer. If it keeps repeating, the step budget ends the loop and the forced final call produces the answer.
Exercise
Why does the forced final call pass an empty tool list instead of the normal tool specs?
Show answer
With no tools offered, the model cannot return another tool call, so the reply must be a text answer. If tools were still offered, the model might request another search and the function would end with no usable answer.