Module 10 Lesson 3: Safety Limits (Max Iterations & Timeouts)
Guarding the Budget. How to prevent your agents from getting stuck in infinite loops and burning through your API credits.
Preventing the Infinite Loop: Agent Safety
Agents are autonomous, which means they can be Stupid autonomously. If an agent tries to use a tool, fails, and then tries the same thing again, it can enter an Infinite Loop. This will burn your entire OpenAI budget in minutes.
1. max_iterations
This is the most important safety setting. It tells the agent: "You only have 5 attempts to solve this. If you don't find the answer, stop and report the failure."
from langchain.agents import create_openai_functions_agent, AgentExecutor
# Inside your AgentExecutor configuration:
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
max_iterations=5, # KILL SWITCH
verbose=True
)
2. Global Timeouts
Sometimes an iteration doesn't "Loop," but the tool takes 5 minutes to respond (e.g., a slow database query). You should set a Maximum Execution Time.
agent_executor = AgentExecutor(
...
max_execution_time=60 # Stop after 60 seconds no matter what
)
3. Visualizing a Loop Failure
graph TD
Start[User: 'Solve Paradox'] --> A[Agent Try 1]
A -->|Fails| B[Agent Try 2]
B -->|Fails| C[Agent Try 3]
C -->|Fails| D[Agent Try 4]
D -->|Fails| E[Agent Try 5]
E -->|STOP| User[Output: 'I could not solve this in 5 steps']
4. The "Last Attempt" Prompt
What happens when the agent hits the max_iterations limit? By default, it just stops. In LangChain, you can configure it to Summarize what it tried so far.
- "I tried searching Wikipedia and Google, but both results were empty. I apologize, I cannot find the answer."
5. Engineering Tip: Human-in-the-Loop
For high-stakes tasks (like deleting a file or sending a payment), don't let the agent be 100% autonomous. Add a "Approval" step where the agent must wait for a human to click "Yes" before the tool executes. (This is covered in depth in the Agentic Course).
Key Takeaways
max_iterationsprevents expensive infinite loops.max_execution_timeprevents hanging processes.- Verbose mode is essential for seeing why a loop is happening.
- Agents should always have a Kill Switch.