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

推荐订阅源

S
SegmentFault 最新的问题
Google Online Security Blog
Google Online Security Blog
L
LINUX DO - 最新话题
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
AI
AI
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
N
News | PayPal Newsroom
G
GRAHAM CLULEY
V
Vulnerabilities – Threatpost
Cisco Talos Blog
Cisco Talos Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
P
Privacy & Cybersecurity Law Blog
Google DeepMind News
Google DeepMind News
L
LangChain Blog
T
Tailwind CSS Blog
腾讯CDC
C
CXSECURITY Database RSS Feed - CXSecurity.com
The Cloudflare Blog
Spread Privacy
Spread Privacy
月光博客
月光博客
WordPress大学
WordPress大学
C
CERT Recently Published Vulnerability Notes
小众软件
小众软件
AWS News Blog
AWS News Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - Franky
O
OpenAI News
W
WeLiveSecurity
H
Heimdal Security Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
V
Visual Studio Blog
The Last Watchdog
The Last Watchdog
有赞技术团队
有赞技术团队
量子位
TaoSecurity Blog
TaoSecurity Blog
V
V2EX
罗磊的独立博客
雷峰网
雷峰网
Latest news
Latest news
Jina AI
Jina AI
Simon Willison's Weblog
Simon Willison's Weblog
博客园_首页
博客园 - 聂微东
L
Lohrmann on Cybersecurity
V2EX - 技术
V2EX - 技术
T
The Exploit Database - CXSecurity.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Security Latest
Security Latest
Help Net Security
Help Net Security

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
I built a circuit breaker for LLM agents after seeing someone lose $200 overnight
BOSS_METALLIQUE · 2026-06-03 · via DEV Community

A few weeks ago I was lurking in the LangChain Slack instead of doing my actual coursework, and two messages stuck with me.

The first one: someone got billed for 211 looping runs on their very first question. Not their hundredth. Their first. The agent just kept going.

The second one: a dev lost 800 yuan (around $110) because LangChain's default recursion limit is 9999. Nobody sets that on purpose. It's just the default, and the default is "basically infinite."

I'm a student. $110 is a lot of money to me. The idea that an agent could quietly burn that overnight, while you're asleep, because of a malformed tool response and a default value nobody read — that genuinely freaked me out. So I built a thing. This is the story of that thing.

The problem: agents have a gas pedal but no brake

Here's what nobody tells you when you ship your first agent.

You wire up LangGraph, you give the model a tools array, you write a nice prompt, and it works in the demo. Great. Then it goes to production and one of three things eventually happens:

  1. It loops. A tool returns garbage, the model decides to retry, gets the same garbage, retries again... forever. Or until your budget is gone.
  2. It overspends. Nothing is "broken," it's just doing a lot of work, and the bill quietly climbs past anything reasonable.
  3. It does something it shouldn't. A user prompt-injects your support bot and suddenly it's calling delete_database because, well, that function was in the tools list and nobody said it couldn't.

And here's the part that bugged me the most: we already have tools for this, except they all watch instead of act.

LangSmith, Langfuse, Helicone, AgentOps — they're great. I use them. But they're observability. They show you, in a beautiful dashboard, that your agent looped 211 times. After it already did. The dashboard is a security camera. It records the break-in. It doesn't lock the door.

I kept thinking: where's the brake pedal? The thing that stops the agent during the run, before the damage, not the report you read the morning after?

I couldn't find one I liked. So I wrote one.

What I built: AgentBrake

AgentBrake is a Python decorator that sits in front of your tool calls. Every single tool call your agent tries to make passes through it first, and it checks three things before letting the call execute:

  • Loop — are you calling the same tool with the same arguments over and over?
  • Budget — would this call push you past the dollar ceiling you set?
  • Escalation — is this tool even on the allowed list?

If any check trips, it raises an exception instead of running the tool. The agent stops. Mid-run. Before the money is spent or the database is dropped.

That's the whole pitch. It's a circuit breaker. When things go wrong, it pops, and nothing downstream of it gets power.

How it works (it's genuinely 3 lines)

You configure it once:

import agentbrake

agentbrake.init(
    allowed_tools=["search", "read_file"],
    budget_usd=5.0,
)

Then you put the decorator on whatever function dispatches your tools:

@agentbrake.guard()
def call_tool(name: str, args: dict):
    return my_tools[name](**args)

That's it. That's the integration. If the agent loops, blows the $5 budget, or tries to call something outside allowed_tools, call_tool raises AgentBrakeInterrupt instead of executing the tool.

You catch it wherever you run the agent:

from agentbrake import AgentBrakeInterrupt

try:
    agent.run("summarize my inbox")
except AgentBrakeInterrupt as e:
    print(f"Stopped: {e.reason}")  # LOOP, BUDGET, or ESCALATION

Under the hood, the decorator keeps a little RunState in memory — the run ID, the running cost, and the full history of calls. Every call runs through the three detectors in order (escalation → loop → budget), and the first one that fires raises before your tool ever runs.

Let me explain each detector, because they're simpler than you'd think.

Escalation is a one-liner. Is the tool name in the allow-list? No? Stop. This is the cheapest and most decisive check, so it goes first. I don't care if you're under budget — if you're trying to call delete_database and it's not on the list, that's a hard no.

Budget projects the cost before the call. It takes the running total, adds what this next call would cost, and if that projected number is over your ceiling, it trips. The key word is projected — it stops you before you cross the line, not after.

Loop is the one I'm most proud of, so it gets its own section.

The thing I'm proudest of: structural hashing for loops

My first instinct for loop detection was the obvious one: compare the tool name and arguments as strings. If the last 3 calls are identical strings, it's a loop.

That's fragile. {"q": "weather", "lang": "en"} and {"lang": "en", "q": "weather"} are the same call, but as strings they're different. A model that shuffles its argument order — and they do — would slip right past a naive string check.

So instead, each call gets a structural hash:

def _structural_hash(call):
    payload = json.dumps(
        {"name": call.name, "args": call.args},
        sort_keys=True,   # key order can't fool it
        default=str,      # non-JSON values still hash
    )
    return hashlib.sha256(payload.encode()).hexdigest()

sort_keys=True is the whole trick. It normalizes the argument dict before hashing, so {a, b} and {b, a} produce the exact same hash. default=str is the safety net — if an argument isn't JSON-serializable, it gets stringified instead of crashing the detector. The last thing you want is your safety mechanism throwing an unhandled error.

Then loop detection is just: hash the new call, compare it to the last two. Three identical structural hashes in a row → it's a loop → stop. The agent in my demo gets a fake "transient error, please retry the exact same query" response, dutifully retries... and gets caught on the third attempt.

The demo

I recorded a short walkthrough showing all three detectors tripping on a real LangGraph agent — the loop, the runaway budget, and the privilege escalation:

📺 https://youtu.be/uHbjP2SGMsI

Watching an agent get stopped mid-loop is way more satisfying than I expected.

What I actually learned building this

This is the part I'd tell a friend over coffee, because some of it surprised me.

1. The framework actively fights you. This was the big one. My detectors worked perfectly in isolation, then I plugged them into a real LangGraph agent and... nothing stopped. Turns out LangGraph's ToolNode swallows tool exceptions by default and feeds them back to the model as an observation. So my breaker would fire, raise its exception, and the framework would catch it, hand the model a polite "tool failed, want to retry?", and the model would just... keep going. My safety mechanism became another thing for the loop to loop over. The fix was one argument:

# Default behavior eats your exception and tells the model to retry.
# The breaker only works if the exception is allowed to propagate.
tool_node = ToolNode(tools, handle_tool_errors=False)

I would never have guessed that. A circuit breaker is useless if the wiring around it catches the spark.

2. "Before" vs "after" is the entire product. It would have been so easy to build yet another dashboard. The hard, interesting constraint was: every check has to happen before the tool runs. That's why the budget detector projects the cost instead of summing it afterward, and why the whole thing is a decorator that intercepts the call rather than a logger that records it. The moment you let the call run first, you've rebuilt observability.

3. Fail closed, always. I added an optional remote mode where a human can approve or kill a flagged run from a browser. The obvious question: what if that backend is unreachable? My first version just... let the call through, because erroring felt user-hostile. Then I realized that's exactly backwards. A brake that releases when it loses power isn't a brake. So now, if the validation server is down, it stops the run. A safety device that fails open is worse than no safety device, because you think you're protected.

4. Sync over async, on purpose. I wanted to use async everywhere because it feels more "real." But @guard() wraps an arbitrary user function that might be totally synchronous, and forcing someone to bolt on an event loop just so my breaker can pause for human review would be a horrible developer experience. Sometimes the boring choice is the correct one.

It's early, and I'd love your eyes on it

Honest status: this is v0.0.1. Local mode is solid (15/15 tests passing), the LangGraph examples and the remote validation UI work end to end. The cost model is currently a flat per-call estimate rather than real token accounting — that's the next thing on my list. I'm putting it out there because I want real users to tell me where the API feels wrong before I lock it in.

If you've ever had an agent do something dumb and expensive, I'd genuinely love your feedback.

pip install agentbrake

Keep your dashboards. Just add a brake pedal too.

Thanks for reading.