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

推荐订阅源

WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
D
Docker
H
Help Net Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Azure Blog
Microsoft Azure Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
C
Check Point Blog
S
SegmentFault 最新的问题
T
The Blog of Author Tim Ferriss
J
Java Code Geeks
M
MIT News - Artificial intelligence
B
Blog RSS Feed
MyScale Blog
MyScale Blog
大猫的无限游戏
大猫的无限游戏
Hugging Face - Blog
Hugging Face - Blog
腾讯CDC
美团技术团队
I
InfoQ
Blog — PlanetScale
Blog — PlanetScale

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
I almost burned ₹4,000 on Claude API overnight — so I bui...
Advik · 2026-06-14 · via DEV Community

Advik

I almost burned ₹4,000 on Claude API overnight — so I built llm-cost-guard
Last month I wrote what I thought was a harmless script.

Batch-process 847 product descriptions through Claude. Summarize each one. Save to a CSV. Ship it and go to bed.

The loop looked fine. Error handling was there. Retries were capped. I felt responsible.

I woke up to a Slack ping from my own logging bot — not because anything crashed, but because something succeeded way too much.

₹4,000 gone. Overnight. On a side project.

The loop hadn't infinite-looped in the traditional sense. It had expensive-looped. A retry bug on malformed responses meant some items got hit 3–4 times. A few prompts were longer than I estimated. And I had zero visibility into running spend while it was happening.

I stared at the Anthropic dashboard like it was a crime scene.

Why Anthropic billing alerts don't cut it
Anthropic does have billing alerts. They're useful — for finance, eventually.

But they're not a runtime guardrail:

Delayed — you find out after the damage, not mid-request
Account-level — one rogue script takes down your whole API budget
Non-blocking — an email doesn't stop a loop that's already running
What I actually needed was something that sits inside my code and says: "Stop. You've hit your limit. Right now."

Not tomorrow. Not at invoice time. Before request #400 burns another ₹500.

What llm-cost-guard does
It's a drop-in wrapper for your existing LLM client. One line. No SDK rewrite.

import Anthropic from "@anthropic-ai/sdk";
import { guard } from "@advik1228/llm-cost-guard";
const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
const client = guard(anthropic, { dailyLimit: 5, onLimit: "throw" });
// Use client exactly like before — same API, same methods
const response = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [{ role: "user", content: "Summarize this..." }],
});
That's it. If today's spend crosses $5, the next call throws. The loop dies. Your wallet survives.

You can also set monthly caps, per-request limits, per-user budgets, webhook alerts, and streaming support — but the core idea is dead simple: wrap, limit, block.

How it works under the hood
No monkey-patching. No forked SDK.

llm-cost-guard uses a JavaScript Proxy to intercept calls to messages.create (Anthropic), chat.completions.create (OpenAI), and Gemini's generateContent.

When a call completes, it reads the real token counts from the API response — usage.input_tokens, usage.output_tokens, etc. Not tiktoken guesses. The provider already counted them; we just listen.

Then it:

Calculates cost in USD from a built-in pricing table
Increments daily/monthly/user spend in memory or Redis
Checks your limits
Throws, warns, or stays silent — your call
For streaming, it runs a pre-flight estimate before the stream starts, passes every chunk through unchanged, and records spend when the stream finishes.

The Proxy pattern means your existing code doesn't change. Your types mostly don't change. You just wrap once at startup.

Install + quick start
npm install @advik1228/llm-cost-guard
Anthropic:

import { guard } from "@advik1228/llm-cost-guard";
const client = guard(anthropic, {
dailyLimit: 5.0,
warnAt: 4.0,
onLimit: "throw",
});
OpenAI:

const client = guard(openai, {
dailyLimit: 10.0,
perRequestLimit: 0.50,
onLimit: "throw",
});
Multi-tenant / production — plug in Redis so limits are shared across instances:

import { guard, RedisAdapter } from "@advik1228/llm-cost-guard";
const client = guard(anthropic, {
dailyLimit: 100,
storage: new RedisAdapter(redis),
userId: req.user.id,
userDailyLimit: 2.0,
});
Try it — before your next overnight job
I built this because I needed it to exist. Not as a SaaS pitch. Not as an observability platform. Just a small guard that sits between my code and an API that charges by the token.

If you've ever run a batch job and thought "this should be fine" — it probably is, until it isn't.

Star the repo if this saves you once. Install it before your next loop. Set a daily limit low enough to hurt your ego but not your bank account.

GitHub: https://github.com/advikhingmire12-oss/llm-cost-guard
npm: https://www.npmjs.com/package/@advik1228/llm-cost-guard