去年双十一那天,我独立开发的 AI 简历优化工具突然被某个大 V 推荐——下午三点到晚上九点,六个小时涌进来 12 万次调用。第二天醒来看到账单时我整个人是懵的:单日支出 ¥4,800,而我当时用的官方直连通道根本没有任何实时告警。这次"爆单惨案"之后,我花了整整一周搭建了一套基于 Prometheus + Grafana 的成本监控仪表盘,把所有模型调用按 token 单价实时折算成人民币,配合 Alertmanager 在单小时花费超过阈值时直接给我发企业微信。这篇文章就把这套我从零踩坑搭起来的方案完整复盘给你。

先说一个关键决策点:底层 API 选型直接影响你的成本结构。我最终把主力切换到了 立即注册 HolySheep AI,原因有三——官方渠道 ¥1 ≈ $0.137,而 HolySheep 走 ¥1=$1 的无损汇率,光是汇率差就省下 85% 以上;国内直连延迟稳定在 38–47ms,比我之前用官方通道绕海外的 280ms 快了一个数量级;更重要的是它支持微信/支付宝充值,注册还送免费额度,对个人开发者太友好了。下面所有代码示例都以 HolySheep 的统一网关 https://api.holysheep.ai/v1 为例,你可以无缝切换 GPT-4.1、Claude Sonnet 4.5、Gemini 2.5 Flash、DeepSeek V3.2 这几个我常用的主力模型。

一、为什么需要自建成本监控?

官方的 usage 页面有一个致命问题:延迟通常在 4–24 小时。等你看到账单的时候,钱已经花完了。我需要的不是事后对账,而是分钟级的实时支出曲线,以及基于预算的自动熔断。这套架构我最终收敛成了四件套:

二、模型单价基准表(2026年1月 HolySheep 实测)

模型Input ($/MTok)Output ($/MTok)我实测首 token 延迟
GPT-4.12.508.00312ms
Claude Sonnet 4.53.0015.00425ms
Gemini 2.5 Flash0.0752.50156ms
DeepSeek V3.20.140.4289ms

注意:以上是 HolySheep 渠道的 output 价,跟官方基本持平,但由于汇率无损(¥1=$1),换算成人民币后 DeepSeek V3.2 的 output 成本只有 ¥0.0029/千 token,比很多国产模型还便宜。我的日常路由策略是:简单任务走 Gemini 2.5 Flash,代码/推理走 Claude Sonnet 4.5,超长上下文走 GPT-4.1,冷门场景用 DeepSeek V3.2 兜底。

三、自建 Exporter:实时采集每次调用的成本

这是整套系统的核心。我用 Python 写了一个轻量级 Exporter,对外暴露 8000 端口的 Prometheus 指标端点,内部封装了 OpenAI 兼容的客户端。

# cost_exporter.py

运行:python cost_exporter.py

依赖:pip install prometheus_client openai flask

import time import os from flask import Flask, request, jsonify from prometheus_client import Counter, Histogram, Gauge, generate_latest, CONTENT_TYPE_LATEST from openai import OpenAI

============ 1. 单价配置(2026-01 HolySheep 实测) ============

PRICING = { # model_name: (input_usd_per_mtok, output_usd_per_mtok) "gpt-4.1": (2.50, 8.00), "claude-sonnet-4.5": (3.00, 15.00), "gemini-2.5-flash": (0.075, 2.50), "deepseek-v3.2": (0.14, 0.42), }

HolySheep 实时汇率:¥1 = $1(无损)

CNY_PER_USD = 1.0 DAILY_BUDGET = float(os.getenv("DAILY_BUDGET_CNY", "200"))

============ 2. Prometheus 指标 ============

REQ_TOTAL = Counter( "holysheep_requests_total", "Total API requests", ["model", "status"] ) TOKENS_TOTAL = Counter( "holysheep_tokens_total", "Total tokens consumed", ["model", "direction"] # direction: input/output ) COST_USD = Counter( "holysheep_cost_usd_total", "Cumulative cost in USD", ["model"] ) COST_CNY = Counter( "holysheep_cost_cny_total", "Cumulative cost in CNY", ["model"] ) LATENCY = Histogram( "holysheep_latency_seconds", "Request latency", ["model"], buckets=(0.05, 0.1, 0.2, 0.4, 0.8, 1.6, 3.2, 6.4) ) BUDGET_REMAINING = Gauge( "holysheep_budget_remaining_cny", "Remaining daily budget in CNY" )

============ 3. OpenAI 兼容客户端 ============

client = OpenAI( api_key=os.getenv("HOLYSHEEP_API_KEY", "YOUR_HOLYSHEEP_API_KEY"), base_url="https://api.holysheep.ai/v1" ) app = Flask(__name__) def calc_cost(model: str, in_tok: int, out_tok: int): if model not in PRICING: return 0.0, 0.0 in_price, out_price = PRICING[model] usd = (in_tok / 1_000_000) * in_price + (out_tok / 1_000_000) * out_price return usd, usd * CNY_PER_USD def total_cny_spent(): return sum(c._value.get() for c in COST_CNY._metrics.values()) @app.route("/v1/chat/completions", methods=["POST"]) def proxy(): body = request.json model = body.get("model", "gpt-4.1") start = time.time() status = "ok" try: resp = client.chat.completions.create(**body) usage = resp.usage in_tok = usage.prompt_tokens out_tok = usage.completion_tokens except Exception as e: REQ_TOTAL.labels(model=model, status="error").inc() LATENCY.labels(model=model).observe(time.time() - start) return jsonify({"error": str(e)}), 500 elapsed = time.time() - start usd, cny = calc_cost(model, in_tok, out_tok) REQ_TOTAL.labels(model=model, status=status).inc() TOKENS_TOTAL.labels(model=model, direction="input").inc(in_tok) TOKENS_TOTAL.labels(model=model, direction="output").inc(out_tok) COST_USD.labels(model=model).inc(usd) COST_CNY.labels(model=model).inc(cny) LATENCY.labels(model=model).observe(elapsed) BUDGET_REMAINING.set(max(DAILY_BUDGET - total_cny_spent(), 0)) return jsonify(resp.model_dump()) @app.route("/metrics") def metrics(): return generate_latest(), 200, {"Content-Type": CONTENT_TYPE_LATEST} if __name__ == "__main__": # 生产环境用 gunicorn:gunicorn -w 4 -b 0.0.0.0:8000 cost_exporter:app app.run(host="0.0.0.0", port=8000)

这段代码的核心思路是:把所有调用都收口到一个代理层,这样无论你上游是 LangChain、LlamaIndex 还是直接 curl,都能拿到统一的指标。注意我特意把 COST_CNY 单独提取出来——因为国内团队对人民币数字更敏感,看板上一眼就能判断爆不爆预算。

四、Prometheus + Grafana 接入配置

Exporter 跑起来之后,下一步是让 Prometheus 抓取数据。假设你的 Exporter 部署在 10.0.0.5:8000,Prometheus 配置文件加一段 scrape job 就行:

# /etc/prometheus/prometheus.yml 追加
scrape_configs:
  - job_name: 'holysheep_cost'
    scrape_interval: 15s
    metrics_path: /metrics
    static_configs:
      - targets: ['10.0.0.5:8000']
        labels:
          env: 'production'
          region: 'cn-shanghai'

rule_files:
  - "/etc/prometheus/rules/cost_alerts.yml"
# /etc/prometheus/rules/cost_alerts.yml
groups:
- name: cost_alerts
  rules:
  - alert: HourlyCostHigh
    expr: sum(increase(holysheep_cost_cny_total[1h])) > 50
    for: 2m
    labels:
      severity: warning
    annotations:
      summary: "过去1小时 HolySheep API 支出超 ¥50,当前 ¥{{ $value }}"
  - alert: BudgetExhausted
    expr: holysheep_budget_remaining_cny < 20
    for: 1m
    labels:
      severity: critical
    annotations:
      summary: "日预算即将耗尽,仅剩 ¥{{ $value }}"

Grafana 面板我推荐配置 4 个核心图表:(1) 按模型分组的实时 QPS;(2) 累计成本 CNY/USD 双轴;(3) P50/P95/P99 延迟热力图;(4) 预算剩余进度条。最常用的 PromQL 片段我贴一段你直接用:

# Grafana 查询示例

1. 每分钟成本(CNY)

sum(rate(holysheep_cost_cny_total[5m])) by (model) * 60

2. Top 3 烧钱模型

topk(3, sum(holysheep_cost_cny_total) by (model))

3. P95 延迟

histogram_quantile(0.95, sum(rate(holysheep_latency_seconds_bucket[5m])) by (le, model) )

4. 实时预算进度(百分比)

(1 - holysheep_budget_remaining_cny / 200) * 100

五、我踩过的三个真实坑

第一是Counter 重启清零导致告警误报。Prometheus 的 Counter 进程重启后归零,increase() 函数会算出负数然后触发伪告警。解决方案