M4Medium★ Production Agent Essential · Safety GuardPart M · LLM Eval & RAG/Agent Ops
Agent Tool Loop Breaker & Idempotency Guard
Enforce bounded execution steps, canonical argument-hash cycle breaking, and idempotency keys to stop runaway retries and duplicate writes.
⏱️ Time:
O(|ArgsJSON|) 哈希校验💾 Space:
O(MaxSteps)🎯 Interactive Self-Practice Loop (Attempt Before Peeking)
Practice in 4 steps: recall mechanism, complete core lines, check edge cases, and log mastery locally.
Step 1 · Mechanism Recall & Stability Self-Check
Step 2 · Complete Key Implementation Lines
import hashlib
import json
class AgentToolGuard:
"""Bounded cycle-detection, budget cap, and idempotency guard for tool-calling agents."""
def __init__(self, max_steps: int = 8, max_identical_calls: int = 2):
self.max_steps =
self.max_identical_calls = max_identical_calls
self.steps = 0
self.call_counts = {}
self.idempotency_cache = {}
def invoke(self, tool_name: str, args: dict, idempotency_key: str, fn) -> dict:
if self.steps >= self.max_steps:
return {"status": "HALTED", "reason": "max_steps_exceeded"}
self.steps += 1
sig = f"{tool_name}:{hashlib.sha256(json.dumps(args, sort_keys=True).encode()).hexdigest()[:12]}"
self.call_counts[sig] = self.call_counts.get(sig, 0) + 1
if self.call_counts[sig] > self.max_identical_calls:
return {"status": "HALTED", "reason": "cycle_detected"}
if idempotency_key and idempotency_key in self.idempotency_cache:
return {"status": "CACHED_IDEMPOTENT", "result": self.idempotency_cache[idempotency_key]}
result =
if idempotency_key:
self.idempotency_cache[idempotency_key] = result
return {"status": "EXECUTED", "result": result}
Step 3 · Verify Boundary Cases & Assertions
Step 4 · Follow-Up Drill & Review Outcome
Q1: How should an agent pipeline degrade gracefully once a cycle-breaker or step limit triggers?
💡
Core Mental Anchor / Mnemonic
Cap total steps, hash sorted args to catch cycles, and cache side-effect calls by idempotency key.
📐 Mathematical Derivation & Core Formula
### Three Deterministic Guardrails for Agent Loops
Unconstrained ReAct agents frequently repeat identical failing calls, burning tokens or duplicating side effects. Guarding
Unconstrained ReAct agents frequently repeat identical failing calls, burning tokens or duplicating side effects. Guarding
steps < max_steps, hashing canonical json.dumps(args, sort_keys=True) signatures to detect loops, and caching results by idempotency_key protect both cost SLAs and external state.🔄 Tensor Dimensions & Shape Flow
call -> max_steps check -> sorted-key args hash check -> idempotency cache lookup -> invoke & record
🛡️ Numerical Stability & Pitfalls Checklist
- Always serialize arguments with
sort_keys=Truebefore hashing so key permutation does not evade loop detection. - Pair idempotency keys with human-approval checkpoints for destructive or financial write operations.
💻 Reference Code Implementation
import hashlib
import json
class AgentToolGuard:
"""Bounded cycle-detection, budget cap, and idempotency guard for tool-calling agents."""
def __init__(self, max_steps: int = 8, max_identical_calls: int = 2):
self.max_steps = max_steps
self.max_identical_calls = max_identical_calls
self.steps = 0
self.call_counts = {}
self.idempotency_cache = {}
def invoke(self, tool_name: str, args: dict, idempotency_key: str, fn) -> dict:
if self.steps >= self.max_steps:
return {"status": "HALTED", "reason": "max_steps_exceeded"}
self.steps += 1
sig = f"{tool_name}:{hashlib.sha256(json.dumps(args, sort_keys=True).encode()).hexdigest()[:12]}"
self.call_counts[sig] = self.call_counts.get(sig, 0) + 1
if self.call_counts[sig] > self.max_identical_calls:
return {"status": "HALTED", "reason": "cycle_detected"}
if idempotency_key and idempotency_key in self.idempotency_cache:
return {"status": "CACHED_IDEMPOTENT", "result": self.idempotency_cache[idempotency_key]}
result = fn(**args)
if idempotency_key:
self.idempotency_cache[idempotency_key] = result
return {"status": "EXECUTED", "result": result}
🧪 Runnable Assertions & Validation
Copy and run directly in Python / Jupyter:
exec_count = 0
def charge_user(amount):
global exec_count
exec_count += 1
return f"charged_{amount}"
guard = AgentToolGuard(max_steps=6, max_identical_calls=2)
r1 = guard.invoke("charge", {"amount": 50}, "tx_100", charge_user)
r2 = guard.invoke("charge", {"amount": 50}, "tx_100", charge_user) # network retry replay!
r3 = guard.invoke("charge", {"amount": 50}, "tx_100", charge_user) # 3rd identical loop triggers cycle break
assert exec_count == 1, "Idempotency key must execute mutating action only once"
assert r1["status"] == "EXECUTED" and r2["status"] == "CACHED_IDEMPOTENT"
assert r3["status"] == "HALTED" and r3["reason"] == "cycle_detected"
print("✓ Agent loop-breaker & idempotency guard assertion passed")🎯 Core Follow-up Inquiries & Reference Answers
Q1:How should an agent pipeline degrade gracefully once a cycle-breaker or step limit triggers?
Transition deterministically to a synthesis fallback step that summarizes gathered evidence, explicitly states the blocked action, offers human handoff/reformulation, and emits the full trace for offline evaluation.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.