File size: 17,308 Bytes
1b2c3dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
#!/usr/bin/env python3
"""跑分:每个模型、每种设置一个日志文件,只追加。判分在 score.py,这里不判。

用法:
  run_eval.py <questions.jsonl> <out_dir> --model <模型名> --setting closed|open --channel api|claude-cli|codex-cli
              [--base-env X --key-env Y]   # 甲通道:地址和钥匙只从环境变量读,钥匙不落盘、不打印
              [--slot s2]                  # 乙通道 claude-cli:ccpool 的账号槽
              [--workers 6]

规则只有一条(与预注册对应):**每道题只取模型的第一份完整返回,落一行 final,之后不再调这道题。**
- 没拿到完整返回的请求(超时、断线、接口报错、限流、欠费、命令行异常退出)不是模型的作答:记一行 noresp,重发。
- 同一道题连续 5 次拿不到返回:整轮停下,交人看。已经落了 final 的题不受影响;恢复后只补没有 final 的题。
- 每次请求互不相干(没有会话记忆),所以只有产生 final 的那一次请求里的工具调用算数。

日志文件 <模型>.<设置>.jsonl 里有四种行:
  sent             每次请求发出之前写            {"ev":"sent","id"}
  noresp           这次请求没拿到返回            {"ev":"noresp","id","error"}
  unknown_outcome  续跑时发现上次有一个请求发出后既没有 noresp 也没有 final(进程死在中间):
                   那次的结果不明,记下来再重发;final 行和分数表都会报这样的次数
  final            这道题的最终结果,一题一行;final 之后这道题不许再有任何记录
同名 .manifest.json 记这一栏的固定配置;续跑只认它,不重新探测。
文件末尾写到一半的残行截掉;中间有坏行、不认识的行、和 manifest 对不上的 final,都停。
"""
import argparse
import concurrent.futures as cf
import hashlib
import json
import os
import pathlib
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.request

sys.path.insert(0, str(pathlib.Path(__file__).parent))
import prompts  # noqa: E402

MAX_TOKENS = 8192
TIMEOUT = 300
MAX_NORESP = 5            # 同一题连续这么多次拿不到返回,整轮停
PROBE = 'Reply with exactly: {"ok": true}'
CODEX_EFFORT = "medium"
CODEX_OFF = ["apps", "browser_use", "browser_use_external", "browser_use_full_cdp_access", "computer_use",
             "image_generation", "in_app_browser", "in_app_local_automation", "multi_agent", "plugins",
             "remote_plugin", "skill_search", "shell_tool", "unified_exec", "unified_exec_tty", "view_image",
             "hooks", "goals", "sleep_tool", "tool_suggest", "worktrees"]
# codex 事件流里的事件项:这三种不是工具(回答、思考、计划清单),其余一律算工具
CODEX_NOT_TOOL = ("agent_message", "reasoning", "todo_list")
CLAUDE_TOOL_BLOCKS = ("tool_use", "server_tool_use", "mcp_tool_use")
IDENTITY = ("model_requested", "setting", "channel", "questions_sha256", "prompts_sha256", "endpoint", "temperature")


def sha(path):
    return hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest()


def user_prompt(q, setting):
    if setting == "closed":
        return prompts.CLOSED.format(library=q["library"], package=q["package"],
                                     part_a=q["part_a"], part_b=q["part_b"])
    return prompts.OPEN.format(library=q["library"], package=q["package"],
                               part_a=q["part_a"], part_b=q["part_b"],
                               table_a=prompts.table(q["pins_a"]), table_b=prompts.table(q["pins_b"]))


def noresp(error):
    return {"status": "noresp", "error": str(error)[:500]}


# ── 甲通道:OpenAI 兼容接口 ──────────────────────────────────────────────

def http_post(url, key, body):
    req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST",
                                 headers={"Content-Type": "application/json", "Authorization": f"Bearer {key}"})
    with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
        return json.loads(r.read())


def api_once(cfg, user):
    body = {"model": cfg["model"], "max_tokens": MAX_TOKENS, "stream": False,
            "messages": [{"role": "system", "content": prompts.SYSTEM}, {"role": "user", "content": user}]}
    if cfg["temperature"] is not None:
        body["temperature"] = cfg["temperature"]
    try:
        resp = http_post(cfg["url"], cfg["key"], body)
    except urllib.error.HTTPError as e:
        return noresp(f"HTTP {e.code}: " + e.read().decode("utf-8", "replace")[:400])
    except Exception as e:  # 超时、断线、返回的不是 JSON
        return noresp(f"{type(e).__name__}: {e}")
    ch = resp.get("choices") if isinstance(resp, dict) else None
    if not (isinstance(ch, list) and ch and isinstance(ch[0], dict) and isinstance(ch[0].get("message"), dict)):
        return noresp("响应里没有 choices[0].message: " + json.dumps(resp, ensure_ascii=False)[:400])
    msg = ch[0]["message"]
    return {"status": "ok", "tool_calls": len(msg.get("tool_calls") or []), "model_returned": resp.get("model"),
            "provider": resp.get("provider"),     # 聚合接口会回实际托管方;直连接口没有这个字段
            "finish_reason": ch[0].get("finish_reason"), "content": msg.get("content"), "usage": resp.get("usage")}


def api_probe(cfg):
    """用一句与考题无关的话定下这一栏带不带温度参数。探不通就停。返回 0 或 None。"""
    for temp in (0, None):
        r = api_once(dict(cfg, temperature=temp), PROBE)
        if r["status"] == "ok":
            return temp
        if not (temp == 0 and "temperature" in r["error"].lower()):
            sys.exit(f"停:开跑前的探测没通(没有落任何一行):{r['error']}")
    sys.exit("停:探测失败")


# ── 乙通道:官方命令行的无工具模式。一次进程 = 一次请求 ───────────────────

def run_cli(cmd, cfg, **kw):
    try:
        p = subprocess.run(cmd, capture_output=True, text=True, timeout=TIMEOUT, cwd=cfg["empty"], **kw)
        return p.stdout, p.stderr, p.returncode
    except subprocess.TimeoutExpired:
        return "", "超时", None


def events(out):
    for line in out.splitlines():
        try:
            ev = json.loads(line)
        except Exception:
            continue
        if isinstance(ev, dict):
            yield ev


def claude_once(cfg, user):
    sh = ('eval "$(ccpool use "$SLOT" 2>/dev/null)"; exec "$HOME/.claude/bin/claude-network" -p '
          '--system-prompt "$SYS" --tools "" --setting-sources "" --strict-mcp-config '
          '--no-session-persistence --model "$MODEL" --output-format stream-json --verbose')
    env = dict(os.environ, SLOT=cfg["slot"], SYS=prompts.SYSTEM, MODEL=cfg["model"])
    out, err, code = run_cli(["zsh", "-c", sh], cfg, input=user, env=env)
    tool_ids, result = set(), None
    for n, ev in enumerate(events(out)):
        if ev.get("type") == "assistant" and isinstance(ev.get("message"), dict):
            for k, blk in enumerate(ev["message"].get("content") or []):
                if isinstance(blk, dict) and blk.get("type") in CLAUDE_TOOL_BLOCKS:
                    tool_ids.add(blk.get("id") or f"{n}.{k}")
        elif ev.get("type") == "result":
            result = ev
    if (code == 0 and result is not None and result.get("is_error") is False
            and result.get("subtype") == "success" and isinstance(result.get("result"), str)):
        mu = result.get("modelUsage")
        return {"status": "ok", "tool_calls": len(tool_ids),
                "model_returned": ",".join(sorted(mu)) if isinstance(mu, dict) else None,
                "finish_reason": result.get("stop_reason"), "content": result["result"], "usage": result.get("usage")}
    return noresp(f"退出码 {code};" + (json.dumps(result, ensure_ascii=False)[:300] if result else "没有 result 事件")
                  + " " + (err or "")[-200:])


def codex_once(cfg, user):
    cmd = ["codex", "exec", "--skip-git-repo-check", "--ephemeral", "-s", "read-only", "--json",
           "-m", cfg["model"], "-c", f"model_reasoning_effort={CODEX_EFFORT}", "-c", "project_doc_max_bytes=0",
           "-c", 'web_search="disabled"', "-c", "mcp_servers={}", "-C", cfg["empty"]]
    for f in CODEX_OFF:
        cmd += ["--disable", f]
    cmd.append(prompts.SYSTEM + "\n\n" + user)
    out, err, code = run_cli(cmd, cfg, stdin=subprocess.DEVNULL)
    text, usage, done, bad, tool_ids, kinds = None, None, False, "", set(), {}
    for n, ev in enumerate(events(out)):
        t, item = ev.get("type"), ev.get("item")
        if t in ("item.started", "item.updated", "item.completed") and isinstance(item, dict):
            kind = str(item.get("type"))
            if t == "item.completed":
                kinds[kind] = kinds.get(kind, 0) + 1
            if kind == "agent_message":
                if t == "item.completed" and isinstance(item.get("text"), str):
                    text = item["text"]
            elif kind not in CODEX_NOT_TOOL:
                tool_ids.add(item.get("id") or f"line{n}")      # 开始了没完成的也算
        elif t == "turn.completed":
            done, usage = True, ev.get("usage")
        elif t in ("error", "turn.failed"):
            bad = json.dumps(ev, ensure_ascii=False)[:300]
    if code == 0 and done and not bad and text is not None:
        return {"status": "ok", "tool_calls": len(tool_ids), "item_types": kinds, "model_returned": None,
                "finish_reason": None, "content": text, "usage": usage}
    return noresp(f"退出码 {code};{bad} " + (err or "")[-200:])


ONCE = {"api": api_once, "claude-cli": claude_once, "codex-cli": codex_once}


# ── 日志与续跑 ───────────────────────────────────────────────────────────

def load_state(path, man=None):
    """回放日志。返回 {题号: {"final", "noresp", "unknown", "open"}}。末尾残行截掉;别的任何不对都停。"""
    state = {}
    if not path.exists():
        return state
    raw = path.read_bytes()
    if raw and not raw.endswith(b"\n"):
        cut = raw.rfind(b"\n") + 1
        with open(path, "r+b") as f:
            f.truncate(cut)
        raw = raw[:cut]
    for n, line in enumerate(raw.decode("utf-8").splitlines(), 1):
        try:
            r = json.loads(line)
            ev, qid = r["ev"], r["id"]
        except Exception:
            sys.exit(f"停:{path.name} 第 {n} 行不是完整的记录。先人工看这个文件,不续跑。")
        if not isinstance(qid, str) or ev not in ("sent", "noresp", "unknown_outcome", "final"):
            sys.exit(f"停:{path.name} 第 {n} 行是不认识的记录 {ev!r}。")
        s = state.setdefault(qid, {"final": False, "noresp": 0, "unknown": 0, "open": False})
        if s["final"]:
            sys.exit(f"停:{path.name} 第 {n} 行:{qid} 已经有 final,之后不该再有记录。")
        if ev == "sent":
            s["open"] = True
        elif ev in ("noresp", "unknown_outcome"):
            s["open"] = False
            s["noresp" if ev == "noresp" else "unknown"] += 1
        else:
            if man is not None:
                for k in IDENTITY:
                    if r.get(k) != man.get(k):
                        sys.exit(f"停:{path.name} 第 {n} 行的 {k} 和 manifest 不一致。")
            s["final"], s["open"] = True, False
    return state


def load_done(path, man=None):
    return {k for k, s in load_state(path, man).items() if s["final"]}


def run(qs, out_path, cfg, setting, base_row, workers, once, sleep=time.sleep, man=None):
    """可单独测试的主循环。返回 (这次新落的 final 行数, 停跑原因或 None)。"""
    state = load_state(out_path, man)
    lock, stop = threading.Lock(), threading.Event()
    box = {"new": 0, "halt": None}
    out = open(out_path, "a")

    def write(rec):                      # 调用方已经拿着 lock
        out.write(json.dumps(rec, ensure_ascii=False) + "\n")
        out.flush()
        os.fsync(out.fileno())

    def now():
        return time.strftime("%Y-%m-%dT%H:%M:%S%z")

    def work(q):
        s = state.get(q["id"], {"final": False, "noresp": 0, "unknown": 0, "open": False})
        if s["final"]:
            return
        user, misses, total_noresp, unknown = user_prompt(q, setting), 0, s["noresp"], s["unknown"]
        if s["open"]:                    # 上次进程死在这道题的一次请求中间:结果不明,记下来
            unknown += 1
            with lock:
                write({"ev": "unknown_outcome", "id": q["id"], "at": now()})
        while True:
            with lock:                   # 放行和停跑用同一把锁:停了就不再发新请求
                if stop.is_set():
                    return
                write({"ev": "sent", "id": q["id"], "at": now()})
            t0 = time.time()
            try:
                r = once(cfg, user)
            except Exception as e:       # 命令行起不来、返回的形状不认识:都当没拿到返回
                r = noresp(f"脚本异常 {type(e).__name__}: {e}")
            if r["status"] == "ok":
                r.pop("status")
                with lock:
                    write(dict(base_row, ev="final", id=q["id"], requests_without_response=total_noresp,
                               requests_with_unknown_outcome=unknown, seconds=round(time.time() - t0, 1),
                               called_at=now(), **r))
                    box["new"] += 1
                return
            misses += 1
            total_noresp += 1
            with lock:
                if misses >= MAX_NORESP:
                    stop.set()           # 先停,再写日志
                    box["halt"] = box["halt"] or f"{q['id']} 连续 {misses} 次拿不到返回,最后一次:{r['error']}"
                write({"ev": "noresp", "id": q["id"], "error": r["error"], "at": now()})
                if stop.is_set():
                    return
            sleep(min(60, 5 * 2 ** (misses - 1)))

    with cf.ThreadPoolExecutor(workers) as ex:
        for f in [ex.submit(work, q) for q in qs]:
            f.result()
    out.close()
    return box["new"], box["halt"]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("questions")
    ap.add_argument("out_dir")
    ap.add_argument("--model", required=True)
    ap.add_argument("--setting", required=True, choices=["closed", "open"])
    ap.add_argument("--channel", required=True, choices=list(ONCE))
    ap.add_argument("--base-env", default="")
    ap.add_argument("--key-env", default="")
    ap.add_argument("--slot", default="s2")
    ap.add_argument("--workers", type=int, default=6)
    a = ap.parse_args()

    qs = [json.loads(l) for l in open(a.questions)]
    out_dir = pathlib.Path(a.out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    stem = f"{a.model.replace('/', '__').replace(':', '_')}.{a.setting}"
    out_path, man_path = out_dir / f"{stem}.jsonl", out_dir / f"{stem}.manifest.json"

    cfg = {"model": a.model, "slot": a.slot, "temperature": None}
    man = {"model_requested": a.model, "setting": a.setting, "channel": a.channel,
           "questions_sha256": sha(a.questions), "n_questions": len(qs),
           "prompts_sha256": sha(pathlib.Path(__file__).parent / "prompts.py"),
           "max_noresp": MAX_NORESP, "timeout_seconds": TIMEOUT}
    if a.channel == "api":
        base = os.environ[a.base_env].rstrip("/")
        cfg.update(url=base + "/chat/completions", key=os.environ[a.key_env])
        man.update(endpoint=base, max_tokens=MAX_TOKENS)
    else:
        cfg["empty"] = tempfile.mkdtemp(prefix="pcb-empty-")
        man.update(endpoint=a.channel, max_tokens=None)
        if a.channel == "codex-cli":
            man.update(codex_effort=CODEX_EFFORT, codex_disabled=CODEX_OFF)

    if man_path.exists():
        old = json.loads(man_path.read_text())
        diff = {k: (old.get(k), v) for k, v in man.items() if old.get(k) != v}
        if diff:
            sys.exit(f"停:{man_path.name} 记的配置和这次不一样 {diff}。不是同一栏,不续跑。")
        man = old
    else:
        if out_path.exists():
            sys.exit(f"停:{out_path.name} 在,但它的 manifest 不在。")
        man["temperature"] = api_probe(cfg) if a.channel == "api" else None
        man["created_at"] = time.strftime("%Y-%m-%dT%H:%M:%S%z")
        man_path.write_text(json.dumps(man, ensure_ascii=False, indent=1))
    cfg["temperature"] = man["temperature"]

    new, halt = run(qs, out_path, cfg, a.setting, {k: man[k] for k in IDENTITY}, a.workers, ONCE[a.channel], man=man)
    done = len(load_done(out_path, man))
    print(f"{a.model} · {a.setting} · {a.channel} · 这次落 {new} 题 · 累计 {done}/{len(qs)} · 温度 {man['temperature']}"
          + (f" · 已停:{halt}" if halt else ""))
    if halt:
        sys.exit(2)


if __name__ == "__main__":
    main()