~/TechPurAI
~/tutorials/llm-and-advanced-ai/giving-an-agent-real-tools-and-guardrails
advanced·part 18 of 22·3 min read

Giving an Agent Real Tools and Guardrails

Updated Aug 16, 2026AI

Part 17 built a real, working agent loop with an honest, flagged gap: no safety limits at all. This part closes that gap directly, making GreenDesk's real cancel/refund agent genuinely safe to actually deploy.

Real, practical iteration limits

python
def run_agent_loop(user_request: str, tools: list, tool_functions: dict, max_iterations: int = 5) -> str:
    messages = [{"role": "user", "content": user_request}]

    for iteration in range(max_iterations):
        response = client.messages.create(
            model="claude-sonnet-5", max_tokens=1024, tools=tools, messages=messages,
        )
        messages.append({"role": "assistant", "content": response.content})

        if response.stop_reason != "tool_use":
            return response.content[0].text

        tool_call = next(block for block in response.content if block.type == "tool_use")
        real_result = tool_functions[tool_call.name](**tool_call.input)
        messages.append({
            "role": "user",
            "content": [{"type": "tool_result", "tool_use_id": tool_call.id, "content": str(real_result)}],
        })

    return "This request needs human review — it required more steps than expected."

A real, explicit max_iterations cap directly protects against a genuine, real failure mode — a model stuck in a real, unproductive loop (repeatedly calling the same tool, or genuinely unable to resolve a request) now fails safely with a clear message, rather than running indefinitely and generating unbounded, real API cost.

Real, explicit permission scoping per tool

python
DESTRUCTIVE_TOOLS = {"cancel_subscription", "issue_refund", "delete_customer"}

def execute_tool_safely(tool_name: str, tool_input: dict, employee_role: str) -> str:
    if tool_name in DESTRUCTIVE_TOOLS and employee_role != "senior_support":
        return "Permission denied: this action requires senior support approval."
    return tool_functions[tool_name](**tool_input)

This directly extends part 15's role-based access principle to agent actions specifically — a real, structural check on WHO can trigger a genuinely consequential real action, independent of what the model itself decides is appropriate. The model requesting a tool call is never, on its own, sufficient authorization for a real, destructive action.

Why it matters

This is the same real principle from part 15's access-control coverage, applied to actions instead of retrieval: a permission check belongs in your application's actual EXECUTION code, not as an instruction hoping the model declines an inappropriate real request on its own. The model deciding to call cancel_subscription should never be the only real gate before it actually happens.

A real, human confirmation step for genuinely consequential actions

python
def execute_tool_with_confirmation(tool_name: str, tool_input: dict) -> str:
    if tool_name in DESTRUCTIVE_TOOLS:
        pending_action = save_for_human_approval(tool_name, tool_input)
        return f"Action queued for human approval (ID: {pending_action.id})"
    return tool_functions[tool_name](**tool_input)

For GreenDesk's real cancel/refund example specifically, this is the honest, correct production pattern — the agent's real reasoning (deciding cancellation and refund are the right actions) genuinely stays automated, but actual, real execution of a destructive action pauses for a real, human approval click, directly matching the same calibrated caution the AI Projects series applied to its own email generator.

A real, practical audit log

python
def log_agent_action(tool_name: str, tool_input: dict, result: str, employee_id: str) -> None:
    AgentActionLog.objects.create(
        tool_name=tool_name,
        tool_input=json.dumps(tool_input),
        result=result,
        triggered_by=employee_id,
        timestamp=timezone.now(),
    )

A real, complete audit trail of every actual agent action — genuinely important once an agent can take real, consequential actions rather than only generating text — is what makes it possible to review, after the fact, exactly what happened and why, the same real accountability a human-operated system would need.

A real, complete, safe agent for GreenDesk's use case

text
1. max_iterations caps runaway real loops (this part)
2. Permission scoping blocks unauthorized real roles from
   triggering destructive tools (this part)
3. Human confirmation gates genuinely consequential real actions
   before they execute (this part)
4. A real audit log records every actual action taken

This four-layer real safety structure is what turns part 17's honest, flagged-as-unsafe loop into something genuinely appropriate to deploy against real, consequential GreenDesk operations — not a theoretical add-on, but the actual, necessary difference between a demo and production.

Next: evaluating RAG and agent quality — how to actually know, with real evidence, whether any of this series' systems are working correctly.

VK

Vijay Kumar

Founder of TechPurAI — writing hands-on tutorials and honest tool breakdowns.

LinkedIn ↗
← previous17. How AI Agents Worknext →19. Evaluating RAG and Agent Quality