inspect.py
5.2 KB| 1 | #!/usr/bin/env python3 |
| 2 | # -*- coding: utf-8 -*- |
| 3 | """魔搭(ModelScope) API-Inference 模型巡检 |
| 4 | |
| 5 | 流程(对应 SKILL.md 第二节):验钥匙 -> 拉目录 -> 逐个最小请求实测 -> 三色清单 + 快照映射建议。 |
| 6 | |
| 7 | 用法: |
| 8 | export MODELSCOPE_API_TOKEN=ms-xxxxxxxx |
| 9 | python inspect.py # 全量巡检 |
| 10 | python inspect.py --model deepseek-ai/DeepSeek-V4.1-Flash # 只测指定 id(可重复传) |
| 11 | |
| 12 | 纪律: 一次跑完就停;429 是限流不是死档;不跨系列替换,映射只做同系列快照。 |
| 13 | """ |
| 14 | import argparse |
| 15 | import json |
| 16 | import os |
| 17 | import re |
| 18 | import sys |
| 19 | import time |
| 20 | import urllib.error |
| 21 | import urllib.request |
| 22 | |
| 23 | BASE = "https://api-inference.modelscope.cn/v1" |
| 24 | UA = "modelscope-inspect/0.1" |
| 25 | # 验钥匙用主流系模型即可;带日期快照后缀的在役概率高 |
| 26 | KEYCHECK_RE = re.compile(r"(Qwen|DeepSeek|GLM)", re.I) |
| 27 | SNAPSHOT_RE = re.compile(r"-\d{4}(?:-\d{4})?$") |
| 28 | |
| 29 | |
| 30 | def call(path, token, payload=None, timeout=30): |
| 31 | data = json.dumps(payload).encode("utf-8") if payload is not None else None |
| 32 | req = urllib.request.Request( |
| 33 | BASE + path, |
| 34 | data=data, |
| 35 | method="POST" if data is not None else "GET", |
| 36 | headers={ |
| 37 | "Authorization": "Bearer " + token, |
| 38 | "Content-Type": "application/json", |
| 39 | "User-Agent": UA, |
| 40 | }, |
| 41 | ) |
| 42 | try: |
| 43 | with urllib.request.urlopen(req, timeout=timeout) as resp: |
| 44 | return resp.status, resp.read().decode("utf-8", "replace") |
| 45 | except urllib.error.HTTPError as e: |
| 46 | return e.code, e.read().decode("utf-8", "replace") |
| 47 | except Exception as e: # 网络层问题,单独标出 |
| 48 | return -1, "%s: %s" % (type(e).__name__, e) |
| 49 | |
| 50 | |
| 51 | def err_text(body): |
| 52 | try: |
| 53 | j = json.loads(body) |
| 54 | return (j.get("errors") or [{}])[0].get("message") or j.get("message") or body[:120] |
| 55 | except Exception: |
| 56 | return body[:120] |
| 57 | |
| 58 | |
| 59 | def classify(status, body, key_ok): |
| 60 | """-> (label, note)。label: OK / DEAD / AUTH / NA / RATE / NET""" |
| 61 | if status == 200: |
| 62 | return "OK", "" |
| 63 | if status == -1: |
| 64 | return "NET", err_text(body) |
| 65 | low = body.lower() |
| 66 | if status == 400 and ("no provider supported" in low or "unsupported model" in low or "model not found" in low): |
| 67 | return "DEAD", "%d %s" % (status, err_text(body)) |
| 68 | if status == 401: |
| 69 | # 钥匙已验证通过后再见 401,多半是第三方托管模型自己的令牌问题 |
| 70 | return ("AUTH" if key_ok else "DEAD"), "%d %s" % (status, err_text(body)) |
| 71 | if status == 403: |
| 72 | return "NA", "%d %s" % (status, err_text(body)) |
| 73 | if status == 429: |
| 74 | return "RATE", "%d %s" % (status, err_text(body)) |
| 75 | return "ERR", "%d %s" % (status, err_text(body)) |
| 76 | |
| 77 | |
| 78 | def main(): |
| 79 | ap = argparse.ArgumentParser(description="魔搭 API-Inference 模型巡检") |
| 80 | ap.add_argument("--model", action="append", help="只测指定模型 id,可重复") |
| 81 | ap.add_argument("--interval", type=float, default=0.3, help="请求间隔秒数,默认 0.3") |
| 82 | ap.add_argument("--max-tokens", type=int, default=8) |
| 83 | args = ap.parse_args() |
| 84 | |
| 85 | token = os.environ.get("MODELSCOPE_API_TOKEN", "").strip() |
| 86 | if not token: |
| 87 | sys.exit("缺少环境变量 MODELSCOPE_API_TOKEN(modelscope.cn 访问令牌页生成,ms- 开头)") |
| 88 | |
| 89 | # 1. 拉目录 |
| 90 | status, body = call("/models", token) |
| 91 | if status != 200: |
| 92 | sys.exit("拉取模型目录失败: %d %s" % (status, err_text(body))) |
| 93 | ids = [m["id"] for m in json.loads(body).get("data", []) if m.get("id")] |
| 94 | if args.model: |
| 95 | ids = args.model |
| 96 | |
| 97 | # 2. 验钥匙:挑目录里第一个主流系 id 发最小请求 |
| 98 | key_ok = False |
| 99 | for cand in [i for i in ids if KEYCHECK_RE.search(i)]: |
| 100 | st, bd = call("/chat/completions", token, {"model": cand, "messages": [{"role": "user", "content": "回复:ok"}], "max_tokens": args.max_tokens, "stream": False}) |
| 101 | if st == 200: |
| 102 | key_ok = True |
| 103 | print("[key] OK(%s)" % cand) |
| 104 | break |
| 105 | if st == 401: |
| 106 | sys.exit("钥匙无效或过期(401 %s),请到 modelscope.cn 访问令牌页重新生成" % err_text(bd)) |
| 107 | time.sleep(args.interval) |
| 108 | if not key_ok: |
| 109 | print("[key] 警告:主流模型没有一个 200,后续 401 无法区分是钥匙还是第三方令牌") |
| 110 | |
| 111 | # 3. 逐个实测 |
| 112 | rows = {} |
| 113 | for mid in ids: |
| 114 | st, bd = call("/chat/completions", token, {"model": mid, "messages": [{"role": "user", "content": "回复:ok"}], "max_tokens": args.max_tokens, "stream": False}) |
| 115 | label, note = classify(st, bd, key_ok) |
| 116 | rows[mid] = (label, note) |
| 117 | print("[%s] %s %s" % (label, mid, note)) |
| 118 | time.sleep(args.interval) |
| 119 | |
| 120 | # 4. 汇总 + 同系列快照映射建议(只在死亡项上做) |
| 121 | ok = [m for m, (l, _) in rows.items() if l == "OK"] |
| 122 | dead = [m for m, (l, _) in rows.items() if l == "DEAD"] |
| 123 | print("\n== 汇总 ==") |
| 124 | print("可用 %d / 在册 %d" % (len(ok), len(rows))) |
| 125 | for m in ok: |
| 126 | print(" [OK] " + m) |
| 127 | for m in dead: |
| 128 | base = SNAPSHOT_RE.sub("", m) |
| 129 | hit = [o for o in ok if o.startswith(base + "-")] |
| 130 | tip = (" -> 建议映射同系列快照: " + hit[0]) if hit else "(无同系列活快照,保持死亡不替换)" |
| 131 | print(" [DEAD] %s%s" % (m, tip)) |
| 132 | |
| 133 | |
| 134 | if __name__ == "__main__": |
| 135 | main() |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

