Introduction
In our previous lesson, we fortified our agent by implementing error propagation, enabling it to recover from failed tool actions by treating errors as observations. This capability is a cornerstone of resilient systems. However, an agent that can endlessly attempt to recover from an unresolvable error introduces a new, critical risk: the infinite loop. Such loops can lead to runaway API costs, system lockups, and a complete breakdown of reliability.
This lesson addresses that risk directly. We will implement configurable stopping conditions to ensure our agent's execution is bounded, predictable, and terminates correctly. You will learn to design and implement a multi-layered termination strategy using iteration counts, time limits, and explicit goal completion signals. For a software engineer experienced in building robust distributed systems, these concepts—fail-safes, timeouts, and explicit termination handshakes—will be familiar, but we will now apply them to the non-deterministic world of LLM-driven agents.
The Tyranny of the Loop: Why Termination Control is Non-Negotiable
An agent without a guaranteed stop condition is a liability. The probabilistic nature of LLMs means they don't always follow instructions perfectly. They can get stuck in cycles for several reasons:
- Repetitive Re-planning: An agent might encounter a persistent error and repeatedly try the same failing strategy, convinced it will eventually work.
- Goal Ambiguity: The agent might misinterpret the completion criteria, continuing to "refine" an already finished task.
- Tool-Use Fixation: It might get fixated on using a specific tool over and over, even if the tool's output isn't helping it make progress.
To build production-grade systems, we cannot leave termination solely to the agent's discretion. We need deterministic guardrails.
Why AI Agents Get Stuck in Loops, and How to Prevent It
This article provides an excellent framing of the problem and introduces a core principle for solving it.
Read the introduction and the section on Loop Guardrails. Pay close attention to the principle of External Enforcement. This is the idea that the system running the agent, not the agent itself, must be the ultimate guarantor of termination.
The concept of "External Enforcement" is our foundational principle. While we want the agent to be smart enough to stop itself, we must have an external mechanism to force it to stop if it fails to do so.
A Layered Approach to Termination
A robust termination strategy combines internal agent logic with external system-level controls. Let's visualize this using a typical agentic workflow.

We will implement both of these mechanisms.
1. Internal Completion Signals: The Agent Stops Itself
The most elegant way for a loop to end is for the agent to recognize that its task is complete and signal this explicitly. This preserves the agent's autonomy while providing a clear exit point. There are two common patterns for this.
Pattern A: The finish Tool
A highly reliable method is to provide a special tool, such as finish or final_answer, which the agent calls only when it has completed the entire task. The function of this tool isn't to do anything, but simply to act as a structured signal that the loop should terminate.
The system prompt would include instructions like:
Once you have the final answer and have completed all necessary steps, call the 'finish' tool with the complete answer.
Our agent loop can then check for the invocation of this specific tool.
Tiny Agents in Python: a MCP-powered agent in ~70 lines of code
This article demonstrates a minimal agent implementation that uses this exact pattern.
Focus on the code snippet for the Agent.run() method. Notice the first exit condition: if last.get("role") == "tool" and last.get("name") in {t.function.name for t in EXIT_LOOP_TOOLS}: return. This code checks if the last action was a tool call and if that tool's name is in a predefined set of "exit tools."
This pattern is robust because it relies on the structured output of tool calling, which is less ambiguous than parsing natural language.
Pattern B: Keyword-Based Termination
A simpler, though slightly more brittle, approach is to instruct the agent to use a specific keyword, like "Final Answer:", in its last response. The loop then parses the LLM's text output for this keyword.
We saw this approach in the ReAct agent we analyzed previously.
Python: Create a ReAct Agent from Scratch
Let's revisit the agent loop implementation from the "Create a ReAct Agent from Scratch" video.
Watch the section where the automated loop is built, starting around coding the loop. Pay attention to the logic at this point, where the code checks if answer in result: break. This is a classic example of keyword-based termination.
While effective in many cases, this can lead to false positives if the agent uses the keyword in a Thought before it's actually finished. The finish tool pattern is generally preferable for production systems due to its explicitness.
2. External Guardrails: The System Enforces a Stop
These are our fail-safes. They are deterministic, non-negotiable limits that prevent runaway execution regardless of what the agent is thinking or doing.
Why AI Agents Get Stuck in Loops, and How to Prevent It
The same article on infinite loops also provides excellent, practical implementation guidance for these guardrails.
Read the sections titled Key Components and Implementation. We will focus on implementing three of these: global turn limits, time limits, and detecting repetitive actions.
Let's integrate these into our agent loop.
Guardrail 1: Maximum Iterations
This is the simplest and most crucial guardrail. We define a maximum number of Thought -> Action -> Observation cycles.
MAX_ITERATIONS = 15
# ...
iteration_count = 0
while iteration_count < MAX_ITERATIONS:
iteration_count += 1
# ... agent logic ...
else: # This 'else' on a 'while' loop executes if the loop terminates naturally (not via 'break')
print("Termination Warning: Maximum iterations reached.")
# Potentially raise an error or return a timeout status
Setting a reasonable limit (e.g., 10-25 iterations) based on your expected task complexity is a powerful safety net.
Guardrail 2: Time Limits
An iteration limit won't protect you if a single tool call hangs indefinitely. A time limit is essential. Since we are building with async execution in mind, the ideal implementation uses asyncio.wait_for to wrap the execution of each turn or the entire loop.
import asyncio
import time
MAX_EXECUTION_TIME_SECONDS = 300 # 5 minutes
async def run_agent_with_timeout(agent_task, query):
try:
await asyncio.wait_for(
agent_loop(agent_task, query),
timeout=MAX_EXECUTION_TIME_SECONDS
)
except asyncio.TimeoutError:
print(f"Termination Warning: Global timeout of {MAX_EXECUTION_TIME_SECONDS}s exceeded.")
# The agent_loop itself can also check time per iteration
async def agent_loop(agent_task, query):
start_time = time.time()
# ... inside the while loop ...
if time.time() - start_time > MAX_EXECUTION_TIME_SECONDS:
print("Loop terminated by time limit guardrail.")
break
Guardrail 3 (Advanced): Repetitive Action Detection
A more intelligent guardrail can detect when an agent is stuck in a loop, calling the same tool with the same arguments. This involves maintaining a short history of recent actions.
The AgentMonitor class proposed in the "Loop Guardrails" article provides a clear, first-principles implementation of this idea using a deque (a fixed-size queue) to track the last N actions. If all actions in the window are identical, it raises an error, breaking the loop. This is an excellent pattern to consider for enhancing reliability.
The "Stop Hook" Pattern: Verifying Completion
Sometimes, the agent thinking it's done isn't sufficient. For tasks like writing and testing code, we need external verification. The stop hook pattern provides a powerful way to achieve this.
The idea is to treat the agent's internal finish signal not as a final stop, but as a trigger for a verification step.
How to Run Claude Code For Hours Autonomously
This video on making Claude Code run autonomously provides a great explanation of this advanced pattern. While it uses a specific tool, the underlying principle is universal.
Watch the introduction to hooks to understand the concept. Focus on the explanation of the stop hook. The key insight is that when Claude finishes, a hook fires to run tests, and the results are fed back into the agent. Finally, see how this is conceptualized as the "Ralph loop," where the process repeats until a "completion promise" is met or max iterations are hit.
Here is how you would architect a "stop hook" from first principles:
- Agent Prompting: Instruct the agent to call the
finishtool when it believes the task (e.g., "write a function and its unit tests") is complete. - Loop Logic: When the agent calls
finish, instead of breaking the loop immediately, the orchestrator:- Catches the
finishsignal. - Runs a deterministic script (e.g., executes
pytest). - Captures the
stdoutandstderrfrom the script.
- Catches the
- Feedback or Termination:
- If the script succeeds: The "completion promise" is met. The loop can now safely terminate.
- If the script fails: The script's output (the test failure) is formatted as a new
Observationand fed back to the agent in the next turn of the loop. The prompt for this observation could be:Observation: Your proposed solution failed the verification step with the following error: [test output]. Please analyze the error and correct your code.
This turns the agent loop into a powerful, self-correcting cycle that more closely mimics a test-driven development workflow.
Conclusion
Today, we've secured our agent's core engine by implementing critical termination controls. An agent that knows when to stop is one that can be trusted in a production environment.
Your key takeaways are:
- Termination is a core reliability feature: Unbounded loops are a primary failure mode for agentic systems, leading to high costs and unpredictability.
- Employ a layered strategy: Combine internal completion signals (like a
finishtool) with external guardrails (max iterations, time limits). - External enforcement is the ultimate safety net: Your system, not the agent, must have the final say on termination to guarantee it.
- The
finishtool pattern is robust: Using a dedicated tool for termination is more explicit and reliable than parsing keywords from natural language. - Advanced patterns like stop hooks enable self-correction: By verifying an agent's output before terminating, you can create powerful loops that iteratively improve solutions until they meet deterministic quality criteria.
Our agent can now think, act, recover from mistakes, and stop. The core execution loop is nearly complete. In our next and final lesson of this module, we will address observability by implementing real-time streaming of the agent's thoughts and actions, giving us a transparent window into its execution as it happens.