用 Claude Code 时,模型和思考力度(effort)这两个设置看起来都能「让结果更好」,于是很多人干脆一律开最大的模型、最高的力度。这样做多半能用,但钱和时间不一定花在了刀刃上。
这篇教程先讲清两个设置各管什么、四档模型的价格差多少,再用一组实测看同一个任务在六种组合下的得分和花费,最后给一套「先用多少、不够时先升哪个」的判断方法。
练习项目还是 前几篇 用过的积分台账。需要先装好 Claude Code 并登录,方法见 Claude Code 官方安装说明。
我们让六种「模型 + 力度」组合各做 3 次同一个任务:给台账加一个从 CSV 批量导入积分的函数,需求写得很清楚。结果用一份模型看不到的检查脚本打分,共 10 项。
| 组合 | 得分(3 次) | 每次花费(美元) | 平均 | 用时(秒) | 模型自己跑测试(次) |
|---|---|---|---|---|---|
| Haiku 5.5 · 中 | 10、10、10 | 0.013、0.011、0.015 | 0.013 | 55、52、65 | 3、2、2 |
| Sonnet 5.5 · 中 | 10、10、10 | 0.081、0.151、0.083 | 0.105 | 18、39、20 | 1、1、1 |
| Opus 5.5 · 低 | 10、10、10 | 0.170、0.263、0.215 | 0.216 | 32、61、53 | 1、1、1 |
| Opus 5.5 · 中 | 10、10、10 | 0.212、0.186、0.224 | 0.207 | 45、40、58 | 1、1、2 |
| Opus 5.5 · 高 | 10、10、10 | 0.297、0.258、0.254 | 0.270 | 74、62、60 | 1、3、1 |
| Fable 5.2 · 高 | 10、10、10 | 0.728、0.637、0.679 | 0.681 | 82、76、85 | 1、2、1 |
「模型自己跑测试」只数它在运行中真正执行完的测试套件(输出里有 unittest 的结果,没通过的也算),被拒的命令、写进代码里的 unittest 字样都不算;跑完后我们自己再跑的那次 make test 也不算在内。
一个任务、每种组合 3 次,只能当作一个实例,不能拿来给模型排名,也不能推算到更难的任务上。
模型决定能力上限。 每个模型的权重是固定的,你可以给它更多上下文、更好的提示,但它会的东西就那么多。越大的模型越擅长复杂、模糊、需要多步推理的问题,也越贵。
思考力度决定它愿意花多少功夫。 力度不只是「想多久」,它管的是这一轮总共做多少事:读多少文件、做多少验证、走多远才回来问你。力度高,它会自己多读、多跑测试、多检查边界情况;力度低,它更愿意快速给你一个结果,缺信息时宁可问你也不自己去找。
Claude Code 的力度有五档:low、medium、high、xhigh、max。用 /model 换模型,用 /effort 换力度;在选择器里按回车选的模型和力度会存成默认值,力度按模型分开存,每个模型记住自己的那一档;按 s 只对当前会话生效,不改默认值。max 是例外:在界面里选了只管当前会话,下次启动不会保留(除非用环境变量 CLAUDE_CODE_EFFORT_LEVEL 设)。所以新开会话时先跑一次 /model 和 /effort,确认自己现在用的是什么。
原文作者的经验是:
按 Anthropic 官方价格页(2026-11-25 查询),每百万 token 的 API 标价:
| 模型 | 输入 | 缓存读取 | 输出 | 适合 |
|---|---|---|---|---|
| Haiku 5.5 | 0.10 | 0.01 | 0.50 | 高频小活:分类、提取、翻日志 |
| Sonnet 5.5 | 2 | 0.10 | 10 | 日常开发、写清楚了的改动 |
| Opus 5.5 | 4 | 0.20 | 20 | 复杂推理、需要判断的开发工作 |
| Fable 5.2 | 8 | 0.20 | 40 | 最难、最长的任务 |
Haiku 5.5 的这组价格只适用于输入不超过 10 万 token 的请求,超过后输入和输出都按 5 倍计。订阅用户看不到这些价格,但同样的请求消耗的是套餐额度。
本文表格里的「花费」是 Claude Code 按标价估算的数字(运行记录里标着 costBasis: list),不是账单。
任务。 每次都发同一段话:给台账加一个 import_csv(ledger, path),从 CSV 导入积分事件,返回 (成功条数, 跳过条数)。需求里写明了文件约定:UTF-8、可能带 BOM、可能是 CRLF 换行;不带时区的时间按台账时区算;空行不计;字段两边的空白去掉;未知事件、时间解析不了、被每日上限挡住的行都算跳过,并继续导入后面的行。最后要求它加测试、跑 make test。
检查。 跑完后,用一份模型看不到的 check_import.py 打分,共 10 项:普通导入、BOM、CRLF、空行和只有表头的文件、首尾空白、未知事件、坏时间戳、不带时区的时间(放在北京时间的日期分界上)、Z 和 +08:00、被上限挡住的行。每一项都同时检查返回值和台账里实际记下的内容。测试用的具体数据、边界日期和期望结果都不在提示词里。
开跑前我们先验证了检查脚本本身:一份参考实现拿满分,8 种有针对性的错误写法(BOM 没处理、不带时区按 UTC 算、空行算进跳过数、不去空白、丢掉时区、坏时间戳抛异常等)各自在对应的那一项上失败。
对照。 六种组合各 3 次,每一遍轮换先后顺序;每次从同一份干净项目开始,提示词、放行的命令都一样。Claude Code 的运行记录里写着实际用到的模型,我们逐次核对过,和设定一致;力度在运行记录里没有回显,所以表里的力度是我们传给 --effort 的值。
写清楚的任务,小模型就够。 这次的边界情况全写在需求里,六种组合都没漏。原文作者也观察到:需求越具体,不同模型、不同力度的结果越接近。反过来,我们也就没测到「力度高才做对」的情况。
力度高不一定多跑测试。 我们原以为高力度会多验证几轮。实际上,在 Opus 上,低力度三次都只跑了 1 次测试,中力度 1、1、2 次,高力度 1、3、1 次,看不出规律。高力度比中力度平均多花约 0.063 美元,按标价拆开算,约六成来自输出更长(每次 5,500–6,800 个输出 token,中力度 3,500–4,500),其余来自多发的几次请求带来的缓存读写(缓存读取 13–16 万 token,中力度 8–13 万)。低力度也没省下来:它有一次走了 11 轮,输出和读取都比中力度多。Haiku 跑测试的总次数最多(3 次运行共 7 次,其他组合 3–5 次),轮数也最多(14–22 轮),平均用时 57 秒,比 Sonnet(26 秒)和 Opus 低、中两档(49、48 秒)都慢,只是每个 token 便宜得多。
原文说力度真正有用的地方,是隐藏的边界情况多的任务。 作者在一个评测集上看到,力度从低升到高,减少的主要是「漏了边界情况」这类失败,而「思路本身就错了」的失败基本不减。比如一个 HTML 过滤器任务,低力度一次写完、拿一个手写页面测一下就收工;高力度会先对自己的初稿挑刺、读解析器源码、跑标准测试集,最后还写了随机输入的模糊测试。我们的任务把边界都写明了,所以看不到这种差别,这和原文的说法不矛盾。
原文给了一条很好用的判断:
升级的顺序也有讲究:先给它自检的手段(测试、构建、检查脚本),再提一档力度,最后才换更大的模型。前两步都便宜,而且换模型会让缓存作废(见 会话管理那篇),最好在自然的断点换,比如刚清空会话的时候。
这一节是原文的建议,我们这组实测没有出现需要升级的情况,没有验证它。
有一种省钱用法:能自动检查对错的任务,先全部用低力度跑,只把没通过的用高力度重跑。它的期望花费可以这样算:
低力度平均花费 + 低力度失败比例 × 高力度平均花费
我们这组数据里,Opus 低力度 3 次都通过,失败比例是 0,所以期望花费就是低力度的 0.216 美元,比直接用高力度(0.270)省约 2 成;但它和中力度(0.207)几乎一样。
这个算法有两个前提:要有一个可靠的「通过 / 没通过」信号(这里是检查脚本),而且重跑是一次全新的运行。我们的每次运行互相独立,看不出低力度没通过的那几次,换成高力度重跑就一定能过。
会话管理那篇 里,子代理和主会话用同一个模型(Opus),翻日志反而贵了一倍。这次我们给子代理单独定义了模型:在项目里放一个 .claude/agents/log-reader.md:
---
name: log-reader
description: 读日志、统计日志内容并只汇报结论。需要从日志文件里查找或计数时使用。
model: haiku
tools: Read, Grep, Glob, Bash
---
你只读日志,不修改任何文件。按要求统计后,只汇报结论和得出结论用的命令,不要贴大段原始日志。
主会话固定用 Opus 中力度,问同一个问题(4 个日志文件、5,408 行里,被每日上限挡住最多的 3 个用户),一次直接问,一次加一句「用 log-reader 子代理去读日志,只把结论带回来」,各 2 遍:
| 直接问 | 交给 Haiku 子代理 | |
|---|---|---|
| 答对 | 2/2 | 2/2 |
| 整次花费(美元) | 0.111、0.105 | 0.091、0.098 |
| 其中 Haiku 子代理 | — | 0.002、0.003 |
两次交给子代理的运行里,主会话都调用了 log-reader,运行记录的用量里也确实出现了 Haiku 5.5。子代理那部分几乎不花钱,省下的是主会话少做的那几轮;但主会话仍是大头,所以只省了一成左右。日志再大一些、或者这类活反复做,差距会更明显,这一点我们没有测。
没写 model: 的子代理,会跟主会话用同一个模型。
/usage 看钱花在哪交互界面里输入 /usage,能看到本次会话的用量、套餐额度和缓存命中情况。比较两种做法时,记下每一轮的花费,比只看最后的总数有用:恢复会话后,Claude Code 报告的总花费是整个会话累计的。
1. 准备项目。 按 第 3 篇附录 建好积分台账项目,放在 practice/skill-verify/;把 会话管理那篇附录 的 make_logs.py 放在 practice/session/;本文附录的三个文件放在 practice/model-effort/。
2. 先验证检查脚本。 把 reference.py 里的 import_csv 追加到一份干净项目的 src/points/ledger.py 末尾,在项目目录里运行 PYTHONPATH=src POINTS_TZ=Asia/Shanghai python3 <check_import.py 的完整路径>,最后一行应是 SCORE 10/10;再按上文的几种错误改一改,确认对应那一项失败。
3. 运行。 在 practice/model-effort/ 里:
python3 measure.py grid # 6 种组合 × 3 次
python3 measure.py logs # 子代理对照,2 × 2 次
两条命令默认都属于系列 1。同一系列里只要已有一个运行目录,命令就在开跑之前停下,不覆盖已有记录。想再测一组,就在命令后面加一个新的系列名,比如 python3 measure.py grid 2:前一组的记录原样保留,新的一组另算花费,会再跑 18 次。measure.py 每次把项目复制到 ~/aiworkspace/claude/i1742-model/runs/<系列>/ 下(在你的仓库外),git 提交一次作为干净基线,再调用:
claude -p "$TASK" --model claude-opus-5-5 --effort low \
--setting-sources project \
--settings '{"claudeMdExcludes":["/Users/你的用户名/.claude/CLAUDE.md"],"autoMemoryEnabled":false}' \
--permission-mode acceptEdits \
--allowedTools "Bash(make *)" "Bash(python3 *)" "Bash(git diff*)" "Bash(git status*)" "Bash(ls *)" "Bash(cat *)" "Bash(grep *)" "Bash(wc *)" "Bash(head *)" "Bash(tail *)" "Bash(sort *)" "Bash(awk *)" Agent Task \
--output-format stream-json --verbose --no-session-persistence
$TASK 就是 measure.py 里的 TASK。--setting-sources 和 --settings 用来排除你自己的全局 CLAUDE.md 和自动记忆;--allowedTools 列出的会直接执行,不用确认;没列的命令不一定会被拦,被判定为只读的照常执行。我们的运行里有几次组合命令(cat a && cat b、cd ... ; python3 -)被拒,模型都换了写法接着做,没有影响结果。
4. 看结果。 results.jsonl 每行一次运行:score 是检查得分,cost_usd 是 Claude Code 报告的估算花费,init_model 和 models_used 是实际用到的模型,test_runs 是模型自己执行完的测试套件数(口径同上文),tests_pass 是跑完后我们另跑一次 make test 的结果,series 是系列名。同一系列的花费累计到 18 美元时,脚本会在开下一次之前停下。
我们这 22 次一共约 4.9 美元(按 Claude Code 报告的标价估算),用时约 20 分钟。
/model 和 /effort 看清现在是什么,再按任务定:需求清楚、范围小的,先试小一档的模型;边界多、要验证的,先提力度。按自己常做的活定一个默认值,比每个任务都调更省心。积分台账项目与 第 3 篇附录 相同,日志生成脚本 make_logs.py 见 会话管理那篇附录。本文新增三个文件,放在 practice/model-effort/。
check_import.py:
"""Hidden check for import_csv (#1742 article 4). Run in a project copy with PYTHONPATH=src POINTS_TZ=Asia/Shanghai.
Prints one PASS/FAIL line per item and exits 0 only when all pass. Every item checks the returned
(imported, skipped) and the ledger's own state, so a function that miscounts or records skipped rows fails.
"""
import sys
import tempfile
from datetime import datetime, timezone
from pathlib import Path
try:
from points.ledger import Ledger, import_csv
except ImportError as exc:
print(f"FAIL import_csv not importable: {exc}")
sys.exit(1)
TMP = Path(tempfile.mkdtemp())
def run(name, raw: bytes):
p = TMP / f"{name}.csv"
p.write_bytes(raw)
led = Ledger()
try:
r = import_csv(led, str(p))
return led, tuple(r)
except Exception as exc: # noqa: BLE001
return led, ("raised", type(exc).__name__)
def users(led):
return sorted(e[0] for e in led.entries)
def day(e): # the Beijing day of an entry
return e[3].astimezone(timezone.utc).astimezone(__import__("zoneinfo").ZoneInfo("Asia/Shanghai")).date().isoformat()
H = b"user,event,ts\n"
checks = {}
led, r = run("plain", H + b"alice,signup,2026-03-02T10:00:00+08:00\nbob,comment,2026-03-02T10:00:00+08:00\nbob,comment,2026-03-02T11:00:00+08:00\n")
checks["1 plain rows"] = r == (3, 0) and led.balance("alice") == 100 and led.balance("bob") == 4
led, r = run("bom", b"\xef\xbb\xbf" + H + b"alice,signup,2026-03-02T10:00:00+08:00\n")
checks["2 UTF-8 BOM"] = r == (1, 0) and users(led) == ["alice"]
led, r = run("crlf", (H + b"alice,signup,2026-03-02T10:00:00+08:00\nbob,signup,2026-03-02T10:00:00+08:00\n").replace(b"\n", b"\r\n"))
checks["3 CRLF"] = r == (2, 0) and users(led) == ["alice", "bob"]
led, r = run("blank", H + b"\nalice,signup,2026-03-02T10:00:00+08:00\n\n\nbob,signup,2026-03-02T10:00:00+08:00\n\n")
led2, r2 = run("header-only", H)
checks["4 blank lines and header-only"] = r == (2, 0) and len(led.entries) == 2 and r2 == (0, 0) and not led2.entries
led, r = run("spaces", H + b" alice , signup , 2026-03-02T10:00:00+08:00 \n")
checks["5 surrounding whitespace"] = r == (1, 0) and users(led) == ["alice"]
led, r = run("unknown", H + b"alice,share,2026-03-02T10:00:00+08:00\nbob,signup,2026-03-02T10:00:00+08:00\n")
checks["6 unknown event skipped, import continues"] = r == (1, 1) and users(led) == ["bob"]
led, r = run("badts", H + b"alice,signup,yesterday\nbob,signup,2026-03-02T10:00:00+08:00\n")
checks["7 bad timestamp skipped, import continues"] = r == (1, 1) and users(led) == ["bob"]
# Naive times are Beijing time: 23:30 on 03-01 and 00:30 on 03-02 are different days, so both daily logins count.
led, r = run("naive", H + b"carol,daily_login,2026-03-01T23:30:00\ncarol,daily_login,2026-03-02T00:30:00\n")
checks["8 offset-free time is ledger-local"] = r == (2, 0) and sorted(map(day, led.entries)) == ["2026-03-01", "2026-03-02"]
# 16:30Z is 00:30 on 03-02 in Beijing, the same day as 00:10+08:00, so the second login is blocked.
led, r = run("offsets", H + b"dave,daily_login,2026-03-01T16:30:00Z\ndave,daily_login,2026-03-02T00:10:00+08:00\n")
checks["9 Z and +08:00 offsets honoured"] = r == (1, 1) and len(led.entries) == 1 and day(led.entries[0]) == "2026-03-02"
led, r = run("limit", H + b"erin,daily_login,2026-03-02T09:00:00+08:00\nerin,daily_login,2026-03-02T18:00:00+08:00\nerin,signup,2026-03-02T18:00:00+08:00\n")
checks["10 limit-blocked row skipped, not recorded"] = r == (2, 1) and len(led.entries) == 2 and led.balance("erin") == 105
for k, v in checks.items():
print(("PASS " if v else "FAIL ") + k)
print(f"SCORE {sum(checks.values())}/{len(checks)}")
sys.exit(0 if all(checks.values()) else 1)
reference.py:
"""Reference import_csv used only to validate check_import.py (#1742 article 4); not given to the models."""
import csv
from datetime import datetime
def import_csv(ledger, path):
from points.ledger import local_zone
imported = skipped = 0
with open(path, encoding="utf-8-sig", newline="") as f:
rows = csv.reader(f)
next(rows, None)
for row in rows:
if not row or all(not c.strip() for c in row):
continue
try:
user, event, ts = (c.strip() for c in row)
t = datetime.fromisoformat(ts)
if t.tzinfo is None:
t = t.replace(tzinfo=local_zone())
got = ledger.award(user, event, t)
except (ValueError, KeyError):
skipped += 1
continue
if got:
imported += 1
else:
skipped += 1
return imported, skipped
measure.py:
"""Measure model x effort on one CSV import task, plus a Haiku log subagent (#1742 article 4).
Grid: six (model, effort) cells x 3 repetitions, cell order rotated per repetition; every run starts
from a fresh git copy of the practice project outside the repo, headless, isolated from the user's
CLAUDE.md, plugins, hooks and auto memory. check_import.py scores the result afterwards; the model
never sees it. Stops before a run once the Claude Code-reported total reaches BUDGET_STOP.
Usage (from this folder): python3 measure.py grid|logs [SERIES]. SERIES (default 1) names a run folder
under RUNS; a command refuses to start if any of its run folders already exists, so earlier evidence is never
overwritten. Use a new SERIES for a fresh set. One record per run in results.jsonl, tagged with its series.
"""
import json
import pathlib
import re
import shutil
import subprocess
import sys
W = pathlib.Path(__file__).resolve().parent
BASE = W.parent / "skill-verify"
LOGGEN = W.parent / "session" / "make_logs.py"
RUNS = pathlib.Path.home() / "aiworkspace" / "claude" / "i1742-model" / "runs"
BUDGET_STOP = 18.0 # per series
SERIES = sys.argv[2] if len(sys.argv) > 2 else "1"
SETTINGS = json.dumps({"claudeMdExcludes": [str(pathlib.Path.home() / ".claude" / "CLAUDE.md")], "autoMemoryEnabled": False})
ALLOWED = ["Bash(make *)", "Bash(python3 *)", "Bash(git diff*)", "Bash(git status*)", "Bash(ls *)", "Bash(cat *)",
"Bash(grep *)", "Bash(wc *)", "Bash(head *)", "Bash(tail *)", "Bash(sort *)", "Bash(awk *)", "Agent", "Task"]
CELLS = [("claude-haiku-5-5", "medium"), ("claude-sonnet-5-5", "medium"), ("claude-opus-5-5", "low"),
("claude-opus-5-5", "medium"), ("claude-opus-5-5", "high"), ("claude-fable-5-2", "high")]
TASK = """给积分台账加一个模块级函数 import_csv(ledger, path),放在 src/points/ledger.py 里,从 CSV 文件批量导入积分事件,返回 (imported, skipped) 两个整数。
文件约定:
- UTF-8 编码,可能带 BOM;换行可能是 CRLF。
- 第一行是表头 user,event,ts,之后每行一个事件。
- ts 是 ISO 8601 时间:带时区的(如 Z、+08:00)按它自己的时区;不带时区的按台账时区(local_zone())理解。
- 空行忽略,不计入 skipped;每个字段两边的空白要去掉。
- 未知事件、ts 解析不了的行计入 skipped,并继续导入后面的行。
- 被每日上限挡住的行(award 返回 0)计入 skipped。
加上测试,跑 make test。"""
LOGS = "看一下 logs/ 里的积分日志,找出被每日上限挡住(result=limited)次数最多的 3 个用户,给出各自的次数。"
LOGS_SUB = LOGS + "用 log-reader 子代理去读日志,只把结论带回来。"
AGENT = """---
name: log-reader
description: 读日志、统计日志内容并只汇报结论。需要从日志文件里查找或计数时使用。
model: haiku
tools: Read, Grep, Glob, Bash
---
你只读日志,不修改任何文件。按要求统计后,只汇报结论和得出结论用的命令,不要贴大段原始日志。
"""
def sh(cmd, cwd):
return subprocess.run(cmd, cwd=cwd, shell=True, capture_output=True, text=True)
def spent():
p = W / "results.jsonl"
recs = [json.loads(l) for l in open(p)] if p.exists() else []
return sum(r["cost_usd"] for r in recs if r.get("series", "1") == SERIES)
def fresh(dirs):
"""Stop before any paid run if this series already has one of these run folders."""
taken = [d for d in dirs if d.exists()]
if taken:
sys.exit(f"{taken[0]} already exists; keep it and start a new series: python3 measure.py {sys.argv[1]} 2")
def suites(events, ids):
"""Test suites the model actually ran: Bash results (paired by tool_use_id) that print a unittest summary.
Failed suites count; refused commands and files merely mentioning unittest do not."""
n = 0
for e in events:
content = (e.get("message") or {}).get("content") if e.get("type") == "user" else None
for c in content if isinstance(content, list) else []:
if c.get("type") != "tool_result" or c.get("tool_use_id") not in ids:
continue
t = c.get("content")
t = t if isinstance(t, str) else "\n".join(x.get("text", "") for x in t or [] if isinstance(x, dict))
k = len(re.findall(r"^Ran \d+ tests? in ", t, re.M))
if not k and re.search(r"make test|unittest", ids[c["tool_use_id"]]) and re.search(r"^(OK|FAILED \([^)]*\))$", t, re.M):
k = 1 # output piped through tail kept only the verdict line
n += k
return n
def setup(d, logs=False, agent=False):
shutil.copytree(BASE, d, ignore=shutil.ignore_patterns("skill", ".claude", "__pycache__", ".git", ".gitignore"))
if (d / "CLAUDE.md.example").exists(): # the repository copy; a project built from the articles has CLAUDE.md
shutil.move(d / "CLAUDE.md.example", d / "CLAUDE.md")
if logs:
subprocess.run([sys.executable, str(LOGGEN), str(d / "logs")], check=True)
if agent:
(d / ".claude" / "agents").mkdir(parents=True)
(d / ".claude" / "agents" / "log-reader.md").write_text(AGENT, encoding="utf-8")
sh("git init -q && git add -A && git -c user.name=t -c user.email=t@t commit -qm base", d)
def run(d, prompt, model, effort):
cmd = ["claude", "-p", prompt, "--model", model, "--effort", effort,
"--setting-sources", "project", "--settings", SETTINGS,
"--permission-mode", "acceptEdits", "--allowedTools", *ALLOWED,
"--output-format", "stream-json", "--verbose", "--no-session-persistence"]
p = subprocess.run(cmd, cwd=d, capture_output=True, text=True, timeout=3600, stdin=subprocess.DEVNULL)
(d.parent / f"{d.name}.stream.jsonl").write_text(p.stdout)
events = [json.loads(l) for l in p.stdout.splitlines() if l.strip().startswith("{")]
init = next((e for e in events if e.get("type") == "system" and e.get("subtype") == "init"), {})
result = next((e for e in reversed(events) if e.get("type") == "result"), {})
uses = [(c, bool(e.get("parent_tool_use_id"))) for e in events if e.get("type") == "assistant" and isinstance(e.get("message"), dict)
for c in e["message"].get("content", []) if c.get("type") == "tool_use"]
main = [c for c, sub in uses if not sub]
bash = [c["input"].get("command", "") for c in main if c["name"] == "Bash"]
ids = {c["id"]: c["input"].get("command", "") for c in main if c["name"] == "Bash"}
mu = result.get("modelUsage") or {}
return {
"model_flag": model, "effort_flag": effort, "init_model": init.get("model"),
"models_used": {k: round(v.get("costUSD", 0), 4) for k, v in mu.items()},
"cost_usd": round(result.get("total_cost_usd") or 0, 4), "num_turns": result.get("num_turns"),
"duration_s": round((result.get("duration_ms") or 0) / 1000), "is_error": result.get("is_error"),
"permission_denials": len(result.get("permission_denials") or []),
"test_runs": suites(events, ids),
"reads": sum(c["name"] == "Read" for c in main), "bash": [b[:100] for b in bash],
"agent_calls": [c["input"].get("subagent_type") for c in main if c["name"] in ("Agent", "Task")],
"final": (result.get("result") or "")[-1500:],
}
def save(rec):
with open(W / "results.jsonl", "a") as f:
f.write(json.dumps({"series": SERIES, **rec}, ensure_ascii=False) + "\n")
def grid():
fresh([RUNS / SERIES / f"grid-{m.split('-')[1]}-{e}-{r + 1}" for r in range(3) for m, e in CELLS])
for rep in range(3):
for model, effort in CELLS[rep * 2:] + CELLS[:rep * 2]: # rotate the order
if spent() >= BUDGET_STOP:
print(f"BUDGET-STOP at {spent():.2f}", flush=True)
return
d = RUNS / SERIES / f"grid-{model.split('-')[1]}-{effort}-{rep + 1}"
setup(d)
rec = {"exp": "grid", "rep": rep + 1, **run(d, TASK, model, effort)}
chk = subprocess.run([sys.executable, str(W / "check_import.py")], cwd=d, capture_output=True, text=True,
env={"PYTHONPATH": "src", "POINTS_TZ": "Asia/Shanghai", "PATH": "/usr/bin:/bin"})
m = re.search(r"SCORE (\d+)/(\d+)", chk.stdout)
rec.update(score=int(m.group(1)) if m else 0, check_report=chk.stdout.strip()[-800:],
tests_pass=sh("make test", d).returncode == 0,
diff=sh("git diff --stat HEAD", d).stdout.strip()[-400:])
save(rec)
print(f"{d.name} score={rec['score']} cost={rec['cost_usd']} tests={rec['test_runs']} {rec['duration_s']}s total={spent():.2f}", flush=True)
def logs():
fresh([RUNS / SERIES / f"logs-{v}-{r + 1}" for r in range(2) for v in "AB"])
for rep in range(2):
for v in "AB":
if spent() >= BUDGET_STOP:
print(f"BUDGET-STOP at {spent():.2f}", flush=True)
return
d = RUNS / SERIES / f"logs-{v}-{rep + 1}"
setup(d, logs=True, agent=v == "B")
rec = {"exp": "logs", "variant": v, "rep": rep + 1, **run(d, LOGS if v == "A" else LOGS_SUB, "claude-opus-5-5", "medium")}
rec["correct"] = all(re.search(rf"{u}\D{{1,40}}{n}\b", rec["final"], re.S) for u, n in (("u0417", 23), ("u0082", 19), ("u0350", 16)))
save(rec)
print(f"{d.name} correct={rec['correct']} cost={rec['cost_usd']} models={rec['models_used']} agents={rec['agent_calls']} total={spent():.2f}", flush=True)
if __name__ == "__main__":
{"grid": grid, "logs": logs}[sys.argv[1]]()
print("ALL-DONE", flush=True)
| 项目 | 内容 |
|---|---|
| 系统 | macOS 27.0.1(arm64) |
| 工具版本 | Claude Code 2.1.332;模型 claude-haiku-5-5、claude-sonnet-5-5、claude-opus-5-5、claude-fable-5-2;Python 3.15.2 |
| 隔离方式 | --setting-sources project,claudeMdExcludes 排除用户级 CLAUDE.md,关闭自动记忆,不加载个人插件和 hooks;每次从同一份干净副本开始,项目放在仓库外 |
| 放行范围 | 自动接受文件修改;预先放行 make、python3、git diff/status、ls、cat、grep、wc、head、tail、sort、awk 和子代理 |
| 规模 | CSV 导入:6 种组合 × 3 次 = 18 次,每一遍轮换顺序;日志:直接问 / Haiku 子代理各 2 次;共 22 次 |
| 判定方法 | CSV 导入由 check_import.py 10 项打分(返回值 + 台账状态),开跑前用参考实现和 8 种错误写法验证过;再跑 make test;日志题按答案里的三组「用户 + 次数」判定;模型、花费、测试次数、子代理调用都从完整运行记录里读 |
| 结果 | CSV 导入 18/18 满分,make test 全部通过;日志 4/4 答对,Haiku 子代理 2/2 次确实被调用 |
| 实测日期 | 2026-11-25 |
| 价格查询 | Anthropic 官方价格页,2026-11-25 |
| 撰写 / 实跑 | Claude(Claude Code) |
| 复核 | Codex(#1742) |
本文的方法取自以下文章,示例与实测为本站所做: