Course contentsShow
← Machine Learning and Deep Learning
Lesson 2066 of 3,53844. AI Agents: FoundationsFree lesson

Termination Conditions

Implement stopping criteria: task completion signals, maximum steps, or explicit finish actions.

Termination Conditions

You'll learn: How to safely stop an AI agent's execution using completion signals, step limits, and explicit finish actions.

Why Agents Need to Stop

Unlike a single-shot prompt, an AI agent operates in a loop—perceiving, reasoning, and acting repeatedly. Without proper termination conditions, your agent could run indefinitely, waste resources, or get stuck in unproductive cycles. Think of it like setting a timer on your oven: you need to know when the task is "done" or when to give up trying.

Three Core Termination Strategies

1. Task Completion Signals

The agent recognizes it has achieved its goal. For example, after searching for information and generating an answer, the LLM might output a special FINISH action with the final result. You parse this as the success condition.

if action.type == "FINISH":
    return action.result  # Exit the agent loop

2. Maximum Steps

Set a hard limit on iterations to prevent runaway execution. If the agent takes 20 actions without completing, terminate with a timeout message.

MAX_STEPS = 20
for step in range(MAX_STEPS):
    # ... agent loop ...
    if step == MAX_STEPS - 1:
        return "Maximum steps reached without completion"

3. Explicit Finish Actions

The agent's tool registry includes a dedicated "finish" tool that signals intentional completion. This differs from task completion because the agent actively chooses to stop.

tools = ["search", "calculator", "finish"]
# Agent calls finish(answer="Paris is the capital") → terminate

Combining Conditions

Production agents typically use all three: they honor finish signals, respect step limits as safety nets, and allow explicit completion actions. This creates both flexibility and guardrails.

Key Takeaway: Termination conditions prevent infinite loops and resource waste by defining when an agent should stop—through task completion signals, maximum step limits, or explicit finish actions.