Set explicit iteration caps, deterministic state hashes, and circuit‑breaker callbacks to stop agents before they spin forever or deadlock.
Step‑by‑step safeguards
1. Define a hard iteration limit – e.g., max_iterations=20 in AgentExecutor (LangChain) or max_steps=15 in CrewAI’s Crew.
2. Add a loop‑detection hook – compute a SHA‑256 hash of the serialized agent state after each turn; abort if the hash repeats three times.
3. Enforce a token budget – set run_timeout=300 seconds or max_total_tokens=8_000 to cut off runaway tool calls.
4. Make every tool call idempotent – wrap external APIs with a cache keyed by input signature; return cached result on repeat.
5. Insert a circuit‑breaker – raise LoopAbortException when consecutive_errors > 5 or when a tool returns a predefined “lockout” flag.
6. Watchdog thread – in production, spawn a threading.Timer that kills the agent process if elapsed > watchdog_limit.
Comparison of built‑in guards
| Mechanism | LangChain | CrewAI | AutoGen |
|---|---|---|---|
| Max turns | max_iterations | max_steps | max_rounds |
| Loop guard | check_repeat() hook | state_hash dedup | history_dedup |
| Timeout | run_timeout | step_timeout | agent_timeout |
| Token cap | max_total_tokens | token_budget | token_limit |
Example: LangChain configuration
from langchain.agents import AgentExecutor, initialize_agent
from langchain.tools import Tool
executor = AgentExecutor(
agent=initialize_agent(...),
tools=[Tool(... )],
max_iterations=20,
early_stopping_method="force",
run_timeout=300,
callbacks=[LoopGuardCallback()],
)Example: AutoGen circuit‑breaker
class LoopGuardCallback(autogen.Callback):
def on_step_end(self, state):
h = hashlib.sha256(state.serialize()).hexdigest()
if self.history.count(h) >= 3:
raise autogen.LoopAbortException("Repeated state detected")Apply these controls uniformly across all agents to guarantee termination and avoid state lockouts.