为模型配上工具和循环

阅读约需 36分钟 分钟,8节中含4个示例。

版次 2026.11.2 示例于 2026年11月20日 通过 64个示例中有64个通过 变化内容

AI 翻译。由人工以英文核验。 我们如何制作图书

译自英文版图书,版次 2026.11.2。 阅读原文

读完本章,你可以让模型在一个循环中运行,并为它提供三个工具:一个读取文件,一个运行测试,一个以修改后的文件结束任务。循环在三种情况下停止:模型完成任务、步数用尽,或者模型不再发起调用。你会先在一个按脚本行事的模型上运行它,该模型能解决任务;然后在一个录制的开源模型上运行,该模型解决不了,你会看到它在哪里出错。

本章的智能体维护 unitcraft,这是一个小型 Python 库,用来读取、换算和格式化以文本形式书写的物理量,例如 3.5 kg。智能体接收维护者提交的一个问题单,并为库的代码提出修改。它可以在自己的副本上运行可见测试,但永远看不到隐藏检查,而隐藏检查决定一项修改是否算作完成。这种划分是有意为之。能读到自己评分器的智能体会去学习评分器,那样第 10 章中的测量就没有意义了。

吴恩达在 The Batch,第 379 期中的来信(日期为 2026 年 11 月 13 日)把智能体框架(agent harness)描述为包裹在大语言模型外层、为其提供上下文、工具和防护措施的代码。本书用这个词指同一件事。决策由模型做出;框架提供循环、工具,以及对这些工具所能执行操作的限制,本书的大部分内容讲的就是后一部分。

第一个任务 T-01 是单文件修复:修改位于 unitcraft/format.py。可见测试套件在 tests/test_format.py 中失败,问题单写道:“format_quantity 会丢掉末尾的零:3.5 kg 被输出为 3.5 kg,而默认应保留两位小数。”因此 3.5 kg 的预期输出是 3.50 kg。一个人会打开 unitcraft/format.py,阅读,做出修改,再运行一遍测试。智能体必须按顺序完成同样的事,步骤之间没有人介入,而框架必须保证即使模型出了差错,这个顺序也依然成立。

本章从头到尾讲解一个任务。它说明智能体一开始拥有什么、驱动它的循环、它调用的工具,以及让它停下来的第一条规则。随后它把循环运行两次,一次用按脚本行事的模型,一次用录制的模型,并统计所发生的情况。

智能体在一项任务上做什么

智能体开始时只有两条消息:一条是系统提示词,其中列出它的工具及这些工具的参数;另一条是问题(issue)文本。关于这项任务,模型不会再收到其他任何内容。智能体从不接触案例本身。测试框架会为每次运行生成该库的一份临时副本,智能体的每一次写入都只落在这份副本中。运行结束后,副本会被评分,然后被丢弃,因此一次运行不会给下一次运行留下任何改动。

一个修复要算作完成,需要同时满足两个条件:隐藏检查在副本上通过,并且运行以一次 finish 调用结束。对于 T-01,隐藏检查是 H-01,这是一个依据问题文本编写的 pytest 文件。它只断言一件事:format_quantity 会把 3.5、0 和 12 kg 补齐到两位小数,即 3.50 kg、0.00 kg 和 12.00 kg。运行结束后,测试框架会把它复制到该库的一份全新副本中,因此智能体从不读取它。第 10 章把同一条规则应用到整个任务集。是否把改动应用到案例库,是另一项单独的决定,由第 6 章中的审批关卡来做出。

这条规则还堵住了模型可能走的一条捷径:修改可见的测试,直到测试通过。对于 T-01,任务文件规定 tests 文件夹必须保持不变,因此评分器会把该文件夹与案例逐字节比较,只要测试被改动,这次运行就不算完成,即使隐藏检查通过也是如此。一个在猜测修复方式的模型,可能并无作弊的意图却走上这条捷径,而这条规则使这样的运行不被计为完成。

从任务文件加载 T-01 并列出案例的文件,只需要一个简短的示例。

read-the-issue.py Python 3.12.15 通过
"""The issue the agent starts from, task T-01, and the case's files in sorted order. The model reads only theissue and the system prompt, so these are what its first request holds about the task."""from lib.case import CASE, case_files, load_taskstask = load_tasks(only=["T-01"])[0]print("task:", task.id)print("issue:", task.issue)files = case_files(CASE)print("case files:", len(files))for name in files:    print(" ", name)
输出python read-the-issue.py
task: T-01
issue: `format_quantity` drops the trailing zeros: 3.5 kg prints as `3.5 kg`, and the default is two places. CI is red on `tests/test_format.py`.
case files: 25
  .github/workflows/test.yml
  README.md
  pyproject.toml
  tests/test_arith.py
  tests/test_cli.py
  tests/test_convert.py
  tests/test_format.py
  tests/test_parse.py
  tests/test_rounding.py
  tests/test_table.py
  tests/test_temperature.py
  unitcraft/__init__.py
  unitcraft/__main__.py
  unitcraft/arith.py
  unitcraft/cli.py
  unitcraft/convert.py
  unitcraft/errors.py
  unitcraft/format.py
  unitcraft/parse.py
  unitcraft/prefixes.py
  unitcraft/quantity.py
  unitcraft/rounding.py
  unitcraft/table.py
  unitcraft/temperature.py
  unitcraft/units.py

输出先打印问题文本,再按排序后的顺序打印案例的文件。问题文本是模型第一次请求中唯一与具体任务相关的文字,所以之后的每一步都取决于第一次请求包含了什么。该案例有 25 文件,智能体可以从它的副本中读取其中任何一个。

工作准则: 只依据一次运行自己的副本及其任务的检查来为它评分。绝不依据案例本身来评分,因为一旦改动进入了案例,就会让一次并未真正达标的运行被算作达标。

这部分尚未翻译,因此以英文显示。

A loop in about seventy lines

A model produces text, and the harness turns some of that text into actions. Each step sends the messages so far, along with the tool schemas, to the model. The reply comes back as text. The harness reads the tool call inside it, runs the tool on the scratch copy, appends the result to the messages, and goes around again. The model never runs anything itself. Anthropic's documentation for tool use states the contract in those terms: the model emits a structured request, the application runs the operation, and the result goes back into the conversation (How tool use works).

The loop is _loop in examples/lib/loop.py, about seventy lines. The file also holds rules for later chapters: the optional stops in Stops are off by default, and a reply cut off at the token limit is refused whatever the settings. None of this chapter's runs reach either. A step is one model call. A tool call is one request inside a step, and a reply can hold more than one. The loop acts on the first request and answers each other one with an error that says it was not run. Each request gets an ID from a counter, and the ID goes on the tool-result message that answers it. The assistant message that holds the reply carries no ID, and the trace keeps none. The trace, in lib/trace.py, holds one line per step: the step's number, the tool it called and what came back. Every reply stays in the messages too, which is why the model sees its own earlier steps on the next call, and why the request grows with each step.

The model's reply is plain text, and its tool call has a fixed shape: JSON inside <tool_call> tags. The chat template in the model file asks for that shape, a JSON object with a function name and arguments inside the tags (the model file at its pinned revision). The recorded replies use this shape, and the harness reads only what is inside the tags:

<tool_call>
{"name": "read_file", "arguments": {"path": "<case-relative path>"}}
</tool_call>

Text outside the tags is ignored, so a reply may carry prose before the call. A block that doesn't parse isn't run. The harness records it as a malformed call and hands the reason back to the model as an error result, so the model can try again.

Across the run the messages grow in a fixed order: the system prompt, the issue, then each reply followed by the result of its call. Nothing is summarised and nothing is dropped. That makes the transcript readable, and it makes the cost of each step grow with the one before it. Chapter 5 takes up what to do when that growth reaches the model's window. The runs in this chapter are short, and they don't need that yet.

ReAct interleaves written reasoning with actions, and Yao and colleagues reported that the reasoning helps a model keep and revise a plan, and handle exceptions (Yao et al., ReAct). This loop keeps the actions and asks the model for no reasoning between them. Its system prompt says "Reply with a tool call only," and the parser passes over any prose the model writes anyway.

Working rule: Keep every request and its result in the messages, and give each result the ID of the request it answers. A loop that drops a result leaves the model without an answer to its request, and the messages are where that gap shows.

两个工具和一个停止工具

智能体需要读取、测试和修改,因此本章为每项工作各提供一个工具。修改工具同时也是停止工具,因为在这个设计中,一次修改就会结束运行。

工具 参数 返回内容 是否结束运行
read_file path,即本次运行中该用例临时副本内的一个路径 文件的文本,或一条错误 否
run_tests 无 副本上可见测试集的各项计数和失败测试的名称 否
finish path 和 text,即完整的新文件 写入修改后可见测试集的各项计数和失败的测试 是

read_file 返回整个文件,副本之外的路径会被拒绝。run_tests 在副本中运行可见测试集,返回各项计数和失败测试的名称,而不是完整输出。运行超过时间限制的测试集会被停止,其进程组也一并停止。finish 接收某一个文件的新文本,把它写入副本,运行可见测试集,然后结束运行。如果写入被拒绝,错误会作为工具结果返回,运行继续,因此模型还有一次尝试的机会。

在本章中,这些工具在测试框架自身的进程内、在副本上运行。第 7 章会在沙箱中运行测试,也就是这些工具所启动的那一条命令。

读取文件的工具必须决定自己愿意读取哪些路径。下面用两个位于用例之外的路径调用 read_file,可以看到模型请求这样的路径时会得到什么。

tool-refusal.py Python 3.12.15 · pydantic 2.14.3 通过
"""The read tool refuses a path outside the case, and the refusal comes back as text the model can read. Only readsare tried, and a refused path never reaches the disk."""from lib.case import CASEfrom lib.tools import CH1, WorkspaceABSOLUTE = "/etc/secret.txt"ws = Workspace(CASE)for path in ("../secret.txt", ABSOLUTE):    result = CH1.call(ws, "read_file", {"path": path})    # An absolute path differs on every machine, so the output shows a placeholder for it.    print("refused:", result.text.replace(ABSOLUTE, "<absolute path>"))
输出python tool-refusal.py
refused: error: path outside the case: ../secret.txt
refused: error: path outside the case: <absolute path>

两个路径都被拒绝,每次拒绝都是一个工具结果。模型在下一步中会像读取其他结果一样读取它,因此可以改正路径后再试。两次被拒绝的读取都没有触及磁盘。

工作准则: 让每个工具只承担一项工作,并且只让停止工具结束运行。被拒绝的读取或写入,应以模型能够据以行动的错误形式返回给模型,绝不应使循环停止。

完成时停止,或在预算耗尽时停止

没有出口的循环会一直运行,直到有人让它停下,而每一步都要消耗词元。因此,每次运行都以三种方式之一结束,并将其记录为 ended。第一种,模型调用 finish,运行随其所做的改动一同结束。第二种,运行达到步数预算(本章的工具集为八步),以 step_cap 结束。第三种,模型连续两次回复,且完全没有调用工具。第一次出现这样的回复时会重试,并附上一条要求调用一次工具的消息。第二次出现时,运行以 no_tool_call 结束。

对不存在的工具发起调用,会以错误结果返回,运行继续。循环不会因为一次错误调用而停止。它会为这次调用计数,把错误交还给模型,然后等待下一步。预算的作用,是阻止一个不断发出错误调用的模型无限运行下去。预算统计的是模型调用的次数,而不是秒数,因此同一次运行在任何机器上都会在同一步结束。预算与上下文的大小也是两项相互独立的限制:一次运行可能在窗口仍有余量时就触及步数预算,也可能先耗尽窗口。窗口并不是本章所强制执行的限制。

第 2 章补充其余的停止规则,涵盖重复同一调用的运行、不断编辑却没有改变测试数量的运行,以及应当向人提问而不是继续的运行。本章的循环不含这些规则,因此陷入循环的模型会一直循环到第八步。

**工作准则:**在运行开始之前设定步数预算,并将其视为硬性限制。无论最后一步看起来如何,达到预算的运行都没有完成,应当报告为未完成。

在脚本化模型上运行

有了循环、它的工具和它的预算之后,第一次运行使用一个由你自己编写回复的模型。脚本化模型按顺序给出你为它准备的回复,除此之外什么也不做。这让它成为对循环的一次干净的测试:运行中的任何故障都出在循环上,而不在模型上;这次运行展示的是循环如何处理正确的回复,而不是模型会作出什么选择。针对 T-01 的四条脚本化回复依次是:读取实现、读取它的测试、运行可见测试套件,最后给出修正后的文件。

scripted-loop.py Python 3.12.15 · pydantic 2.14.3 通过
"""Four scripted replies solve T-01 through the step loop: read the file, read its test, run the visible suite,then finish with the fixed file. The model is scripted, so the output shows the loop's steps and not a model's choices."""from lib.case import load_tasksfrom lib.chapter1 import SOLUTION, call, reportfrom lib.models import ScriptedModelfrom lib.tools import CH1task = load_tasks(only=["T-01"])[0]model = ScriptedModel([    call("read_file", path="unitcraft/format.py"),    call("read_file", path="tests/test_format.py"),    call("run_tests"),    call("finish", path="unitcraft/format.py", text=SOLUTION.read_text(encoding="utf-8")),])run, done = report(model, task, CH1)  # CH1: three tools, their system prompt and a budget of eight steps; report prints the trace and scores the runassert done, "the scripted run should solve T-01"
输出python scripted-loop.py
step 1: read_file: 23 lines
step 2: read_file: 27 lines
step 3: run_tests: 8 failed, 22 passed
step 4: finish: 7 failed, 23 passed
steps: 4
tool calls: 4
ended: finish

这次运行用四步解决了 T-01,而这也正是脚本化运行所能证明的全部:循环能把正确的回复一路带到通过检查。修正后的文件是本书自己的解答,与用例数据存放在一起,示例断言这次运行被计为完成。

请按顺序阅读输出。每一行写明一次调用以及它返回的内容,因此这些行合起来显示了模型在每一步面前所拥有的信息。计数在第 3 步和第 4 步之间发生变化:修复使可见测试套件从 8 个失败变为 7 个失败,而且 issue 所描述的那个测试现在通过了。其余 7 个失败的是同一可见测试套件中的其他测试。对 T-01 起决定作用的检查是 H-01,它通过了。这次运行共 4 步,进行了 4 次工具调用,每步一次,并以 finish 结束。

**工作准则:**在任何模型上运行循环之前,先在脚本化模型上运行它。如果脚本化运行失败,故障出在测试框架,而模型运行只会把它掩盖起来。如果脚本化运行通过而模型运行失败,故障就出在模型或提示词上。

在录制的模型上运行

录制的运行来自 Qwen3-4B-Instruct-2507,这是一个量化为 Q4_K_M 的开源模型,在 CPU 上以温度 0 和固定种子运行。它的回复以其生成的原始文本保存,录制的清单中写明了模型、模型修订版本、提示词的哈希值和词元数。回放会检查每个请求是否与录制中保存的请求一致,这里的请求是指该步骤发送的消息和工具模式,然后返回录制的回复。

recorded-run.py Python 3.12.15 · pydantic 2.14.3 通过
"""The recorded run of T-01, replayed step by step: each request must match the one recorded, and the replies arethe recorded text, mistakes included. The run stops at the step cap without a finish, so the task is not done."""from lib.case import load_tasksfrom lib.chapter1 import Recorder, reportfrom lib.models import ReplayModelfrom lib.tools import CH1from collections import Countertask = load_tasks(only=["T-01"])[0]model = Recorder(ReplayModel("chapter-1-t01", "T-01"))run, done = report(model, task, CH1)assert not done, "the recorded run should not solve T-01"reasons = [reason for reply in model.replies for reason in reply.malformed]print("malformed calls:", len(reasons))for reason, count in sorted(Counter(reasons).items()):    print(f"  {count} x {reason}")assert all('"text": """' in reply.text for reply in model.replies[2:]), "from step 3 the call's text opens with triple quotes"print("prompt tokens:", run.prompt_tokens)print("completion tokens:", run.completion_tokens)
输出python recorded-run.py
step 1: read_file: 23 lines
step 2: run_tests: 8 failed, 22 passed
step 3: malformed: error: malformed call
step 4: malformed: error: malformed call
step 5: malformed: error: malformed call
step 6: malformed: error: malformed call
step 7: malformed: error: malformed call
step 8: malformed: error: malformed call
steps: 8
tool calls: 8
ended: step_cap
malformed calls: 6
  6 x not JSON (Expecting ',' delimiter)
prompt tokens: 13009
completion tokens: 2128

录制的模型始终没有完成任务。它的前两步是有效的调用:先是 read_file,然后是 run_tests。从第三步起,每条回复都是携带整个新文件的 finish 调用,而这些调用每一次都解析失败。这种情况出现了 6 次,原因都相同,运行最终以 step_cap 结束,共 8 步和 8 次工具调用。harness 将每次失败作为错误结果返回,模型则以形式相同的 finish 调用作答。

每次失败调用的形式如下。文件内容被省略,调用的文本以 ... 表示:

<tool_call>
{"name": "finish", "arguments": {"path": "unitcraft/format.py", "text": """ ...the whole file...\""}}
</tool_call>

该值以三个引号开头。JSON 将前两个引号读作空字符串,因此解析器在第三个引号处停止,而它在那里期望的是逗号。该值还以单个引号结尾,这个引号位于一个转义引号之后。

模型对问题的理解从第 2 步起就是错的,而格式失败掩盖了这一点。在第 2 步,模型写道 format_quantity“丢弃小数部分末尾的零,这是正确的”(这是模型的原话,出自录制文件 replies.jsonl 的第 2 步)。第 3 步的文件保留了这个错误:它仍然用 frac.rstrip("0") 去掉小数部分的零。本次运行中没有任何 finish 调用能够解析,因此该文件从未到达隐藏检查。书中示例之外的一次探测运行了第 3 步的文件,该文件从其代码块中复制,放在针对 H-01 的用例副本中,使用书中固定的 pytest 9.2.0:

FAILED test_t01.py::test_pads_to_two_places - AssertionError: assert '3.5 kg'...

书中自带的解答能通过同一项检查。所以模型提出的修改是错的,只是格式失败使它没有被检查。

该示例断言这次运行不算完成,并且从第三步起,每条回复都把文件放在调用内的三重引号中。停止工具(finish)是唯一携带整个文件的工具,所以格式失败出在这里。第 3 章会回到这个工具,并改变发送修改的方式,这消除了三重引号包裹的文件,不过小幅编辑会带来它自己的引号问题。这并不能解决第 2 步的误读:以正确形式发送的修改仍可能是错的。

工作准则: 每次运行都以同样的方式回放录制,绝不要为了让运行通过而编辑它。失败的录制显示了模型真实的行为。修复应当落在 harness、提示词或模型选择上,而修复的结果是一份新的录制。

出了什么问题,计什么数

重放的运行中的这次记录运行以两种方式失败。第一种由循环捕获,但循环没有修复它:每个格式错误的调用都返回了一条模型可以读取的错误结果,最终由步数预算结束了这次运行。第二种是错误的修改。循环从未发现它,因为没有任何一次 finish 调用能被解析,所以没有任何修改被执行。在这份记录中,模型从未调用错误的工具,也从未在没有调用的情况下提前以一段回复结束。格式错误反复出现,直到预算用尽,并且掩盖了模型的误读。

本书中的每次运行都用四个计数来描述。步数统计模型调用的次数,工具调用数统计请求的次数,其中包括格式错误的请求。两个词元计数分别是提示词元数和补全词元数:前者是对运行中每一次请求求和的结果,后者是模型生成的词元数。词元由固定版本模型自己的分词器在录制时计数,计数结果存储在记录的清单中。重放时读取已存储的计数,不再重新分词。对于这次记录运行,提示词元数为 13009,补全词元数为 2128。提示词元总数偏高,是因为每一步都会重新发送完整的对话记录。

工作准则: 每次运行都以相同的方式统计步数和工具调用数,以便比较两次运行。当某次运行因预算用尽而结束时,先阅读它的错误行,再去修改提示词或更换模型。错误行会显示模型是否在重复同一个错误,由此可以判断应当检查测试框架的哪一部分。

本章的决定

  • 工具在测试框架自身的进程中运行,作用于一份临时副本。 这足以演示循环,但并不是一种防护。在沙箱接管这些工具之前,这份副本只是写入操作的落脚处。
  • 停止工具接收一个文件的全部新文本。 这是停止工具所能承载的最简单的改动,也是已录制的模型无法以解析器可读的格式发送的那种改动。换用不同的停止工具,就需要重新录制。
  • 步数预算为八步。 这个数字很小,因为本章的任务大约需要四步,而与任务相称的预算会让走了弯路的运行显得突出。
  • 已录制的运行按实际发生的情况呈现。 格式失败和误读都保留在书中,因为为了通过而修改过的录制,展示的是一个并不存在的模型。录制的原始回复与计数一同保存,因此任何人都可以核对解析器如何处理了每一条回复。

工作准则: 在改动上述任何决定之前,先弄清这一改动会对本章打印的数字产生什么影响。新的步数预算会改变步数,新的停止工具意味着新的录制,而沙箱会改变工具所能触及的范围。请按该决定所在章的条件来做改动,并在信任结果之前,重新运行脚本化示例和已录制示例。

本章,在本版次中

版次 2026.11.2示例于 2026年11月20日 通过本章 4个示例 个示例中有 4 个通过

译自英文版图书,版次 2026.11.2。

引用本节

格式

每种格式均引用英文原书,本译本以其为准。

每种格式都会注明该版次。其链接会打开当前版次,节标题处会说明该节文本最后一次修改的时间。访问日期和检索日期即为您打开此页的当天。

本页内容

第 1 章,共 12 章: 为模型配上工具和循环

  1. 智能体在一项任务上做什么
  2. A loop in about seventy lines
  3. 两个工具和一个停止工具
  4. 完成时停止,或在预算耗尽时停止
  5. 在脚本化模型上运行
  6. 在录制的模型上运行
  7. 出了什么问题,计什么数
  8. 本章的决定

返回顶部全部章节