← 返回知识库
# OpenAI 只读用量/额度接口(5号 :18920)
日期:2026-11-30 · 维护:5hao-hermes · 代码:`/root/scripts/openai_usage_api.py` · 单元:`hermes-openai-usage.service`
监听:`10.0.0.5:18920`(只绑 WireGuard 内网,公网不可达)· 已登记 `service-registry` id=`openai-usage`
## 一、给外部节点(如 m4)用的最小面
只有一条路由,quota 作用域 token 只能用这条:
```
GET http://10.0.0.5:18920/quota
Authorization: Bearer <专用只读 token> # 也可 ?token=...(不推荐,会进日志)
```
返回(2026-11-30 05:36 实测):
```json
{
"ok": true,
"generated_at": "2026-11-30T05:36:10+08:00",
"currency": "USD",
"month": "2026-11",
"month_to_date_usd": 60.6125,
"today_usd": 60.1025,
"today_bucket_utc_date": "2026-11-29",
"bucket_timezone": "UTC",
"balance_usd": null,
"balance_available": false,
"cached_seconds": 60,
"note": "花费取自 OpenAI organization/costs(UTC 日桶,可能有数小时延迟);余额为人工锚点推算,非 OpenAI 直读",
"balance_note": "未设余额锚点:...credit_grants 对 secret key 403..."
}
```
其他行为(实测):无/错 token → `401`;用 quota token 打 `/usage|/keys|/summary` → `403 scope_denied`;
限频每 IP `60 次/小时`、`6 次/分钟`,超出 `429` + `Retry-After: 60`;`/health` 免鉴权。
## 二、余额的口径(事实,别改)
- OpenAI **没有余额查询 API**:`GET /v1/dashboard/billing/credit_grants` 对 secret key 返回
`403 must be made with a session key`(只认浏览器 session)。5号 的 Chrome 无 platform.openai.com 登录态,
也抓不了后台。
- 因此 `balance_usd` 用**人工锚点扣减**:`balance = 锚点余额 − 锚点之后真实花费`。
打锚:`python3 /root/scripts/openai_usage_api.py --set-balance 23.45`(把后台 Billing 页看到的数写进去,600 文件
`/root/.secrets/openai_balance_anchor.json`);查锚点:`--anchor-status`。
- 锚点未设 → `balance_usd = null`、`balance_available = false`,不编数。
- 精度:花费桶按 UTC 天切,锚点当天可能整桶计入 → 余额偏保守(偏低),适合做下限告警。
## 三、token 与作用域
| 作用域 | 文件 | 可用路由 |
|---|---|---|
| full(内部) | `/root/.secrets/openai_usage_token` | `/quota` `/usage` `/keys` `/summary` |
| quota(外部) | `/root/.secrets/openai_quota_token` | 仅 `/quota` |
quota token 缺失时服务启动自动生成(`oq_...`,600)。轮换:删文件 → `systemctl restart hermes-openai-usage`。
管理密钥 `/root/.secrets/openai_admin.key` 只在服务进程内读,任何路由都不回显、不外发。
## 四、运维
```bash
systemctl status hermes-openai-usage
journalctl -u hermes-openai-usage -n 50 --no-pager
curl -s http://10.0.0.5:18920/health
```