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

推荐订阅源

J
Java Code Geeks
GbyAI
GbyAI
阮一峰的网络日志
阮一峰的网络日志
Cloudbric
Cloudbric
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
宝玉的分享
宝玉的分享
I
Intezer
Simon Willison's Weblog
Simon Willison's Weblog
博客园_首页
The Cloudflare Blog
C
Cisco Blogs
AWS News Blog
AWS News Blog
IT之家
IT之家
Cyberwarzone
Cyberwarzone
罗磊的独立博客
美团技术团队
V
V2EX
Project Zero
Project Zero
A
Arctic Wolf
C
Cyber Attacks, Cyber Crime and Cyber Security
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 聂微东
有赞技术团队
有赞技术团队
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
雷峰网
雷峰网
S
Schneier on Security
P
Privacy International News Feed
V
Visual Studio Blog
量子位
T
Tor Project blog
S
Securelist
腾讯CDC
A
About on SuperTechFans
T
Threat Research - Cisco Blogs
G
GRAHAM CLULEY
B
Blog RSS Feed
D
DataBreaches.Net
博客园 - 三生石上(FineUI控件)
B
Blog
NISL@THU
NISL@THU
L
Lohrmann on Cybersecurity
V
Vulnerabilities – Threatpost
人人都是产品经理
人人都是产品经理
博客园 - 【当耐特】
L
LINUX DO - 热门话题
Recorded Future
Recorded Future

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to Fix Tool-Use Loops in Autonomous Coding Agents
Alan West · 2026-05-26 · via DEV Community

Last month I was helping a friend debug their autonomous coding agent. It had been "working" on a task for 47 minutes, burned through roughly twelve bucks in API costs, and somehow ended up exactly where it started. The logs showed it had called read_file on the same five files 23 times.

If you've built or experimented with AI coding agents, you've probably seen something like this. It's not a fun bug to debug — the agent isn't crashing, it isn't erroring, it just... never finishes.

The Problem: Why Agents Loop Forever

Tool-use loops are the most expensive failure mode in agent design. From the outside, the agent looks busy. It's reading files, calling tools, generating thoughts, producing output. But it's not making progress toward the goal.

The shape is almost always the same:

  • Agent reads file A
  • Agent realizes it needs context from file B
  • Reads file B, gets confused by something unexpected
  • Goes back to file A "to double-check"
  • Reads file B again because file A didn't have what it needed
  • Repeat until your wallet cries

I've now seen this in three different agent setups across two side projects and one client engagement. The symptoms are identical every time.

Root Cause: Stateless Decision-Making

The fundamental issue is that the agent's working state looks nearly identical at step N and step N+5. Same task description in the system prompt, same files implicitly available, same general feel of the conversation. So the model — given essentially the same inputs — makes essentially the same decision.

There are three concrete causes worth separating:

  1. No explicit action history. The agent has called read_file("config.yaml") four times, but each turn the model mostly "sees" the latest tool result, not the pattern of what it's already tried.
  2. No reflection step. Nothing in the loop ever asks "am I actually making progress?"
  3. Errors get summarized away. A tool failure gets compressed into a vague "the previous call had an issue" and the model retries with the same broken inputs.

Let's walk through fixing each one.

Step 1: Track Tool Calls Explicitly

Don't rely on the conversation history to encode what's been tried. Build a structured log the model can actually reason about.

from collections import Counter
from dataclasses import dataclass, field
from typing import Any

@dataclass
class ToolCallLog:
    # Counts repeated (tool_name, args) pairs so we can detect loops
    calls: Counter = field(default_factory=Counter)
    history: list = field(default_factory=list)

    def record(self, name: str, args: dict[str, Any], result: str):
        key = (name, _hash_args(args))  # stable hash of args
        self.calls[key] += 1
        self.history.append({"name": name, "args": args, "result_preview": result[:200]})

    def summary_for_model(self) -> str:
        # Surface repeated calls so the model SEES the loop forming
        repeated = [(k, n) for k, n in self.calls.items() if n > 1]
        if not repeated:
            return "No repeated tool calls so far."
        lines = [f"- {name}{args} called {n}x" for (name, args), n in repeated]
        return "Repeated calls detected:\n" + "\n".join(lines)

Enter fullscreen mode Exit fullscreen mode

Then inject log.summary_for_model() into the system prompt every turn. Suddenly the model can see that it's about to call read_file("config.yaml") for the fifth time, and most modern models will course-correct on their own.

Step 2: Add a Loop Detector

Don't trust the model to always notice. Add a circuit breaker:

MAX_IDENTICAL_CALLS = 3
MAX_TOTAL_STEPS = 40

def should_force_reflection(log: ToolCallLog) -> str | None:
    # Return a reflection prompt if we detect a loop, else None
    for key, count in log.calls.items():
        if count >= MAX_IDENTICAL_CALLS:
            name, args = key
            return (
                f"You've called {name} with the same args {count} times. "
                "This is a loop. Stop and explain in one sentence what you "
                "actually need, then choose a different strategy."
            )
    if len(log.history) >= MAX_TOTAL_STEPS:
        return (
            "You've taken many steps without finishing. Summarize what you "
            "know, what you still need, and propose a single next action."
        )
    return None

Enter fullscreen mode Exit fullscreen mode

When this triggers, inject the returned string as a user message before the next model call. I've found this single change cuts wasted tokens by something like half on the workflows I've tested. Your mileage will vary, but the direction is consistent.

Step 3: Force Reflection on a Schedule

Even without a detected loop, models drift on long tasks. A periodic forced reflection helps. The cadence I've landed on is every 8–10 tool calls:

REFLECTION_INTERVAL = 8

def maybe_reflect(step: int, task: str) -> str | None:
    if step > 0 and step % REFLECTION_INTERVAL == 0:
        return (
            f"Pause. Original task: {task}\n"
            "In 3 short bullets, answer:\n"
            "1. What have I actually accomplished?\n"
            "2. What is still blocking completion?\n"
            "3. Is my current approach working, or should I change it?"
        )
    return None

Enter fullscreen mode Exit fullscreen mode

This is borrowed from human pair programming — "hey, where are we?" every so often is healthy.

Step 4: Make Errors Loud

The last fix is the most boring but probably the most important. When a tool fails, don't soften the error message:

def format_tool_error(name: str, args: dict, exc: Exception) -> str:
    # Be specific about what failed. Generic errors invite retries.
    return (
        f"TOOL ERROR: {name} failed with {type(exc).__name__}: {exc}.\n"
        f"Inputs were: {args}.\n"
        "Do NOT retry with identical arguments. Either fix the inputs "
        "or choose a different tool."
    )

Enter fullscreen mode Exit fullscreen mode

The "Do NOT retry with identical arguments" line sounds silly but actually moves the needle. I tested with and without it on the same task three times — without it, the agent retried failing calls about 60% of the time. With it, closer to 10%. Tiny sample size, but the effect was obvious.

Prevention: Design Choices That Help

A few patterns I now reach for by default when building agents:

  • Cap context per tool. Truncate read_file results to the relevant section instead of dumping whole files. Less noise, more signal.
  • Use scratchpad files. Give the agent a notes.md it can write to. Externalized memory is cheaper than re-deriving state from chat history.
  • Separate planning from execution. A small "planner" call that emits a 5-step plan, followed by an executor that follows it, loops far less than a single agent doing both.
  • Log everything during development. You cannot debug what you cannot see. Persist full tool histories to disk for the first few weeks of any new agent.

None of this is novel — the broader agent research community has been writing about reflection, planning, and memory for a while. But it's easy to skip these when you're hacking together a prototype and assume "the model will figure it out." It won't. Not reliably.

Wrapping Up

Tool-use loops are not a model problem so much as a harness problem. The model is doing exactly what you'd expect given identical inputs every turn. Your job, as the person building the loop around the model, is to make sure the inputs aren't identical — that the agent can see its own history, get nudged when it's stuck, and feel the weight of its errors.

Fix those four things and most of your runaway agent costs go away. The rest is just tuning.