Reducing Redundant Calls: Guardrails for Recursive Agent Loops
Stop agents from re-calling the same tool and spinning on failed plans: call-signature detection, state-hash cycle checks, hard recursion caps, tool memoization, progress predicates, and a runnable LangGraph example.
Published on • November 16, 2026
AI Assistant

An agent calls fetch_policy with identical arguments seven times. Another rewrites the same three-step plan forever because step two keeps failing. A third spawns subtasks from subtasks, and nobody notices until the token meter spins past $200 overnight. Redundant calls are the quiet failure mode of agentic systems: each call looks reasonable in isolation, and the loop only surfaces in the aggregate bill.
In this post, you will learn how to stop them: detecting loops with call-signature repetition and state-hash cycle checks, enforcing hard iteration and recursion caps, memoizing tool results within a run, defining progress predicates that force the agent to change or halt, injecting cycle-breaking interrupts back to the LLM — all grounded in LangGraph primitives like recursion_limit, node caching, and checkpointing. You’ll finish with a runnable example that trips a guard and recovers.
Prerequisites
pip install langgraphand Python 3.10+.- Basic LangGraph fluency: state schemas, nodes, conditional edges. The example uses a mock “LLM” node so it runs offline with no API key.
- An existing agent or tool loop to harden — the patterns transfer to any framework.
Three Ways Agent Loops Burn Tokens
Each mode needs a different detection signal:
- Repeated identical tool calls. The model asks for the same thing twice — same tool, same arguments. The tool result is identical, but the LLM turn wrapping it is not free: every iteration re-sends the whole conversation, so input tokens per run grow roughly quadratically with iteration count.
- Plan ping-pong. State oscillates between configurations — plan A, plan B, plan A. Nothing is being repeated verbatim; the state is cycling. Signature checks miss this; state hashes catch it.
- Unbounded recursion. A node spawns more subtasks with no base case — in graph terms, a very long walk, which is exactly what the recursion limit exists to stop.
Memoization alone doesn’t fix #1: the cached result saves the tool’s work, but the model still pays for the turn that re-requests it. You need detection and caching and caps.
Detect Repetition: Call Signatures and State Hashes
A call signature canonicalizes a tool invocation so trivial differences — key order, types — hash identically. A state hash does the same for the task-relevant slice of graph state, turning “are we going in circles?” into a set-membership test:
import hashlib
import json
def call_signature(tool: str, args: dict) -> str:
"""Canonical hash of a tool invocation; arg order must not matter."""
blob = json.dumps({"tool": tool, "args": args}, sort_keys=True, default=str)
return hashlib.sha256(blob.encode()).hexdigest()[:16]
def state_hash(state: dict, keys: tuple[str, ...]) -> str:
"""Hash the state fields that represent real progress (plan, subgoals...)."""
blob = json.dumps({k: state.get(k) for k in keys}, sort_keys=True, default=str)
return hashlib.sha256(blob.encode()).hexdigest()[:16]
class LoopGuard:
"""Flags repeated signatures, state cycles, and iteration overruns."""
def __init__(self, max_iterations: int = 25, repeat_threshold: int = 2,
cycle_window: int = 12):
self.max_iterations = max_iterations
self.repeat_threshold = repeat_threshold
self.cycle_window = cycle_window
self._sigs: list[str] = []
self._hashes: list[str] = []
def observe(self, sig: str | None = None, shash: str | None = None,
iteration: int = 0) -> str | None:
"""Record observations; return 'cap' | 'repeat' | 'cycle' | None."""
if iteration >= self.max_iterations:
return "cap"
if sig is not None:
self._sigs.append(sig)
if self._sigs.count(sig) >= self.repeat_threshold:
return "repeat"
if shash is not None:
window = self._hashes[-self.cycle_window:]
if shash in window:
return "cycle"
self._hashes.append(shash)
return None
Keep the ring buffers bounded — a guard that grows its own state forever is a leak in a different costume. cycle_window matters too: the previous state alone misses A → B → C → A, while all history misfires on legitimate revisits; a sliding window is the pragmatic middle.
Hard Caps: Never Trust the Model to Self-Limit
Detection is probabilistic; caps are not. Every run needs a ceiling regardless of what the model decides, and LangGraph gives you one natively: the recursion limit caps how many super-steps a single run may execute, raising GraphRecursionError when exceeded. Per the LangGraph docs, the default is 10,007 super-steps as of v1.1.4 — far too generous for an interactive agent, where a runaway should fail in seconds, not hours. Override it per run as a top-level config key (not under configurable):
from langgraph.errors import GraphRecursionError
try:
result = graph.invoke(
{"messages": [{"role": "user", "content": task}]},
config={"recursion_limit": 40, # ~2-3x your healthy p95
"configurable": {"thread_id": "run-1"}},
)
except GraphRecursionError:
# Halt loudly, surface to an operator, resume later from the checkpoint.
result = {"status": "guard:recursion_cap"}
Set the number empirically: instrument a week of healthy runs, take the p95 iteration count, multiply by 2–3. A cap at 10× the norm never fires. You can also set LANGGRAPH_DEFAULT_RECURSION_LIMIT process-wide as a backstop for code paths that forget the config. On top of the graph-level cap, keep application-level budgets: max iterations per run, max calls per tool, max wall-clock seconds — each fails at a different granularity, so catch them at the cheapest one first.
Memoize Tool Results Within a Run
Within a single run, an identical tool call should never execute twice — the answer cannot have changed:
class ToolMemo:
"""Run-scoped cache: identical signatures return the first result."""
def __init__(self):
self._cache: dict[str, object] = {}
self.hits = self.misses = 0
def call(self, fn, tool: str, args: dict):
sig = call_signature(tool, args)
if sig in self._cache:
self.hits += 1
return self._cache[sig]
self.misses += 1
result = self._cache[sig] = fn(**args)
return result
memo = ToolMemo()
policy = memo.call(fetch_policy, "fetch_policy", {"doc": "refund-policy"})
Two caveats. First, a run-scoped memo is deliberately not a cross-run cache: yesterday’s stock price must be refetched, so scope it to one invocation (or a short TTL) and log hits — a climbing hit rate is your earliest warning that an agent is spinning. Second, LangGraph can do this at node level: pass a cache at compile time and attach a CachePolicy to a node, and the runtime caches node and task results by input. Use that for expensive deterministic nodes; keep the explicit memo for conditional tool calls.
Progress Predicates: State Must Change or Halt
Repetition detection catches verbatim loops; progress predicates catch steps that look new but never advance. The rule: after each step, the state must show progress or the run halts — a new plan step, a resolved subgoal, or, generally, a state hash not seen in the current window:
PROGRESS_KEYS = ("plan", "resolved_subgoals", "next_action")
def progressed(state: dict, guard: LoopGuard) -> bool:
"""True when this state represents forward motion, not a revisit."""
return state_hash(state, PROGRESS_KEYS) not in guard._hashes
Predicate design is where teams get burned: hashing all of state guarantees false cycles (timestamps and retry fields change every step, so nothing ever matches and the guard never fires). Hash only the fields a human would point at when asked “is this further along than before?” If progressed() returns False twice, don’t argue — route to recovery.
Cycle-Breaking Interrupts Back to the LLM
Silent halts waste the run; a model that knows what it did wrong often escapes next turn. Append a message stating the violation, the evidence, and the allowed exits:
def guard_nudge(verdict: str, tool: str, count: int) -> str:
return (
f"GUARD: you called `{tool}` {count} times with identical arguments. "
"The result is unchanged and cached — repeating it will not help. "
"Do not call it again. Either take a genuinely different action, "
"or reply DONE with the answer you already have."
)
Use a two-strike policy: the first violation gets the nudge (models recover surprisingly often), the second hard-halts and escalates to a fallback. The message names the tool and the count for a reason — vague prompts like “try something else” get ignored, while specific evidence is hard to rationalize past.
Putting It All Together: A Graph That Trips and Recovers
Here’s a complete LangGraph run: the mock agent stubbornly re-requests the same document until the guard’s interrupt appears — a stand-in for a model that has fallen into a loop:
from typing import Annotated, TypedDict
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.graph.message import add_messages
from langgraph.types import Command
def fetch_policy(doc: str) -> str:
"""A mock tool that hits a (fake) backend every time it runs."""
return f"[{doc}] Refunds accepted within 30 days (fetched once)."
memo = ToolMemo() # defined in the memoization section above
class State(TypedDict):
messages: Annotated[list, add_messages]
signatures: list[str]
iterations: int
def agent(state: State):
nudged = any("GUARD:" in (m.content or "") for m in state["messages"])
if nudged:
return {"messages": [{"role": "assistant",
"content": "DONE: policy already retrieved; answering from cache."}],
"iterations": state["iterations"] + 1}
return {"messages": [{"role": "assistant",
"content": "NEED fetch_policy refund-policy"}],
"iterations": state["iterations"] + 1}
def tool(state: State):
_, tool_name, arg = state["messages"][-1].content.split(" ", 2)
sig = call_signature(tool_name, {"doc": arg})
result = memo.call(fetch_policy, tool_name, {"doc": arg})
return {"messages": [{"role": "assistant", "content": f"RESULT: {result}"}],
"signatures": state["signatures"] + [sig]}
def guard(state: State):
last = state["messages"][-1].content
if last.startswith("DONE"):
return Command(goto="finish") # clean exit
if last.startswith("RESULT:"):
sigs = state["signatures"]
if sigs.count(sigs[-1]) >= 2: # repeat detected
nudge = guard_nudge("repeat_call", "fetch_policy", sigs.count(sigs[-1]))
return Command(update={"messages": [{"role": "user", "content": nudge}]},
goto="agent") # interrupt, then retry
if state["iterations"] >= 10: # hard cap
return Command(update={"messages": [{"role": "user",
"content": "GUARD: iteration cap; halting."}]},
goto="finish")
return Command(goto="agent") # no verdict: keep going
def finish(state: State):
return {} # terminal: room for bookkeeping
builder = StateGraph(State)
builder.add_node("agent", agent)
builder.add_node("tool", tool)
builder.add_node("guard", guard)
builder.add_node("finish", finish)
builder.add_edge(START, "agent")
builder.add_edge("agent", "tool")
builder.add_edge("tool", "guard") # guard routes itself via Command(goto=...)
builder.add_edge("finish", END)
graph = builder.compile(checkpointer=InMemorySaver())
final = graph.invoke(
{"messages": [{"role": "user", "content": "What's the refund policy?"}],
"signatures": [], "iterations": 0},
config={"recursion_limit": 40, "configurable": {"thread_id": "run-1"}},
)
print(final["messages"][-1].content)
print("signatures:", final["signatures"], "| iterations:", final["iterations"])
Run it and you get the story in three lines:
DONE: policy already retrieved; answering from cache.
signatures: ['3f9a...', '3f9a...'] | iterations: 3
Trace it: the first tool step misses the memo and executes fetch_policy; the second hits it — same signature, zero extra work — and the guard sees count >= 2, injects the nudge, and the agent finishes with DONE. Three model iterations instead of a dozen, one tool execution instead of two. The InMemorySaver checkpointer saved a checkpoint at every super-step, so a run that dies at the guard resumes from thread_id: run-1 instead of paying to redo earlier steps: guards become recoverable pauses, not lost work. One reminder — checkpoints land at super-step boundaries, so side effects in a re-run node must be idempotent.
Conclusion and Next Steps
You started with an agent that could re-call the same tool until the budget ran out, and ended with layered defenses: call signatures and state hashes that detect repetition and cycles, a recursion_limit that caps any run regardless of model behavior, a run-scoped memo that makes repeats free, a progress predicate that demands forward motion, and a two-strike interrupt that gives the model one honest chance to escape — all persisted through LangGraph checkpoints so recovery is resume, not restart.
Homework, in order of leverage:
- Log call signatures per run and chart the memo hit rate — you can’t fix a loop rate you don’t measure.
- Set
recursion_limitfrom your healthy p95 iteration count, not the 10,007 default, and give every tool a per-run call budget. - Make memo entries TTL-aware where freshness matters; keep hits/misses in your trace.
- Review traces for
guard:*outcomes — every halted run is a prompt or tool-design bug worth fixing at the source.