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

Harness engineeringHarness 工程

The loop around the model: prompt assembly, tool execution, budgets, checks, logs.包裹模型的那层循环:组装提示词、执行工具、控制预算、检查结果、记录日志。

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

What是什么

The harness is the program that runs the model. It assembles the prompt, offers tools, executes the calls the model asks for, feeds results back, decides when to stop, checks the answer, and records what happened.Harness 是运行模型的那个程序。它组装提示词、提供工具、执行模型请求的调用、把结果送回去、决定何时停止、检查回答,并记录发生了什么。

Why为什么

A model call is stateless and cannot act. Which tools exist, how many rounds are allowed, what gets truncated, what is checked before the user sees it: all of that is the harness. Two systems with the same model and different harnesses behave like different products.模型调用是无状态的,也无法执行任何操作。有哪些工具、允许多少轮、什么内容会被截断、用户看到之前检查什么,这些全都由 Harness 决定。同一个模型配上不同的 Harness,表现得就像两个不同的产品。

How it works工作原理

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

Needs first前置模块

  • API and gatewayAPI 与网关The harness sits behind the gateway contract. Keys carry scopes, and the harness reads the scope to decide whether a caller gets tools.Harness 位于网关契约之后。密钥带有权限范围,Harness 根据它决定调用方能否使用工具。Build out of order不按顺序搭建 Stand in with:可用以下替代: One anonymous caller with tools always on.一个匿名调用方,工具始终开启。
  • Inference engineering推理工程The planner is a model call. Round budgets and output caps are set from measured rates.规划节点就是一次模型调用。轮次预算和输出上限根据测得的速率设定。Build out of order不按顺序搭建 Stand in with:可用以下替代: The fake model with a scripted policy. Every harness lab uses it.带脚本策略的假模型。Harness 的所有 lab 都用它。
  • State and storage状态与存储Concurrent tool results have to merge into one conversation without overwriting each other. The merge rules exist before the loop that relies on them.并发的工具结果必须合并进同一个对话而不互相覆盖。合并规则要先于依赖它的循环而存在。Build out of order不按顺序搭建 Stand in with:可用以下替代: A plain dict and sequential tool execution: the flat loop.一个普通字典加顺序执行工具,也就是扁平循环。
  • Tools and MCP工具与 MCPA loop with no tools is a chat proxy. You need a registry with at least one tool to exercise the tool path.没有工具的循环只是个聊天代理。至少要有一个带工具的注册表,才能走通工具路径。Build out of order不按顺序搭建 Stand in with:可用以下替代: One local function such as a clock.一个本地函数,比如返回当前时间。

Unlocks解锁

  • Skills技能(Skills)A skill is text injected during prompt composition. Without that step there is nowhere to load it.技能是在组装提示词时注入的文本。没有那一步,它就无处加载。
  • Memory记忆Memory is read at prompt composition and written after the response. Both are harness stages.记忆在组装提示词时读取,在响应之后写入。这两处都是 Harness 的阶段。
  • Guardrails and verification护栏与验证The guard is a stage in the loop, after the draft and before the response. Hooks wrap tool execution. Both need the loop's plug points.护栏是循环中的一个阶段,在草稿之后、响应之前。钩子包裹工具执行。两者都需要循环提供的接入点。
  • Evaluation评估End-to-end evals send requests through the agent and read which tools it used.端到端评估通过智能体发送请求,并读取它用了哪些工具。
  • Multi-agent patterns多智能体模式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 循环。要运行多个,先得有一个能用的循环和波次执行器。
  • SDKs and frameworksSDK 与框架You evaluate an SDK by comparing it with a loop you understand. Without that, every framework's defaults look like requirements.评估一个 SDK,靠的是把它和你理解的循环做比较。没有这个基础,任何框架的默认值看起来都像是必须如此。
  • Operations and deployment运维与部署The agent server is the main service. Its health path and busy marker are what the supervisor and scheduler read.智能体服务是主服务。守护进程和调度器读取的正是它的健康检查路径和忙碌标记。

In the reference build在参考系统中

Path路径Role作用
apps/agent-server/main.pyHTTP surface: chat completions, models, feedback, health.HTTP 接口:chat completions、models、feedback、health。
apps/agent-server/graph.pyA 110-line wave executor: fan-out, fan-in, merge rules, wave budget, trace.110 行的波次执行器:扇出、扇入、合并规则、波次预算、追踪。
apps/agent-server/agent_loop.pyThe planner and tool graph, prompt composition, streaming, logging.规划与工具图、提示词组装、流式输出、日志。
apps/agent-server/AGENT.mdThe base system prompt.基础系统提示词。

Process map流程图

One request through the harness一个请求如何通过 Harness

  1. 1
    Compose prompt组装提示词Base instructions, at most one skill, the caller's memory.基础指令、至多一个技能、调用方的记忆。
  2. 2
    Planner规划节点Model call with tool schemas. Returns an answer or tool calls.带工具 schema 的模型调用。返回回答或工具调用。
  3. 3
    Tool wave工具波次All requested calls run at once. Hooks run first. Results are capped and logged.所有被请求的调用并发执行。先跑钩子。结果被截断并记录日志。
    ↺ loops to step回到第 2步: back to the planner, up to the round budget回到规划节点,直到轮次预算用完
  4. 4
    Budget check预算检查Out of rounds: withdraw tools and ask for an answer from the evidence.轮次用完:撤掉工具,要求根据已有证据作答。
  5. 5
    Guard护栏Check the draft against this request's evidence. One corrective retry.把草稿与本次请求的证据比对。允许一次纠正重试。
  6. 6
    Respond响应Return the answer in the format the caller sent.以调用方使用的格式返回回答。
  7. 7
    Record记录Request log, tool log, memory. After the answer, never before.请求日志、工具日志、记忆。都在回答之后进行,绝不提前。

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. 1Build the flat loop and bound it搭建扁平循环并设上限
  2. 2Write the wave executor编写波次执行器
  3. 3Express the loop as planner and tool nodes把循环表达为规划节点和工具节点
  4. 4Handle a spent budget as a designed outcome把预算耗尽当作设计内的结果来处理
  5. 5Compose the system prompt from parts分部分组装系统提示词
  6. 6Add hooks before tool execution在工具执行前加入钩子
  7. 7Assemble run(): guard, retry, log, record组装 run():护栏、重试、日志、记录
  8. 8Put cheap deterministic gates in front of the planner在规划节点前放置便宜的确定性关卡
  9. 9Add streaming last最后再加流式输出
01Build the flat loop and bound it搭建扁平循环并设上限
Why this step is here为什么这一步排在这里The flat loop is the smallest thing that is an agent. It joins the model client and the tool registry. Get it correct and bounded before adding concurrency, because every later feature is a refinement of it.扁平循环是能称为智能体的最小形态。它把模型客户端和工具注册表连在一起。先把它做对、设好上限,再加并发,因为后面的每项功能都是在它之上的改进。

Do this操作

  1. Call the model with the tool schemas.带着工具 schema 调用模型。
  2. If the reply has tool calls: run each through the registry and append a role=tool message with the matching tool_call_id.如果回复里有工具调用:逐个通过注册表执行,并追加带对应 tool_call_id 的 role=tool 消息。
  3. If the reply has none: return its content.如果没有工具调用:返回其内容。
  4. Stop after a fixed number of rounds.达到固定轮数后停止。
labs/m07_harness/loop.py · flat
def flat_loop(messages: list, registry: Registry, max_rounds: int = 6, policy=None) -> Optional[str]:
    """Call the model, run the tools it asks for, repeat. Sequential and bounded."""
    messages = list(messages)
    for _ in range(max_rounds):
        msg = llm.chat(messages, tools=registry.schemas(), policy=policy)["choices"][0]["message"]
        messages.append(msg)
        calls = msg.get("tool_calls") or []
        if not calls:
            return msg["content"]
        for call in calls:
            args = json.loads(call["function"]["arguments"] or "{}")
            messages.append({"role": "tool", "tool_call_id": call["id"],
                             "content": registry.call_as_text(call["function"]["name"], args)})
    return None        # out of rounds; the wave version handles this properly
run
python3 -m labs.m07_harness.demo
Recorded output / 记录的输出 · m07.demo
1 flat loop  : The lodging cap is 220 dollars per night (policy NW-FIN-012, Section 3). B. Chen paid 219.00 dollars for lodging in Boston on 2026-06-02, which is under the cap.
You are done when完成标志The answer states the cap and the amount, and both came from tool results.回答说出了上限和金额,而且两者都来自工具结果。
Produces产出`flat_loop()`: the correctness reference for everything after.`flat_loop()`:后续所有实现的正确性参照。
02Write the wave executor编写波次执行器
Why this step is here为什么这一步排在这里It follows the flat loop because it is the same behavior with two additions: tool calls in one turn run concurrently, and their results merge safely. It needs the merge rules from the state module.它排在扁平循环之后,因为行为相同,只多了两点:同一轮的工具调用并发执行,结果安全合并。它需要状态模块里的合并规则。

Do this操作

  1. A node is an async function from state to a pair: an update, and the next nodes by name.节点是一个异步函数,输入状态,输出一对值:更新内容,以及按名称给出的后继节点。
  2. Run every node in the wave with gather.用 gather 并发运行这一波的所有节点。
  3. Merge every update first. Then build the next wave as a dict keyed by node name.先合并所有更新,再以节点名为键构建下一波的字典。
  4. Record the node names of each wave in a trace. Stop at a wave limit.把每一波的节点名记入 trace。达到波次上限时停止。
labs/m07_harness/graph.py · run_graph
async def run_graph(entry_name: str, entry_fn, initial_state: dict, max_waves: int = 12) -> dict:
    state = dict(initial_state)
    wave = {entry_name: entry_fn}
    trace = []
    for wave_idx in range(1, max_waves + 1):
        if not wave:
            break
        trace.append({"wave": wave_idx, "nodes": list(wave)})
        results = await asyncio.gather(*[fn(state) for fn in wave.values()])   # fan-out
        for update, _ in results:              # merge every update first ...
            if update:
                merge_state(state, update)
        next_wave = {}
        for _, edges in results:               # ... then route
            next_wave.update(edges)            # same name twice = one entry = fan-in
        wave = next_wave
    else:
        state["budget_exhausted"] = True
    state["trace"] = trace
    return state
You are done when完成标志You can explain why three tool nodes that each return `{"planner": fn}` cause one planner run.你能解释为什么三个都返回 `{"planner": fn}` 的工具节点,只会触发一次规划节点。
Produces产出`run_graph()`: also used by the multi-agent module.`run_graph()`:多智能体模块也会用到。
03Express the loop as planner and tool nodes把循环表达为规划节点和工具节点
Why this step is here为什么这一步排在这里Now the two pieces meet: the flat loop's logic, run by the wave executor.现在两部分汇合:扁平循环的逻辑,交给波次执行器来运行。

Do this操作

  1. Planner: call the model. No tool calls means terminal. Tool calls mean one tool node per call.规划节点:调用模型。没有工具调用即终止。有工具调用,就为每个调用创建一个工具节点。
  2. Tool node: run hooks, call the registry, append the tool message, log, route to the planner.工具节点:运行钩子、调用注册表、追加工具消息、记日志、路由回规划节点。
  3. Run blocking calls in a thread so the wave is truly concurrent.把阻塞调用放进线程执行,让同一波真正并发。
labs/m07_harness/loop.py · nodes
async def _planner(self, state: dict) -> tuple:
    offer_tools = not state.get("final_turn")
    resp = await asyncio.to_thread(llm.chat, state["messages"],
                                   self.registry.schemas() if offer_tools else None, None, 512, self.policy)
    msg = resp["choices"][0]["message"]
    update = {"messages_append": [msg], "model_calls": 1,
              "prompt_tokens": resp["usage"]["prompt_tokens"],
              "completion_tokens": resp["usage"]["completion_tokens"]}
    calls = msg.get("tool_calls") or []
    if not calls or not offer_tools:
        update["draft"] = msg.get("content") or ""
        return update, {}                                    # terminal: no next nodes
    update["rounds"] = state.get("rounds", 0) + 1
    if update["rounds"] > self.max_rounds:                   # budget spent: one last turn, no tools
        note = {"role": "user", "content": "[harness] You are out of tool rounds. Answer now from the evidence above. "
                                           "Say plainly what is still unknown."}
        return {"messages_append": [note], "final_turn": True, "budget_exhausted": True,
                "model_calls": 1}, {"planner": self._planner}
    return update, {f"tool:{c['id']}": self._tool_node(c) for c in calls}   # fan-out

def _tool_node(self, call: dict):
    async def node(state: dict) -> tuple:
        name = call["function"]["name"]
        args = json.loads(call["function"]["arguments"] or "{}")
        blocked = next((r for r in (h(name, args) for h in self.pre_tool_hooks) if r), None)
        content = (json.dumps({"error": "blocked by policy: " + blocked}) if blocked
                   else await asyncio.to_thread(self.registry.call_as_text, name, args))
        self._log("tool_calls", {"request_id": state["request_id"], "tool": name, "arguments": args,
                                 "blocked": blocked, "chars": len(content),
                                 "empty": '"count": 0' in content or '"results": []' in content})
        return ({"messages_append": [{"role": "tool", "tool_call_id": call["id"], "name": name, "content": content}],
                 "tools_used_append": [name]},
                {"planner": self._planner})                  # every tool node names the same successor
    return node
Recorded output / 记录的输出 · m07.demo
2 wave agent : The lodging cap is 220 dollars per night (policy NW-FIN-012, Section 3). B. Chen paid 219.00 dollars for lodging in Boston on 2026-06-02, which is under the cap.
  waves      : [['planner'], ['tool', 'tool'], ['planner']]
  model calls: 2 | tool messages: 2
You are done when完成标志The waves read planner, then two tool nodes, then planner. Model calls are 2.波次依次是:规划节点、两个工具节点、规划节点。模型调用次数为 2。
Produces产出An agent whose tool calls in one turn run in parallel.同一轮工具调用可以并行执行的智能体。
04Handle a spent budget as a designed outcome把预算耗尽当作设计内的结果来处理
Why this step is here为什么这一步排在这里It depends on the round counter in the planner. Without it, hitting the limit returns nothing after the user has waited the longest.它依赖规划节点里的轮次计数。没有它的话,达到上限时什么都不返回,而此时用户已经等了最久。

Do this操作

  1. Count rounds in the planner.在规划节点里统计轮次。
  2. When the count passes the limit, append a harness note and run the planner once more with no tools.超过上限时,追加一条 Harness 提示,再运行一次不带工具的规划节点。
  3. Mark harness notes so they are never mistaken for the user's words. The lab prefixes them with `[harness]`.给 Harness 的提示做标记,避免被当成用户说的话。lab 用 `[harness]` 作前缀。
  4. Log that the budget ran out.记录预算已耗尽。
Recorded output / 记录的输出 · m07.demo
3 budget of 2: exhausted after 6 waves -> The lodging cap is 220 dollars per night (policy NW-FIN-012, Section 3 ...
You are done when完成标志With a model that never stops searching and a budget of 2, the run still ends with an answer from the evidence.面对一个不停搜索的模型,预算设为 2 时,运行仍然以基于证据的回答结束。
Produces产出A bounded run that always returns something, and a logged signal for the learner.一个有上限且总有返回的运行过程,以及一条供学习任务使用的日志信号。
05Compose the system prompt from parts分部分组装系统提示词
Why this step is here为什么这一步排在这里Composition has to exist before skills and memory can plug in. It is kept short because the prompt is charged on every turn.先要有组装这一步,技能和记忆才有地方接入。它要保持简短,因为提示词每一轮都计费。

Do this操作

  1. Start with a short base prompt that says when to use tools and what may be reported.从简短的基础提示词开始,说明何时使用工具、可以报告什么。
  2. Add at most one skill, chosen by a function you pass in.加入至多一个技能,由你传入的函数来选择。
  3. Add a memory briefing for this caller, if a memory object is passed in.如果传入了记忆对象,就加上该调用方的记忆摘要。
labs/m07_harness/loop.py · compose
def compose_system_prompt(self, user_text: str, partition: str) -> tuple:
    """Base instructions + at most one skill + this caller's memory. Returns (prompt, skill name)."""
    parts = [self.base_prompt]
    skill = self.skills(user_text) if self.skills else None
    if skill:
        parts.append(f"## Skill: {skill['name']}\n{skill['body']}")
    if self.memory:
        briefing = self.memory.briefing(partition)
        if briefing:
            parts.append("## What you know about this user\n" + briefing)
    return "\n\n".join(parts), (skill or {}).get("name")
You are done when完成标志With no skills and no memory passed in, the prompt is the base prompt alone.不传技能和记忆时,提示词就只有基础部分。
Produces产出`compose_system_prompt()`: the plug point for the skills and memory modules.`compose_system_prompt()`:技能和记忆模块的接入点。
06Add hooks before tool execution在工具执行前加入钩子
Why this step is here为什么这一步排在这里Hooks sit inside the tool node, so that node must exist. They enforce policy in code, which holds whatever the model was told.钩子位于工具节点内部,所以工具节点必须先存在。它们用代码强制执行策略,不管模型被告知了什么都有效。

Do this操作

  1. A hook takes a tool name and arguments and returns a reason to block, or nothing.钩子接收工具名和参数,返回阻止的原因,或什么都不返回。
  2. A blocked call returns an error object as the tool message. The model sees the refusal.被阻止的调用会返回一个错误对象作为工具消息。模型能看到这次拒绝。
  3. Log every block.记录每一次阻止。
Recorded output / 记录的输出 · m07.demo
4 hook blocks one tool: The lodging cap is 220 dollars per night (policy NW-FIN-012, Section 3). I could not read  ...
You are done when完成标志With expense data blocked, the answer states the cap and says it could not read the records.报销数据被阻止后,回答说出了上限,并说明无法读取记录。
Produces产出`pre_tool_hooks`: the plug point for the guardrails module.`pre_tool_hooks`:护栏模块的接入点。
07Assemble run(): guard, retry, log, record组装 run():护栏、重试、日志、记录
Why this step is here为什么这一步排在这里This is the last piece because it orders everything else: compose, execute, check, respond, record.这是最后一块,因为它给其余部分排好顺序:组装、执行、检查、响应、记录。

Do this操作

  1. Compose the prompt and run the graph.组装提示词并运行图。
  2. If a guard is passed in and rejects the draft: append its corrective note, run one more turn without tools, check again. If it still fails, return the guard's fallback text.如果传入了护栏且草稿被拒:追加纠正提示,再跑一轮不带工具的调用,重新检查。仍然不通过就返回护栏的兜底文本。
  3. Write one request log line: question, answer, tools used, model calls, guard result, budget flag.写一行请求日志:问题、回答、用过的工具、模型调用次数、护栏结果、预算标记。
  4. Hand the exchange to memory after the answer exists.在回答产生之后,再把这次对话交给记忆模块。
labs/m07_harness/loop.py · run
async def run(self, messages: list, partition: str = "anon", thread: str = "t1") -> dict:
    user_text = llm.last_user(messages)
    system, skill = self.compose_system_prompt(user_text, partition)
    state = await run_graph("planner", self._planner, {
        "request_id": uuid.uuid4().hex[:8],
        "messages": [{"role": "system", "content": system}] + list(messages)})
    answer, verdict = state.get("draft", ""), None
    if self.guard:
        verdict = self.guard(state["messages"], answer, skill)
        if not verdict["ok"]:                                # one corrective retry, then a safe fallback
            state["messages"] += [{"role": "user", "content": "[harness] " + verdict["corrective"]}]
            state = await run_graph("planner", self._planner, {**state, "draft": "", "final_turn": True})
            retry = self.guard(state["messages"], state.get("draft", ""), skill)
            answer = state.get("draft", "") if retry["ok"] else verdict["fallback"]
            verdict = {**retry, "retried": True, "used_fallback": not retry["ok"]}
    self._log("requests", {"request_id": state["request_id"], "partition": partition, "skill": skill,
                           "question": user_text, "answer": answer, "tools": state.get("tools_used", []),
                           "model_calls": state.get("model_calls"), "guard": verdict and verdict["ok"],
                           "budget_exhausted": bool(state.get("budget_exhausted"))})
    if self.memory:                                          # after the answer exists, never before
        self.memory.record_async(partition, thread, user_text, answer)
    return {"answer": answer, "skill": skill, "waves": state["trace"], "tools": state.get("tools_used", []),
            "model_calls": state.get("model_calls", 0), "guard": verdict,
            "budget_exhausted": bool(state.get("budget_exhausted")), "messages": state["messages"]}
Recorded output / 记录的输出 · m07.demo
5 empty result: I searched the expense records and found nothing. month emptied this result. Values that exist: {'category': [ ...
6 logs written: ['requests.jsonl', 'tool_calls.jsonl']
You are done when完成标志Two log files exist. The empty-result question is answered with what was searched and the diagnostic.生成了两个日志文件。结果为空的问题,回答中说明了查了什么,并附上诊断信息。
Produces产出`Agent.run()` and two logs: requests.jsonl and tool_calls.jsonl.`Agent.run()` 以及两份日志:requests.jsonl 和 tool_calls.jsonl。
Feeds供给
08Put cheap deterministic gates in front of the planner在规划节点前放置便宜的确定性关卡
Why this step is here为什么这一步排在这里Triage runs before the planner, so add it once the planner path is stable. It removes whole classes of slow requests.分流在规划节点之前运行,所以等规划路径稳定后再加。它能直接消除几类慢请求。
Uses用到

Do this操作

  1. List request types that need no tools, such as questions about the agent itself.列出不需要工具的请求类型,比如关于智能体自身的问题。
  2. Detect them with a regex first, then with embedding similarity to a few examples, and let the model decide only what is left.先用正则识别,再用与少量示例的向量相似度识别,剩下的才交给模型判断。
  3. Log each decision with its reason.记录每次判断及其理由。
labs/m07_harness/triage.py · triage
SELF_REF = re.compile(r"\b(what can you do|who are you|what tools do you have|how do you work)\b", re.I)
CANONICAL_SELF = ["what are you able to help me with", "describe your capabilities", "which tools are available to you"]
SIM_THRESHOLD = 0.60          # chosen on the examples below; re-check it when the embedder changes
_CANON = [llm.embed(x) for x in CANONICAL_SELF]


def needs_tools(user_text: str) -> tuple:
    """Returns (decision, reason). Cheapest gate first."""
    if SELF_REF.search(user_text):
        return False, "regex"
    best = max(llm.cosine(llm.embed(user_text), c) for c in _CANON)
    if best >= SIM_THRESHOLD:
        return False, f"similar to a self question ({best:.2f})"
    return True, f"planner decides (best similarity {best:.2f})"
run
python3 -m labs.m07_harness.triage
Recorded output / 记录的输出 · m07.triage
1 What can you do?                         needs_tools=False [regex]
  without triage: 2 model calls, 1 tool calls | with triage: 1 model calls, 0 tool calls
1 Describe your capabilities, please.      needs_tools=False [similar to a self question (0.87)]
  without triage: 2 model calls, 1 tool calls | with triage: 1 model calls, 0 tool calls
1 Which tools are available to you here?   needs_tools=False [similar to a self question (0.91)]
  without triage: 2 model calls, 1 tool calls | with triage: 1 model calls, 0 tool calls
1 What is the nightly lodging cap?         needs_tools=True  [planner decides (best similarity 0.18)]
  without triage: 2 model calls, 1 tool calls | with triage: 2 model calls, 1 tool calls
2 decisions logged: 4 lines in triage.jsonl
You are done when完成标志Three self questions go out with 1 model call and 0 tool calls instead of 2 and 1. The policy question still reaches the planner with tools.三个关于智能体自身的问题,从 2 次模型调用加 1 次工具调用降到 1 次模型调用、0 次工具调用。关于政策的问题仍然带着工具交给规划节点。
Produces产出Fewer model calls on requests that never needed tools.对那些本来就不需要工具的请求,减少了模型调用。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。
09Add streaming last最后再加流式输出
Why this step is here为什么这一步排在这里Streaming changes how output leaves the loop and interacts with the guard. Add it when the loop and guard are stable.流式输出会改变结果离开循环的方式,并与护栏相互影响。等循环和护栏稳定后再加。

Do this操作

  1. Emit server-sent events in the standard chunk format.按标准分块格式发送 SSE 事件。
  2. Accumulate tool-call deltas until a call is complete, then execute it.累积工具调用的增量片段,直到一个调用完整,再执行。
  3. Hold answer tokens until the guard has passed, then release them line by line.在护栏通过之前先扣住回答的 token,通过后逐行放出。
  4. Evaluate the streaming path separately. It is different code and fails differently.流式路径要单独评估。它是另一套代码,失败方式也不同。
labs/m07_harness/stream.py · gate
def sse(obj) -> bytes:
    return f"data: {obj if isinstance(obj, str) else json.dumps(obj)}\n\n".encode()


def chunk(text: str = "", role: str = "") -> dict:
    delta = {"role": role} if role else {"content": text}
    return {"object": "chat.completion.chunk", "choices": [{"index": 0, "delta": delta}]}


def stream_guarded(agent: Agent, messages: list):
    """Yield SSE events. The role chunk goes out at once so the client sees progress.
    Text goes out only after the agent's guard (and its one retry) is finished."""
    yield sse(chunk(role="assistant"))
    result = asyncio.run(agent.run(messages))
    for line in result["answer"].splitlines(keepends=True) or [result["answer"]]:
        yield sse(chunk(line))
    yield sse("[DONE]")

The same file has merge_tool_call_delta(), which reassembles a tool call that arrives in fragments.同一个文件里还有 merge_tool_call_delta(),用来把分片到达的工具调用重新拼起来。

run
python3 -m labs.m07_harness.stream
Recorded output / 记录的输出 · m07.stream
1 four fragments -> query_expenses {'employee': 'B. Chen', 'category': 'lodging'}
2 events received: 3, first event after 26 ms
3 client saw     : The lodging cap is 220 dollars per night (policy NW-FIN-012, Section 3). B. Chen paid 219.00 dollars
4 rejected draft figure 312.40 reached the client: False
You are done when完成标志Four fragments rebuild one tool call. The first event reaches the client at once, and the figure from the rejected draft never does.四个分片重新拼成一个工具调用。第一个事件立即到达客户端,而被拒绝草稿里的数字始终没有到达。
Produces产出A streamed response path with the same guarantees.一条具有同样保障的流式响应路径。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。

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

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

2026-10

Right query, right rows, wrong answer查询对了,数据对了,回答错了

What happened发生了什么
The agent ran correct queries, received correct rows, then answered with a table about an unrelated subject and invented totals. Nothing compared the answer with the tool results.智能体执行了正确的查询、拿到了正确的数据,却给出了一张无关主题的表格和编造的合计数。当时没有任何环节把回答与工具结果做比对。
Fix修复
A deterministic guard that requires figures in the answer to appear in the evidence.加入确定性的护栏,要求回答中的数字必须出现在证据里。
Lesson教训
Correct retrieval does not guarantee a grounded answer. Check the last step.检索正确不代表回答有依据。最后一步也要检查。
2026-10

Out of rounds meant no answer轮次用完就没有回答

What happened发生了什么
When the tool-round limit was reached, the user got a limit message after the longest wait.达到工具轮次上限时,用户等了最久,却只得到一条“已达上限”的提示。
Fix修复
One final turn without tools that answers from the evidence gathered.增加最后一轮不带工具的调用,根据已收集的证据作答。
Lesson教训
Design what happens at every limit. A limit with no behavior is an outage.每个上限触发时会发生什么,都要事先设计。没有后续行为的上限就是一次故障。
2026-07

A point-to-point loop that could not fan out无法扇出的点到点循环

What happened发生了什么
The first loop ran tool calls one after another. Three lookups in one turn took three times as long.最初的循环逐个执行工具调用。同一轮里的三次查询要花三倍时间。
Fix修复
A wave executor with merge rules.改用带合并规则的波次执行器。
Lesson教训
Concurrency needs merge rules first. The executor is 40 lines once they exist.并发先要有合并规则。规则有了之后,执行器只需要 40 行。

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

Platform平台How this module maps本模块如何对应
DatabricksWrite the loop with any framework and wrap it as an MLflow ResponsesAgent. Deploy it with Agent Bricks, as a Databricks App or on Agent Runtime. MLflow tracing replaces your JSON-lines logs.用任意框架编写循环,并封装为 MLflow ResponsesAgent。通过 Agent Bricks 部署,可以是 Databricks App,也可以运行在 Agent Runtime 上。MLflow tracing 取代你的 JSON Lines 日志。
IBM watsonxwatsonx Orchestrate is the harness. You declare agents, tools, and collaborators with the Agent Development Kit, and the platform runs the loop. Custom loop logic goes into tools or an imported LangGraph agent.watsonx Orchestrate 本身就是 Harness。你用 Agent Development Kit 声明智能体、工具和协作者,平台负责运行循环。自定义的循环逻辑放进工具,或放进导入的 LangGraph 智能体。
CodexCodex is a finished harness for coding work. You shape it with AGENTS.md, skills, MCP servers, and approval and sandbox settings. To build your own loop, use the OpenAI Agents SDK.Codex 是面向编程任务的现成 Harness。你通过 AGENTS.md、技能、MCP 服务以及审批和沙箱设置来调整它。要自建循环,就用 OpenAI Agents SDK。
CursorCursor is a finished harness inside an editor. Rules, AGENTS.md, MCP, hooks, and subagents are your control points. You cannot change its loop, so policy belongs in hooks and tools.Cursor 是嵌在编辑器里的现成 Harness。规则、AGENTS.md、MCP、钩子和子智能体是你的控制点。它的循环改不了,所以策略要放在钩子和工具里。
Claude Code / Agent SDKClaude Code is a harness with the same parts: a project instruction file, skills, hooks, MCP tools, subagents. The Agent SDK exposes that loop as a library.Claude Code 是具有相同部件的 Harness:项目指令文件、技能、钩子、MCP 工具、子智能体。Agent SDK 把这个循环以库的形式提供出来。
Another machineThe lab loop is plain Python and one HTTP call. Copy the folder and set the endpoint URL.lab 的循环是纯 Python 加一个 HTTP 调用。复制目录,设置端点 URL 即可。

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

Explain it back讲给自己听

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

Why build the flat loop before the wave graph?为什么先做扁平循环,再做波次图?
A strong answer参考答案The graph is the flat loop plus concurrency and safe merging. The flat loop is the correctness reference and is easy to test. Start with the graph and you debug orchestration and agent behavior at the same time.图就是扁平循环加上并发和安全合并。扁平循环是正确性的参照,也容易测试。如果一上来就做图,就得同时调试编排逻辑和智能体行为。
How does the executor avoid running the planner three times after three tool calls?三次工具调用之后,执行器如何避免把规划节点运行三次?
A strong answer参考答案The next wave is a dict keyed by node name. Each tool node names the planner as its successor, and writing the same key three times leaves one entry.下一波是以节点名为键的字典。每个工具节点都把规划节点作为后继,同一个键写三次,最后只有一条。
List the plug points and which module fills each.列出各个接入点,以及分别由哪个模块填充。
A strong answer参考答案skills: a function from text to one skill or none. memory: an object with briefing and record_async. guard: a function from messages and a draft to a verdict. pre_tool_hooks: functions from a tool call to a reason or nothing.skills:输入文本、返回一个技能或空的函数。memory:带 briefing 和 record_async 的对象。guard:输入消息和草稿、返回裁定的函数。pre_tool_hooks:输入工具调用、返回原因或空的函数。
Where do you enforce that the agent may never write outside one folder, and why there?“智能体绝不能写到某个目录之外”这条规则应该在哪里强制执行?为什么?
A strong answer参考答案In a pre-tool hook. It runs in code on every call regardless of what the model was told, and it produces a logged refusal.在工具执行前的钩子里。它以代码形式在每次调用时运行,不受模型被告知了什么的影响,并且会留下拒绝日志。
You move to a platform that owns the loop. What do you still own?你迁移到一个由平台掌管循环的环境。哪些东西仍然归你?
A strong answer参考答案Tool definitions and their limits, the instructions and skills, the checks on the answer, the eval sets, and the logs or traces you review. The loop is the most replaceable part.工具定义及其限制、指令和技能、对回答的检查、评估集,以及你要审阅的日志或 trace。循环本身是最容易被替换的部分。

Terms术语

Wave波次The set of nodes that run concurrently in one step of the executor.执行器一步之内并发运行的一组节点。
Fan-in扇入Several nodes converging on one successor, which then runs once.多个节点汇聚到同一个后继节点,该后继只运行一次。
Round轮次One planner turn that requested tools.规划节点请求了工具的一轮调用。
Hook钩子Code that runs before a tool call and can block 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就本模块向导师提问