Course contentsShow
← AI Engineering
Lesson 635 of 1,88616. AI Agents - ImplementationFree lesson

Implementing Stop Conditions

Define and check termination criteria to prevent infinite loops and signal completion.

Implementing Stop Conditions

You'll learn how to programmatically halt your agent loop when the job is done—or when it needs to be.

Why Stop Conditions Matter

An AI agent loop runs continuously: observe → reason → act → observe again. Without clear exit points, your agent becomes a runaway train—burning tokens, making unnecessary API calls, and potentially getting stuck in circular reasoning. Stop conditions are the off-switch that signals "mission accomplished" or "something went wrong, bail out."

Core Implementation Pattern

You've already designed the agent loop and handled execution results. Now you check after each iteration whether any termination criteria are met:

def should_stop(state, iteration_count, max_iterations):
    # Max iterations reached?
    if iteration_count >= max_iterations:
        return True, "iteration_limit"
    
    # Goal achieved?
    if state.get("goal_complete"):
        return True, "success"
    
    # Error condition?
    if state.get("error"):
        return True, "error"
    
    # Timeout?
    if state.get("elapsed_time") > state.get("timeout"):
        return True, "timeout"
    
    return False, None

Place this check at the end of each loop iteration, before starting the next cycle. Your agent loop becomes:

while True:
    observation = observe(state)
    action = decide(observation)
    result = execute(action)
    state = update_state(result)
    
    stop, reason = should_stop(state, iteration, max_iterations)
    if stop:
        return state, reason

Think of stop conditions like landing gear—you need them deployed at the right moment, or you'll overshoot your destination.

Key Takeaway: Stop conditions prevent infinite loops and resource waste by explicitly checking termination criteria after every agent iteration—combining iteration limits, goal signals, errors, and timeouts into a single decision point.