DEV Community

Anindya Mukherjee
Anindya Mukherjee

Posted on

I Watched My AI Agent Loop for 40 Minutes. Here's the Guardrail I Added.

I left my laptop open, made coffee, came back, and the terminal was still scrolling.

Same tool call. Same "almost done" message. Same apology. Over and over. Forty minutes of a very polite infinite loop.

If you've ever handed an LLM a task and walked away thinking it'll figure it out, this is the part nobody puts in the demo reel.

The setup that felt smart

I wanted a tiny research agent. Nothing fancy:

  1. Search for a topic
  2. Open the top results
  3. Summarize what matters
  4. Write a short brief to a markdown file

Classic "agentic" pitch: give it a goal, give it tools, let it cook.

I wired up a simple loop — think, act, observe, repeat — with a web search tool and a file writer. The first run looked magical. It found sources. It took notes. It even said "Draft complete."

Then I gave it a slightly messier topic.

That's when the coffee happened.

What a runaway agent actually looks like

The logs were almost funny if you squint:

Thought: I should verify one more source.
Action: search("...")
Observation: (same three links as last time)
Thought: Great, I'll open the first one again to be sure.
Enter fullscreen mode Exit fullscreen mode

It wasn't "thinking harder." It was stuck in a hallway with three doors, opening the same door, nodding solemnly, and opening it again.

Like a Roomba that found a particularly meaningful sock.

The model kept producing confident next steps. The tools kept returning near-identical observations. Nothing in my code said stop, you're not making progress. So it didn't.

Forty minutes later I had:

  • 200+ near-duplicate tool calls
  • a half-written brief
  • a slightly warmer laptop
  • zero new insight

Autonomy without brakes isn't autonomy. It's a very expensive fidget spinner.

The real bug wasn't the model

I wanted to blame the LLM. Easy story. Bad diagnosis.

The model did what models do: it proposed the next plausible action given the context. The failure was mine — I built a loop with a goal and no concept of done enough, stuck, or this is costing real money.

Chatbots fail politely in one reply. Agents fail operationally, over time, with side effects.

That distinction is the whole game.

The guardrail I added (copy-paste this)

I didn't rebuild the agent. I added three boring checks that would have saved the morning:

  1. Hard step budget — absolute max iterations
  2. No-progress detector — same tool + similar args too many times in a row
  3. Circuit breaker — stop, summarize what you know, ask a human

Here's a minimal version you can drop into a toy agent loop:

import hashlib
import json
from collections import deque

class AgentGuardrails:
    def __init__(self, max_steps=12, repeat_limit=3):
        self.max_steps = max_steps
        self.repeat_limit = repeat_limit
        self.steps = 0
        self.recent = deque(maxlen=repeat_limit)

    def _sig(self, tool: str, args: dict) -> str:
        payload = json.dumps({"tool": tool, "args": args}, sort_keys=True)
        return hashlib.sha256(payload.encode()).hexdigest()[:16]

    def check(self, tool: str, args: dict) -> str | None:
        """Return a stop reason, or None if the agent may continue."""
        self.steps += 1
        if self.steps > self.max_steps:
            return f"max_steps_exceeded:{self.max_steps}"

        sig = self._sig(tool, args)
        self.recent.append(sig)
        if len(self.recent) == self.repeat_limit and len(set(self.recent)) == 1:
            return f"no_progress_repeated_tool:{tool}"

        return None


# --- usage inside your loop ---
guard = AgentGuardrails(max_steps=12, repeat_limit=3)

while True:
    thought, tool, args = plan_next_action(state)  # your planner
    stop = guard.check(tool, args)
    if stop:
        state["stop_reason"] = stop
        state["draft"] = summarize_partial(state)
        break
    state["obs"] = run_tool(tool, args)
Enter fullscreen mode Exit fullscreen mode

Is this elegant multi-agent research? No.

Is it the difference between "neat weekend project" and "why is my API bill a horror movie"? Yes.

Why these three checks punch above their weight

Step budgets turn infinite loops into finite embarrassments. Twelve steps is arbitrary — pick a number that matches the task. Research briefs don't need 200 tool calls. If they do, your task is underspecified.

No-progress detection catches the Roomba-sock pattern. Agents love re-checking. Humans do too, but we get bored. Code should get bored for you.

Circuit breakers restore the human to the loop on purpose. The best agent systems I've used don't pretend to be infallible. They fail loudly, early, with a partial artifact you can actually use.

Think of it like a kitchen timer on a toaster oven. The toaster doesn't become a worse toaster because it dings. It becomes a toaster that won't burn the apartment down while you answer Slack.

What I changed in the prompt (small, high leverage)

Guardrails in code are half the fix. The other half is telling the model how to behave when it's unsure:

If you notice you are about to repeat a tool call with the same arguments,
STOP. Write the best brief you can from current notes. List 1–3 unknowns
instead of fetching "one more source."
Enter fullscreen mode Exit fullscreen mode

Models respond surprisingly well to explicit stop conditions. Without them, "be thorough" quietly becomes "never finish."

The weekend checklist before you trust an agent alone

Before you let anything run unattended:

  • [ ] Max steps (hard cap)
  • [ ] Repeat/no-progress detector
  • [ ] Timeout on each tool call
  • [ ] Cost ceiling if you're on paid APIs
  • [ ] Partial-result writer on stop
  • [ ] A log you can read without crying

You don't need a platform. You need seatbelts.

The punchline

Agentic AI is less "magic intern who never sleeps" and more "power tool with a very confident trigger finger."

The demo is the happy path. Production is everything that happens when the happy path gets lonely and starts humming to itself for forty minutes.

Add the boring guardrail. Ship the partial brief. Keep your coffee hot and your laptop cool.


Your turn: What's the dumbest loop you've caught an agent (or yourself) stuck in? Drop the war story — I want the ridiculous ones.

Top comments (0)