The earlier modules assumed a well-behaved agent in a friendly environment. This module is what changes when the agent can take real, destructive actions — like editing a database — and needs to be trusted to do so safely.
Five guardrails, each solving a specific failure mode:
| Guardrail | Problem it prevents |
|---|---|
Human approval for add_customer / delete_customer / update_customer_country |
Agent silently makes high-stakes writes without a human in the loop |
Loop detection (detect_loop) |
Agent retries the exact same failing call forever |
Write budget (MAX_WRITES_PER_RUN) |
A single run makes unbounded destructive changes even with approval |
Retry with backoff (call_with_retry) |
Transient errors (locks, timeouts) get treated as permanent failures |
SQL allow-list (query_db rejects non-SELECT) |
The “read” tool is used to sneak in a write |
Every tool call passes through one dispatcher (run_tool) before it runs — that’s the choke point where every guardrail is enforced, in order: loop check → budget check → approval check → execute → count. No individual tool function is trusted to protect itself; the dispatcher is.
def run_tool(tool_name, tool_input, recent_calls, auto_approved, write_count):
if detect_loop(recent_calls, tool_name, tool_input):
return "Loop detected..."
if tool_name in WRITE_TOOLS and write_count[0] >= MAX_WRITES_PER_RUN:
return "Write budget exceeded..."
if tool_name in TOOLS_REQUIRING_APPROVAL and tool_name not in auto_approved:
decision = request_approval(tool_name, tool_input)
...
The system prompt also asks Claude to plan before acting on multi-step tasks, and to explicitly confirm before destructive operations — a second, model-level layer on top of the code-level guardrails above. Neither layer alone is sufficient: prompting alone can be ignored or bypassed by a confused model; code-level checks alone can’t tell a legitimate bulk update from a runaway loop without some model judgment in the mix.
pip install -r requirements.txt
export ANTHROPIC_API_KEY=your_key_here
python setup_db.py # creates company.db with sample customers/products/orders
python db_agent.py
Try asking it to delete a customer, then try asking it to do the same destructive thing three times in a row to see loop detection kick in.
You’ve gone from a single stateless API call (Module 1) to a tool-using loop (Module 2), to memory (Module 3), specialization (Module 4), and now safety (Module 5) — the same pieces every real agent in production is built from.
Module 6 — Multi-Agent Orchestration — instead of one agent doing everything, an orchestrator that delegates to specialists.