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

Multi-agent patterns多智能体模式

Several model roles with separate context, tools, and budgets, coordinated by code.多个模型角色,各有独立的上下文、工具和预算,由代码协调。

What it is and why it exists它是什么,为什么需要它

What是什么

A multi-agent system splits work across model calls that each have their own instructions, tools, and context. This module builds two patterns: an orchestrator that fans out to narrow workers, and two independent judges that vote.多智能体系统把工作分给多次模型调用,每次调用都有自己的指令、工具和上下文。本模块搭建两种模式:向专职子智能体扇出的编排器,以及两个独立投票的裁判。

Why为什么

One context window cannot hold everything, and one role cannot check itself. Separate roles give isolation of context and independence of judgment. They also multiply cost and failure modes, so each split needs a measured reason.一个上下文窗口装不下所有东西,一个角色也无法检查自己。分开的角色带来上下文隔离和判断独立。但它们也会成倍增加成本和故障方式,所以每一次拆分都需要有实测的理由。

How it works工作原理

Where it sits in the build order它在搭建顺序中的位置

Needs first前置模块

  • Harness engineeringHarness 工程A sub-agent is a harness loop run as a node. You need one working loop and the wave executor before you can run several.子智能体就是作为节点运行的一个 Harness 循环。要运行多个,先得有一个能用的循环和波次执行器。Build out of order不按顺序搭建 Stand in with:可用以下替代: Two sequential model calls with different system prompts.两次顺序的模型调用,使用不同的系统提示词。
  • Skills技能(Skills)Roles are defined by scoped instructions. A worker's base prompt is a skill that is always on.角色由限定范围的指令来定义。子智能体的基础提示词相当于一个始终生效的技能。Build out of order不按顺序搭建 Stand in with:可用以下替代: Hard-coded role prompts.写死的角色提示词。
  • Evaluation评估Every added agent adds cost and latency. Only an eval can show that a split improved results.每增加一个智能体就增加成本和延迟。只有评估能证明拆分确实改善了结果。Build out of order不按顺序搭建 Stand in with:可用以下替代: Manual comparison on five questions. Enough to learn the pattern, too little to justify it.在五个问题上人工比较。足以学会这个模式,但不足以证明它值得。

Unlocks解锁

Nothing depends on this. It is an end point of the map.没有模块依赖它。它是地图上的一个终点。

In the reference build在参考系统中

Path路径Role作用
apps/agent-server/graph.pyThe executor that runs concurrent nodes.运行并发节点的执行器。
apps/agent-server/nightly/claim_verify.pyTwo-vote check of served claims against their source.对已启用的论断与其来源进行双票核查。
ROLE-DIMENSION-ARCHITECTURE-v2.mdDesign for specialist roles by question dimension.按问题维度划分专职角色的设计。

Process map流程图

Orchestrator and workers编排器与子智能体

  1. 1
    Compound question复合问题Two or more parts that need different data.包含两个或更多部分,分别需要不同的数据。
  2. 2
    Split拆分Each part gets a worker type.每个部分分配一种子智能体。
  3. 3
    Worker wave子智能体波次Workers run at once. Each sees only its part and its tools.各子智能体同时运行。每个只看到自己的那部分问题和自己的工具。
  4. 4
    Fan-in扇入Every worker names the same successor, so it runs once.每个子智能体都指向同一个后继节点,所以后继只运行一次。
  5. 5
    Synthesize汇总Findings are merged in the original order.按原始顺序合并各自的结论。

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 down what the split is for写下拆分的目的
  2. 2Create narrow workers创建专职子智能体
  3. 3Fan out, fan in, synthesize扇出、扇入、汇总
  4. 4Measure what the split cost测量拆分的代价
  5. 5Build two independent judges搭建两个相互独立的裁判
  6. 6Calibrate the judges before they remove anything在裁判移除任何内容之前先校准
01Write down what the split is for写下拆分的目的
Why this step is here为什么这一步排在这里Decide before building. A second agent is justified by one of two needs, and each has a test.动手之前先决定。增加第二个智能体只有两种正当理由,每种都有对应的检验方法。
Uses用到

Do this操作

  1. Isolation: would the sub-task's context crowd out the main one? Test: measure context size per approach.隔离:子任务的上下文会不会挤占主任务的上下文?检验:测量每种做法的上下文大小。
  2. Independence: does the result need a check by something that did not produce it? Test: does a second vote change outcomes on labeled cases.独立性:结果是否需要由没有参与生成它的一方来检查?检验:在已标注的案例上,第二票是否改变了结果。
  3. If neither applies, stay with one agent.两者都不适用,就继续用一个智能体。
You are done when完成标志You can name the need and the measurement that will confirm it.你能说出具体需求,以及用来确认它的测量方式。
Produces产出A stated reason and a test for it.一个明确的理由和对应的检验方法。
02Create narrow workers创建专职子智能体
Why this step is here为什么这一步排在这里Workers come before the orchestrator. A worker is defined by what it cannot reach.先有子智能体,再有编排器。子智能体由“它接触不到什么”来定义。

Do this操作

  1. Build a registry that exposes a subset of tools.创建一个只暴露部分工具的注册表。
  2. Create one Agent per role with that registry and a one-line base prompt.为每个角色创建一个 Agent,使用该注册表和一行基础提示词。
  3. Classify each sub-question to a role. The lab uses rules. A planner model does this in production.把每个子问题分配给一个角色。lab 用规则实现,生产环境由规划模型完成。
labs/m12_multi/orchestrator.py · split
def split(question: str) -> list:
    """Break a compound question into (worker, sub-question). Rules here; a planner model in production."""
    parts = [p.strip(" ?.") for p in re.split(r"\?\s+|\band also\b|;\s*", question) if p.strip(" ?.")]
    out = []
    for p in parts:
        worker = "data" if re.search(r"spen[dt]|paid|total|how much was", p, re.I) else "policy"
        out.append((worker, p + "?"))
    return out
run
python3 -m labs.m12_multi.demo
Recorded output / 记录的输出 · m12.demo
1 split: [('policy', 'What is the deadline for filing an expense report?'), ('data', 'how much was spent on air travel in total?')]
You are done when完成标志The deadline question goes to the policy worker and the spending question to the data worker.关于期限的问题分给了政策子智能体,关于支出的问题分给了数据子智能体。
Produces产出`split()` and a registry subset per role.`split()` 以及每个角色的注册表子集。
Feeds供给
03Fan out, fan in, synthesize扇出、扇入、汇总
Why this step is here为什么这一步排在这里Now the wave executor does for agents what it did for tools. This step reuses it unchanged.现在波次执行器对智能体做的事,和它之前对工具做的一样。这一步原样复用它。

Do this操作

  1. A dispatch node returns one worker node per sub-question.分发节点为每个子问题返回一个子智能体节点。
  2. Each worker node runs its agent and appends a finding.每个子智能体节点运行自己的智能体,并追加一条结论。
  3. Every worker node names the same synthesize node.所有子智能体节点都指向同一个汇总节点。
  4. Synthesize orders the findings and joins them.汇总节点把结论排好顺序并合并。
labs/m12_multi/orchestrator.py · orchestrate
async def orchestrate(question: str, registry: Registry, policy=None) -> dict:
    workers = {"policy": Agent(subset(registry, ["search_policy"]), policy=policy,
                               base_prompt="You answer only from policy documents. Cite the section."),
               "data": Agent(subset(registry, ["query_expenses"]), policy=policy,
                             base_prompt="You answer only from expense records. Name the filters you used.")}
    tasks = split(question)

    def worker_node(i: int, kind: str, sub: str):
        async def node(state: dict) -> tuple:
            r = await workers[kind].run([{"role": "user", "content": sub}])
            return ({"findings_append": [{"i": i, "worker": kind, "question": sub, "answer": r["answer"],
                                          "context_chars": sum(len(str(m.get("content") or "")) for m in r["messages"])}],
                     "model_calls": r["model_calls"]},
                    {"synthesize": synthesize})                 # all workers converge on one node
        return node

    async def dispatch(state: dict) -> tuple:
        return {}, {f"worker:{i}:{k}": worker_node(i, k, s) for i, (k, s) in enumerate(tasks)}

    async def synthesize(state: dict) -> tuple:
        ordered = sorted(state["findings"], key=lambda f: f["i"])
        return {"answer": " ".join(f["answer"] for f in ordered)}, {}

    state = await run_graph("dispatch", dispatch, {"question": question})
    return {"answer": state["answer"], "waves": state["trace"], "findings": sorted(state["findings"], key=lambda f: f["i"]),
            "model_calls": state["model_calls"]}
Recorded output / 记录的输出 · m12.demo
2 waves: [['dispatch'], ['worker:policy', 'worker:data'], ['synthesize']]
3 worker policy context  1477 chars -> Expense reports are due within 30 days after the trip ends. A report filed
3 worker data   context   671 chars -> I found 3 matching expense records totaling 1297.50 dollars.
4 merged: Expense reports are due within 30 days after the trip ends. A report filed after 60 days is not reimbursed without a waiver from the finance director. ...
You are done when完成标志The waves read dispatch, two workers, synthesize. Each finding shows its own context size.波次依次是:分发、两个子智能体、汇总。每条结论都显示了各自的上下文大小。
Produces产出`orchestrate()`: one answer from several isolated agents.`orchestrate()`:由多个相互隔离的智能体得出的一个回答。
Feeds供给
04Measure what the split cost测量拆分的代价
Why this step is here为什么这一步排在这里Right after it works, measure it. This is the test you wrote down in the first step.一跑通就测量。这正是第一步里写下的检验。
Uses用到

Do this操作

  1. Run the same question through one agent with all tools.把同一个问题交给一个拥有全部工具的智能体。
  2. Compare model calls and the largest context each approach needed.比较两种做法的模型调用次数和所需的最大上下文。
  3. Then run both through the agent eval to compare answers.然后让两者都通过智能体评估,比较回答质量。
Recorded output / 记录的输出 · m12.demo
5 cost: orchestrated 4 model calls, largest context 1477 chars | single agent 2 model calls, context 1961 chars
You are done when完成标志You can state the trade: here the split doubles model calls and reduces the largest context.你能说清这笔交换:在这里,拆分让模型调用次数翻倍,同时减小了最大上下文。
Produces产出A measured cost and benefit for this split.这次拆分的实测成本和收益。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。
05Build two independent judges搭建两个相互独立的裁判
Why this step is here为什么这一步排在这里The second pattern is independence. It is built here because the learning loop and the evaluation module both call it.第二种模式是独立性。它放在这里搭建,因为学习循环和评估模块都会调用它。
Uses用到

Do this操作

  1. Judge one is literal: every number in the claim must be in the passage, and most content words too.裁判一是字面型:论断里的每个数字都必须出现在段落中,大部分实词也是。
  2. Judge two is semantic: the claim must be about the same thing, and its numbers must be present. In production this judge is a model prompt.裁判二是语义型:论断必须和段落讲的是同一件事,且其中的数字必须在段落里。在生产环境中这个裁判是一段模型提示词。
  3. Keep when both pass. Flag when one dissents. Remove only when both fail.两者都通过则保留。一方有异议则标记。只有两者都否决才移除。
labs/m12_multi/judges.py · judges
def judge_literal(claim: str, passage: str) -> dict:
    """Strict reader: every number and most content words of the claim must be in the passage."""
    nums = set(NUM.findall(claim))
    missing = [n for n in nums if n not in NUM.findall(passage)]
    words = {w for w in re.findall(r"[a-z]+", claim.lower()) if w not in STOP and len(w) > 2}
    have = set(re.findall(r"[a-z]+", passage.lower()))
    coverage = len(words & have) / max(len(words), 1)
    ok = not missing and coverage >= 0.7
    return {"judge": "literal", "supported": ok,
            "why": f"numbers missing: {missing}" if missing else f"word coverage {coverage:.2f}"}


def judge_semantic(claim: str, passage: str) -> dict:
    """Lenient reader: is the claim about the same thing, and are its numbers present?
    With a real model this judge is a prompt. Here it is embedding similarity."""
    sim = llm.cosine(llm.embed(claim), llm.embed(passage))
    nums_ok = all(n in NUM.findall(passage) for n in NUM.findall(claim))
    return {"judge": "semantic", "supported": sim >= 0.30 and nums_ok, "why": f"similarity {sim:.2f}, numbers present: {nums_ok}"}


def verify(claim: str, passage: str) -> dict:
    votes = [judge_literal(claim, passage), judge_semantic(claim, passage)]
    failed = sum(not v["supported"] for v in votes)
    verdict = "keep" if failed == 0 else "keep (one dissent, flag for review)" if failed == 1 else "remove: unsupported"
    return {"verdict": verdict, "votes": votes}
Recorded output / 记录的输出 · m12.demo
6 Lodging is reimbursed up to 220 dollars per night.         -> keep                                 literal:yes / semantic:yes
6 Lodging cost above 220 dollars per night requires written  -> keep (one dissent, flag for review)  literal:no / semantic:yes
6 Lodging is reimbursed up to 250 dollars per night.         -> remove: unsupported                  literal:no / semantic:no
6 Meals are limited to 75 dollars per day.                   -> remove: unsupported                  literal:no / semantic:no
You are done when完成标志The exact claim is kept, the paraphrase is kept with one dissent, the wrong number is removed, the unrelated claim is removed.原样的论断被保留;换了说法的论断被保留但有一票异议;数字错误的被移除;无关的论断被移除。
Produces产出`verify()`: a verdict with both votes and reasons.`verify()`:包含两票及其理由的裁定。
06Calibrate the judges before they remove anything在裁判移除任何内容之前先校准
Why this step is here为什么这一步排在这里A judge that acts is a guard on stored knowledge. Like the answer guard, it runs in report mode first.会执行动作的裁判,就是针对已存储知识的护栏。和回答护栏一样,它要先以只报告的模式运行。

Do this操作

  1. Label a sample of claims yourself.自己标注一批论断样本。
  2. Run both judges in a dry run and compare with your labels.让两个裁判空跑一遍,与你的标注对比。
  3. Read every disagreement. Fix the judge, then recheck what it rejected.逐条查看不一致之处。修正裁判,然后重新检查它否决过的内容。
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
2 literal  wrong (said no ): Hotel stays are paid at actual cost with a nightly ceiling of 220 dollars.
2 literal  wrong (said no ): Receipts are needed for a single meal over 25 dollars.
2 literal  wrong (said yes): Business class is allowed for flights of six hours or more.
2 literal  wrong (said no ): Reports must be filed within one month of returning.
2 literal  wrong (said yes): Reports filed after 60 days are reimbursed automatically.
2 semantic wrong (said no ): Hotel stays are paid at actual cost with a nightly ceiling of 220 dollars.
2 semantic wrong (said yes): Lodging above the cap can be approved after the trip.
2 semantic wrong (said yes): Business class is allowed for flights of six hours or more.
2 semantic wrong (said no ): Reports must be filed within one month of returning.
2 semantic wrong (said yes): Reports filed after 60 days are reimbursed automatically.
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 know each judge's agreement rate and the kind of claim each gets wrong. In the lab both word-based judges miss paraphrases and pass claims that contradict the passage while sharing its words.你知道每个裁判的一致率,以及各自容易判错哪类论断。在 lab 里,两个基于词语的裁判都识别不了改写,并且会放过那些与原文用词相同、意思却相反的论断。
Produces产出Judges trusted enough to act in the learning loop.可信度足以在学习循环中执行动作的裁判。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。

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

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

2026-10

One judge removed true claims单个裁判移除了正确的论断

What happened发生了什么
A single strict judge voted against claims that were correct simplifications of their source.一个严格的裁判对那些正确简化了来源内容的论断投了反对票。
Fix修复
Two votes. A simplification or an omission alone keeps the claim.改为双票制。仅仅是简化或省略,论断仍然保留。
Lesson教训
Requiring agreement to remove trades a few missed bad claims for far fewer wrongly removed good ones.要求两票一致才移除:会多放过少量坏论断,但误删的好论断少得多。
found while building the labs搭建 lab 时发现

A splitter that misread a word拆分器误读了一个词

What happened发生了什么
The first split rule sent any text containing the word expense to the data worker, including a question about expense report deadlines.最初的拆分规则把任何含有 expense 一词的文本都分给数据子智能体,包括一个关于报销单提交期限的问题。
Fix修复
Match on verbs of spending, and test the split on its own.改为匹配表示“花费”的动词,并单独测试拆分函数。
Lesson教训
Routing between agents is a classifier. Give it examples and score it like the skill router.智能体之间的路由就是一个分类器。给它示例,并像技能路由器那样给它打分。

The same idea on other platforms同样的思路在其他平台上

Platform平台How this module maps本模块如何对应
DatabricksSub-agents can be separate deployed agents or functions inside one agent. Frameworks such as LangGraph and the OpenAI Agents SDK run inside a deployed agent and supply handoffs.子智能体可以是分别部署的智能体,也可以是同一个智能体里的函数。LangGraph、OpenAI Agents SDK 等框架可以在已部署的智能体内部运行,并提供交接机制。
IBM watsonxOrchestrate agents list collaborators and route work among them. This is the platform's core pattern.Orchestrate 的智能体列出协作者,并在它们之间分派工作。这是该平台的核心模式。
CodexSubagents run tasks in separate contexts. The Agents SDK supports handoffs between agents.子智能体在独立的上下文中执行任务。Agents SDK 支持智能体之间的交接。
CursorSubagents and background agents run tasks in parallel with their own context.子智能体和后台智能体各自带着独立上下文并行执行任务。
Claude Code / Agent SDKSubagents have their own context window and tool set, defined in files. The SDK can spawn them from code.子智能体有自己的上下文窗口和工具集,用文件定义。SDK 可以在代码中启动它们。
Another machineThe wave executor is plain Python. Sub-agents are objects.波次执行器是纯 Python。子智能体就是对象。

Step-by-step guides per platform各平台的分步指南

Explain it back讲给自己听

Answer aloud first. Then open the answer and compare.先自己说一遍答案,再展开对照。

Give one good reason and one bad reason to add a second agent.分别举一个增加第二个智能体的好理由和坏理由。
A strong answer参考答案Good: you need an independent check, or a sub-task's context would crowd out the main one. Bad: the architecture diagram looks more capable. Without an eval showing a gain, it is only more cost.好理由:你需要独立的检查,或者子任务的上下文会挤占主任务的上下文。坏理由:架构图看起来更厉害。没有评估证明有提升,那就只是多花成本。
Why two votes for claim verification?为什么论断核查要用两票?
A strong answer参考答案A single judge's error would remove true claims. Requiring both to fail trades some missed bad claims for far fewer wrongly removed good ones.单个裁判出错会移除正确的论断。要求两者都否决才移除:会漏掉一些坏论断,但误删的好论断少得多。
What makes a worker a worker?是什么让一个子智能体成为“子智能体”?
A strong answer参考答案A smaller tool set, its own instructions, and its own message list. It is the same Agent class. Nothing it reads enters another worker's context.更小的工具集、自己的指令、自己的消息列表。它用的是同一个 Agent 类。它读到的任何内容都不会进入其他子智能体的上下文。
How does the orchestrator reuse the harness?编排器如何复用 Harness?
A strong answer参考答案It runs on the same wave executor. Workers fan out as nodes in one wave, each names the synthesize node, and the dict keyed by name runs it once.它运行在同一个波次执行器上。子智能体作为同一波里的节点扇出,各自指向汇总节点,而以名称为键的字典保证汇总节点只运行一次。

Terms术语

Orchestrator编排器Code that splits work, runs workers, and merges results.负责拆分工作、运行子智能体并合并结果的代码。
Worker子智能体An agent with a narrow tool set and its own context.工具集专一、拥有独立上下文的智能体。
Dissent异议One judge of two voting against. It flags a claim and does not remove it.两个裁判中有一个投反对票。它会标记论断,但不会移除。

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就本模块向导师提问