The Nightmare Scenario
Agent gọi tool, nhận error, retry, nhận error, retry... cho đến khi bill explodes.
Root Causes of Infinite Loops
1. Unrecoverable Errors
Agent không nhận ra error là permanent (rate limit, not found, etc.)
2. Conflicting Goals
Agent A muốn X, Agent B muốn NOT X → Loop forever
3. Ambiguous Success Criteria
Agent không biết khi nào done → Luôn improve thêm nữa
Defense Mechanisms
1. Hard Iteration Limits
Set max_iterations và force_summarize khi đạt limit.
2. Loop Detection
Track action history, detect repetition pattern (same action 3+ times).
3. Cost Circuit Breaker
Track total cost, raise exception khi exceed budget.
4. Timeout Wrapper
asyncio.wait_for với timeout, graceful degradation khi timeout.
Graceful Degradation
Khi phải force-stop, vẫn trả về useful output:
- Summarize progress đạt được
- Identify remaining blockers
- Suggest next steps cho human
Monitoring Dashboard
Track metrics:
- iterations_per_task
- loop_detections
- forced_stops
- cost_per_task
- timeout_rate
Alert khi rates bất thường.
🛡️ Production Rule: Mỗi agent PHẢI có cả 3 guards: iteration limit, cost limit, và timeout. Không bao giờ deploy agent unbounded.
