Evaluation评估
Sealed test sets, layered metrics, and enough repeats to trust a difference.封存的测试集、分层的指标,以及足够多次的重复,让差异值得相信。
What it is and why it exists它是什么,为什么需要它
What是什么
Evaluation is the fixed questions, expected results, and scoring scripts that tell you whether a change made the system better. This module builds a seal, a retrieval eval with variants, an end-to-end agent eval with mechanical grading, and a history file.评估是一组固定的问题、预期结果和评分脚本,用来判断一次改动是否让系统变好。本模块搭建:封存机制、带变体的检索评估、用代码评分的端到端智能体评估,以及一个历史记录文件。
Why为什么
Agent systems change daily and fail quietly. Without numbers, each change is judged by the last conversation someone remembers. With a learning loop the risk is higher: a loop that can influence its own test raises its score without learning anything.智能体系统每天都在变,而且失败时悄无声息。没有数字,每次改动就只能靠某人记得的最近一次对话来判断。有了学习循环,风险更高:如果循环能影响自己的考题,它不用学到任何东西也能提高分数。
How it works工作原理
- Each layer gets its own eval so a failure can be located: retrieval is scored without the chat model, the agent is scored end to end.每一层都有自己的评估,以便定位故障:检索评分时不涉及聊天模型,智能体则做端到端评分。
- Test material is sealed before any learning job runs. A manifest of hashes is verified at the top of every eval.测试材料在任何学习任务运行之前封存。每次评估开始时都会校验哈希清单。
- Every ranking feature has a flag. The same script compares on and off against the same gold set.每项排序功能都有开关。同一个脚本对同一套标准集比较开和关的效果。
- Results are read with their sample size and spread. A difference smaller than the spread is reported as no difference.读结果时要看样本量和波动范围。小于波动范围的差异,按“没有差异”报告。
Where it sits in the build order它在搭建顺序中的位置
Needs first前置模块
- RAG and knowledge graphRAG 与知识图谱The retrieval eval calls search and scores what it returns. Gold items name chunk ids, so the index has to exist.检索评估调用 search 并对返回结果评分。标准条目里写的是 chunk id,所以索引必须已经存在。Build out of order不按顺序搭建 Stand in with:可用以下替代: Score a hard-coded list of results. The metric code can be built and tested with no search.对一个写死的结果列表评分。指标代码可以在没有检索的情况下搭建和测试。
- Harness engineeringHarness 工程End-to-end evals send requests through the agent and read which tools it used.端到端评估通过智能体发送请求,并读取它用了哪些工具。Build out of order不按顺序搭建 Stand in with:可用以下替代: Evaluate a bare model endpoint. The scripts are the same and only the target changes.直接评估一个裸模型端点。脚本相同,只是目标不同。
- Knowledge management知识管理Held-out material is sampled from the corpus. You cannot seal chunks that have not been ingested.留出材料是从语料中抽样的。没有入库的文本块无法封存。Build out of order不按顺序搭建 Stand in with:可用以下替代: Six hand-written questions with expected answers.六道手写的问题,带预期答案。
Unlocks解锁
- Multi-agent patterns多智能体模式Every added agent adds cost and latency. Only an eval can show that a split improved results.每增加一个智能体就增加成本和延迟。只有评估能证明拆分确实改善了结果。
- Self-evolving agents自进化智能体A loop optimizes what it can measure. Sealed evals have to exist before the loop runs, or it grades itself.循环会优化它能测量的东西。封存评估必须先于循环存在,否则它就是在给自己打分。
- Operations and deployment运维与部署Scheduled evals and the daily report are how you learn that a change made things worse.定时评估和每日报告,是你得知某次改动让情况变糟的途径。
In the reference build在参考系统中
| Path路径 | Role作用 |
|---|---|
| apps/agent-server/nightly/seal_evals.py | Creates the frozen question set and the held-out chunk manifest.创建冻结的问题集和留出文本块清单。 |
| apps/agent-server/nightly/retrieval_eval.py | Builds the retrieval gold set and scores hit rate and MRR.构建检索标准集,并计算命中率和 MRR。 |
| apps/agent-server/nightly/chat_eval.py | Multi-turn conversations through the full agent.通过完整智能体进行的多轮对话评估。 |
| apps/agent-server/nightly/stream_eval.py | The same questions through the streaming path, repeated.同样的问题走流式路径,并重复多次。 |
| evals/ | Gold sets, sealed material, run outputs, and history files.标准集、封存材料、运行输出和历史文件。 |
Process map流程图
From a proposed change to a decision从提出改动到做出决定
- 1Seal封存Once, before learning. Files are hashed and chunks are marked held out.只做一次,在学习之前。对文件做哈希,把部分文本块标记为留出。
- 2Verify the seal校验封存Every run starts by checking hashes. A changed file voids the run.每次运行先校验哈希。文件被改动则本次运行无效。
- 3Baseline run基线运行Score the current system. Repeat to learn the spread.给当前系统打分。重复多次以了解波动范围。
- 4Variant run变体运行Same script and gold set, one flag changed.同一脚本、同一标准集,只改一个开关。
- 5Compare with noise结合噪声比较Is the difference larger than the spread between repeats?差异是否大于多次重复之间的波动?
- 6Append history追加历史One line per run with metrics and flags.每次运行一行,记录指标和开关。
- 7Decide决定Make it the default, keep it off, or collect more data.设为默认、保持关闭,或继续收集数据。
Build steps搭建步骤
Follow them in order the first time. Each step names what it uses from earlier steps and what it leaves for later ones. Code is read from the lab files, and output is what the lab printed when it was run.第一次请按顺序做。每一步都写明它用到前面步骤的什么成果,又为后面的步骤留下什么。代码直接读取自 lab 文件,输出是 lab 实际运行时打印的内容。
- 1Write the human baseline questions编写人工基线问题
- 2Build a retrieval gold set构建检索标准集
- 3Seal the test material before anything learns在任何学习发生之前封存测试材料
- 4Write the rank metrics编写排名指标
- 5Run variants and append history运行变体并追加历史
- 6Read the table and decide what stays读懂表格,决定保留什么
- 7Evaluate the whole agent with mechanical checks用代码检查评估整个智能体
- 8Repeat, and report the spread重复运行,并报告波动范围
- 9Add model judges with two votes and calibration加入模型裁判:双票制加校准
- 10Schedule the evals and print one line each给评估排上日程,每项输出一行
01Write the human baseline questions编写人工基线问题
- real requests to draw questions from用来提炼问题的真实请求 ← Harness engineeringHarness 工程 7: Assemble run(): guard, retry, log, record组装 run():护栏、重试、日志、记录
Do this操作
- Write real questions a user would ask, with strings a correct answer must contain and the tool it must use.写下用户真实会问的问题,并注明正确回答必须包含的字符串和必须使用的工具。
- Include at least one question the system currently gets wrong, and say why.至少包含一道系统目前答错的问题,并说明原因。
- Add a question each time the system fumbles a real request. Add it to a new versioned file, never to a sealed one.系统每搞砸一个真实请求,就加一道题。加到新版本的文件里,绝不要加进已封存的文件。
{
"_note": "Human-written end-to-end questions. The headline metric. Written before any learning ran.",
"items": [
{"q": "What is the nightly lodging cap?", "must_contain": ["220"], "needs_tool": "search_policy"},
{"q": "Did B. Chen's Boston lodging exceed the lodging cap?", "must_contain": ["219", "under"], "needs_tool": "query_expenses"},
{"q": "Did B. Chen's Chicago lodging exceed the lodging cap?", "must_contain": ["236", "over"], "needs_tool": "query_expenses"},
{"q": "How much was spent on meals in 2026-07?", "must_contain": ["358.60"], "needs_tool": "query_expenses",
"why": "July has no rows. A passing answer retries without the month and reports the total that does exist."},
{"q": "How much was spent on air travel in total?", "must_contain": ["1297.50"], "needs_tool": "query_expenses"},
{"q": "How much was spent on lodging in Denver?", "must_contain": ["198"], "needs_tool": "query_expenses"}
]
}- Evaluation评估 3: Seal the test material before anything learns在任何学习发生之前封存测试材料 (the question file to seal待封存的问题文件)
02Build a retrieval gold set构建检索标准集
- chunk ids to point at要指向的 chunk id ← RAG and knowledge graphRAG 与知识图谱 2: Embed and load, driven by the ledger由台账驱动,向量化并入库
Do this操作
- For sampled chunks, write one question the chunk answers, in different words. Record the chunk id.对抽样的文本块,各写一个它能回答的问题,用不同的措辞。记录 chunk id。
- Tag each with a type: define, rule, cite. Types let you score one kind of question alone.给每题打上类型标签:define、rule、cite。有了类型就能单独给某一类问题评分。
- If a model writes the questions, drop any that copy a six-word run from the chunk. Those test string matching.如果让模型出题,丢弃那些从文本块里照搬连续六个词的题。那种题测的只是字符串匹配。
def copies_passage(question: str, passage: str, n: int = 6) -> bool:
"""True when the question lifts an n-word run from the passage. Such a question
tests string matching, so a generated gold set drops it."""
q = question.lower().split()
p = " ".join(passage.lower().split())
return any(" ".join(q[i:i + n]) in p for i in range(len(q) - n + 1))python3 -m labs.m11_eval.demo3 gold filter: True (copied run, dropped) vs False (paraphrase, kept)- Evaluation评估 3: Seal the test material before anything learns在任何学习发生之前封存测试材料 (the gold file to seal待封存的标准集文件)
- Evaluation评估 4: Write the rank metrics编写排名指标 (the chunk id formatchunk id 的格式)
03Seal the test material before anything learns在任何学习发生之前封存测试材料
- the question file to seal待封存的问题文件 ← Evaluation评估 1: Write the human baseline questions编写人工基线问题
- the gold file to seal待封存的标准集文件 ← Evaluation评估 2: Build a retrieval gold set构建检索标准集
- the heldout column on chunks文本块上的 heldout 列 ← State and storage状态与存储 3: Create the schema, grouped by owner按归属分组建表
Do this操作
- Copy the question files into a frozen folder and record a SHA-256 for each in a manifest.把问题文件复制到 frozen 目录,并在清单里记录每个文件的 SHA-256。
- Mark a deterministic sample of chunks as held out in the database.在数据库里把一批按确定性规则抽样的文本块标记为留出。
- `assert_sealed()` recomputes the hashes and raises if any differ. Call it first in every eval.`assert_sealed()` 重新计算哈希,有任何不一致就报错。每个评估都要先调用它。
- `studiable()` returns the only chunks a learner may read.`studiable()` 返回学习任务唯一可以读取的文本块。
def seal(db: sqlite3.Connection, eval_dir: Path, heldout_every: int = 4) -> dict:
frozen = eval_dir / "frozen"
if (eval_dir / "SEAL.json").exists():
raise RuntimeError("already sealed. Sealing happens once. Make a new versioned set instead of resealing.")
frozen.mkdir(parents=True)
hashes = {}
for name in ("frozen_questions.json", "gold_v1.json"):
dest = frozen / name
shutil.copy2(HERE / name, dest)
hashes[name] = hashlib.sha256(dest.read_bytes()).hexdigest()
os.chmod(dest, 0o444)
ids = [r[0] for r in db.execute("SELECT chunk_id FROM kb_chunks ORDER BY chunk_id")]
# Deterministic sample: the same chunks are held out on every machine.
held = [c for c in ids if int(hashlib.md5(c.encode()).hexdigest(), 16) % heldout_every == 0]
db.executemany("UPDATE kb_chunks SET heldout=1 WHERE chunk_id=?", [(c,) for c in held])
db.commit()
manifest = {"files": hashes, "heldout_chunks": held}
(eval_dir / "SEAL.json").write_text(json.dumps(manifest, indent=1))
os.chmod(eval_dir / "SEAL.json", 0o444)
return manifest
def assert_sealed(eval_dir: Path) -> dict:
"""Call at the top of every eval. Raises if any sealed file differs from its recorded hash."""
manifest = json.loads((eval_dir / "SEAL.json").read_text())
for name, digest in manifest["files"].items():
if hashlib.sha256((eval_dir / "frozen" / name).read_bytes()).hexdigest() != digest:
raise RuntimeError(f"SEAL BROKEN: {name} changed after sealing. Results from this set are void.")
return manifest
def studiable(db: sqlite3.Connection) -> list:
"""The only chunks a learning job may read."""
return [r[0] for r in db.execute("SELECT chunk_id FROM kb_chunks WHERE NOT heldout AND NOT retired ORDER BY 1")]1 sealed: ['frozen_questions.json', 'gold_v1.json'] | held out 4 of 20 chunks | studiable 16
2 reseal refused: already sealed. Sealing happens once. Make a ...
7 tampered gold set: SEAL BROKEN: gold_v1.json changed after sealing. Results from this set are void.- Skills技能(Skills) 7: Score routing with examples the router never saw用路由器没见过的例子给路由打分 (the sealing mechanism封存机制)
- Evaluation评估 5: Run variants and append history运行变体并追加历史 (assert_sealed()assert_sealed())
- Evaluation评估 7: Evaluate the whole agent with mechanical checks用代码检查评估整个智能体 (the sealed questions已封存的问题)
- Self-evolving agents自进化智能体 8: Extend the loop to learn from documents把循环扩展到从文档中学习 (studiable(), the exclusion liststudiable(),即排除清单)
04Write the rank metrics编写排名指标
Do this操作
- From the ordered list of returned chunk ids compute: hit at 1, 3, 5, neighbor hit, document hit, reciprocal rank.根据返回的 chunk id 有序列表计算:前 1、3、5 命中,相邻块命中,文档命中,倒数排名。
- Report several. Exact hit is strict. Document hit shows you are in the right place and chunked badly.多报几个指标。精确命中最严格。文档命中说明位置找对了,但切块有问题。
def score(gold_id: str, results: list) -> dict:
"""Rank metrics for one question, from the ordered list of returned chunk ids."""
doc, idx = gold_id.rsplit("::", 1)
near = {f"{doc}::{int(idx) + d}" for d in (-1, 0, 1)}
rank = results.index(gold_id) + 1 if gold_id in results else 0
return {"hit@1": int(rank == 1), "hit@3": int(0 < rank <= 3), "hit@5": int(0 < rank <= 5),
"near@5": int(any(r in near for r in results[:5])),
"doc@5": int(any(r.startswith(doc + "::") for r in results[:5])),
"mrr": 1 / rank if rank else 0.0}05Run variants and append history运行变体并追加历史
- assert_sealed()assert_sealed() ← Evaluation评估 3: Seal the test material before anything learns在任何学习发生之前封存测试材料
- score()score() ← Evaluation评估 4: Write the rank metrics编写排名指标
- the flags on each ranking feature各项排序功能上的开关 ← RAG and knowledge graphRAG 与知识图谱 6: Add the authority nudge and collapse duplicates加入权威度微调并合并重复
Do this操作
- Define each variant as a set of environment flags.把每个变体定义为一组环境变量开关。
- Verify the seal, set the flags, run every gold question, restore the flags.校验封存、设置开关、跑完所有标准题、恢复开关。
- Append one JSON line: time, variant, sample size, metrics, flags.追加一行 JSON:时间、变体、样本量、指标、开关。
def run(db: sqlite3.Connection, eval_dir: Path, variant: str = "full", only_type: str = "") -> dict:
assert_sealed(eval_dir)
gold = json.loads((eval_dir / "frozen" / "gold_v1.json").read_text())["items"]
gold = [g for g in gold if not only_type or g["type"] == only_type]
saved = {k: os.environ.get(k) for k in ("RAG_HYBRID", "RAG_AUTHORITY", "RAG_DEDUP", "RAG_GRAPH")}
os.environ.update(VARIANTS[variant])
try:
t0 = time.time()
per = [score(g["gold"], [r["chunk_id"] for r in search(db, "POLICY", g["q"], top_k=5)["results"]]) for g in gold]
seconds = time.time() - t0
finally:
for k, v in saved.items(): # leave the environment as we found it
os.environ.pop(k, None) if v is None else os.environ.__setitem__(k, v)
summary = {k: round(sum(p[k] for p in per) / len(per), 3) for k in per[0]}
record = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S"), "variant": variant, "type": only_type or "all",
"n": len(per), **summary, "flags": VARIANTS[variant], "ms_per_query": round(1000 * seconds / len(per), 1)}
with (eval_dir / "retrieval_history.jsonl").open("a") as f: # one line per run, forever
f.write(json.dumps(record) + "\n")
record["misses"] = [g["q"] for g, p in zip(gold, per) if not p["hit@5"]]
return record4 retrieval, same gold set, one flag changed per row:
variant n hit@1 hit@3 hit@5 doc@5 mrr
full 15 0.667 1.000 1.000 1.000 0.800
dense-only 15 0.600 0.733 0.800 0.867 0.683
no-authority 15 0.600 1.000 1.000 1.000 0.767
no-dedup 15 0.667 1.000 1.000 1.000 0.800
no-graph 15 0.667 1.000 1.000 1.000 0.800
misses with everything on: []
type define n=5: hit@5 full 1.00 vs no-graph 1.00
type rule n=8: hit@5 full 1.00 vs no-graph 1.00
type cite n=2: hit@5 full 1.00 vs no-graph 1.00
history lines: 12- Evaluation评估 6: Read the table and decide what stays读懂表格,决定保留什么 (the comparison table对比表)
- Evaluation评估 10: Schedule the evals and print one line each给评估排上日程,每项输出一行 (the history file to read from要读取的历史文件)
- Operations and deployment运维与部署 8: Wire the nightly window把夜间时间窗串起来 (the retrieval eval unit检索评估单元)
- Operations and deployment运维与部署 9: Adopt a change discipline建立改动纪律 (flags and the history file开关和历史文件)
06Read the table and decide what stays读懂表格,决定保留什么
Do this操作
- Compare each variant with `full`. In the recorded run, turning off the keyword side drops hit@1 from 0.667 to 0.600 and hit@5 from 1.000 to 0.800. Hybrid stays.把每个变体与 `full` 对比。在记录的这次运行里,关掉关键词一路后 hit@1 从 0.667 降到 0.600,hit@5 从 1.000 降到 0.800。混合检索保留。
- Turning off authority drops hit@1 to 0.600. It stays.关掉权威加分后 hit@1 降到 0.600。保留。
- Turning off dedup or graph expansion changes nothing on this set. That is a finding. Either the set does not exercise them, or they do not help here.关掉去重或图扩展,在这套题上没有任何变化。这本身就是一个发现:要么这套题没有考到它们,要么它们在这里没有帮助。
- For a feature that shows no gain: write gold questions that should need it, then measure again. Do not keep it on belief.对没有显示出收益的功能:先写出应当需要它的标准题,再重新测量。不要凭信念保留它。
4 retrieval, same gold set, one flag changed per row:
variant n hit@1 hit@3 hit@5 doc@5 mrr
full 15 0.667 1.000 1.000 1.000 0.800
dense-only 15 0.600 0.733 0.800 0.867 0.683
no-authority 15 0.600 1.000 1.000 1.000 0.767
no-dedup 15 0.667 1.000 1.000 1.000 0.800
no-graph 15 0.667 1.000 1.000 1.000 0.800
misses with everything on: []
type define n=5: hit@5 full 1.00 vs no-graph 1.00
type rule n=8: hit@5 full 1.00 vs no-graph 1.00
type cite n=2: hit@5 full 1.00 vs no-graph 1.00
history lines: 1207Evaluate the whole agent with mechanical checks用代码检查评估整个智能体
- the sealed questions已封存的问题 ← Evaluation评估 3: Seal the test material before anything learns在任何学习发生之前封存测试材料
- Agent.run() and its result fieldsAgent.run() 及其结果字段 ← Harness engineeringHarness 工程 7: Assemble run(): guard, retry, log, record组装 run():护栏、重试、日志、记录
- check(), reused to grade figurescheck(),复用来给数字评分 ← Guardrails and verification护栏与验证 2: Write the grounding check编写依据检查
Do this操作
- Send each frozen question through `Agent.run()`.把每道冻结问题交给 `Agent.run()`。
- Grade with code: was the right tool used, are the expected strings present, are the figures grounded.用代码评分:是否用了正确的工具,是否包含预期字符串,数字是否有依据。
- Use a model judge only for what code cannot decide.只有代码无法判断的部分才交给模型裁判。
def grade(item: dict, result: dict) -> dict:
"""Mechanical checks first. A model judge is for what code cannot decide."""
answer = result["answer"]
checks = {
"used_right_tool": item["needs_tool"] in result["tools"],
"has_expected": all(s.lower() in answer.lower() for s in item["must_contain"]),
"figures_grounded": check(answer, result["messages"])["ok"],
}
return {"pass": all(checks.values()), **checks}5 agent eval, deterministic model: 5 of 6
fails: How much was spent on meals in 2026-07? {'used_right_tool': True, 'has_expected': False, 'figures_grounded': True}- Evaluation评估 8: Repeat, and report the spread重复运行,并报告波动范围 (the agent eval to repeat要重复运行的智能体评估)
- Self-evolving agents自进化智能体 1: Check the four preconditions检查四项前提条件 (the sealed agent eval封存的智能体评估)
- Self-evolving agents自进化智能体 4: Assemble the nightly loop with the eval gate组装夜间循环,并加上评估关卡 (agent_eval.run()agent_eval.run())
08Repeat, and report the spread重复运行,并报告波动范围
- the agent eval to repeat要重复运行的智能体评估 ← Evaluation评估 7: Evaluate the whole agent with mechanical checks用代码检查评估整个智能体
Do this操作
- Run the same six questions seven times against a model that invents a figure 30 percent of the time.对一个有 30% 概率编造数字的模型,把同样六道题跑七遍。
- Read the totals. In the recorded run they range from 2 to 5.看各次的总分。在记录的运行中,分数从 2 到 5 不等。
- Note that one run alone would have reported 5 of 6, and another 2 of 6, for the same system.注意:对同一个系统,单看某一次会报告 5/6,单看另一次会报告 2/6。
- Report mean, range, and number of runs together. Never a single total.均值、范围和运行次数要一起报告。绝不只报一个总分。
def run(make_agent, eval_dir: Path, repeats: int = 1) -> dict:
"""make_agent(repeat_index) -> Agent. Returns per-question pass rates and the spread across repeats."""
assert_sealed(eval_dir)
items = json.loads((eval_dir / "frozen" / "frozen_questions.json").read_text())["items"]
per_question = {i["q"]: [] for i in items}
totals = []
for rep in range(repeats):
agent = make_agent(rep)
passed = 0
for item in items:
result = asyncio.run(agent.run([{"role": "user", "content": item["q"]}]))
g = grade(item, result)
per_question[item["q"]].append(g)
passed += g["pass"]
totals.append(passed)
return {"n": len(items), "repeats": repeats, "totals": totals,
"mean": round(statistics.mean(totals), 2),
"spread": (min(totals), max(totals)),
"stdev": round(statistics.stdev(totals), 2) if repeats > 1 else None,
"pass_rate": {q: round(sum(g["pass"] for g in gs) / len(gs), 2) for q, gs in per_question.items()},
"detail": per_question}6 a model that invents a figure 30% of the time, 7 runs of the same 6 questions:
totals [5, 4, 4, 3, 2, 5, 4] | mean 3.86 | spread (2, 5) | stdev 1.07
run 1 alone says 5 of 6 and run 5 alone says 2 of 6- Evaluation评估 9: Add model judges with two votes and calibration加入模型裁判:双票制加校准 (the habit of measuring before trusting先测量、再相信的习惯)
- Multi-agent patterns多智能体模式 1: Write down what the split is for写下拆分的目的 (a way to tell a real gain from noise区分真实提升与噪声的方法)
- Self-evolving agents自进化智能体 7: Know what the lab does not prove明确 lab 没有证明什么 (the noise floor of the agent eval智能体评估的噪声基线)
09Add model judges with two votes and calibration加入模型裁判:双票制加校准
- the habit of measuring before trusting先测量、再相信的习惯 ← Evaluation评估 8: Repeat, and report the spread重复运行,并报告波动范围
- the two-vote implementation双票制的实现 ← Multi-agent patterns多智能体模式 5: Build two independent judges搭建两个相互独立的裁判
Do this操作
- Use two independent judges. Act only when both agree.使用两个相互独立的裁判。只有两者一致时才采取行动。
- Label 50 items yourself and measure each judge's agreement with you.自己标注 50 条,测量每个裁判与你的一致率。
- Review a sample of judge decisions on a schedule. Judge errors are systematic.定期抽查裁判的决定。裁判的错误是系统性的。
def calibrate(items: list, passages: dict) -> dict:
rows = []
for it in items:
p = passages[it["section"]]
rows.append({**it, "literal": judge_literal(it["claim"], p)["supported"],
"semantic": judge_semantic(it["claim"], p)["supported"],
"removed": verify(it["claim"], p)["verdict"].startswith("remove")})
n = len(rows)
agree = {j: sum(r[j] == r["supported"] for r in rows) / n for j in ("literal", "semantic")}
true_removed = [r for r in rows if r["supported"] and r["removed"]] # the costly mistake
false_kept = [r for r in rows if not r["supported"] and not r["removed"]]
return {"n": n, "agreement": agree, "true_claims_removed": true_removed,
"false_claims_kept": false_kept, "rows": rows}python3 -m labs.m12_multi.calibrate1 18 hand-labelled claims | agreement with labels: literal 0.72, semantic 0.72
3 two-vote rule: true claims it would remove 2, false claims it would keep 3
kept but false: Lodging above the cap can be approved after the trip.
kept but false: Business class is allowed for flights of six hours or more.
kept but false: Reports filed after 60 days are reimbursed automatically.10Schedule the evals and print one line each给评估排上日程,每项输出一行
- the history file to read from要读取的历史文件 ← Evaluation评估 5: Run variants and append history运行变体并追加历史
- a scheduler that yields to live traffic一个会给实时流量让路的调度器 ← Operations and deployment运维与部署 5: Schedule background work with preemption and a duty cycle用抢占和占空比来调度后台任务
Do this操作
- Run retrieval and routing evals nightly, the agent eval weekly.检索和路由评估每晚运行,智能体评估每周运行。
- Pause them while a live request is in flight.有实时请求在处理时暂停它们。
- Print the latest value beside the previous value in a daily report.在每日报告里,把最新值和上一次的值并排列出。
METRICS = [("retrieval_history.jsonl", "RETRIEVAL hit@5", "hit@5"), ("retrieval_history.jsonl", "RETRIEVAL mrr", "mrr"),
("routing_history.jsonl", "ROUTING accuracy", "accuracy")]
def report_lines(eval_dir: Path, drop: float = 0.05) -> list:
"""One line per metric: latest, previous, and a flag when it fell by more than `drop`."""
out = []
for fname, label, key in METRICS:
rows = [json.loads(x) for x in (eval_dir / fname).read_text().splitlines()] if (eval_dir / fname).exists() else []
if not rows:
out.append(f"{label:18s} no runs yet")
continue
now = rows[-1][key]
prev = rows[-2][key] if len(rows) > 1 else None
flag = " REGRESSED" if prev is not None and now < prev - drop else ""
out.append(f"{label:18s} {now:.3f}" + (f" (previous {prev:.3f})" if prev is not None else " (first run)") + flag)
return outpython3 -m labs.m15_ops.nightly_evals1 night 1: units ['retrieval-eval', 'routing-eval'], paused for a live request 0 checks (50 ms apart)
daily report:
RETRIEVAL hit@5 1.000 (first run)
RETRIEVAL mrr 0.800 (first run)
ROUTING accuracy 0.667 (first run)
2 night 2: units ['retrieval-eval', 'routing-eval'], paused for a live request 5 checks (50 ms apart)
daily report:
RETRIEVAL hit@5 0.800 (previous 1.000) REGRESSED
RETRIEVAL mrr 0.683 (previous 0.800) REGRESSED
ROUTING accuracy 0.667 (previous 0.667)How it works with the other parts它如何与其他部分协作
- Self-evolving agents自进化智能体The learner may change knowledge and rules. The sealed agent eval is the gate each change must pass.学习任务可以修改知识和规则。封存的智能体评估是每次改动必须通过的关卡。
- Guardrails and verification护栏与验证The guard's check() grades figures in the agent eval. Each guard rule started as an eval failure.护栏的 check() 在智能体评估中给数字评分。每条护栏规则最初都来自一次评估失败。
- RAG and knowledge graphRAG 与知识图谱Every ranking flag is an eval variant, kept or dropped on the history.每个排序开关都是一个评估变体,依据历史记录决定去留。
- Operations and deployment运维与部署Evals run from the scheduler, yield to live traffic, and write into the daily report.评估由调度器运行,给实时流量让路,并写入每日报告。
What went wrong in the real build真实搭建中踩过的坑
Two instruments disagreed about the main result两套测量工具对核心结论给出了不同答案
- What happened发生了什么
- A 30-item single run showed a 23-point gain from learned knowledge. A 75-item set over seven runs showed 0.3 items.30 道题的单次运行显示,学到的知识带来 23 个百分点的提升。75 道题跑七次的结果显示只有 0.3 道题。
- Fix修复
- Stop quoting either number. Record both with sample sizes and investigate the difference.两个数字都不再引用。连同样本量一起记录,并调查差异的原因。
- Lesson教训
- A single run on a small set is an anecdote with a decimal point.小样本上的单次运行,只是带了小数点的个例。
Judges rejected correct claims裁判否决了正确的论断
- What happened发生了什么
- Claim judges treated two names for one organization as different entities and voted against true claims.论断裁判把同一机构的两个名称当成了不同实体,对正确的论断投了反对票。
- Fix修复
- State the equivalence in the judge prompt and recheck every claim rejected for that reason.在裁判提示词里说明两者等价,并重新检查因此被否决的每条论断。
- Lesson教训
- Audit the judge. Its errors are systematic and silent.要审计裁判。它的错误是系统性的,而且悄无声息。
No number moved when search broke检索坏了,却没有任何指标变化
- What happened发生了什么
- The only eval measured answers from a small model. A chunking or ranking change could degrade search with no visible signal.当时唯一的评估测的是小模型的回答。切块或排序的改动可能让检索变差,却看不到任何信号。
- Fix修复
- A dedicated retrieval eval with a sealed gold set.建立专门的检索评估,配封存的标准集。
- Lesson教训
- Give each layer its own measurement.给每一层都配上自己的测量。
A graph feature that moved no metric一个没有改变任何指标的图功能
- What happened发生了什么
- The lab's own eval shows identical scores with graph expansion on and off, on 15 questions.lab 自己的评估显示,在 15 道题上,图扩展开或关得分完全相同。
- Fix修复
- Treat it as unproven. Write questions that need an edge, then measure.把它视为未经证实。先写出需要用到边的题目,再测量。
- Lesson教训
- An eval that never says no is not being read.从不说“不”的评估,说明没有人在认真读它。
The same idea on other platforms同样的思路在其他平台上
| Platform平台 | How this module maps本模块如何对应 |
|---|---|
| Databricks | `mlflow.genai.evaluate` runs scorers over an evaluation dataset stored as a Unity Catalog table, and traces link each score to the run that produced it. Gold sets become tables. Sealing becomes table permissions. The metric code here can be written as custom scorers.`mlflow.genai.evaluate` 在以 Unity Catalog 表形式存储的评估数据集上运行 scorer,trace 把每个分数关联到产生它的运行。标准集变成表,封存变成表权限。这里的指标代码可以写成自定义 scorer。 |
| IBM watsonx | watsonx.governance evaluates and monitors deployed models and agents, and the Orchestrate ADK includes an evaluation framework for agent trajectories. Keep your own gold sets and feed them in.watsonx.governance 对已部署的模型和智能体进行评估和监控,Orchestrate ADK 包含针对智能体轨迹的评估框架。保留你自己的标准集并输入进去。 |
| Codex | Use the provider's evals tooling or plain scripts. Codex can run your eval scripts headless as part of a change, which makes eval a gate in the coding loop.使用供应商的评估工具或普通脚本。Codex 可以在一次改动中以无界面方式运行你的评估脚本,让评估成为编码流程中的关卡。 |
| Cursor | Evals are scripts in your repo. A rule or hook can require the retrieval eval to pass before a change to ranking code is accepted.评估就是你仓库里的脚本。可以用规则或钩子要求:改动排序代码之前,检索评估必须通过。 |
| Claude Code / Agent SDK | Run eval scripts through the coding agent. Keep gold files out of the agent's writable paths.通过编程智能体运行评估脚本。让标准集文件处于智能体可写路径之外。 |
| Another machine | The eval scripts are Python and JSON files. They move with the repo. Rebuild the gold set only if the corpus changed.评估脚本是 Python 和 JSON 文件,随仓库一起迁移。只有语料变了才需要重建标准集。 |
Step-by-step guides per platform各平台的分步指南
Explain it back讲给自己听
Answer aloud first. Then open the answer and compare.先自己说一遍答案,再展开对照。
Why must sealing happen before the learning loop runs, and why is a prompt not enough?为什么封存必须在学习循环运行之前完成?为什么光靠提示词不够?
Your end-to-end score dropped. In what order do you check, and why?端到端得分下降了。你按什么顺序排查?为什么?
A change improves a 6-question eval from 4 to 5 in one run. What do you say?一次改动让 6 道题的评估在一次运行中从 4 分提高到 5 分。你怎么说?
The eval shows a feature has no effect. What are the two possible readings?评估显示某项功能没有效果。有哪两种可能的解读?
What can you evaluate with only a model endpoint and no agent?只有模型端点、没有智能体时,你能评估什么?
Terms术语
| Held-out留出 | Material excluded from learning so it can test generalization.不参与学习、用来检验泛化能力的材料。 |
| MRRMRR(平均倒数排名) | The average of 1/rank of the correct item, zero if absent.正确条目的 1/名次 的平均值,未出现则计 0。 |
| Variant变体 | A named set of flags evaluated against the same gold set.在同一标准集上评估的一组具名开关配置。 |
| Noise floor噪声基线 | The spread between repeated runs of an unchanged system.系统不变时,多次重复运行之间的波动范围。 |
From the live build来自实时构建
Recent changes and files the sync job filed under this module. These lines are in English as written in the build.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。
- Search returns one copy of a paragraph that is in several files; same@10 and distinct@10 in the retrieval eval; dated scheduler log; notice when a no-query draft is replaced; skill: a status is half an answer
- Knowledge graph: 'defines' edges from set definitional forms, used in retrieval for definitional questions; gold set and nightly eval
- Chat eval: the round-limit message counts as a fallback, not a bad answer delivered
- Answer guard checks counts; chat eval in the Sunday cycle; CHAT line in the daily report
- Answer guard: plain message when the model returns nothing twice; chat eval allows 6000 output tokens
- Recall similarity floor 0.35 (eval: lowest hit 0.55, highest unrelated 0.24)
- Weekly agent quiz in the daily cycle; AGENT line in the report
- Citation layer: kb_finance.citations, citation gold set, graph expansion (off)
- FINANCE: name the actual authority, don't just summarize — and show it in practice, not just recite the rule
- Issues 7, 8 and 9 — diagnosis and fix
- BUILD-HOST — user guide
- guards on the retrieval changes of 2026-09-30. Run: venv/bin/python3 test_retrieval.py (no database, no network) 1. SQL v2 renders for nomic (768) and Qwen3 (1024) with no stray fields, and passes the query vector as a parameter (the 5.4 s bug was a CTE) 2.
- does search_knowledge_base find the right passage? (2026-09-30) The weekly quiz measures whether a 9B model answers better with learned atoms. Nothing measured retrieval itself, so a chunker, embedding or ranking change could make search worse and no number would move.
- the agent-facing wrapper around claim_recall. REGISTERED 2026-08-18, AFTER IT EARNED IT. ------------------------------------------ This file sat unregistered until the T5 discrimination drill said it was worth registering.
- the "defines" edge of the knowledge graph. venv/bin/python3 nightly/defines.py --index # scan new chunks (incremental) venv/bin/python3 nightly/defines.py --stats venv/bin/python3 nightly/defines.py --build-gold # once; sealed The citation layer links a passage to what it CITES.
- what the chat box actually does (2026-10-06). chat_eval.py and agent_quiz.py call agent_loop.run(), the non-streaming path. The chat box streams.
- how does the agent answer real multi-turn questions? (2026-10-02) The quiz and the gold sets are single questions with one right letter or one right passage. They never measured the thing a person does in the chat box: ask something, then follow up in five words.
- does conversation recall find the right exchange, stay quiet when nothing fits, and keep users apart? (2026-10-01) Seeds two synthetic users (partitions eval:recall-a / eval:recall-b) straight into mem.turns, asks paraphrased questions, removes the seed rows.
- the discrimination quiz through the REAL agent path (2026-09-30). The audit's top evaluation gap: quiz_runner.py measures the 9B model with and without atoms, never what a user gets.