Agent Build智能体搭建 Tutor教程
Map地图 / Module模块 11 / labs/m11_*

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工作原理

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.pyCreates the frozen question set and the held-out chunk manifest.创建冻结的问题集和留出文本块清单。
apps/agent-server/nightly/retrieval_eval.pyBuilds the retrieval gold set and scores hit rate and MRR.构建检索标准集,并计算命中率和 MRR。
apps/agent-server/nightly/chat_eval.pyMulti-turn conversations through the full agent.通过完整智能体进行的多轮对话评估。
apps/agent-server/nightly/stream_eval.pyThe 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从提出改动到做出决定

  1. 1
    Seal封存Once, before learning. Files are hashed and chunks are marked held out.只做一次,在学习之前。对文件做哈希,把部分文本块标记为留出。
  2. 2
    Verify the seal校验封存Every run starts by checking hashes. A changed file voids the run.每次运行先校验哈希。文件被改动则本次运行无效。
  3. 3
    Baseline run基线运行Score the current system. Repeat to learn the spread.给当前系统打分。重复多次以了解波动范围。
  4. 4
    Variant run变体运行Same script and gold set, one flag changed.同一脚本、同一标准集,只改一个开关。
  5. 5
    Compare with noise结合噪声比较Is the difference larger than the spread between repeats?差异是否大于多次重复之间的波动?
  6. 6
    Append history追加历史One line per run with metrics and flags.每次运行一行,记录指标和开关。
  7. 7
    Decide决定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 实际运行时打印的内容。

  1. 1Write the human baseline questions编写人工基线问题
  2. 2Build a retrieval gold set构建检索标准集
  3. 3Seal the test material before anything learns在任何学习发生之前封存测试材料
  4. 4Write the rank metrics编写排名指标
  5. 5Run variants and append history运行变体并追加历史
  6. 6Read the table and decide what stays读懂表格,决定保留什么
  7. 7Evaluate the whole agent with mechanical checks用代码检查评估整个智能体
  8. 8Repeat, and report the spread重复运行,并报告波动范围
  9. 9Add model judges with two votes and calibration加入模型裁判:双票制加校准
  10. 10Schedule the evals and print one line each给评估排上日程,每项输出一行
01Write the human baseline questions编写人工基线问题
Why this step is here为什么这一步排在这里These come first because they must predate your own tooling. Questions written before any learning existed are the only true pre-learning baseline you will ever have.它们排第一,因为必须早于你自己的任何工具。在任何学习发生之前写下的问题,是你唯一能拥有的真正“学习前”基线。
Uses用到

Do this操作

  1. Write real questions a user would ask, with strings a correct answer must contain and the tool it must use.写下用户真实会问的问题,并注明正确回答必须包含的字符串和必须使用的工具。
  2. Include at least one question the system currently gets wrong, and say why.至少包含一道系统目前答错的问题,并说明原因。
  3. Add a question each time the system fumbles a real request. Add it to a new versioned file, never to a sealed one.系统每搞砸一个真实请求,就加一道题。加到新版本的文件里,绝不要加进已封存的文件。
labs/m11_eval/frozen_questions.json
{
  "_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"}
  ]
}
You are done when完成标志Each item has `must_contain` and `needs_tool`.每个条目都有 `must_contain` 和 `needs_tool`。
Produces产出`frozen_questions.json`: the headline metric.`frozen_questions.json`:最核心的指标。
02Build a retrieval gold set构建检索标准集
Why this step is here为什么这一步排在这里Retrieval is scored before end-to-end quality because it is deterministic, fast, needs no judge, and is the most common root cause.先给检索打分,再看端到端质量,因为它确定、快速、不需要裁判,而且是最常见的根本原因。

Do this操作

  1. For sampled chunks, write one question the chunk answers, in different words. Record the chunk id.对抽样的文本块,各写一个它能回答的问题,用不同的措辞。记录 chunk id。
  2. Tag each with a type: define, rule, cite. Types let you score one kind of question alone.给每题打上类型标签:define、rule、cite。有了类型就能单独给某一类问题评分。
  3. If a model writes the questions, drop any that copy a six-word run from the chunk. Those test string matching.如果让模型出题,丢弃那些从文本块里照搬连续六个词的题。那种题测的只是字符串匹配。
labs/m11_eval/retrieval_eval.py · gold-filter
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))
run
python3 -m labs.m11_eval.demo
Recorded output / 记录的输出 · m11.demo
3 gold filter: True (copied run, dropped) vs False (paraphrase, kept)
You are done when完成标志The copied question is flagged True and the paraphrase False.照搬的问题被标记为 True,换了说法的问题为 False。
Produces产出`gold_v1.json`: question, gold chunk id, type.`gold_v1.json`:问题、标准 chunk id、类型。
03Seal the test material before anything learns在任何学习发生之前封存测试材料
Why this step is here为什么这一步排在这里Sealing must precede the learning loop and cannot be done afterward. Once a learner has read a chunk or seen a question, that item no longer measures generalization.封存必须先于学习循环,而且事后无法补做。学习任务一旦读过某个文本块或见过某道题,它就不再能衡量泛化能力。
Uses用到

Do this操作

  1. Copy the question files into a frozen folder and record a SHA-256 for each in a manifest.把问题文件复制到 frozen 目录,并在清单里记录每个文件的 SHA-256。
  2. Mark a deterministic sample of chunks as held out in the database.在数据库里把一批按确定性规则抽样的文本块标记为留出。
  3. `assert_sealed()` recomputes the hashes and raises if any differ. Call it first in every eval.`assert_sealed()` 重新计算哈希,有任何不一致就报错。每个评估都要先调用它。
  4. `studiable()` returns the only chunks a learner may read.`studiable()` 返回学习任务唯一可以读取的文本块。
labs/m11_eval/seal.py · seal
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")]
Recorded output / 记录的输出 · m11.demo
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.
You are done when完成标志Resealing is refused. A gold file edited after sealing stops the eval with SEAL BROKEN.重复封存被拒绝。封存后被修改的标准文件会让评估以 SEAL BROKEN 终止。
Produces产出`SEAL.json`, `assert_sealed()`, and `studiable()`. The learner depends on all three.`SEAL.json`、`assert_sealed()` 和 `studiable()`。学习任务依赖这三样。
04Write the rank metrics编写排名指标
Why this step is here为什么这一步排在这里Metric code follows the gold set because the definitions depend on what a gold item identifies: a chunk, its neighbors, its document.指标代码排在标准集之后,因为指标的定义取决于标准条目标识的是什么:一个文本块、它的相邻块、它所在的文档。
Uses用到

Do this操作

  1. 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 命中,相邻块命中,文档命中,倒数排名。
  2. Report several. Exact hit is strict. Document hit shows you are in the right place and chunked badly.多报几个指标。精确命中最严格。文档命中说明位置找对了,但切块有问题。
labs/m11_eval/retrieval_eval.py · score
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}
You are done when完成标志A gold id at position 2 scores hit@1 0, hit@3 1, and reciprocal rank 0.5.标准 id 排在第 2 位时:hit@1 为 0,hit@3 为 1,倒数排名为 0.5。
Produces产出`score()`: one question's metrics.`score()`:单个问题的各项指标。
05Run variants and append history运行变体并追加历史
Why this step is here为什么这一步排在这里This needs the seal, the score function, and the flags built into retrieval. It is the mechanism that turns every later change into an experiment.这一步需要封存、评分函数,以及检索模块里内置的开关。正是这个机制把之后的每次改动变成一次实验。

Do this操作

  1. Define each variant as a set of environment flags.把每个变体定义为一组环境变量开关。
  2. Verify the seal, set the flags, run every gold question, restore the flags.校验封存、设置开关、跑完所有标准题、恢复开关。
  3. Append one JSON line: time, variant, sample size, metrics, flags.追加一行 JSON:时间、变体、样本量、指标、开关。
labs/m11_eval/retrieval_eval.py · run
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 record
Recorded output / 记录的输出 · m11.demo
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: 12
You are done when完成标志The table has one row per variant, all with the same n.表格里每个变体一行,样本量 n 全都相同。
Produces产出`retrieval_history.jsonl` and a comparison table.`retrieval_history.jsonl` 和一张对比表。
06Read the table and decide what stays读懂表格,决定保留什么
Why this step is here为什么这一步排在这里A table is not a decision. This step is the discipline: keep a feature only if a number moved.有表格不等于有决定。这一步是纪律:只有指标真的变了,才保留一项功能。

Do this操作

  1. 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。混合检索保留。
  2. Turning off authority drops hit@1 to 0.600. It stays.关掉权威加分后 hit@1 降到 0.600。保留。
  3. 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.关掉去重或图扩展,在这套题上没有任何变化。这本身就是一个发现:要么这套题没有考到它们,要么它们在这里没有帮助。
  4. For a feature that shows no gain: write gold questions that should need it, then measure again. Do not keep it on belief.对没有显示出收益的功能:先写出应当需要它的标准题,再重新测量。不要凭信念保留它。
Recorded output / 记录的输出 · m11.demo
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: 12
You are done when完成标志For every flag you can state the measured effect and the sample size, here 15 questions.对每个开关,你都能说出实测效果和样本量,这里是 15 道题。
Produces产出A keep or drop decision per feature, with a number behind it.每项功能保留或去掉的决定,背后都有数字。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。
07Evaluate the whole agent with mechanical checks用代码检查评估整个智能体
Why this step is here为什么这一步排在这里End-to-end evals come after the layer evals, so when the full score drops you already know which layer to check.端到端评估排在分层评估之后,这样总分下降时你已经知道该检查哪一层。

Do this操作

  1. Send each frozen question through `Agent.run()`.把每道冻结问题交给 `Agent.run()`。
  2. Grade with code: was the right tool used, are the expected strings present, are the figures grounded.用代码评分:是否用了正确的工具,是否包含预期字符串,数字是否有依据。
  3. Use a model judge only for what code cannot decide.只有代码无法判断的部分才交给模型裁判。
labs/m11_eval/agent_eval.py · grade
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}
Recorded output / 记录的输出 · m11.demo
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}
You are done when完成标志The deterministic agent scores 5 of 6, and the failing question shows which check failed.确定性智能体得分 5/6,未通过的问题显示了是哪项检查没过。
Produces产出`agent_eval.run()`: the gate the learning loop must pass.`agent_eval.run()`:学习循环必须通过的关卡。
08Repeat, and report the spread重复运行,并报告波动范围
Why this step is here为什么这一步排在这里This is what makes the earlier steps worth doing. It needs a working agent eval, and it comes before you trust any single result.正是这一步让前面的工作有价值。它需要智能体评估已经可用,并且要在你相信任何单次结果之前完成。
Uses用到

Do this操作

  1. Run the same six questions seven times against a model that invents a figure 30 percent of the time.对一个有 30% 概率编造数字的模型,把同样六道题跑七遍。
  2. Read the totals. In the recorded run they range from 2 to 5.看各次的总分。在记录的运行中,分数从 2 到 5 不等。
  3. Note that one run alone would have reported 5 of 6, and another 2 of 6, for the same system.注意:对同一个系统,单看某一次会报告 5/6,单看另一次会报告 2/6。
  4. Report mean, range, and number of runs together. Never a single total.均值、范围和运行次数要一起报告。绝不只报一个总分。
labs/m11_eval/agent_eval.py · run
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}
Recorded output / 记录的输出 · m11.demo
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
You are done when完成标志You can say the spread of your own eval before claiming any improvement.在宣称任何改进之前,你能说出自己评估的波动范围。
Produces产出A measured noise floor. A change must beat it to count.一个实测的噪声基线。改动必须超过它才算数。
Feeds供给
09Add model judges with two votes and calibration加入模型裁判:双票制加校准
Why this step is here为什么这一步排在这里Judges are needed for free-text fidelity, and they are models with their own errors. They come late because you calibrate them against the deterministic checks you already have.判断自由文本是否忠实需要裁判,但裁判也是会出错的模型。它们放在后面,因为要用你已有的确定性检查来校准。
Uses用到

Do this操作

  1. Use two independent judges. Act only when both agree.使用两个相互独立的裁判。只有两者一致时才采取行动。
  2. Label 50 items yourself and measure each judge's agreement with you.自己标注 50 条,测量每个裁判与你的一致率。
  3. Review a sample of judge decisions on a schedule. Judge errors are systematic.定期抽查裁判的决定。裁判的错误是系统性的。
labs/m12_multi/calibrate.py · calibrate
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}
run
python3 -m labs.m12_multi.calibrate
Recorded output / 记录的输出 · m12.calibrate
1 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.
You are done when完成标志You can state each judge's agreement rate with your labels, and how many true claims the two-vote rule would remove. In the lab both judges agree with the labels 0.72 of the time, which is not good enough to act on.你能说出每个裁判与你标注的一致率,以及双票制会误删多少条真实论断。在 lab 里两个裁判与标注的一致率都是 0.72,还不足以据此采取行动。
Produces产出Calibrated judges for what code cannot grade.经过校准的裁判,用于代码无法评分的部分。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。
10Schedule the evals and print one line each给评估排上日程,每项输出一行
Why this step is here为什么这一步排在这里Automation comes after the evals are trusted. Scheduling an eval you do not believe produces a dashboard nobody reads.等评估值得信任之后再自动化。把一个你自己都不信的评估排上日程,只会得到一个没人看的仪表盘。
Uses用到

Do this操作

  1. Run retrieval and routing evals nightly, the agent eval weekly.检索和路由评估每晚运行,智能体评估每周运行。
  2. Pause them while a live request is in flight.有实时请求在处理时暂停它们。
  3. Print the latest value beside the previous value in a daily report.在每日报告里,把最新值和上一次的值并排列出。
labs/m15_ops/nightly_evals.py · 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 out
run
python3 -m labs.m15_ops.nightly_evals
Recorded output / 记录的输出 · m15.nightly
1 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)
You are done when完成标志The report shows each eval's latest and previous value, and on night 2 it flags the retrieval drop caused by switching keyword search off.报告显示每项评估的最新值和上一次的值;第二晚,它标出了关闭关键词检索导致的检索指标下降。
Produces产出A regression signal you see without asking.一个不用主动去查就能看到的回归信号。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。

How it works with the other parts它如何与其他部分协作

What went wrong in the real build真实搭建中踩过的坑

2026-09

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.小样本上的单次运行,只是带了小数点的个例。
2026-10

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.要审计裁判。它的错误是系统性的,而且悄无声息。
2026-08

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.给每一层都配上自己的测量。
found while building the labs搭建 lab 时发现

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 watsonxwatsonx.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 包含针对智能体轨迹的评估框架。保留你自己的标准集并输入进去。
CodexUse 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 可以在一次改动中以无界面方式运行你的评估脚本,让评估成为编码流程中的关卡。
CursorEvals 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 SDKRun eval scripts through the coding agent. Keep gold files out of the agent's writable paths.通过编程智能体运行评估脚本。让标准集文件处于智能体可写路径之外。
Another machineThe 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?为什么封存必须在学习循环运行之前完成?为什么光靠提示词不够?
A strong answer参考答案A loop optimizes whatever is measurable. If it can select or phrase its own test, the score climbs while nothing is learned. An instruction can be ignored. A hash check that refuses to run cannot.循环会优化任何可测量的东西。如果它能挑选或改写自己的考题,分数会上升,却什么都没学到。指令可以被忽略,而一个不匹配就拒绝运行的哈希校验无法被绕过。
Your end-to-end score dropped. In what order do you check, and why?端到端得分下降了。你按什么顺序排查?为什么?
A strong answer参考答案Retrieval eval, then routing eval, then the guard log, then the model. That order goes from deterministic and cheap to stochastic and expensive, and it follows the direction data flows.检索评估、路由评估、护栏日志、最后是模型。这个顺序从确定且便宜到随机且昂贵,也与数据流动的方向一致。
A change improves a 6-question eval from 4 to 5 in one run. What do you say?一次改动让 6 道题的评估在一次运行中从 4 分提高到 5 分。你怎么说?
A strong answer参考答案That it is not yet known. The lab's own repeats range from 2 to 5 on those questions for one system. Run it several times, report the spread, and use a larger set.还不能下结论。lab 自己的重复运行显示,同一个系统在这些题上的得分从 2 到 5 不等。多跑几次,报告波动范围,并使用更大的题集。
The eval shows a feature has no effect. What are the two possible readings?评估显示某项功能没有效果。有哪两种可能的解读?
A strong answer参考答案The set does not contain questions that exercise it, or it does not help. Write questions that should need it and measure again. Until then it is unproven and stays behind its flag.要么题集里没有能考到它的题,要么它确实没用。写出应当需要它的题目再测一次。在此之前它属于未经证实,继续留在开关后面。
What can you evaluate with only a model endpoint and no agent?只有模型端点、没有智能体时,你能评估什么?
A strong answer参考答案Everything in the scoring scripts. Point them at the endpoint. You learn the unaided baseline, which is the number the agent has to beat.评分脚本里的所有内容。把它们指向端点即可。你会得到无辅助的基线,也就是智能体必须超过的那个数字。

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.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。

Ask the tutor about this module就本模块向导师提问