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

推荐订阅源

L
Lohrmann on Cybersecurity
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Recorded Future
Recorded Future
S
Schneier on Security
I
Intezer
Latest news
Latest news
N
News and Events Feed by Topic
Scott Helme
Scott Helme
T
Threat Research - Cisco Blogs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
U
Unit 42
量子位
博客园 - 【当耐特】
S
Security @ Cisco Blogs
Google Online Security Blog
Google Online Security Blog
博客园 - 叶小钗
酷 壳 – CoolShell
酷 壳 – CoolShell
NISL@THU
NISL@THU
The Cloudflare Blog
李成银的技术随笔
T
ThreatConnect
L
LINUX DO - 最新话题
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
有赞技术团队
有赞技术团队
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Jina AI
Jina AI
T
Tor Project blog
The Hacker News
The Hacker News
人人都是产品经理
人人都是产品经理
小众软件
小众软件
S
Security Archives - TechRepublic
美团技术团队
博客园 - Franky
Security Latest
Security Latest
J
Java Code Geeks
P
Proofpoint News Feed
V
V2EX
The GitHub Blog
The GitHub Blog
WordPress大学
WordPress大学
Application and Cybersecurity Blog
Application and Cybersecurity Blog
H
Help Net Security
PCI Perspectives
PCI Perspectives
Cyberwarzone
Cyberwarzone
Hugging Face - Blog
Hugging Face - Blog
N
Netflix TechBlog - Medium
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
SecWiki News
SecWiki News
腾讯CDC
爱范儿
爱范儿
D
Docker

DEV Community

From Half‑dead Prototype to Local‑Only AI Medical Assistant: Rewiring MedClinic with GitHub Copilot Runninig a forkbomb in Jenkins What’s Actually Happening When You Use Git Building a Rock-Paper-Scissors CLI with TypeScript — Union Types, Conditionals, and Jest Your AI Coding Agent Wastes 80% of Its Context. Fixed That with Graph Theory. Why Flutter Has Become the Go-To Framework for Fintech App Development We built a scripting language just for AI agents. Here's why. Stop building AI inboxes. Build decision layers instead. Meme Monday Why I Built @editora/ui-react? Are AI tools the next level of abstraction in software development? Identity on Solana: Your Wallet Is Your Account One API Call Changed Everything The Internet Career Nobody Talks About Enough: What Is DevRel? Solar Panel Wiring Diagram: Series vs Parallel Hello everyone! Glad to join the dev.to community I Built an AI Agent That Tailors My Resume - Here's How Agents Actually Work I Built a WhatsApp OTP + AI Chatbot Platform for African Businesses MTP Explained — And Why It Matters for Android on Mac Most Beginners Learn Full-Stack Development Backwards GitHub Glow-Up: Open Source, READMEs, Badges, Streaks, Git and gh CLI System Design Cheat Sheet: Concepts Every Developer Should Know Are Junior Developer Roles Actually Dying? A Fresher's Honest Take Using DigitalOcean Droplets as Ephemeral Sandboxes for AI Agents I built a VSCode extension that visualises your code navigation as a call tree — made for legacy codebase pain Vite predev/prebuild: chaining scripts without losing your mind A website to save you from messy browser tabs Dear Web2 Developer... Solana is here calling Postgres JSONB indexes: GIN vs BTREE on the same column The $5 AI That Remembers Everything What are your goals for the week? #180 Zettelkasten for Developers: A Practical Method That Works OpenClaw vs Hermes Agent: Stars, Downloads & Usage 2026 `act` vs. `waitFor` Global Teams Don’t Struggle With Time Zones. They Struggle With Context Python as a JavaScript Dev $5.4 Billion in Damage. 8.5 Million Machines Down. Three YAML Controls Would Have Prevented It. Here's the Structural Analysis. 🚫 Stop Using PN532 V1 for Your NFC Projects (Real Debugging Experience) Probabilistic Graph Neural Inference for smart agriculture microgrid orchestration for extreme data sparsity scenarios Inference Is Becoming the New Steady-State Cost Center Why AI-Generated Code Is Always Good Enough — And Never Great I built a dark admin dashboard template in HTML — no React, no npm, just pure HTML What is the Difference Between Lattice-Based and Hash-Based Signatures? Next.js App Router caching: revalidate, dynamic, and no-store without the folklore Next.js App Router caching: revalidate, dynamic y no-store sin folklore I built Stashly — a full-stack content manager with a rich text editor published: false tags: react, node, mongodb, typescript Why I Started Building React Projects Instead of Just Watching Tutorials ? Every Tool Eventually Becomes Tuesday Nobody Warns You That Real Software Engineering Feels Chaotic Tích hợp VNPay, Stripe trong Odoo 19 BeautifulSoup and Requests for Web Scraping With Python: When Simple Still Works I Was Stuck Debugging React — Then Developer Tools Changed It Buck Converter Ripple: Sizing the Inductor and Capacitor With Confidence AWS Just Made Its MCP Server Generally Available. Here's What It Actually Gives AI Agents. RAMPART Tests Your AI Agents in Dev. What Catches Malicious Tool Calls in Production? Vibe Team Software Engineering: What a Real AI Human Dev Team Workflow Actually Looks Like An npm Package for AI Agent Orchestration Just Shipped With Its Front Door Unlocked. Here's What the CVE Actually Reveals. Microsoft Foundry Just Added CI/CD for AI Agents. Here's What That Actually Changes. The Best Career Insurance Is a Tech Event You Don't Want to Attend Your GitHub Profile Already Tells Recruiters More Than Your Resume. Most Devs Just Don't Surface It. How to Add Execution Budgets to OpenAI Agents SDK Binary Tree Interview Problems: 6 Traversal Patterns, 15 Problems We trained a personal voice DoRA on Qwen3-8B for $1.50 — beat stock model 100% in blind A/B Stop Leaking API Keys: Why I Built a Local-First Vault for Developers 🔐 RAG Explained: How Retrieval-Augmented Generation Actually Works I Built a Fast Async JioSaavn API Wrapper in Python 🎧 chown & chgrp Deploying Your First App on Kubernetes: A Beginner's Guide (Minikube & Kind) Logs in code It's called a PR "review" for a reason DePIN GPU Market: The Failed Job Receipt Developers Should Demand Why Your AI Agent Monitoring is Wrong (And How to Fix It) Lock Down Your Cloud Shares: A Beginner’s Guide to Azure Files Security. Building a Multi-Channel Content Syndication Pipeline with EmDash Plugins Turn Your Phone Into Voice Input for Any React Text Field Which package is bloating your Docker image? Putting Claude Code Under Version Control: Configs Since July, Memory Since April What I Thought DevRel Was vs. What It Actually Is (A Mentee's Honest Take) What I Thought DevRel Was vs. What It Actually Is (A Mentee's Honest Take) 400 Million Tokens Burned Overnight Reviving My Linux Mastery Game from a Merge Conflict — A Finish-Up-A-Thon Comeback Don’t let AI break your collective thinking: a practical guide for engineering teams First Gemma 4 ExecuTorch Deployment on Raspberry Pi 5 — and Why It's 7.7 Slower Than llama.cpp Per-Turn Evaluation: Dynamic Governance for AI Agents The AI Triforce of seed4j: Power, Wisdom, and Courage for Your Dev Agent Your AI agent reports 80% task completion. It fabricated it. Pourquoi les overlays d'accessibilité ne tiennent pas leurs promesses (et ce que la FTC vient d'acter) AI May Break Product-Market Fit in Enterprise Software I’m Building Around the Gap Between AI Output and Repo Truth How to Build a Stripe Customer Portal in Next.js SaaS On-Demand Pricing Feels Safe - Until You See the Bill Building an Internal Developer Portal with Backstage A Production Deployment Guide After the Last Song Sudoers Configuration in Linux Terraform + Terragrunt + Ansible: A Hands-On Learning Journey Switching Users in Linux (su, sudo) AI 智能体的鲁莽速度 Quick Win Card #01 — Ton backlog.md t'a menti (la cure en 30 secondes) Quick Win Card #01 — Your backlog.md lied to you (a 30-second cure) How to Manage an IT Team: Structure, Scaling, and Daily Workflows That Work
Preventing Recursive Tool Loops in LangChain Agents
Joakim Willi · 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

Enter fullscreen mode Exit fullscreen mode

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.”

Enter fullscreen mode Exit fullscreen mode

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: []
};

Enter fullscreen mode Exit fullscreen mode


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?

Enter fullscreen mode Exit fullscreen mode


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);
  }
);

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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.