How to Detect Infinite Loops in LangChain Agents #207
bmdhodl
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
If you've built a LangChain agent that calls tools, you've probably seen this: the agent calls the same tool with the same arguments, over and over, burning through your API budget while doing nothing useful.
LangChain has
max_iterationsto cap the total number of steps, but that doesn't distinguish between productive work and a stuck agent repeating itself. An agent doing 20 different things is fine. An agent callingsearch("weather in NYC")20 times is broken.The pattern
Here's what an infinite loop looks like in agent logs:
The agent gets the same result, doesn't know what to do with it, and tries again. This can happen with any model (GPT-4, Claude, Gemini) and any tool configuration.
Detecting loops at runtime
Instead of relying on iteration caps, you can detect the actual pattern — repeated identical tool calls — and stop execution immediately.
Here's how with AgentGuard's
LoopGuard:When the agent enters a loop,
LoopGuardraisesLoopDetectedwith details about which tool and arguments triggered it. You can catch this and handle it however you want — retry with a different prompt, fall back to a simpler model, or return an error.How it works under the hood
LoopGuardmaintains a sliding window of recent tool calls. Each call is a(tool_name, hash(tool_args))pair. If the same pair appearsmax_repeatstimes within the window, it's a loop.The sliding window is important because it allows the agent to call the same tool multiple times with different arguments (productive work), while still catching the pathological case of identical repeated calls.
Adding budget limits too
Loops are one failure mode. The other is cost blowouts — even without loops, a complex agent can run up a large bill. You can layer
BudgetGuardon top:What about fuzzy loops?
Sometimes agents loop with slightly different arguments — e.g.,
search("weather NYC")thensearch("NYC weather"). The basicLoopGuardwon't catch this because the args differ.For this, AgentGuard has
FuzzyLoopGuardwhich detects repeated calls to the same tool regardless of arguments, and also catches A-B-A-B alternation patterns:Install
The SDK is MIT licensed, zero dependencies, and works with Python 3.9+.
Repo: https://github.com/bmdhodl/agent47
What loop patterns have you seen in your agents? Drop a comment — I'm collecting failure modes to improve detection.
Beta Was this translation helpful? Give feedback.
All reactions