test: 電腦操作量測每題從乾淨的狀態開始,並記下每題花的 token
- 每輪、每題開始前清掉對話、工作紀錄和記憶(沒加 --keep-skills 也清掉技能):之前上一題學到的答案會帶到下一題,數字不能用 - --meter:經過本機轉送點,算每題的請求數、輸入/輸出/快取/推理 token 和截圖張數,並存下每題第一個請求 - --label;量測用的 Bot 電腦還不存在時先建好 - 改搜尋引擎題:前置清掉 Chromium 政策檔;檢查也看桌面 Chromium 自己的設定檔和每個 Bot 的設定檔 - 讀對話檔的新位置 data/chats/bot-<id>.json Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha4mzWbjJAWAsDVuBun
This commit is contained in:
parent
3f46911ba4
commit
1fd1d539b4
|
|
@ -13,6 +13,112 @@ own (cloudbox.rs own_volume), and a data folder that is a copy, not the real one
|
||||||
--out results.json [--tasks T1,T4] [--runs 1]
|
--out results.json [--tasks T1,T4] [--runs 1]
|
||||||
"""
|
"""
|
||||||
import argparse, json, os, re, shutil, subprocess, sys, time
|
import argparse, json, os, re, shutil, subprocess, sys, time
|
||||||
|
import http.client, http.server, threading, urllib.parse
|
||||||
|
|
||||||
|
|
||||||
|
class Meter:
|
||||||
|
"""A pass-through to the model service that counts what each task cost: requests, tokens in
|
||||||
|
and out (cached and reasoning too), pictures sent, request bytes. AnyBot keeps no usage of its
|
||||||
|
own for OpenAI-style services, so the bot's provider points here (--meter); streamed requests
|
||||||
|
are asked to report their usage (stream_options.include_usage)."""
|
||||||
|
|
||||||
|
def __init__(self, upstream):
|
||||||
|
u = urllib.parse.urlparse(upstream)
|
||||||
|
self.scheme, self.host, self.base = u.scheme, u.netloc, u.path.rstrip("/")
|
||||||
|
self.lock = threading.Lock()
|
||||||
|
self.reset()
|
||||||
|
|
||||||
|
def reset(self, dump=""):
|
||||||
|
with self.lock:
|
||||||
|
self.stats = {"requests": 0, "tokens_in": 0, "tokens_out": 0, "cached_in": 0, "reasoning": 0, "images": 0, "req_bytes": 0}
|
||||||
|
# The task's first request is kept here (what a call is made of: instructions, tools, chat).
|
||||||
|
self.dump = dump
|
||||||
|
|
||||||
|
def take(self):
|
||||||
|
with self.lock:
|
||||||
|
return dict(self.stats)
|
||||||
|
|
||||||
|
def add(self, **kw):
|
||||||
|
with self.lock:
|
||||||
|
for k, v in kw.items():
|
||||||
|
self.stats[k] = self.stats.get(k, 0) + (v or 0)
|
||||||
|
|
||||||
|
def usage(self, u):
|
||||||
|
if not isinstance(u, dict):
|
||||||
|
return
|
||||||
|
self.add(tokens_in=u.get("prompt_tokens") or u.get("input_tokens"), tokens_out=u.get("completion_tokens") or u.get("output_tokens"),
|
||||||
|
cached_in=(u.get("prompt_tokens_details") or {}).get("cached_tokens"), reasoning=(u.get("completion_tokens_details") or {}).get("reasoning_tokens"))
|
||||||
|
|
||||||
|
def start(self):
|
||||||
|
meter = self
|
||||||
|
|
||||||
|
class H(http.server.BaseHTTPRequestHandler):
|
||||||
|
def log_message(self, *a):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def forward(self, method):
|
||||||
|
body = self.rfile.read(int(self.headers.get("Content-Length") or 0)) if method == "POST" else b""
|
||||||
|
if body:
|
||||||
|
try:
|
||||||
|
j = json.loads(body)
|
||||||
|
if j.get("stream"):
|
||||||
|
j.setdefault("stream_options", {})["include_usage"] = True
|
||||||
|
pics = sum(1 for m in j.get("messages") or [] for c in (m.get("content") if isinstance(m.get("content"), list) else []) if isinstance(c, dict) and c.get("type") in ("image_url", "input_image", "image"))
|
||||||
|
body = json.dumps(j).encode()
|
||||||
|
meter.add(requests=1, images=pics, req_bytes=len(body))
|
||||||
|
with meter.lock:
|
||||||
|
dump, meter.dump = meter.dump, ""
|
||||||
|
if dump:
|
||||||
|
open(dump, "wb").write(body)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
path = meter.base + self.path[len("/v1"):] if self.path.startswith("/v1") else self.path
|
||||||
|
conn = (http.client.HTTPSConnection if meter.scheme == "https" else http.client.HTTPConnection)(meter.host, timeout=900)
|
||||||
|
headers = {k: v for k, v in self.headers.items() if k.lower() not in ("host", "content-length", "accept-encoding", "connection")}
|
||||||
|
headers["Accept-Encoding"] = "identity"
|
||||||
|
conn.request(method, path, body=body or None, headers=headers)
|
||||||
|
r = conn.getresponse()
|
||||||
|
self.send_response(r.status)
|
||||||
|
for k, v in r.getheaders():
|
||||||
|
if k.lower() not in ("transfer-encoding", "content-length", "connection", "content-encoding"):
|
||||||
|
self.send_header(k, v)
|
||||||
|
self.send_header("Connection", "close")
|
||||||
|
self.end_headers()
|
||||||
|
buf, whole = b"", b""
|
||||||
|
while True:
|
||||||
|
chunk = r.read1(65536) if hasattr(r, "read1") else r.read(65536)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
self.wfile.write(chunk)
|
||||||
|
self.wfile.flush()
|
||||||
|
except OSError:
|
||||||
|
break
|
||||||
|
buf += chunk
|
||||||
|
whole += chunk if len(whole) < 4_000_000 else b""
|
||||||
|
while b"\n" in buf:
|
||||||
|
line, buf = buf.split(b"\n", 1)
|
||||||
|
if line.startswith(b"data:") and b'"usage"' in line:
|
||||||
|
try:
|
||||||
|
meter.usage(json.loads(line[5:].strip()).get("usage"))
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
if not whole.lstrip().startswith(b"data:") and b'"usage"' in whole:
|
||||||
|
try:
|
||||||
|
meter.usage(json.loads(whole).get("usage"))
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
conn.close()
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
self.forward("POST")
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
self.forward("GET")
|
||||||
|
|
||||||
|
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), H)
|
||||||
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||||
|
return srv.server_address[1]
|
||||||
|
|
||||||
BOX = os.environ.get("ANYBOT_BOX_NAME", "")
|
BOX = os.environ.get("ANYBOT_BOX_NAME", "")
|
||||||
VOL = os.environ.get("ANYBOT_BOX_VOLUME", "")
|
VOL = os.environ.get("ANYBOT_BOX_VOLUME", "")
|
||||||
|
|
@ -81,14 +187,17 @@ TASKS = [
|
||||||
"check": lambda dh, ans: "7006652" in digits(ans) and dx("pgrep -x galculator", dh)[0] == 0},
|
"check": lambda dh, ans: "7006652" in digits(ans) and dx("pgrep -x galculator", dh)[0] == 0},
|
||||||
{"id": "T3", "route": "screen-or-browser", "name": "Chromium 預設搜尋引擎",
|
{"id": "T3", "route": "screen-or-browser", "name": "Chromium 預設搜尋引擎",
|
||||||
# Back to Chromium's own default (an earlier run may have set Bing): browser closed, the
|
# Back to Chromium's own default (an earlier run may have set Bing): browser closed, the
|
||||||
# saved choice removed from its preferences.
|
# saved choice removed from its preferences, and no policy file forcing one (a bot once
|
||||||
"setup": "pkill -f '^/usr/lib/chromium/chromium' ; sleep 2; python3 - <<'PY'\n"
|
# wrote /etc/chromium/policies/managed/default_search.json instead: it outlives the task).
|
||||||
"import json\nfor p in ['/home/bot/.config/anybot-profile/Default/Preferences', '/home/bot/.config/chromium/Default/Preferences']:\n"
|
"setup": "pkill -f '^/usr/lib/chromium/chromium' ; rm -rf /etc/chromium/policies/managed /etc/chromium/policies/recommended; sleep 2; python3 - <<'PY'\n"
|
||||||
|
"import json, glob\nfor p in ['/home/bot/.config/anybot-profile/Default/Preferences', '/home/bot/.config/chromium/Default/Preferences'] + glob.glob('/home/bot/.config/anybot-profiles/*/Default/Preferences'):\n"
|
||||||
" try:\n d = json.load(open(p))\n except Exception:\n continue\n"
|
" try:\n d = json.load(open(p))\n except Exception:\n continue\n"
|
||||||
" d.pop('default_search_provider_data', None); d.pop('default_search_provider', None)\n json.dump(d, open(p, 'w'))\n print('reset', p)\nPY",
|
" d.pop('default_search_provider_data', None); d.pop('default_search_provider', None)\n json.dump(d, open(p, 'w'))\n print('reset', p)\nPY",
|
||||||
"ask": "把你電腦上 Chromium 瀏覽器的預設搜尋引擎改成 Bing。",
|
"ask": "把你電腦上 Chromium 瀏覽器的預設搜尋引擎改成 Bing。",
|
||||||
# Chromium writes its preferences up to ~10 s after a change: look for 15 s.
|
# Chromium writes its preferences up to ~10 s after a change: look for 15 s. The desktop's
|
||||||
"check": lambda dh, ans: "bing" in dx("for i in $(seq 15); do python3 - <<'PY' && break\nimport json, sys\np='/home/bot/.config/anybot-profile/Default/Preferences'\ntry:\n t=json.dumps(json.load(open(p)).get('default_search_provider_data',{})).lower()\nexcept Exception as e: t=str(e)\nprint(t)\nsys.exit(0 if 'bing' in t else 1)\nPY\nsleep 1; done", dh)[1]},
|
# own Chromium (~/.config/chromium) counts too: on a box from version 10 on, AnyBot's profile
|
||||||
|
# is a folder of its own, no longer a link to it (a bot that set Bing there was marked wrong).
|
||||||
|
"check": lambda dh, ans: "bing" in dx("for i in $(seq 15); do python3 - <<'PY' && break\nimport json, sys, glob\nt=''\nfor p in ['/home/bot/.config/anybot-profile/Default/Preferences', '/home/bot/.config/chromium/Default/Preferences'] + glob.glob('/home/bot/.config/anybot-profiles/*/Default/Preferences'):\n try:\n t+=json.dumps(json.load(open(p)).get('default_search_provider_data',{})).lower()\n except Exception as e: t+=str(e)\nprint(t)\nsys.exit(0 if 'bing' in t else 1)\nPY\nsleep 1; done", dh)[1]},
|
||||||
{"id": "T4", "route": "command", "name": "照片依月份分類",
|
{"id": "T4", "route": "command", "name": "照片依月份分類",
|
||||||
"setup": "rm -rf ~/bench/photos && mkdir -p ~/bench/photos && cd ~/bench/photos && "
|
"setup": "rm -rf ~/bench/photos && mkdir -p ~/bench/photos && cd ~/bench/photos && "
|
||||||
"for m in 2026-08 2026-09 2026-10; do for i in 1 2 3 4; do f=IMG_${m}_$i.jpg; echo x > $f; touch -d ${m}-1${i}T10:00:00 $f; done; done; "
|
"for m in 2026-08 2026-09 2026-10; do for i in 1 2 3 4; do f=IMG_${m}_$i.jpg; echo x > $f; touch -d ${m}-1${i}T10:00:00 $f; done; done; "
|
||||||
|
|
@ -295,7 +404,11 @@ def main():
|
||||||
ap.add_argument("--runs", type=int, default=1)
|
ap.add_argument("--runs", type=int, default=1)
|
||||||
ap.add_argument("--secs", type=int, default=600)
|
ap.add_argument("--secs", type=int, default=600)
|
||||||
ap.add_argument("--keep-skills", action="store_true", help="carry skills learned in one run into the next (to measure replay)")
|
ap.add_argument("--keep-skills", action="store_true", help="carry skills learned in one run into the next (to measure replay)")
|
||||||
|
ap.add_argument("--meter", default="", help="the bot's model service (e.g. https://api.x.ai/v1): count each task's tokens through a local pass-through")
|
||||||
|
ap.add_argument("--label", default="", help="a name for this variant in the results (e.g. baseline, text-looks)")
|
||||||
a = ap.parse_args()
|
a = ap.parse_args()
|
||||||
|
meter = Meter(a.meter) if a.meter else None
|
||||||
|
meter_port = meter.start() if meter else 0
|
||||||
if not BOX or not VOL or BOX == "anybot-box" or VOL == "anybot-box-home":
|
if not BOX or not VOL or BOX == "anybot-box" or VOL == "anybot-box-home":
|
||||||
sys.exit("set ANYBOT_BOX_NAME and ANYBOT_BOX_VOLUME to a throwaway box of its own")
|
sys.exit("set ANYBOT_BOX_NAME and ANYBOT_BOX_VOLUME to a throwaway box of its own")
|
||||||
real = os.path.realpath(os.path.expanduser("~/Library/Application Support/AnyBot"))
|
real = os.path.realpath(os.path.expanduser("~/Library/Application Support/AnyBot"))
|
||||||
|
|
@ -306,6 +419,22 @@ def main():
|
||||||
results = json.load(open(a.out)) if os.path.exists(a.out) else []
|
results = json.load(open(a.out)) if os.path.exists(a.out) else []
|
||||||
env = dict(os.environ, ANYBOT_DATA_DIR=a.data, ANYBOT_ASK_SECS=str(a.secs))
|
env = dict(os.environ, ANYBOT_DATA_DIR=a.data, ANYBOT_ASK_SECS=str(a.secs))
|
||||||
kept_skills = []
|
kept_skills = []
|
||||||
|
# What a bot learns in one task must not reach the next (the skills and memories live in the
|
||||||
|
# data folder, outside state.json): each task starts from none — except the skills of this
|
||||||
|
# round under --keep-skills, which measures exactly that.
|
||||||
|
def forget(skills: bool) -> None:
|
||||||
|
for name in ["chats", "oplog"] + (["skills"] if skills else []):
|
||||||
|
shutil.rmtree(os.path.join(a.data, name), ignore_errors=True)
|
||||||
|
for name in os.listdir(a.data):
|
||||||
|
if name.startswith("memory.db"):
|
||||||
|
os.remove(os.path.join(a.data, name))
|
||||||
|
forget(skills=True)
|
||||||
|
# A box of its own that doesn't exist yet: one plain question first makes it (the first task's
|
||||||
|
# setup needs it running).
|
||||||
|
if subprocess.run(["docker", "inspect", BOX], capture_output=True, env=dict(os.environ, DOCKER_HOST=a.docker_host)).returncode != 0:
|
||||||
|
print("== making the bench box", flush=True)
|
||||||
|
shutil.copyfile(a.template, os.path.join(a.data, "state.json"))
|
||||||
|
subprocess.run([a.bin, "--ask", "在你自己的電腦上執行 true,然後回答好了"], capture_output=True, text=True, env=env, timeout=1800)
|
||||||
for run in range(a.runs):
|
for run in range(a.runs):
|
||||||
for t in tasks:
|
for t in tasks:
|
||||||
print(f"== {t['id']} {t['name']} (run {run + 1})", flush=True)
|
print(f"== {t['id']} {t['name']} (run {run + 1})", flush=True)
|
||||||
|
|
@ -313,10 +442,21 @@ def main():
|
||||||
# makes in the bot's home is handed back to the bot.
|
# makes in the bot's home is handed back to the bot.
|
||||||
# Every task starts on a clear desktop: apps a previous task left open are closed.
|
# Every task starts on a clear desktop: apps a previous task left open are closed.
|
||||||
dx("for a in galculator xterm mousepad lxappearance pcmanfm; do pkill -x $a; done; pkill -f '^/usr/lib/chromium/chromium'; sleep 1; true", a.docker_host, user="root")
|
dx("for a in galculator xterm mousepad lxappearance pcmanfm; do pkill -x $a; done; pkill -f '^/usr/lib/chromium/chromium'; sleep 1; true", a.docker_host, user="root")
|
||||||
rc, out = dx(t["setup"].replace("sudo ", "") + "; chown -R bot:bot /home/bot/bench 2>/dev/null; true", a.docker_host, check=False, timeout=900, user="root")
|
rc, out = dx(t["setup"].replace("sudo ", "") + "\nchown -R bot:bot /home/bot/bench 2>/dev/null; true", a.docker_host, check=False, timeout=900, user="root")
|
||||||
print(" setup:", out.strip().replace("\n", " ")[-160:], flush=True)
|
print(" setup:", out.strip().replace("\n", " ")[-160:], flush=True)
|
||||||
shutil.copyfile(a.template, os.path.join(a.data, "state.json"))
|
shutil.copyfile(a.template, os.path.join(a.data, "state.json"))
|
||||||
os.chmod(os.path.join(a.data, "state.json"), 0o600)
|
os.chmod(os.path.join(a.data, "state.json"), 0o600)
|
||||||
|
# Each chat is a file of its own (data/chats/bot-<id>.json): a clean start each task,
|
||||||
|
# with no memories, work log or (unless kept) skills from the tasks before.
|
||||||
|
forget(skills=not a.keep_skills)
|
||||||
|
if meter:
|
||||||
|
# The bot's provider goes through the meter (this task's count starts at zero).
|
||||||
|
st0 = json.load(open(os.path.join(a.data, "state.json")))
|
||||||
|
kind = str(st0["bots"][0].get("provider", "")).lower()
|
||||||
|
provs = st0.setdefault("providers", {})
|
||||||
|
provs.setdefault(kind, {})["base_url"] = f"http://127.0.0.1:{meter_port}/v1"
|
||||||
|
json.dump(st0, open(os.path.join(a.data, "state.json"), "w"), ensure_ascii=False)
|
||||||
|
meter.reset(dump=os.path.join(os.path.dirname(os.path.abspath(a.out)), f"request-{a.label or 'run'}-{t['id']}.json"))
|
||||||
if a.keep_skills and kept_skills:
|
if a.keep_skills and kept_skills:
|
||||||
st0 = json.load(open(os.path.join(a.data, "state.json")))
|
st0 = json.load(open(os.path.join(a.data, "state.json")))
|
||||||
st0["skills"] = kept_skills
|
st0["skills"] = kept_skills
|
||||||
|
|
@ -331,7 +471,9 @@ def main():
|
||||||
st = json.load(open(os.path.join(a.data, "state.json")))
|
st = json.load(open(os.path.join(a.data, "state.json")))
|
||||||
if a.keep_skills:
|
if a.keep_skills:
|
||||||
kept_skills = st.get("skills", [])
|
kept_skills = st.get("skills", [])
|
||||||
msgs = st["bots"][0]["messages"]
|
bot_id = st["bots"][0]["id"]
|
||||||
|
chat = os.path.join(a.data, "chats", f"bot-{bot_id}.json")
|
||||||
|
msgs = json.load(open(chat)).get("messages", []) if os.path.exists(chat) else st["bots"][0].get("messages", [])
|
||||||
r = analyze(msgs)
|
r = analyze(msgs)
|
||||||
try:
|
try:
|
||||||
ok = bool(t["check"](a.docker_host, r.get("answer", "")))
|
ok = bool(t["check"](a.docker_host, r.get("answer", "")))
|
||||||
|
|
@ -340,12 +482,15 @@ def main():
|
||||||
r["check_error"] = str(e)
|
r["check_error"] = str(e)
|
||||||
r["skills"] = [{"name": k.get("name"), "steps": len(k.get("steps", []))} for k in st.get("skills", [])]
|
r["skills"] = [{"name": k.get("name"), "steps": len(k.get("steps", []))} for k in st.get("skills", [])]
|
||||||
r["replayed"] = "replay_skill" in r.get("tools", [])
|
r["replayed"] = "replay_skill" in r.get("tools", [])
|
||||||
r.update({"id": t["id"], "name": t["name"], "expected_route": t["route"], "ok": ok, "run": run + 1,
|
if meter:
|
||||||
|
r["usage"] = meter.take()
|
||||||
|
r.update({"id": t["id"], "name": t["name"], "expected_route": t["route"], "ok": ok, "run": run + 1, "label": a.label,
|
||||||
"process_s": wall, "at": time.strftime("%Y-%m-%d %H:%M"), "log_tail": log[-1500:]})
|
"process_s": wall, "at": time.strftime("%Y-%m-%d %H:%M"), "log_tail": log[-1500:]})
|
||||||
results.append(r)
|
results.append(r)
|
||||||
json.dump(results, open(a.out, "w"), ensure_ascii=False, indent=1)
|
json.dump(results, open(a.out, "w"), ensure_ascii=False, indent=1)
|
||||||
|
u = r.get("usage") or {}
|
||||||
print(f" ok={ok} steps={r.get('steps')} total={r.get('total_s')}s model={r.get('model_s')}s tool={r.get('tool_s')}s "
|
print(f" ok={ok} steps={r.get('steps')} total={r.get('total_s')}s model={r.get('model_s')}s tool={r.get('tool_s')}s "
|
||||||
f"routes={r.get('by_route')} switches={r.get('switches')}", flush=True)
|
f"routes={r.get('by_route')} switches={r.get('switches')} tokens_in={u.get('tokens_in')} out={u.get('tokens_out')} pics={u.get('images')}", flush=True)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue