LLM账单太高?这个自制分析器让我每月省下$30
大家好,今天聊聊一个实操性超强的话题:怎么控制你的 ChatGPT/Claude API 开销?
Dev.to 上一位开发者分享了他自制"LLM账单分析器"的经历,每月省下$30。我们一起来看看怎么做。
一、问题:LLM账单为啥容易失控?
很多团队和个人使用 LLM API 时,会遇到:
- 不知道钱花在哪:API返回total cost,但不告诉你哪个功能/用户花了多少
- 突增的费用:某个循环里多调用了几次,费用翻倍
- 无法优化:因为没有数据,只能盲目调参数或限制使用
这就像你有个水龙头,只看到总用水量,不知道哪里在漏水。
二、解决方案:自制 Profiler
作者的方法是:记录每一次LLM调用的详细数据。
核心字段:
{
timestamp: '2024-02-20T10:30:00Z',
model: 'gpt-4-turbo',
prompt_tokens: 1250,
completion_tokens: 340,
total_tokens: 1590,
cost_usd: 0.82,
user_id: 'alice',
feature: 'customer_support',
session_id: 'abc123'
}
然后用这个数据做:
- 按user/feature分组统计
- 识别高成本调用
- 发现异常峰值
三、具体实现(简化版)
思路:
- 在 LLM 客户端封装一层中间件
- 每次调用前后记录 token 数和时间
- 根据模型定价(openai.com/pricing)计算费用
- 存储到数据库或日志文件
代码示例(Node.js):
class LLMProfiler {
constructor() {
this.logs = []
}
async call(model, messages, user, feature) {
const start = Date.now()
const response = await openai.chat.completions.create({
model, messages
})
const usage = response.usage
const cost = this.calculateCost(model, usage.prompt_tokens, usage.completion_tokens)
this.logs.append({
timestamp: new Date().toISOString(),
model,
prompt_tokens: usage.prompt_tokens,
completion_tokens: usage.completion_tokens,
cost,
user,
feature,
latency_ms: Date.now() - start
})
return response
}
calculateCost(model, prompt, completion) {
// 根据openai定价表计算
const prices = {
'gpt-4-turbo': [0.01, 0.03], // per 1K tokens
'gpt-3.5-turbo': [0.0005, 0.0015]
}
const [prompt_price, completion_price] = prices[model]
return (prompt/1000)*prompt_price + (completion/1000)*completion_price
}
getReport() {
// 生成报表:按user、feature汇总
}
}
四、作者的发现(省$30的关键)
运行 profiler 一周后,作者发现:
-
不必要的模型升级:
- 内部测试用 gpt-4-turbo($0.03/1K tokens)
- 实际上 gpt-3.5-turbo 效果足够($0.0015/1K tokens)
- 节省: 70%
-
长prompt优化:
- 有些功能每次传入 2000 tokens 的系统提示
- 精简后降到 500 tokens,效果不变
- 节省: 75%
-
缓存重复查询:
- FAQ类问题结果可以缓存24小时
- 命中率约30%,大幅降低调用次数
- 节省: 20%
合计: 月账单从 $120 降到 $90,省下$30。
五、行动步骤(你也可以做)
如果你用LLM API:
- 本周:在代码里加日志(至少记录model, tokens, user)
- 2周内:跑一周数据,生成一个简单的cost breakdown
-
1月内:
- 识别top 3高cost features/users
- 尝试优化(换 cheaper 模型、缓存、压缩prompt)
- 持续:每周看报表,设置预算 alert
工具推荐:
- 如果你用 Python LangChain,有
CallbackHandler可记录 - 如果用直接 API,自己封装一层
- 数据存 SQLite 或 Google Sheets 都行
六、更深层的思考
费用控制不只是技术问题,更是产品设计问题:
- 为什么需要LLM? 有没有规则引擎能替代?
- 用户是否愿意付费? 高价值场景才用强模型
- 体验 vs. 成本:找到最优平衡点
七、结尾
"You can't manage what you don't measure."
先把数据记下来,再谈优化。哪怕是一个简单的 logger,也能让你看清账单的真相。
本期任务:
打开你的 LLM 调用代码,加一行日志,记录 tokens 和 cost。一周后告诉我你省了多少钱。
参考: I Built a Profiler for My LLM Bill (and It Saved Me $30/month) by lakshmisravyavedantham (Dev.to)
Top comments (1)
Tracking LLM costs is genuinely underrated — most people don't realize how fast it compounds until they see the bill. Structuring prompts well is one of the easiest wins: tighter prompts = fewer tokens per call. I built flompt for exactly this kind of iteration — it lets you decompose prompts into semantic blocks and compile them into lean, structured XML. flompt.dev / github.com/Nyrok/flompt