為模型配備工具與迴圈
閱讀約需 37 分鐘 分鐘,8 節 中共有 4 個範例。
讀完本章後,你可以讓模型在迴圈中執行,並為它配備三項工具:一項讀取檔案,一項執行測試,一項以修改後的檔案作為結束。迴圈會在模型宣告完成、步數用盡,或模型不再發出呼叫時停止。你會先用一個照腳本行事的模型解決任務,再用一個錄製下來的開放模型來執行,後者無法解決任務,你也會看到它在哪裡出錯。
本章的代理程式負責維護 unitcraft,這是一個小型 Python 函式庫,能讀取、轉換並格式化以文字書寫的物理量,例如 3.5 kg。代理程式會接手維護者提出的 issue,並對函式庫的程式碼提出修改。它可以在自己的副本上執行可見的測試,但永遠看不到那項隱藏的檢查,而那項檢查決定一項修改是否算完成。這樣的區隔是刻意設計的。如果代理程式能讀到自己的評分程式,它就會學會這個評分程式,第 10 章的量測結果也就毫無意義。
Andrew Ng 在 The Batch 第 379 期的信中(日期為 2026 年 11 月 13 日)指出,代理程式框架(agent harness)是包裹在 LLM 外層的程式碼,為它提供脈絡、工具與護欄。本書以同樣的意思使用這個詞。決策由模型做出,而框架則提供迴圈、工具,以及對這些工具可執行範圍的限制,本書大部分內容談的就是後者。
第一項任務 T-01 是只需修改一個檔案的修正:修改位置在 unitcraft/format.py。可見的測試套件在 tests/test_format.py 中失敗,而 issue 寫道:「format_quantity 會丟掉尾端的零:3.5 kg 印成 3.5 kg,而預設應為兩位小數。」因此 3.5 kg 的預期輸出是 3.50 kg。一個人會打開 unitcraft/format.py,閱讀內容,進行修改,然後再次執行測試。代理程式必須依序做同樣的事,而且步驟之間沒有人介入,框架則必須確保即使模型出了差錯,這個順序仍然成立。
本章從頭到尾處理一項任務。內容說明代理程式一開始擁有什麼、驅動它的迴圈、它所呼叫的工具,以及讓它停止的第一條規則。接著,本章會把迴圈執行兩次,一次用照腳本行事的模型,一次用錄製下來的模型,並統計實際發生的情況。
代理在單一任務中的行為
代理一開始只有兩則訊息:一則是列出其工具與引數的系統提示,另一則是議題文字。關於這項任務,模型不會收到其他任何資訊。代理從不直接接觸案例本身。測試框架每次執行都會建立一份函式庫的暫存副本,代理的每一次寫入都只會落在這份副本中。執行結束後,副本會先被評分,接著被丟棄,因此一次執行不會留下任何變更影響下一次執行。
一項修正要算作完成,必須同時滿足兩個條件:隱藏檢查在副本上通過,而且執行是以一次 finish 呼叫結束。就 T-01 而言,隱藏檢查是 H-01,這是依據議題文字撰寫的 pytest 檔案。它只斷言一件事:format_quantity 會將 3.5、0 與 12 公斤補齊到小數點後兩位,分別為 3.50 kg、0.00 kg 與 12.00 kg。測試框架會在執行結束後,將它複製到一份全新的函式庫副本中,因此代理絕不會讀到它。第 10 章會把同一條規則套用到整個任務集。將變更套用到案例函式庫是另一項獨立的決定,由第 6 章中的核准關卡來做出。
這條規則也堵住了模型可能採取的一條捷徑:修改可見的測試,直到測試通過。就 T-01 而言,任務檔案規定 tests 資料夾必須維持不變,因此評分器會將該資料夾與案例逐位元組比對,只要測試被修改,即使隱藏檢查通過,該次執行也不算完成。一個在猜測修正方式的模型,可能在毫無作弊意圖的情況下走上這條捷徑,而這條規則正是讓這種做法不被計入的依據。
從任務檔案載入 T-01 並列出案例的檔案,只需要一個簡短的範例。
1"""The issue the agent starts from, task T-01, and the case's files in sorted order. The model reads only the2issue and the system prompt, so these are what its first request holds about the task."""3from lib.case import CASE, case_files, load_tasks45task = load_tasks(only=["T-01"])[0]6print("task:", task.id)7print("issue:", task.issue)8files = case_files(CASE)9print("case files:", len(files))10for name in files:11 print(" ", name)
python read-the-issue.pytask: 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 接收單一檔案的新文字,將它寫入副本,執行可見測試套件,然後結束執行。如果寫入被拒絕,錯誤會以工具結果的形式回傳,執行會繼續,模型因此有再試一次的機會。
在本章中,這些工具在測試框架(harness)自己的行程內、對副本執行。第 7 章則在沙箱中執行測試,也就是這些工具所啟動的那一個指令。
讀取檔案的工具必須決定哪些路徑可以讀取。以兩個位於案例之外的路徑呼叫 read_file,就能看到模型提出這類要求時會得到什麼回應。
1"""The read tool refuses a path outside the case, and the refusal comes back as text the model can read. Only reads2are tried, and a refused path never reaches the disk."""3from lib.case import CASE4from lib.tools import CH1, Workspace56ABSOLUTE = "/etc/secret.txt"7ws = Workspace(CASE)8for path in ("../secret.txt", ABSOLUTE):9 result = CH1.call(ws, "read_file", {"path": path})10 # An absolute path differs on every machine, so the output shows a placeholder for it.11 print("refused:", result.text.replace(ABSOLUTE, "<absolute path>"))
python tool-refusal.pyrefused: error: path outside the case: ../secret.txt
refused: error: path outside the case: <absolute path>
兩個路徑都被拒絕,而且每次拒絕都是一個工具結果。模型會在下一步像讀取其他結果一樣讀取它,因此可以修正路徑再試一次。兩次被拒絕的讀取都沒有存取磁碟。
實用原則: 讓每個工具只負責一項工作,並且只有停止工具可以結束執行。被拒絕的讀取或寫入,應該以模型能夠據以採取行動的錯誤回傳給它,絕不應該中止迴圈。
完成時停止,或預算用盡時停止
沒有出口的迴圈會一直執行,直到有人把它停下來,而且每一步都會耗用 token。因此每次執行都以三種方式之一結束,並將結果記錄為 ended。第一種是模型呼叫 finish,執行隨即結束,並附上它所做的變更。第二種是執行達到步數預算(本章的工具集為八步),並以 step_cap 結束。第三種是模型連續兩次回覆都沒有任何工具呼叫。第一次出現這種回覆時會重試,並附上一則要求呼叫一個工具的訊息;第二次則以 no_tool_call 結束執行。
呼叫不存在的工具時,會以錯誤結果回傳,執行會繼續進行。迴圈不會因為一次錯誤的呼叫而停止。它會計入這次呼叫,回傳錯誤,然後等待下一步。若模型不斷發出錯誤的呼叫,是預算讓它不致永遠執行下去。預算計算的是模型呼叫次數,而非秒數,因此同一次執行在任何機器上都會在同一步結束。預算也與上下文的大小是各自獨立的限制:一次執行可能在視窗仍有餘裕時就達到步數預算,也可能先用完視窗。本章不對視窗施加限制。
第 2 章會補上其餘的停止規則,涵蓋重複相同呼叫的執行、一再編輯卻沒有改變測試數量的執行,以及應該向使用者提問而非繼續進行的執行。本章的迴圈沒有這些規則,因此陷入迴圈的模型會一直循環到第八步。
**實用原則:**在執行開始前設定步數預算,並將它視為硬性限制。無論最後一步看起來如何,達到預算的執行都沒有完成,應回報為未完成。
在腳本化模型上執行
在迴圈、工具與預算都就位之後,第一次執行使用的是回覆由你自己撰寫的模型。腳本化模型只會依序回傳你給它的回覆,不會做別的事。這讓它成為迴圈的單純測試:執行中的任何錯誤都出在迴圈,而不是模型;而且這次執行呈現的是迴圈如何處理正確的回覆,而不是模型會做出什麼選擇。針對 T-01 的四則腳本化回覆依序是:讀取實作、讀取其測試、執行可見的測試套件,最後交出修正後的檔案。
1"""Four scripted replies solve T-01 through the step loop: read the file, read its test, run the visible suite,2then finish with the fixed file. The model is scripted, so the output shows the loop's steps and not a model's choices."""3from lib.case import load_tasks4from lib.chapter1 import SOLUTION, call, report5from lib.models import ScriptedModel6from lib.tools import CH178task = load_tasks(only=["T-01"])[0]9model = ScriptedModel([10 call("read_file", path="unitcraft/format.py"),11 call("read_file", path="tests/test_format.py"),12 call("run_tests"),13 call("finish", path="unitcraft/format.py", text=SOLUTION.read_text(encoding="utf-8")),14])15run, done = report(model, task, CH1) # CH1: three tools, their system prompt and a budget of eight steps; report prints the trace and scores the run16assert done, "the scripted run should solve T-01"
python scripted-loop.pystep 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 個失敗,而議題所描述的那個測試現在通過了。剩下的七個失敗屬於同一個可見套件中的其他測試。對 T-01 而言,算數的檢查是 H-01,而它通過了。這次執行共 4 個步驟、進行 4 次工具呼叫,每個步驟一次,並以 finish 結束。
實用原則: 在任何模型上執行迴圈之前,先在腳本化模型上執行。如果腳本化執行失敗,錯誤就在測試駕馭框架(harness),而用模型執行只會把它掩蓋。如果腳本化執行通過而模型執行失敗,錯誤就在模型或提示。
在錄製的模型上執行
錄製的執行結果來自 Qwen3-4B-Instruct-2507,這是一個量化為 Q4_K_M 的開放模型,在 CPU 上以溫度 0 和固定的種子執行。它的回覆以模型產生的原始文字儲存,錄製檔附有清單(manifest),記載模型名稱、模型修訂版本、提示的雜湊值以及 token 數量。重播時會檢查每個請求是否與錄製檔中保存的請求相符,此處的請求是指該步驟送出的訊息與工具綱要(schema),接著才回傳錄製的回覆。
1"""The recorded run of T-01, replayed step by step: each request must match the one recorded, and the replies are2the recorded text, mistakes included. The run stops at the step cap without a finish, so the task is not done."""3from lib.case import load_tasks4from lib.chapter1 import Recorder, report5from lib.models import ReplayModel6from lib.tools import CH178from collections import Counter910task = load_tasks(only=["T-01"])[0]11model = Recorder(ReplayModel("chapter-1-t01", "T-01"))12run, done = report(model, task, CH1)13assert not done, "the recorded run should not solve T-01"14reasons = [reason for reply in model.replies for reason in reply.malformed]15print("malformed calls:", len(reasons))16for reason, count in sorted(Counter(reasons).items()):17 print(f" {count} x {reason}")18assert all('"text": """' in reply.text for reply in model.replies[2:]), "from step 3 the call's text opens with triple quotes"19print("prompt tokens:", run.prompt_tokens)20print("completion tokens:", run.completion_tokens)
python recorded-run.pystep 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'...
本書自己的解答能通過同一項檢查。因此模型提出的修改是錯的,只是格式失敗使它沒有被檢查到。
此範例斷言這次執行不算完成,而且從第三步起,每個回覆都把檔案以三重引號放在呼叫之中。停止工具是唯一帶有整個檔案的工具,所以格式失敗出在這裡。第 3 章會回頭討論該工具,並改變修改內容的傳送方式,這能消除三重引號包住的檔案,不過小幅編輯也會帶來它自己的引號問題。它無法解決第 2 步的誤讀:以正確形式送出的修改仍然可能是錯的。
實用原則: 每次執行都以相同方式重播錄製檔,絕不為了讓執行通過而去修改它。失敗的錄製檔顯示了模型實際做了什麼。修正應該放在測試框架、提示或模型選擇上,而修正的結果是一份新的錄製檔。
哪裡出了問題,以及計算什麼
重播的執行中的那次紀錄執行以兩種方式失敗。第一種由迴圈捕捉到,但沒有修復:每一次格式錯誤的呼叫都回傳了一個模型可以讀取的錯誤結果,最後由步驟預算結束了這次執行。第二種是錯誤的修改。迴圈從未察覺這一點,因為沒有任何一次 finish 呼叫能被解析,所以也沒有任何修改被執行。在這份紀錄中,模型從未呼叫錯誤的工具,也從未在沒有呼叫的情況下提前以一則回覆結束。格式錯誤不斷重複,直到預算用盡,並且掩蓋了誤解。
本書中的每一次執行都以四個計數來描述。步驟數計算模型呼叫的次數,工具呼叫數計算 requests 的數量,包含格式錯誤的呼叫。兩個 token 計數分別是提示 token 數與補全 token 數:前者是整次執行中每個請求加總的結果,後者是模型產生的 token 數。token 在製作紀錄時,以固定版本模型本身的分詞器計算,計數會儲存在該紀錄的清單檔(manifest)中。重播時讀取已儲存的計數,不會重新分詞。對這次紀錄執行而言,提示 token 數為 13009,補全 token 數為 2128。提示 token 的總數偏高,是因為每個步驟都會再次送出完整的對話紀錄。
實用原則: 每次執行都以相同的方式計算步驟數與工具呼叫數,這樣兩次執行才能互相比較。當執行在預算用盡時結束,請先閱讀它的錯誤行,再決定是否更改提示或模型。錯誤行會顯示模型是否一再重複同一個錯誤,這也告訴你應該檢視執行框架(harness)的哪個部分。
本章的決定
- 工具在 harness 自己的行程中執行,作用於一份暫存副本。 這足以展示迴圈的運作,但並不是防禦措施。在沙箱真正容納這些工具之前,這份副本只是讓寫入動作落地的地方。
- 停止工具接收單一檔案的完整新內容。 這是停止工具所能承載的最簡單的修改,也正是錄製下來的模型無法以剖析器讀得懂的格式送出的修改。換用不同的停止工具,就需要重新錄製。
- 步數預算為八。 這個數字很小,因為本章的任務大約只需要四個步驟,而與任務相符的預算會讓漫無目的的執行顯得突出。
- 錄製的執行過程照實呈現。 格式失敗與誤讀都留在書中,因為經過編修而通過的錄製,展示的會是一個不存在的模型。錄製的原始回覆與計數一併保留,任何人都可以檢查剖析器對每一則回覆的解讀結果。
實用原則: 在更動上述任何一項決定之前,先弄清楚這項更動會對本章印出的數字造成什麼影響。新的步數預算會改變步數計數,新的停止工具意味著需要新的錄製,而沙箱會改變工具能夠觸及的範圍。請在該決定所屬章節的脈絡下進行更動,並在採信結果之前,重新執行腳本化與錄製的範例。
本章,於本版次中
版次 2026.11.2範例於 2026年11 月 20 通過測試本章 4 個範例 個範例中有 4 個通過
譯自英文書,版次 2026.11.2。