Lab: Limits, Loop Detection and Timeouts
Build a tool loop with five independent guards (turn cap, cumulative token budget, per-tool and session timeouts, repeat fingerprints and per-tool failure streaks) and run six scenarios: four guards each stop a runaway run, the tool timeout cuts a hung call short, and you trigger the turn cap yourself.
Contentsand lesson path
On this page
- The Operational Risks of Unbounded Agent Loops
- Lab goal and setup
- Step 1: Action Fingerprinting and Loop Detection
- Steps 2 to 5: Run the Guards Against Six Scenarios
- Practice questions
- Apply it
- Review prompt
Lessons of Agent Loops & ReAct
- What Makes Something an Agent, and Where Agents Pay Off Concept · 15 min
- The Loop in Sixty Lines Worked example · 25 min
- From ReAct Prompts to Native Tool Calls and Reasoning Models Concept · 15 min
- Lab: Limits, Loop Detection and Timeouts Lab · 25 min
- Recovering from Failed Actions Lab · 20 min
- Check: Predict the Next Step Knowledge check · 8 questions
What you will learn
- Enforce step, time and token limits and detect loops or repeated failing calls.
Prerequisites: Tool Calling
01. The Operational Risks of Unbounded Agent Loops
A normal program follows paths that a developer wrote down, so its loops end when their conditions say so. An agent loop is different: the model decides on each turn whether to call another tool or to stop, and nothing in the code forces that decision to arrive. When a tool returns an empty result, an unexpected shape or a transient error, a model may retry the same call, alternate between two tools, or wait on a service that never answers. Every extra turn re-sends the whole history, so a stuck run spends tokens and quota without making progress. From the context it has, another call often looks like a reasonable next step to the model.
So treat the model as a planner whose choices your runtime must bound. This lab builds five guards that work independently, because each one catches a failure that the others miss:
- Turn cap: a maximum number of model calls per run (often between 8 and 20, tuned to the task), so the loop ends even if the model never gives a final answer.
- Cumulative token budget: input, output and reasoning tokens added up over every call in the run. This is not the per-call
max_tokensparameter, which only caps the length of one reply. - Deadlines: a timeout for each tool call and one for the whole session. In this lab the session deadline is checked before each model call and also caps each tool wait, so a hung tool cannot hold the run open. The loop does not check it during a model call, so a hung model request needs its own timeout on the API client. A timeout stops the loop from waiting; stopping the work itself needs a timeout on the underlying client, or a subprocess you can kill.
- Repeat detection: a fingerprint of each tool name and its arguments, so an identical call is noticed before it runs again.
- Failure streaks: a count of failed calls in a row for each tool, whatever the arguments, so a model that keeps rewording a search that cannot succeed is stopped as well.
02. Lab goal and setup
In this lab you build a tool loop with five independent guards and watch four of them stop a different failure (you trigger the fifth, the turn cap, yourself in step 5): a repeated call, a search reworded again and again, a run that outgrows its token budget, a hung tool and a session that runs out of time. The model is a scripted fake that picks its next action from the history, so the lab is free, offline and repeatable.
You need: Python 3.12 or later and nothing else (standard library only, no API key). Tested with Python 3.12.13. Create an empty folder loop-lab and save each file from the steps into it.
loop-lab/
├── loop_detector.py step 1: action fingerprints
├── tools.py step 2: fixture tools, one of them hangs
├── fake_model.py step 2: scripted stand-in for a model API
├── guarded_loop.py step 3: the loop and its five guards
└── run_lab.py step 4: six scenarios03. Step 1: Action Fingerprinting and Loop Detection
The most common trap is the repeated action. The agent searches a document index, gets nothing back, and on the next turn issues the same search with the same arguments. The model sees almost the same context as before, so it often makes the same choice. A variant alternates between two tools: search, nothing found, verify, nothing found, search again.
To catch both, the loop fingerprints every action before running it:
- Take the tool name and its argument dictionary.
- Serialise the arguments as JSON with sorted keys and fixed separators, so the same arguments always give the same text, whatever order the model wrote them in.
- Hash that text with SHA-256 and keep the first eight hex characters as a short fingerprint.
- Keep the fingerprints of recent actions in a sliding window (the last four here), which also catches an A, B, A, B cycle between two tools.
When a fingerprint is already in the window, the loop does not end the run at once. It first sends a reflection notice in place of the tool result: you already ran this exact call, so change the arguments or use another tool. Many models change course after one clear notice. If the model repeats the same action after the notice, the loop stops the run.
A fingerprint only matches identical calls. A model that rewords its query on each turn ("annual report 2025", then "2025 annual report") produces a new fingerprint every time, so the detector never fires. Step 3 adds a second guard for that case: a per-tool count of failures in a row.
import hashlib
import json
from typing import Any, Dict, List, Tuple
class LoopDetector:
def __init__(self, window_size: int = 4, max_repeats: int = 2):
self.window_size = window_size
self.max_repeats = max_repeats
self.history: List[str] = []
def compute_fingerprint(self, tool_name: str, args: Dict[str, Any]) -> str:
# Deterministic serialization with sorted keys
canonical_json = json.dumps(args, sort_keys=True, separators=(",", ":"))
payload = f"{tool_name}:{canonical_json}".encode("utf-8")
return hashlib.sha256(payload).hexdigest()[:8]
def record_and_check(
self, tool_name: str, args: Dict[str, Any]
) -> Tuple[bool, str]:
fp = self.compute_fingerprint(tool_name, args)
recent_window = self.history[-self.window_size:]
occurrences = recent_window.count(fp)
self.history.append(fp)
# Flag once the same action has been seen max_repeats times in the window
is_loop = occurrences >= (self.max_repeats - 1)
return is_loop, fpCheck the detector before you build on it. From inside loop-lab, record a search, a reworded version of it, and the first search again. The reworded query gets its own fingerprint, and only the exact repeat is flagged:
python3 - <<'EOF'
from loop_detector import LoopDetector
d = LoopDetector()
print(d.record_and_check("search_docs", {"query": "annual report 2025"}))
print(d.record_and_check("search_docs", {"query": "2025 annual report"}))
print(d.record_and_check("search_docs", {"query": "annual report 2025"}))
EOF(False, '6ddb9009')
(False, '3c2f0604')
(True, '6ddb9009')04. Steps 2 to 5: Run the Guards Against Six Scenarios
Step 2: fixtures. The document index files reports by fiscal year, so a search for "annual report 2025" finds nothing, as in the story above. fetch_ledger sleeps for five seconds to stand in for a hung upstream service.
The scripted model has four styles. adaptive retries the failed search once, then changes its query after a duplicate-call notice. stubborn keeps repeating the same call. rewording changes the words of its failing query on every turn but never the idea. slow calls the hung tool. Token usage is estimated as one token per four characters of the whole history plus 400 tokens of system prompt and tool schemas, because a real API is sent the full history on every call.
"""Fixture tools: a document index keyed by fiscal year, and one slow tool."""
import time
DOCS = {"doc_9918": "Revenue grew 14% to $120M in FY2025."}
def search_docs(query):
if "fiscal 2025" in query:
return {"found": 1, "doc_id": "doc_9918"}
return {"found": 0, "message": "no matching documents"}
def read_doc(doc_id):
return {"content": DOCS[doc_id]}
def fetch_ledger(account):
time.sleep(5) # simulates a hung upstream call
return {"account": account, "balance": 1200}
TOOLS = {"search_docs": search_docs, "read_doc": read_doc,
"fetch_ledger": fetch_ledger}"""A scripted stand-in for a tool-calling model, so the lab runs offline."""
import json
import math
PREAMBLE_TOKENS = 400 # system prompt + tool schemas sent on every call
REWORDINGS = ["annual report 2025", "2025 annual report", "annual report for 2025",
"report annual 2025"]
def count_tokens(obj):
return math.ceil(len(json.dumps(obj)) / 4) # rough: ~4 characters per token
class ScriptedModel:
"""Chooses the next action from the history, like a (very simple) model."""
def __init__(self, style):
self.style = style # "adaptive", "stubborn", "rewording" or "slow"
def complete(self, messages):
reply = self._decide(messages)
usage = {"input_tokens": PREAMBLE_TOKENS + count_tokens(messages),
"output_tokens": count_tokens(reply)}
return reply, usage
def _decide(self, messages):
results = [json.loads(m["content"]) for m in messages if m["role"] == "tool"]
last = results[-1] if results else None
if self.style == "slow":
if last is None:
return _call("fetch_ledger", account="ACME-7")
return {"role": "assistant", "content": f"Could not finish: {last}"}
if self.style == "rewording": # new words each time, same failing idea
return _call("search_docs", query=REWORDINGS[len(results) % 4])
if last is None or last.get("found") == 0: # first try, then a blind retry
return _call("search_docs", query="annual report 2025")
if last.get("error") == "duplicate_call": # only "adaptive" changes course
if self.style == "adaptive":
return _call("search_docs", query="financial report fiscal 2025")
return _call("search_docs", query="annual report 2025")
if "doc_id" in last:
return _call("read_doc", doc_id=last["doc_id"])
return {"role": "assistant", "content": f"Answer: {last['content']}"}
def _call(name, **args):
return {"role": "assistant", "tool_call": {"name": name, "args": args}}Step 3: the guarded loop. Each guard is checked in a different place. The deadline is checked before each model call, the token budget after each reply, the loop detector before each tool call, and each tool call waits no longer than the per-tool timeout or the time left in the session, whichever is shorter. The first repeat of an action gets a notice instead of a second execution; a repeat after that notice ends the run.
After each tool call that really ran, streak counts that tool's failures in a row (an error, or a search that found nothing) and resets to zero on a success. Three in a row end the run, even when every call had different arguments. A duplicate-call notice does not count, because the tool did not run.
"""A tool loop with five guards: turns, tokens, wall clock, repeats, failure streaks."""
import json
import time
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import TimeoutError as ToolTimeout
from loop_detector import LoopDetector
class Stop(RuntimeError):
"""Raised when a guard ends the run; the message says which one."""
def failed(result): # an error, or a search that found nothing
return "error" in result or result.get("found") == 0
def run(model, tools, task, max_turns=10, token_budget=6000,
deadline_s=15.0, tool_timeout_s=2.0, max_failures=3):
detector, warned = LoopDetector(window_size=4, max_repeats=2), set()
streak = {} # tool name -> failed calls in a row, whatever the arguments
messages = [{"role": "user", "content": task}]
used, start = 0, time.monotonic()
pool = ThreadPoolExecutor(max_workers=4) # a timed-out call keeps its thread
try:
for turn in range(1, max_turns + 1):
if time.monotonic() - start > deadline_s:
raise Stop(f"wall-clock deadline of {deadline_s}s passed")
reply, usage = model.complete(messages)
used += usage["input_tokens"] + usage["output_tokens"]
if used > token_budget:
raise Stop(f"token budget: {used} > {token_budget}")
messages.append(reply)
call = reply.get("tool_call")
if call is None:
print(f"Turn {turn}: final answer -> {reply['content']}")
return {"turns": turn, "tokens": used}
name, args = call["name"], call["args"]
print(f"Turn {turn}: {name}({json.dumps(args)})")
is_loop, fp = detector.record_and_check(name, args)
if is_loop and fp in warned:
raise Stop(f"loop: {fp} repeated after a reflection notice")
if is_loop:
warned.add(fp)
result = {"error": "duplicate_call", "message": (
"You already ran this exact call and saw its result. "
"Change the arguments or use another tool.")}
print(f" [loop] repeat of {fp}: notice injected, tool not run")
else:
left = deadline_s - (time.monotonic() - start)
wait = round(max(0.0, min(tool_timeout_s, left)), 1)
future = pool.submit(tools[name], **args)
try: # never wait past the session deadline
result = future.result(timeout=wait)
except ToolTimeout:
result = {"error": "timeout", "after_s": wait}
streak[name] = streak.get(name, 0) + 1 if failed(result) else 0
print(f" result: {json.dumps(result)[:66]}")
if streak.get(name, 0) >= max_failures:
raise Stop(f"{name} failed {streak[name]} times in a row")
messages.append({"role": "tool", "content": json.dumps(result)})
raise Stop(f"turn cap of {max_turns} reached")
finally:
pool.shutdown(wait=False, cancel_futures=True)Step 4: run six scenarios. The script runs the loop once per scenario and reports which guard, if any, ended the run.
"""Runs six scenarios; each one is stopped (or not) by a different guard."""
import time
from fake_model import ScriptedModel
from guarded_loop import Stop, run
from tools import TOOLS
SCENARIOS = [
("adaptive model", "adaptive", {}),
("stubborn model", "stubborn", {}),
("rewording model", "rewording", {}),
("tight token budget", "adaptive", {"token_budget": 2500}),
("hung tool", "slow", {"tool_timeout_s": 2.0}),
("session deadline", "slow", {"deadline_s": 1.5}),
]
for title, style, limits in SCENARIOS:
print(f"== {title} {limits or ''}".rstrip())
t0 = time.monotonic()
try:
task = "Fetch the 2025 annual report"
stats = run(ScriptedModel(style), TOOLS, task, **limits)
print(f"OK: {stats['turns']} turns, {stats['tokens']} tokens", end="")
except Stop as stop:
print(f"STOPPED: {stop}", end="")
print(f" ({time.monotonic() - t0:.1f}s)\n")python3 run_lab.py== adaptive model
Turn 1: search_docs({"query": "annual report 2025"})
result: {"found": 0, "message": "no matching documents"}
Turn 2: search_docs({"query": "annual report 2025"})
[loop] repeat of 6ddb9009: notice injected, tool not run
result: {"error": "duplicate_call", "message": "You already ran this exact
Turn 3: search_docs({"query": "financial report fiscal 2025"})
result: {"found": 1, "doc_id": "doc_9918"}
Turn 4: read_doc({"doc_id": "doc_9918"})
result: {"content": "Revenue grew 14% to $120M in FY2025."}
Turn 5: final answer -> Answer: Revenue grew 14% to $120M in FY2025.
OK: 5 turns, 2733 tokens (0.0s)
== stubborn model
Turn 1: search_docs({"query": "annual report 2025"})
result: {"found": 0, "message": "no matching documents"}
Turn 2: search_docs({"query": "annual report 2025"})
[loop] repeat of 6ddb9009: notice injected, tool not run
result: {"error": "duplicate_call", "message": "You already ran this exact
Turn 3: search_docs({"query": "annual report 2025"})
STOPPED: loop: 6ddb9009 repeated after a reflection notice (0.0s)
== rewording model
Turn 1: search_docs({"query": "annual report 2025"})
result: {"found": 0, "message": "no matching documents"}
Turn 2: search_docs({"query": "2025 annual report"})
result: {"found": 0, "message": "no matching documents"}
Turn 3: search_docs({"query": "annual report for 2025"})
result: {"found": 0, "message": "no matching documents"}
STOPPED: search_docs failed 3 times in a row (0.0s)
== tight token budget {'token_budget': 2500}
Turn 1: search_docs({"query": "annual report 2025"})
result: {"found": 0, "message": "no matching documents"}
Turn 2: search_docs({"query": "annual report 2025"})
[loop] repeat of 6ddb9009: notice injected, tool not run
result: {"error": "duplicate_call", "message": "You already ran this exact
Turn 3: search_docs({"query": "financial report fiscal 2025"})
result: {"found": 1, "doc_id": "doc_9918"}
Turn 4: read_doc({"doc_id": "doc_9918"})
result: {"content": "Revenue grew 14% to $120M in FY2025."}
STOPPED: token budget: 2733 > 2500 (0.0s)
== hung tool {'tool_timeout_s': 2.0}
Turn 1: fetch_ledger({"account": "ACME-7"})
result: {"error": "timeout", "after_s": 2.0}
Turn 2: final answer -> Could not finish: {'error': 'timeout', 'after_s': 2.0}
OK: 2 turns, 920 tokens (2.0s)
== session deadline {'deadline_s': 1.5}
Turn 1: fetch_ledger({"account": "ACME-7"})
result: {"error": "timeout", "after_s": 1.5}
STOPPED: wall-clock deadline of 1.5s passed (1.5s)Step 5: read the result. The adaptive model recovers after one notice and finishes in five turns. The stubborn model ignores the notice and is stopped on its third call, long before the turn cap. The rewording model never repeats a fingerprint, so the detector stays silent; the failure streak stops it after three empty searches. With a 2,500-token budget, the same healthy run is stopped after four turns: the healthy run needs 2,733 tokens, so this budget was set below normal usage. That is why you size budgets from measured runs, not from a guess. The hung tool costs two seconds instead of five, and in the last scenario the tool wait is cut to the 1.5 seconds left in the session, so the deadline ends the run.
Now change one thing at a time and predict the result before you run it: raise max_failures to 5 for the rewording model (its fifth query repeats the first, so the detector takes over, but only after more wasted turns); raise token_budget to 2,800; set deadline_s=30 for the hung tool. None of the six scenarios reaches the turn cap, so trigger it yourself: set the limits of the adaptive scenario in run_lab.py to {"max_turns": 3}. It finds the document on turn 3 and is stopped with turn cap of 3 reached before it can read it.
05. Practice questions
06. Apply it
Take the guards from this lab into a loop of your own, or into the loop from The Loop in Sixty Lines:
- Give every run a turn cap, a cumulative token budget and a session deadline. Size the budget and the deadline from measured runs (for example the 95th percentile of observed usage times 1.5), and keep the run budget separate from the per-call
max_tokenscap. - Canonicalise arguments before hashing: sort keys, and trim whitespace in strings, so trivial differences do not hide a repeat.
- Keep a window of the last four to six fingerprints, so a two-tool A, B, A, B cycle is caught as well.
- Count failures in a row per tool, and decide per tool what a failure is (an error, an empty result, a validation failure).
- When a guard ends the run, save the full trace and send the task to a person, with the name of the guard that fired.
07. Review prompt
Without looking back, name the five guards from the lab and one failure that only that guard catches. Then explain why a fingerprint misses a reworded query, and why a duplicate-call notice comes before the hard stop.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.