Files
SupplierSystem/tools/design-consistency/check-ai-cost.py
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

148 lines
6.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AI 成本 / 计量点闸门(2026-09-29 建立)
**背景(实测,可复现)**:台账 R2-D 写「解析路径**零 token 计量、零配额、零租户归属**
(唯一控制是每 IP 60 次/分 + 余额告警)」。本闸门建立时实测更精确:
`grep -rln "prompt_tokens\\|total_tokens" server/src` ⇒ **仅 4 个文件命中**,
且 `arkService.ts`(统一出口)与 `openaiCompatibleLlmAdapter.ts`(多供应商出口)**都不记录 usage**。
⇒ 结论比台账写的更硬:**不是"没建模",是连原始数据都没有** —— 没有 token 数就算不出每单成本,
也算不出"100 个客户一个月花多少钱"这个 FDE 现场必被问到的问题。
本闸门读登记表 §三,并做四件事:
1. §三 每个计量点必须给「文件:行」且文件真实存在;
2. **每个登记在案的 LLM 出口(§二 中脱敏列 ≠ 非大模型出口)至少要有一个计量点** —— 否则 FAIL;
3. 「是否落库 = 否」的计量点**不计入覆盖**(进程内日志核算不了);
4. 代码侧扫"疑似计量但没登记"的地方(`total_tokens`/`usage` 等),出现即提示登记 ——
防"代码里偷偷加了计量、表里没记"。
用法:python3 tools/design-consistency/check-ai-cost.py [-v]
退出码:0 = 计量点登记完备;1 = 缺计量点/出口无计量;2 = 登记表缺失。
"""
import io
import os
import re
import subprocess
import sys
ROOT = os.environ.get("DC_ROOT") or os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
REG = "docs/design/20260929-AI门槛与计量登记表.md"
VERBOSE = "-v" in sys.argv
EXEMPT_MARK = "经审计非大模型出口"
PENDING = "待补"
USAGE_PAT = re.compile(r"prompt_tokens|completion_tokens|total_tokens|\busage\b")
def parse_md_table(text, first_col_name):
lines = text.split("\n")
for i, l in enumerate(lines):
if not l.strip().startswith("|"):
continue
hdr = [c.strip() for c in l.strip().strip("|").split("|")]
if not hdr or hdr[0] != first_col_name:
continue
if i + 1 >= len(lines) or not re.match(r"^\|[\s\-:|]+\|?\s*$", lines[i + 1] or ""):
continue
rows, j = [], i + 2
while j < len(lines) and lines[j].strip().startswith("|"):
rows.append([c.strip() for c in lines[j].strip().strip("|").split("|")])
j += 1
return hdr, rows
return None, []
def main():
path = os.path.join(ROOT, REG)
if not os.path.exists(path):
print("❌ 登记表不存在:%s" % REG)
return 2
text = io.open(path, encoding="utf-8").read()
_, exit_rows = parse_md_table(text, "出口 ID")
hdr_m, mt_rows = parse_md_table(text, "计量点 ID")
if not exit_rows or not mt_rows:
print("❌ 登记表里缺少 §二(出口 ID 表)或 §三(计量点 ID 表)")
return 2
problems = []
# 出口侧:哪些是 LLM 出口
llm_exits = []
for cells in exit_rows:
if len(cells) < 5:
continue
eid, _loc, _dom, _feats, redact = [c.strip() for c in cells[:5]]
if redact != EXEMPT_MARK:
llm_exits.append(eid)
# 计量点侧
landed = 0
covered_exits = set()
print("登记:LLM 出口 %d 个 | 计量点 %d 行" % (len(llm_exits), len(mt_rows)))
for cells in mt_rows:
if len(cells) < 5:
problems.append(("计量点行字段数不足", " | ".join(cells)[:70]))
continue
mid, loc, what, stored, tenant = [c.strip() for c in cells[:5]]
if PENDING in loc or PENDING in what:
problems.append(("%s 仍是「待补」" % mid,
"没有计量点 = 算不出每单成本(FDE 现场必被问)"))
print(" ⚠️ %s 文件:行=%s 落库=%s 租户归属=%s" % (mid, loc, stored, tenant))
continue
m = re.match(r"`?([^`:\s]+)`?:(\d+)", loc)
if not m:
problems.append(("%s 的定位格式不对(应形如 `路径:行号`)" % mid, loc))
continue
rel = m.group(1)
if not os.path.exists(os.path.join(ROOT, rel)):
problems.append(("%s 登记的文件不存在" % mid, rel))
continue
if PENDING in tenant:
problems.append(("%s 未登记租户归属列" % mid, tenant))
if stored in ("否", "", "-", "—"):
problems.append(("%s 未落库(进程内日志核算不了,不计入覆盖)" % mid, what))
print(" ⚠️ %s %s 未落库" % (mid, rel))
else:
landed += 1
covered_exits.add(mid)
print(" ✅ %s %s:%s 落库=%s 租户列=%s"
% (mid, rel, m.group(2), stored, tenant))
if landed == 0:
problems.append(("没有任何一个已落库的计量点", "⇒ %d 个 LLM 出口全部无计量" % len(llm_exits)))
# 代码侧"疑似计量未登记"
p = subprocess.run(["grep", "-rlE", USAGE_PAT.pattern, "--include=*.ts",
os.path.join(ROOT, "server/src")], capture_output=True, text=True)
hit_files = sorted({os.path.relpath(x.strip(), ROOT) for x in p.stdout.split("\n")
if x.strip() and "node_modules" not in x})
registered_files = {m.group(1) for c in mt_rows if len(c) >= 2
for m in [re.match(r"`?([^`:\s]+)`?:(\d+)", c[1].strip())] if m}
unregistered = [f for f in hit_files if f not in registered_files]
if VERBOSE:
print(" 代码侧含 usage 的文件:%s" % ("、".join(hit_files) or "(无)"))
print("\n已落库计量点 %d 个 | 覆盖出口 %d/%d | 代码侧疑似计量文件 %d 个"
% (landed, len(covered_exits), len(llm_exits), len(hit_files)))
if problems:
print("\n🔴 %d 处不满足:" % len(problems))
for kind, detail in problems[:30]:
print(" - [%s] %s" % (kind, detail))
if unregistered:
print("\nℹ️ 代码侧这些文件出现 token/usage 字样,但登记表没有对应计量点(需人工确认是否真计量):")
for f in unregistered[:12]:
print(" - %s" % f)
print("\n处置分两层(别混):")
print(" ① **登记层**(本闸门管):把真实计量点逐条登记;没有的写「待补」+ 负责人;")
print(" ② **实现层**(需批准,属产品代码):在出口统一记录 usage 并落库到带 `branch_code` 的表 ——")
print(" 这是「能算出每单成本」的前提,也是 FDE 报价与容量规划的前提。")
return 1
print("✅ 每个 LLM 出口都有已落库、可归属租户的计量点")
return 0
if __name__ == "__main__":
sys.exit(main())