惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
有赞技术团队
有赞技术团队
Jina AI
Jina AI
H
Help Net Security
D
Docker
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Blog — PlanetScale
Blog — PlanetScale
Hugging Face - Blog
Hugging Face - Blog
罗磊的独立博客
MyScale Blog
MyScale Blog
N
Netflix TechBlog - Medium
B
Blog RSS Feed
Martin Fowler
Martin Fowler
WordPress大学
WordPress大学
T
The Blog of Author Tim Ferriss
U
Unit 42
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
MongoDB | Blog
MongoDB | Blog
美团技术团队
M
MIT News - Artificial intelligence
阮一峰的网络日志
阮一峰的网络日志
博客园 - 司徒正美
Microsoft Security Blog
Microsoft Security Blog
IT之家
IT之家

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Preventing Recursive Tool Loops in LangChain Agents
Joakim William Hauge · 2026-05-25 · via DEV Community

Joakim William Hauge

One of the fastest ways for LangChain agents to become unstable in production is not model quality.

It’s recursive tool loops.

A workflow starts normally:

  • search
  • retrieve
  • summarize

Then suddenly:

  • the same tool gets called repeatedly
  • retries compound
  • context grows
  • token usage spikes
  • execution drifts indefinitely

The agent technically remains “alive.”

Operationally, it stopped making progress a long time ago.

This article shows a simple way to detect and interrupt recursive tool loops in LangChain agents using TypeScript.


The Problem

A basic agent workflow often looks harmless:

```ts id="jlwm4"
const result = await agentExecutor.invoke({
input: userPrompt
});




But production agents can drift into patterns like:



```txt id="0jlwm4"
search_documents
→ search_documents
→ search_documents
→ search_documents

or:

```txt id="1jlwm4"
search
→ summarize
→ retry
→ search
→ summarize
→ retry




This usually happens because:

* the model fails to converge
* tool outputs are ambiguous
* retries reinforce uncertainty
* the agent misinterprets partial progress

The result is:

## runaway execution.

# Why This Is Dangerous

Most AI workflows behave normally most of the time.
T
he problem comes from tail events:

* recursive retries
* unstable recovery behavior
* escalating context windows
* repeated tool invocation

A tiny percentage of unstable runs can consume a disproportionate amount of:

* inference cost
* latency
* compute
* operational attention

This is not just an observability issue.

It’s a runtime governance issue.

---

# Basic Strategy

We want to:

* track recent tool usage
* detect repetition patterns
* interrupt execution safely

before the workflow spirals.

The simplest version:



```txt id="2jlwm4"
“If the same tool is called too many times consecutively, stop execution.”

Simple.
Effective.
Easy to implement.


Step 1 — Track Tool History

We’ll maintain lightweight runtime state:

```ts id="3jlwm4"
type ExecutionState = {
toolHistory: string[];
};




Initialize it:



```ts id="4jlwm4"
const state: ExecutionState = {
  toolHistory: []
};


Step 2 — Detect Recursive Patterns

Now create a helper:

```ts id="5jlwm4"
function detectRecursiveLoop(
toolHistory: string[],
threshold = 3
): boolean {
if (toolHistory.length < threshold) {
return false;
}

const recent = toolHistory.slice(-threshold);

return recent.every(
tool => tool === recent[0]
);
}




This checks:



```txt id="6jlwm4"
Did the same tool run 3 times in a row?


Step 3 — Wrap Tool Execution

Now intercept tool calls:

```ts id="7jlwm4"
async function guardedToolCall(
toolName: string,
execute: () => Promise
) {
state.toolHistory.push(toolName);

if (detectRecursiveLoop(state.toolHistory)) {
throw new Error(
Recursive loop detected for tool: ${toolName}
);
}

return execute();
}




---

# Step 4 — Use Inside LangChain Tools

Example:



```ts id="8jlwm4"
const result = await guardedToolCall(
  "search_documents",
  async () => {
    return searchTool.invoke(query);
  }
);

That’s it.

Now your workflow can:

  • detect runaway repetition
  • interrupt unstable execution
  • prevent unnecessary cost escalation

Why Simple Detection Works Surprisingly Well

A lot of teams initially assume they need:

  • anomaly detection
  • reinforcement learning
  • advanced telemetry pipelines

But simple operational heuristics already eliminate many expensive failures.

Especially:

  • recursive retries
  • retry storms
  • repeated tool churn

You do not need perfect intelligence initially.

You need:

bounded execution.


Production Improvements

The minimal approach above works surprisingly well, but production systems usually add:

  • semantic similarity detection
  • token velocity monitoring
  • execution depth limits
  • tool-call budgets
  • runtime ceilings
  • timeout policies
  • adaptive thresholds

Example:

```txt id="9jlwm4"
search
→ search
→ search




is easy to detect.

More advanced loops look like:



```txt id="10jlwm4"
search
→ summarize
→ retry
→ search
→ summarize
→ retry

These require broader trajectory analysis.


The Distributed Systems Parallel

Distributed systems eventually evolved:

  • retry limits
  • circuit breakers
  • bounded failure domains
  • timeout controls

because unconstrained retries became dangerous at scale.

Autonomous agent systems are beginning to encounter similar operational realities.

As agents become:

  • more autonomous
  • more persistent
  • more deeply integrated

runtime governance becomes increasingly important.


Final Thoughts

Most teams focus heavily on:

  • prompts
  • model quality
  • orchestration frameworks

But production AI systems also need:

  • bounded execution
  • runtime constraints
  • operational safeguards
  • economic stability

Because eventually:
the challenge is not just building autonomous agents.

It is building governable autonomous agents.