Learn Claude Code · 大白话教程
16
关键片段 · 19 处注解

单步交给模型,编排交给脚本Workflow Runtime

demo 离线跑;只有交互 CLI 才装真实 runner

解决什么问题 · 多步流程里,如果每一步都由模型决定下一步,既慢又贵,而且同一份输入跑两次结果可能不同。这一章的 demo 默认用 MockAgentRunner,不联网、不花钱;真实模型只在交互模式里接上。

思路

  1. 编排写成脚本:谁先谁后、串行还是并行、失败怎么重试;
  2. 每一步仍是一次模型调用,但只负责「这一步」;
  3. 带 schema 的输出会校验,失败重试一次;
  4. 每一步追加写 journal;resume 时只有 key 完全相同才复用缓存。
s16_workflow_runtime/code.py · L285–322 GitHub 原文 ↗
285class AnthropicAgentRunner:
L285–285

真实 runner:用 host 的 client 和模型名,一次只做一步。

286 """Run workflow agents through the same API client as the host."""
287 
288 def __init__(self, client, model):
289 self.client = client
290 self.model = model
291 
292 def run(self, prompt, schema=None, label=None):
293 request = prompt
294 if schema is not None:
L286–294

要结构化输出就把 schema 写进 prompt,再解析;失败重试一次,也会再计费一次。

295 request += (
L295–295

把 schema 和要求拼进 prompt;模型看到的是文字,没有工具。

296 "\n\nReturn only one JSON object matching this schema:\n"
297 + json.dumps(schema, ensure_ascii=True, sort_keys=True)
298 )
299 response = self.client.messages.create(
L296–299

唯一真正调用模型的地方;demo 模式不会走到这里。

300 model=self.model,
301 system=(
302 "You are a focused workflow agent. Complete only the supplied step. "
303 + f"{WORKFLOW_AGENT_ENVIRONMENT} "
304 + "Do not claim access to files or results not included in the prompt."
305 ),
306 messages=[{"role": "user", "content": request}],
307 max_tokens=2000,
L300–307

单步输出上限 2000 token,防止一步写太长。

308 )
309 text = _response_text(response)
L308–309

把响应里的文字块拼成文本,后面按有没有 schema 决定怎么解析。

310 if schema is None:
311 value = text
312 else:
313 try:
314 value = _parse_runner_json(text)
L310–314

解析失败只影响返回值,不会撤销已经产生的请求费用。

315 except WorkflowInputError:
316 # Let ExecutionState's schema check trigger its single retry.
317 value = text
318 usage = getattr(response, "usage", None)
L315–318

token 只用于预算和展示;请求在上一步已经发出,可能已计费。

319 tokens = int(getattr(usage, "input_tokens", 0) or 0) + int(
320 getattr(usage, "output_tokens", 0) or 0
321 )
322 return RunnerOutput(value, tokens)
L319–322

统一返回「值 + token 数」;token 统计是记账,不是计费开关。

s16_workflow_runtime/code.py · L795–811 GitHub 原文 ↗
795def install_workflow_tool(host):
L795–795

交互模式才调用:把 Workflow 挂到 s15 host,同时换上真实 runner。

796 """Extend the s15 host tool pool without changing its dispatch loop."""
797 global RUNNER_FACTORY
798 RUNNER_FACTORY = lambda: AnthropicAgentRunner(host.client, host.MODEL)
L796–798

真实 runner 要 client、model 两个参数;直接写类名会 TypeError。

799 if getattr(host, "_workflow_tool_installed", False):
L799–799

已经装过就返回;重复包装会让工具池出现两份。

800 return
801 base_assemble = host.assemble_tool_pool
802 
803 def assemble_with_workflow():
L800–803

包装 host 原有的工具池,只追加 Workflow,不改它的分发循环。

804 tools, handlers = base_assemble()
805 if not any(tool.get("name") == "Workflow" for tool in tools):
806 tools.append(WORKFLOW_TOOL)
L804–806

Workflow 作为普通工具进池,模型像调其他工具一样调它。

807 handlers["Workflow"] = run_workflow_sync
808 return tools, handlers
809 
810 host.assemble_tool_pool = assemble_with_workflow
811 host._workflow_tool_installed = True
L807–811

这个标记防止重复安装。

s16_workflow_runtime/code.py · L895–899 GitHub 原文 ↗
895if __name__ == "__main__":
L895–895

两条入口:demo/resume 走离线,否则进交互 CLI。

896 if sys.argv[1:] and sys.argv[1] in {"demo", "resume"}:
L896–896

只认 demo 和 resume;拼错参数会掉进交互模式。

897 asyncio.run(run_demo(sys.argv[1:]))
L897–897

demo 和 resume 都用 MockAgentRunner:不联网、不花钱。

898 else:
899 run_cli()
L898–899

无参数才装真实 runner;之后每次请求都可能产生费用。

记住这几条

三种入口

`demo` 离线演示、`resume` 离线续跑、无参数进入交互 CLI。

demo/resume 不花钱

默认 RUNNER_FACTORY = MockAgentRunner,返回确定性结果。

真实 runner 由 host 安装

install_workflow_tool(host) 里改成 AnthropicAgentRunner(host.client, host.MODEL)。

不能无参替换

AnthropicAgentRunner 的构造函数需要 client 和 model;直接替换类名会 TypeError。

journal 支持续跑

resume 只读同一次 run 的 journal;新 demo 是新 run;key = kind + label + prompt + schema,四项全同才复用。

费用看请求,不看返回

`client.messages.create` 发出就可能计费;解析失败、重试或抛异常都不会退。

容易踩的坑

  • 以为 `demo` 在调真模型——它用的是 MockAgentRunner。
  • 把 RUNNER_FACTORY 直接赋成 AnthropicAgentRunner:缺少 client/model,直接报错。
  • 以为只有成功返回才计费:请求一发出就可能计费,解析失败也一样。
  • 以为改了 prompt 还能命中缓存:key 含 kind/label/prompt/schema,改了就会重跑。
  • 以为后台任务会主动叫醒模型:只有主循环每轮开头 collect 才注入通知。

动手改一改

步骤:在 `s16_workflow_runtime/` 目录跑 `python code.py demo`,记下输出的 `agents` 数、`tokens` 和 `journal=.runtime/<runId>.journal.jsonl`;再跑 `python code.py resume`。确定性验收:两次退出码为 0;resume 打印 `resuming <runId>`;agents 数小于第一次;tokens 是 Mock 按字符估算的数值,不代表真实计费;journal 文件存在,里面能查到第一次的记录;resume 的进度里会出现 cached。观察项:result 里的具体条目和摘要文字。常见失败:在错误 cwd 运行(找不到 s15)、没有先 demo 就 resume、删了 `.runtime`、无参数进入 CLI(会走真实 runner,可能计费)。