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工作原理
- A worker is the same Agent class with a smaller tool registry and its own message list.子智能体就是同一个 Agent 类,只是工具注册表更小、消息列表是自己的。
- The orchestrator splits a question, runs workers as nodes in one wave, and merges their findings in a final node.编排器拆分问题,把各个子智能体作为同一波里的节点运行,再在最后一个节点合并它们的结论。
- Two judges with different methods vote on whether a claim is supported. A claim is removed only when both fail it.两个方法不同的裁判对一条论断是否有依据进行投票。只有两者都否决时,论断才被移除。
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.py | The executor that runs concurrent nodes.运行并发节点的执行器。 |
| apps/agent-server/nightly/claim_verify.py | Two-vote check of served claims against their source.对已启用的论断与其来源进行双票核查。 |
| ROLE-DIMENSION-ARCHITECTURE-v2.md | Design for specialist roles by question dimension.按问题维度划分专职角色的设计。 |
Process map流程图
Orchestrator and workers编排器与子智能体
- 1Compound question复合问题Two or more parts that need different data.包含两个或更多部分,分别需要不同的数据。
- 2Split拆分Each part gets a worker type.每个部分分配一种子智能体。
- 3Worker wave子智能体波次Workers run at once. Each sees only its part and its tools.各子智能体同时运行。每个只看到自己的那部分问题和自己的工具。
- 4Fan-in扇入Every worker names the same successor, so it runs once.每个子智能体都指向同一个后继节点,所以后继只运行一次。
- 5Synthesize汇总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 实际运行时打印的内容。
- 1Write down what the split is for写下拆分的目的
- 2Create narrow workers创建专职子智能体
- 3Fan out, fan in, synthesize扇出、扇入、汇总
- 4Measure what the split cost测量拆分的代价
- 5Build two independent judges搭建两个相互独立的裁判
- 6Calibrate the judges before they remove anything在裁判移除任何内容之前先校准
01Write down what the split is for写下拆分的目的
- a way to tell a real gain from noise区分真实提升与噪声的方法 ← Evaluation评估 8: Repeat, and report the spread重复运行,并报告波动范围
Do this操作
- Isolation: would the sub-task's context crowd out the main one? Test: measure context size per approach.隔离:子任务的上下文会不会挤占主任务的上下文?检验:测量每种做法的上下文大小。
- Independence: does the result need a check by something that did not produce it? Test: does a second vote change outcomes on labeled cases.独立性:结果是否需要由没有参与生成它的一方来检查?检验:在已标注的案例上,第二票是否改变了结果。
- If neither applies, stay with one agent.两者都不适用,就继续用一个智能体。
02Create narrow workers创建专职子智能体
- the reason for the split拆分的理由 ← Multi-agent patterns多智能体模式 1: Write down what the split is for写下拆分的目的
- the Agent classAgent 类 ← Harness engineeringHarness 工程 7: Assemble run(): guard, retry, log, record组装 run():护栏、重试、日志、记录
- a registry to take a subset of用来取子集的注册表 ← Tools and MCP工具与 MCP 2: Build the registry搭建注册表
Do this操作
- Build a registry that exposes a subset of tools.创建一个只暴露部分工具的注册表。
- Create one Agent per role with that registry and a one-line base prompt.为每个角色创建一个 Agent,使用该注册表和一行基础提示词。
- Classify each sub-question to a role. The lab uses rules. A planner model does this in production.把每个子问题分配给一个角色。lab 用规则实现,生产环境由规划模型完成。
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 outpython3 -m labs.m12_multi.demo1 split: [('policy', 'What is the deadline for filing an expense report?'), ('data', 'how much was spent on air travel in total?')]- Multi-agent patterns多智能体模式 3: Fan out, fan in, synthesize扇出、扇入、汇总 (workers and the split子智能体和拆分函数)
03Fan out, fan in, synthesize扇出、扇入、汇总
- workers and the split子智能体和拆分函数 ← Multi-agent patterns多智能体模式 2: Create narrow workers创建专职子智能体
- run_graph()run_graph() ← Harness engineeringHarness 工程 2: Write the wave executor编写波次执行器
- an append key for findings用于结论的追加键 ← State and storage状态与存储 4: Define merge rules for run state定义运行状态的合并规则
Do this操作
- A dispatch node returns one worker node per sub-question.分发节点为每个子问题返回一个子智能体节点。
- Each worker node runs its agent and appends a finding.每个子智能体节点运行自己的智能体,并追加一条结论。
- Every worker node names the same synthesize node.所有子智能体节点都指向同一个汇总节点。
- Synthesize orders the findings and joins them.汇总节点把结论排好顺序并合并。
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"]}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. ...- Multi-agent patterns多智能体模式 4: Measure what the split cost测量拆分的代价 (both paths to compare可供比较的两条路径)
04Measure what the split cost测量拆分的代价
- both paths to compare可供比较的两条路径 ← Multi-agent patterns多智能体模式 3: Fan out, fan in, synthesize扇出、扇入、汇总
Do this操作
- Run the same question through one agent with all tools.把同一个问题交给一个拥有全部工具的智能体。
- Compare model calls and the largest context each approach needed.比较两种做法的模型调用次数和所需的最大上下文。
- Then run both through the agent eval to compare answers.然后让两者都通过智能体评估,比较回答质量。
5 cost: orchestrated 4 model calls, largest context 1477 chars | single agent 2 model calls, context 1961 chars05Build two independent judges搭建两个相互独立的裁判
- embed(), and chat() when a judge is a modelembed();裁判是模型时还需要 chat() ← Inference engineering推理工程 5: Write one client function and use it everywhere写一个客户端函数,全系统共用
Do this操作
- Judge one is literal: every number in the claim must be in the passage, and most content words too.裁判一是字面型:论断里的每个数字都必须出现在段落中,大部分实词也是。
- 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.裁判二是语义型:论断必须和段落讲的是同一件事,且其中的数字必须在段落里。在生产环境中这个裁判是一段模型提示词。
- Keep when both pass. Flag when one dissents. Remove only when both fail.两者都通过则保留。一方有异议则标记。只有两者都否决才移除。
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}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- Evaluation评估 9: Add model judges with two votes and calibration加入模型裁判:双票制加校准 (the two-vote implementation双票制的实现)
- Multi-agent patterns多智能体模式 6: Calibrate the judges before they remove anything在裁判移除任何内容之前先校准 (verify()verify())
- Self-evolving agents自进化智能体 8: Extend the loop to learn from documents把循环扩展到从文档中学习 (verify(), the two-vote checkverify(),即双票核查)
06Calibrate the judges before they remove anything在裁判移除任何内容之前先校准
- verify()verify() ← Multi-agent patterns多智能体模式 5: Build two independent judges搭建两个相互独立的裁判
- the observe-first practice先观察再执行的做法 ← Guardrails and verification护栏与验证 4: Run in observe mode first先以观察模式运行
Do this操作
- Label a sample of claims yourself.自己标注一批论断样本。
- Run both judges in a dry run and compare with your labels.让两个裁判空跑一遍,与你的标注对比。
- Read every disagreement. Fix the judge, then recheck what it rejected.逐条查看不一致之处。修正裁判,然后重新检查它否决过的内容。
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
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.How it works with the other parts它如何与其他部分协作
- Harness engineeringHarness 工程Workers are Agent instances. The orchestrator is three nodes on the same executor.子智能体是 Agent 的实例。编排器是同一个执行器上的三个节点。
- Evaluation评估The agent eval decides whether a split helped. Judges are calibrated like any eval instrument.由智能体评估来判断拆分是否有帮助。裁判要像任何评估工具一样校准。
- Self-evolving agents自进化智能体The nightly loop uses the two-vote check to take unsupported claims out of service.夜间循环用双票核查把没有依据的论断停用。
- Operations and deployment运维与部署Background agents pause while a live request holds the busy marker.实时请求持有忙碌标记期间,后台智能体暂停。
What went wrong in the real build真实搭建中踩过的坑
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.要求两票一致才移除:会多放过少量坏论断,但误删的好论断少得多。
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本模块如何对应 |
|---|---|
| Databricks | Sub-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 watsonx | Orchestrate agents list collaborators and route work among them. This is the platform's core pattern.Orchestrate 的智能体列出协作者,并在它们之间分派工作。这是该平台的核心模式。 |
| Codex | Subagents run tasks in separate contexts. The Agents SDK supports handoffs between agents.子智能体在独立的上下文中执行任务。Agents SDK 支持智能体之间的交接。 |
| Cursor | Subagents and background agents run tasks in parallel with their own context.子智能体和后台智能体各自带着独立上下文并行执行任务。 |
| Claude Code / Agent SDK | Subagents have their own context window and tool set, defined in files. The SDK can spawn them from code.子智能体有自己的上下文窗口和工具集,用文件定义。SDK 可以在代码中启动它们。 |
| Another machine | The 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.分别举一个增加第二个智能体的好理由和坏理由。
Why two votes for claim verification?为什么论断核查要用两票?
What makes a worker a worker?是什么让一个子智能体成为“子智能体”?
How does the orchestrator reuse the harness?编排器如何复用 Harness?
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.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。
- The Role Dimension — Architecture v2
- The Role Dimension — Architecture