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工作原理
- A planner node calls the model. If the model answers, the run ends. If it requests tool calls, each call becomes a node and all of them run at once.规划节点调用模型。模型给出回答,运行就结束。模型请求工具调用,每个调用就成为一个节点,全部并发执行。
- Tool nodes append results and route back to the planner. Several nodes naming the same successor collapse into one run of it.工具节点追加结果,然后路由回规划节点。多个节点指向同一个后继时,后继只运行一次。
- A round budget bounds the cycle. When it runs out, one final turn without tools answers from the evidence gathered.轮次预算限制循环次数。预算用完时,再进行一轮不带工具的调用,根据已收集的证据作答。
- Skills, memory, the guard, and hooks plug into fixed points. Each is its own module.技能、记忆、护栏和钩子接入固定的位置。它们各自是一个独立模块。
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.py | HTTP surface: chat completions, models, feedback, health.HTTP 接口:chat completions、models、feedback、health。 |
| apps/agent-server/graph.py | A 110-line wave executor: fan-out, fan-in, merge rules, wave budget, trace.110 行的波次执行器:扇出、扇入、合并规则、波次预算、追踪。 |
| apps/agent-server/agent_loop.py | The planner and tool graph, prompt composition, streaming, logging.规划与工具图、提示词组装、流式输出、日志。 |
| apps/agent-server/AGENT.md | The base system prompt.基础系统提示词。 |
Process map流程图
One request through the harness一个请求如何通过 Harness
- 1Compose prompt组装提示词Base instructions, at most one skill, the caller's memory.基础指令、至多一个技能、调用方的记忆。
- 2Planner规划节点Model call with tool schemas. Returns an answer or tool calls.带工具 schema 的模型调用。返回回答或工具调用。
- 3Tool 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回到规划节点,直到轮次预算用完
- 4Budget check预算检查Out of rounds: withdraw tools and ask for an answer from the evidence.轮次用完:撤掉工具,要求根据已有证据作答。
- 5Guard护栏Check the draft against this request's evidence. One corrective retry.把草稿与本次请求的证据比对。允许一次纠正重试。
- 6Respond响应Return the answer in the format the caller sent.以调用方使用的格式返回回答。
- 7Record记录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 实际运行时打印的内容。
- 1Build the flat loop and bound it搭建扁平循环并设上限
- 2Write the wave executor编写波次执行器
- 3Express the loop as planner and tool nodes把循环表达为规划节点和工具节点
- 4Handle a spent budget as a designed outcome把预算耗尽当作设计内的结果来处理
- 5Compose the system prompt from parts分部分组装系统提示词
- 6Add hooks before tool execution在工具执行前加入钩子
- 7Assemble run(): guard, retry, log, record组装 run():护栏、重试、日志、记录
- 8Put cheap deterministic gates in front of the planner在规划节点前放置便宜的确定性关卡
- 9Add streaming last最后再加流式输出
01Build the flat loop and bound it搭建扁平循环并设上限
- chat()chat() ← Inference engineering推理工程 5: Write one client function and use it everywhere写一个客户端函数,全系统共用
- schemas() and call_as_text()schemas() 和 call_as_text() ← Tools and MCP工具与 MCP 2: Build the registry搭建注册表
Do this操作
- Call the model with the tool schemas.带着工具 schema 调用模型。
- 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 消息。
- If the reply has none: return its content.如果没有工具调用:返回其内容。
- Stop after a fixed number of rounds.达到固定轮数后停止。
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 properlypython3 -m labs.m07_harness.demo1 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.- Harness engineeringHarness 工程 3: Express the loop as planner and tool nodes把循环表达为规划节点和工具节点 (the logic to preserve需要保持的逻辑)
02Write the wave executor编写波次执行器
- merge_state()merge_state() ← State and storage状态与存储 4: Define merge rules for run state定义运行状态的合并规则
Do this操作
- A node is an async function from state to a pair: an update, and the next nodes by name.节点是一个异步函数,输入状态,输出一对值:更新内容,以及按名称给出的后继节点。
- Run every node in the wave with gather.用 gather 并发运行这一波的所有节点。
- Merge every update first. Then build the next wave as a dict keyed by node name.先合并所有更新,再以节点名为键构建下一波的字典。
- Record the node names of each wave in a trace. Stop at a wave limit.把每一波的节点名记入 trace。达到波次上限时停止。
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- Harness engineeringHarness 工程 3: Express the loop as planner and tool nodes把循环表达为规划节点和工具节点 (the executor执行器)
- Multi-agent patterns多智能体模式 3: Fan out, fan in, synthesize扇出、扇入、汇总 (run_graph()run_graph())
03Express the loop as planner and tool nodes把循环表达为规划节点和工具节点
- the logic to preserve需要保持的逻辑 ← Harness engineeringHarness 工程 1: Build the flat loop and bound it搭建扁平循环并设上限
- the executor执行器 ← Harness engineeringHarness 工程 2: Write the wave executor编写波次执行器
Do this操作
- Planner: call the model. No tool calls means terminal. Tool calls mean one tool node per call.规划节点:调用模型。没有工具调用即终止。有工具调用,就为每个调用创建一个工具节点。
- Tool node: run hooks, call the registry, append the tool message, log, route to the planner.工具节点:运行钩子、调用注册表、追加工具消息、记日志、路由回规划节点。
- Run blocking calls in a thread so the wave is truly concurrent.把阻塞调用放进线程执行,让同一波真正并发。
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 node2 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- Harness engineeringHarness 工程 4: Handle a spent budget as a designed outcome把预算耗尽当作设计内的结果来处理 (the planner node规划节点)
- Harness engineeringHarness 工程 5: Compose the system prompt from parts分部分组装系统提示词 (the agent class to extend要扩展的智能体类)
- Harness engineeringHarness 工程 6: Add hooks before tool execution在工具执行前加入钩子 (the tool node工具节点)
04Handle a spent budget as a designed outcome把预算耗尽当作设计内的结果来处理
- the planner node规划节点 ← Harness engineeringHarness 工程 3: Express the loop as planner and tool nodes把循环表达为规划节点和工具节点
Do this操作
- Count rounds in the planner.在规划节点里统计轮次。
- When the count passes the limit, append a harness note and run the planner once more with no tools.超过上限时,追加一条 Harness 提示,再运行一次不带工具的规划节点。
- Mark harness notes so they are never mistaken for the user's words. The lab prefixes them with `[harness]`.给 Harness 的提示做标记,避免被当成用户说的话。lab 用 `[harness]` 作前缀。
- Log that the budget ran out.记录预算已耗尽。
3 budget of 2: exhausted after 6 waves -> The lodging cap is 220 dollars per night (policy NW-FIN-012, Section 3 ...- Harness engineeringHarness 工程 7: Assemble run(): guard, retry, log, record组装 run():护栏、重试、日志、记录 (a run that always ends一个总会结束的运行过程)
05Compose the system prompt from parts分部分组装系统提示词
- the agent class to extend要扩展的智能体类 ← Harness engineeringHarness 工程 3: Express the loop as planner and tool nodes把循环表达为规划节点和工具节点
Do this操作
- Start with a short base prompt that says when to use tools and what may be reported.从简短的基础提示词开始,说明何时使用工具、可以报告什么。
- Add at most one skill, chosen by a function you pass in.加入至多一个技能,由你传入的函数来选择。
- Add a memory briefing for this caller, if a memory object is passed in.如果传入了记忆对象,就加上该调用方的记忆摘要。
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")- Harness engineeringHarness 工程 7: Assemble run(): guard, retry, log, record组装 run():护栏、重试、日志、记录 (the system prompt系统提示词)
- Skills技能(Skills) 5: Plug the router into the harness把路由器接入 Harness (the skills plug point技能接入点)
- Memory记忆 5: Plug memory into the harness and test isolation把记忆接入 Harness 并测试隔离性 (the memory plug point记忆接入点)
- Self-evolving agents自进化智能体 4: Assemble the nightly loop with the eval gate组装夜间循环,并加上评估关卡 (the base prompt the rules are appended to规则所附加到的基础提示词)
06Add hooks before tool execution在工具执行前加入钩子
Do this操作
- A hook takes a tool name and arguments and returns a reason to block, or nothing.钩子接收工具名和参数,返回阻止的原因,或什么都不返回。
- A blocked call returns an error object as the tool message. The model sees the refusal.被阻止的调用会返回一个错误对象作为工具消息。模型能看到这次拒绝。
- Log every block.记录每一次阻止。
4 hook blocks one tool: The lodging cap is 220 dollars per night (policy NW-FIN-012, Section 3). I could not read ...07Assemble run(): guard, retry, log, record组装 run():护栏、重试、日志、记录
- the system prompt系统提示词 ← Harness engineeringHarness 工程 5: Compose the system prompt from parts分部分组装系统提示词
- a run that always ends一个总会结束的运行过程 ← Harness engineeringHarness 工程 4: Handle a spent budget as a designed outcome把预算耗尽当作设计内的结果来处理
- the hook path钩子路径 ← Harness engineeringHarness 工程 6: Add hooks before tool execution在工具执行前加入钩子
- append_log() for JSON-lines logs用于 JSON Lines 日志的 append_log() ← State and storage状态与存储 6: Give every background job a cursor给每个后台任务一个游标
Do this操作
- Compose the prompt and run the graph.组装提示词并运行图。
- 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.如果传入了护栏且草稿被拒:追加纠正提示,再跑一轮不带工具的调用,重新检查。仍然不通过就返回护栏的兜底文本。
- Write one request log line: question, answer, tools used, model calls, guard result, budget flag.写一行请求日志:问题、回答、用过的工具、模型调用次数、护栏结果、预算标记。
- Hand the exchange to memory after the answer exists.在回答产生之后,再把这次对话交给记忆模块。
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"]}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']- Harness engineeringHarness 工程 8: Put cheap deterministic gates in front of the planner在规划节点前放置便宜的确定性关卡 (the request log, to find which requests waste tool rounds请求日志,用来找出哪些请求在浪费工具轮次)
- Harness engineeringHarness 工程 9: Add streaming last最后再加流式输出 (a stable loop稳定的循环)
- Skills技能(Skills) 1: Write one skill from a real failure从一次真实的失败出发写一个技能 (the request log that shows what went wrong显示出错情况的请求日志)
- Memory记忆 5: Plug memory into the harness and test isolation把记忆接入 Harness 并测试隔离性 (the place run() hands off the exchangerun() 交出对话的位置)
- Guardrails and verification护栏与验证 1: Start from logged failures从日志里的失败案例出发 (the request log请求日志)
- Guardrails and verification护栏与验证 5: Enforce: corrective retry, then fallback强制执行:先纠正重试,再兜底 (the guard plug point and retry path护栏接入点和重试路径)
- Evaluation评估 1: Write the human baseline questions编写人工基线问题 (real requests to draw questions from用来提炼问题的真实请求)
- Evaluation评估 7: Evaluate the whole agent with mechanical checks用代码检查评估整个智能体 (Agent.run() and its result fieldsAgent.run() 及其结果字段)
- Multi-agent patterns多智能体模式 2: Create narrow workers创建专职子智能体 (the Agent classAgent 类)
- Self-evolving agents自进化智能体 1: Check the four preconditions检查四项前提条件 (the two log files两份日志文件)
- SDKs and frameworksSDK 与框架 1: Map SDK features to parts you built把 SDK 的功能对应到你搭建过的部件 (the list of parts to map要对应的部件清单)
- SDKs and frameworksSDK 与框架 5: Run all three and compare三个都跑一遍并比较 (the hand-built loop as reference作为参照的手写循环)
- Operations and deployment运维与部署 4: Add the busy marker to the server给服务加上忙碌标记 (the request path to wrap要包裹的请求路径)
- Operations and deployment运维与部署 7: Rotate logs and keep signal apart from noise轮转日志,并把信号与噪音分开 (the two structured logs两份结构化日志)
08Put cheap deterministic gates in front of the planner在规划节点前放置便宜的确定性关卡
- the request log, to find which requests waste tool rounds请求日志,用来找出哪些请求在浪费工具轮次 ← Harness engineeringHarness 工程 7: Assemble run(): guard, retry, log, record组装 run():护栏、重试、日志、记录
Do this操作
- List request types that need no tools, such as questions about the agent itself.列出不需要工具的请求类型,比如关于智能体自身的问题。
- Detect them with a regex first, then with embedding similarity to a few examples, and let the model decide only what is left.先用正则识别,再用与少量示例的向量相似度识别,剩下的才交给模型判断。
- Log each decision with its reason.记录每次判断及其理由。
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})"python3 -m labs.m07_harness.triage1 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.jsonl09Add streaming last最后再加流式输出
- a stable loop稳定的循环 ← Harness engineeringHarness 工程 7: Assemble run(): guard, retry, log, record组装 run():护栏、重试、日志、记录
- the guard, which decides when tokens may be released护栏,由它决定何时可以放出 token ← Guardrails and verification护栏与验证 5: Enforce: corrective retry, then fallback强制执行:先纠正重试,再兜底
Do this操作
- Emit server-sent events in the standard chunk format.按标准分块格式发送 SSE 事件。
- Accumulate tool-call deltas until a call is complete, then execute it.累积工具调用的增量片段,直到一个调用完整,再执行。
- Hold answer tokens until the guard has passed, then release them line by line.在护栏通过之前先扣住回答的 token,通过后逐行放出。
- Evaluate the streaming path separately. It is different code and fails differently.流式路径要单独评估。它是另一套代码,失败方式也不同。
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(),用来把分片到达的工具调用重新拼起来。
python3 -m labs.m07_harness.stream1 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: FalseHow it works with the other parts它如何与其他部分协作
- Skills技能(Skills)The harness asks for at most one skill per request and injects its body.Harness 每个请求最多取一个技能,并注入其正文。
- Memory记忆Memory is read during prompt composition and written after the response.记忆在组装提示词时读取,在响应之后写入。
- Guardrails and verification护栏与验证Hooks act on tool calls. The answer guard acts on the draft. Both are called by the loop.钩子作用于工具调用,回答护栏作用于草稿。两者都由循环调用。
- Evaluation评估Evals send requests through run() and read the two logs.评估通过 run() 发送请求,并读取这两份日志。
- Multi-agent patterns多智能体模式The same executor runs sub-agents as nodes. A sub-agent is an Agent with fewer tools.同一个执行器把子智能体当节点运行。子智能体就是工具更少的 Agent。
What went wrong in the real build真实搭建中踩过的坑
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.检索正确不代表回答有依据。最后一步也要检查。
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.每个上限触发时会发生什么,都要事先设计。没有后续行为的上限就是一次故障。
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本模块如何对应 |
|---|---|
| Databricks | Write 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 watsonx | watsonx 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 智能体。 |
| Codex | Codex 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。 |
| Cursor | Cursor 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 SDK | Claude 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 machine | The 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?为什么先做扁平循环,再做波次图?
How does the executor avoid running the planner three times after three tool calls?三次工具调用之后,执行器如何避免把规划节点运行三次?
List the plug points and which module fills each.列出各个接入点,以及分别由哪个模块填充。
Where do you enforce that the agent may never write outside one folder, and why there?“智能体绝不能写到某个目录之外”这条规则应该在哪里强制执行?为什么?
You move to a platform that owns the loop. What do you still own?你迁移到一个由平台掌管循环的环境。哪些东西仍然归你?
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.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。
- Out of tool rounds: one final turn without tools answers from the evidence gathered; restate standing after promotion; ordered promotion queue
- BUSY sentinel is held until a streamed response finishes, so the learner pauses for the whole chat answer
- Spending orchestration
- 03 — The Agent Harness, Deep Dive
- Agent-Server Latency Investigation — Summary (2026-07-30)
- builds the specific planner/tool graph on top of graph.py's generic engine, and exposes the same run() contract main.py already calls.
- U7/U8: the account layer, and the reconciliation. Two tools: budget_execution the appropriation's own story: total resources -> obligated -> outlaid -> unobligated, by Treasury Account, program activity or object class. THE ONLY PLACE OUTLAYS LIVE.
- supplemental_appropriations: emergency and disaster money, by the law that created it.
- minimal state-graph execution engine. Why this exists (v2 refinement, 2026-07-27): step 2's agent_loop.py was a flat sequential loop — call the model, run whatever tools it asked for in one batch, repeat.