給模型不會誤用的工具
閱讀約需 32 分鐘 分鐘,6 節 中共有 5 個範例。
讀完本章後,你可以為模型提供一組工具,由框架(harness)在任何工具執行之前先檢查其引數,並寫出模型能據以行動的拒絕訊息。
這個代理的工作是修復 unitcraft,一個負責格式化與轉換數量的小型 Python 函式庫。本章要談的問題出現在它的編輯動作上,因為少一個引號就會讓編輯失敗。代理在函式庫的暫存副本上工作。在第 1 章中,它第一次被記錄下來的執行就因為一次呼叫而中斷。那個開放模型是 Qwen3-4B,由其錄製內容重播而來。它讀了正確的檔案,把議題誤解為要它去掉零,接著把每項變更都寫成整個檔案,用 Python 的三重引號,放在一次 finish 呼叫的 JSON 之中。三重引號在 JSON 字串內並不合法,所以那些引數從未被成功解析。沒有任何工具執行,這次執行在步數上限時結束。
本章比較兩組工具。工具集 v1 是製作任務集錄製內容時所用的七個工具:list_files、read_file、run_tests、write_file、edit_file、ask_user 與 finish。工具集 v2 擁有相同的工具、相同的描述語句與相同的系統提示,只有三項改變:嚴格的引數模型、在每則拒絕訊息中標明錯誤類型,以及編輯失敗時提供最接近的行的錯誤訊息。
誤解是模型自己造成的,任何工具設計都無法修正。那些格式錯誤的呼叫有兩個部分。其一,呼叫的形狀是框架無法讀取的;其二,變更是放在一個模型必須正確跳脫的字串裡傳遞。本章同時處理這兩個問題。每個工具都有一份引數結構描述,框架在執行前先檢查它,而拒絕訊息則以模型能據以行動的文字回傳給模型。在工具集 v1 中,變更也不再經由 finish 傳遞:模型以 edit_file 與 write_file 編輯它的副本,而 finish 只帶一份摘要。小幅度的編輯也有它自己的引號問題,最後一節會談到。
綱要說明允許什麼
模型是根據別人告訴它的工具資訊來撰寫工具呼叫,而測試框架(harness)要拒絕錯誤的呼叫,也只能依據同一份描述來檢查。工具集中的每個工具都有三個部分:名稱、一句描述,以及參數模型(argument model)。參數模型是一個小型的 pydantic 類別,列出該工具接受的欄位。測試框架在請求中附上每個工具的綱要(schema),而綱要是由這個類別產生的,因此模型讀到的文字與測試框架執行的檢查出自同一處。
這個單一來源之所以重要,是因為綱要包含的不只是欄位名稱。可以把它想成模型在發出呼叫之前要填寫的表單。表單的每一行會指出欄位名稱,說明需要哪一種答案,也可能說明答案的大小限制。表單可以引導填寫的人,卻無法阻止錯誤的答案被寫下來。表單作為防線到此就不再有用,表單做不到的檢查必須由測試框架來做。
Pydantic 會把每個欄位的型別、描述、預設值與界限寫進綱要。本案例的工具只接受路徑與字串,所以本節改用另一個讀取工具,它帶有行數上限,而工具集中沒有任何工具使用這個上限。它是教學用的模型,目的是展示界限的樣貌。印出它的綱要是了解模型被告知什麼的最快方式,其中該讀的是界限與預設值這幾行。
1"""The JSON schema pydantic makes for a read with a line limit: its bounds, its default and the descriptions the2model reads before it calls. The point of the prose rests on the max_lines lines: the bounds, the default and the3description."""4from lib.tools import LinesArgs56schema = LinesArgs.model_json_schema()7limit = schema["properties"]["max_lines"] # the schema of the one field with a bound8print("required:", ", ".join(schema["required"]))9print("max_lines minimum:", limit["minimum"])10print("max_lines maximum:", limit["maximum"])11print("max_lines default:", limit["default"])12print("max_lines description:", limit["description"])13print("path description:", schema["properties"]["path"]["description"])14# LinesArgs has no extra="forbid", so its schema says nothing about other keys. The tool classes do forbid them.15assert "additionalProperties" not in schema
python schema-from-model.pyrequired: path
max_lines minimum: 1
max_lines maximum: 1000
max_lines default: 200
max_lines description: The most lines to return, from 1 to 1000; the default is 200.
path description: A file path relative to the case root, with / as the separator.
請用模型閱讀的方式來讀這份輸出。唯一必要的參數是 path。max_lines 接受從 1 到 1000 的值。
預設值是這個欄位的另一半。當模型省略 max_lines 時,其值為 200。這些界限存在於模型讀取的綱要中,而不只是存在於檢查它們的程式碼中,欄位本身的描述也用文字說了同樣的事:「The most lines to return, from 1 to 1000; the default is 200.」
綱要中的預設值是一則註記,而不是規則。JSON Schema validation specification 把 default 視為註解(annotation):它提供一個值,但不檢查任何東西。測試框架是否填入預設值由測試框架自行決定,光靠綱要並不會讓這件事發生。
模型所讀內容的另一半,是每個工具的那一句描述。這些句子在每次請求中都與各自的綱要並列,所以下面的範例會把它們印出來。有兩行值得核對:一行說明第 1 章的哪些工具與本工具集使用相同的句子,另一行說明 finish 並不相同。
1"""The one-sentence description of each tool in the v1 set, the text the model reads beside each schema. The point2rests on the last two printed lines: which chapter 1 tools carry the same sentence in v1, and that finish does not."""3from lib.tools import CH1, V145print("v1 tools:", len(V1.tools))6for tool in V1.tools:7 print(f"v1 {tool.name}: {tool.description}")8# The chapter 1 tools whose sentence is exactly the one v1 gives the same tool.9shared = [t.name for t in CH1.tools if V1.get(t.name) and V1.get(t.name).description == t.description]10print("ch1 tools with the same sentence in v1:", ", ".join(shared))11print("ch1 finish has the same sentence in v1:", V1.get("finish").description == CH1.get("finish").description)12assert shared == ["read_file", "run_tests"]
python tool-descriptions.pyv1 tools: 7
v1 list_files: List the files in the case, by their case-relative paths.
v1 read_file: Read one file in the case, given by its case-relative path.
v1 run_tests: Run the visible test suite on your copy and return the counts of passed and failed tests.
v1 write_file: Create a new file in your copy with this text; it is refused when the file already exists.
v1 edit_file: Replace the one occurrence of old text with new text in a file in your copy.
v1 ask_user: Ask the person a question and end the run; use it when the task needs their decision.
v1 finish: End the run with a summary of what you changed and why.
ch1 tools with the same sentence in v1: read_file, run_tests
ch1 finish has the same sentence in v1: False
工具集 v1 有 7 個工具,每個工具各有一句描述。輸出證實第 1 章的工具在本工具集中保留了原有的句子,共有 read_file, run_tests 個。改變的是 finish,因為它的工作改變了。一句描述說明工具的用途,它無法承載測試框架不會檢查的規則。
**實用原則:**把每個界限、型別與預設值寫在參數模型中,由測試框架在那裡檢查,並為每個欄位提供模型讀得懂的描述。工具的那一句描述只說明工具的用途。只存在於那一句描述中的規則,只是測試框架永遠不會強制執行的提示。
預設寬鬆,必要時嚴格
模型被要求提供數字時,可能寫出 "50",旗標也可能以 true 的形式送達。工具框架必須決定是否照字面意思接受這些值,而 pydantic 以模式來回答這個問題。在預設的寬鬆模式下,若轉換的結果明確,值就會被轉換;若不明確,值就會被拒絕。在嚴格模式下,值必須已經是宣告的型別。工具集 v1 的引數模型使用預設模式,而工具集 v2 中對應的副本則是嚴格模式。
結構描述只是提示,而不是保證。OpenAI 的函式呼叫指南描述了一項同樣稱為 strict 的設定,它會限制模型的生成內容:開啟時,呼叫會穩定地遵循結構描述;關閉時,則只能盡力而為。Pydantic 的嚴格模式是不同的機制,它在呼叫送達之後才進行檢查,並不限制生成。這套工具框架在模型寫出內容的當下並不加以限制,因此無論結構描述怎麼寫,每個呼叫在送達後都要經過檢查。
模型為行數上限寫出 "50",多半是指五十,因此直接拒絕會讓一個幾乎正確的呼叫白白浪費一個步驟。模型為同一個欄位送出 true,則完全是另一種意思,把它轉成數字反而會掩蓋這一點。這兩種處理方式都無法適用於每個欄位,因此必須針對包含這些欄位的每個引數模型選擇模式。本章是在每個模型上設定模式,而不是在每個欄位上設定。
下一個範例會將相同的值分別送入兩種模式。請比較每種模式對每個值的處理。
1"""Pydantic's default (lax) mode and strict mode, given the same values for an int field: lax takes the string "50"2and the bool True as ints, strict refuses both, and each refusal names its error type. The point of the prose rests3on the last lines: on a string field the two modes refuse the same values, and the two tool sets' schemas differ4only in their titles."""5from lib.tools import LinesArgs, PathArg, StrictLinesArgs, StrictPathArg, V1, V26from pydantic import ValidationError78values = [("str 50", "50"), ("int 50", 50), ("bool True", True), ("float 2.0", 2.0), ("float 2.5", 2.5)]9outcomes = {}10for label, value in values:11 for mode, model in (("lax", LinesArgs), ("strict", StrictLinesArgs)):12 try:13 model.model_validate({"path": "unitcraft/format.py", "max_lines": value})14 outcomes[mode, label] = "accepted"15 except ValidationError as exc:16 outcomes[mode, label] = exc.errors()[0]["type"] # the first error's type, which a refusal names17 print(f"{mode}, max_lines {label}: {outcomes[mode, label]}")18assert outcomes["lax", "str 50"] == "accepted" and outcomes["strict", "str 50"] == "int_type"1920# The case's tools take only strings. On a string field the modes agree, because lax mode does not turn a number,21# a flag or nothing into a string.22for label, value in [("str a.py", "a.py"), ("int 3", 3), ("float 3.5", 3.5), ("bool True", True), ("None", None),23 ("list", []), ("object", {})]:24 results = {}25 for mode, model in (("lax", PathArg), ("strict", StrictPathArg)):26 try:27 model.model_validate({"path": value})28 results[mode] = "accepted"29 except ValidationError as exc:30 results[mode] = exc.errors()[0]["type"] # the first error's type, which a refusal names31 print(f"{mode}, path {label}: {results[mode]}")32 assert results["lax"] == results["strict"]333435def untitled(node):36 """A schema with its titles removed, so the two tool sets can be compared on everything else."""37 if isinstance(node, dict):38 return {key: untitled(value) for key, value in node.items() if key != "title"}39 if isinstance(node, list):40 return [untitled(item) for item in node]41 return node424344same = [untitled(a.schema()) == untitled(b.schema()) for a, b in zip(V1.tools, V2.tools)]45print("v1 and v2 schemas differ before titles are removed:", any(a.schema() != b.schema() for a, b in zip(V1.tools, V2.tools)))46print("v1 and v2 schemas equal once titles are removed:", all(same))47assert all(same)
python lax-and-strict.pylax, max_lines str 50: accepted
strict, max_lines str 50: int_type
lax, max_lines int 50: accepted
strict, max_lines int 50: accepted
lax, max_lines bool True: accepted
strict, max_lines bool True: int_type
lax, max_lines float 2.0: accepted
strict, max_lines float 2.0: int_type
lax, max_lines float 2.5: int_from_float
strict, max_lines float 2.5: int_type
lax, path str a.py: accepted
strict, path str a.py: accepted
lax, path int 3: string_type
strict, path int 3: string_type
lax, path float 3.5: string_type
strict, path float 3.5: string_type
lax, path bool True: string_type
strict, path bool True: string_type
lax, path None: string_type
strict, path None: string_type
lax, path list: string_type
strict, path list: string_type
lax, path object: string_type
strict, path object: string_type
v1 and v2 schemas differ before titles are removed: True
v1 and v2 schemas equal once titles are removed: True
嚴格模式改變的只有轉換,範例顯示的其他部分都沒有變。符合宣告型別的值在兩種模式下都能通過。字串 "50" 在寬鬆模式下被接受,在嚴格模式下被拒絕,並顯示 int_type。旗標也是以同樣方式處理:True 在寬鬆模式下被接受,嚴格模式則拒絕它,並顯示 int_type。寬鬆模式也會把 2.0 當作 int 接受,因為轉換時不會損失任何資訊。它會拒絕 2.5,因為小數部分會遺失,其拒絕訊息為 int_from_float。
工具集 v2 的副本是以工具集 v1 類別的子類別寫成。每個副本保留其父類別的所有欄位,只改變模式,因此工具集 v1 保有原本的類別,輸出的內容也與先前相同。在舊設定旁邊新增設定,而不是取代舊設定,可以讓工具集有所變動,卻不改變先前執行所輸出的內容。模式不會出現在模型讀取的結構描述中。範例顯示,兩個工具集的結構描述只有各類別的標題不同:工具集 v2 為 StrictPathArg,工具集 v1 則為 PathArg。類別名稱是模型能看到的、與嚴格模式有關的唯一線索。
嚴格模式並非沒有代價。它會把原本可用的呼叫變成拒絕,模型接著必須重試。它換來的是:工具收到的計數確實是計數,而旗標絕不會被意外當成數字。這項取捨是否值得,取決於欄位;而在本案例的工具上,它不會改變任何事。本案例工具的每個引數都是字串。在字串欄位上,寬鬆與嚴格模式拒絕的值相同。輸出的最後幾行嘗試了字串、數字、浮點數、旗標、空值、串列與物件,例如數字在兩種模式下都會被拒絕,並顯示 string_type。因此,工具集 v2 的嚴格設定,並不會改變 JSON 呼叫在這些工具上可能造成的任何拒絕。它保護的是日後某個工具可能新增為數字的欄位。只有有界讀取會進行轉換,而沒有任何工具使用它。
實用原則: 當轉換符合模型的原意時,使用寬鬆模式;當悄悄進行的轉換會改變工具的行為時,使用嚴格模式。在依賴每個模型之前,先用型別錯誤的值測試它,並閱讀拒絕訊息所指出的錯誤類型,因為那正是模型會看到的內容。
模型讀得懂的錯誤
只有當模型能讀懂自己的呼叫哪裡出錯時,拒絕才有幫助。如果執行在第一次錯誤呼叫就中止,模型什麼也學不到。如果框架(harness)默默丟棄錯誤的呼叫,模型在下一步只能憑空猜測。因此,每一則拒絕都以工具結果的文字形式送回,和其他結果是同一類文字,模型會在下一步讀到它。
錯誤的呼叫會在不同的環節失敗,框架必須依序檢查。在某一步中送達的拒絕,就是對話紀錄裡多出來的一筆工具結果。執行會繼續,模型的下一次回覆可以對它做出反應,步數上限依然適用。所以一次錯誤的呼叫會讓模型多花一步,而拒絕的內容決定了這一步是否花得有價值。
這個範例中的每一個錯誤呼叫,錯法都不相同。它們先經過工具集 v2,再經過工具集 v1,輸出結果顯示了每個工具集送回的內容:
1"""Five bad calls, sent by a ScriptedModel. Each parsed call is run through the v2 tool set and through v1, and each2refusal is the text the model reads on its next step. The point of the prose rests on the v2 lines and the v1 lines3for calls 2 to 5. A call whose JSON is cut off never reaches a schema, so neither set runs it."""4import shutil56from lib.case import scratch_copy7from lib.models import ScriptedModel8from lib.tools import V1, V2, Workspace910CALLS = [11 '<tool_call>{"name": "read_file", "arguments": {"path": "unitcraft/format.py"</tool_call>',12 '<tool_call>{"name": "read_file", "arguments": {}}</tool_call>',13 '<tool_call>{"name": "read_file", "arguments": {"path": "unitcraft/format.py", "lines": 5}}</tool_call>',14 '<tool_call>{"name": "read_file", "arguments": {"path": 3}}</tool_call>',15 '<tool_call>{"name": "read_files", "arguments": {"path": "unitcraft/format.py"}}</tool_call>',16]17scratch = scratch_copy()18ws = Workspace(scratch)19model = ScriptedModel(CALLS)20for number in range(1, len(CALLS) + 1):21 reply = model.reply([], V2.schemas()) # the schemas are sent with each request; a scripted model ignores them22 if reply.malformed: # the reply parser's reason for a call whose JSON it cannot read23 print(f"call {number}, not run, the JSON is not read: {reply.malformed[0]}")24 continue25 call = reply.tool_calls[0]26 print(f"call {number}, {call['name']}, v2: {V2.call(ws, call['name'], call['arguments']).text}")27 print(f"call {number}, {call['name']}, v1: {V1.call(ws, call['name'], call['arguments']).text}")28shutil.rmtree(scratch, ignore_errors=True)
python bad-arguments-handed-back.pycall 1, not run, the JSON is not read: not JSON (Expecting ',' delimiter)
call 2, read_file, v2: error: invalid arguments: path (missing): Field required
call 2, read_file, v1: error: invalid arguments: path: Field required
call 3, read_file, v2: error: invalid arguments: lines (extra_forbidden): Extra inputs are not permitted
call 3, read_file, v1: error: invalid arguments: lines: Extra inputs are not permitted
call 4, read_file, v2: error: invalid arguments: path (string_type): Input should be a valid string
call 4, read_file, v1: error: invalid arguments: path: Input should be a valid string
call 5, read_files, v2: error: invalid arguments: name (literal_error): Input should be 'list_files', 'read_file', 'run_tests', 'write_file', 'edit_file', 'ask_user' or 'finish'
call 5, read_files, v1: error: unknown tool: read_files
第一種失敗發生在查閱任何結構描述(schema)之前。JSON 被截斷的那次呼叫永遠不會到達工具,因為回覆剖析器無法讀取它。它的原因是 not JSON,後面接著 JSON 剖析器自己的訊息。該訊息來自 Python 標準函式庫,而不是 pydantic,而且這次呼叫沒有欄位可以指名,因為它的引數根本沒有剖析成功。
其他呼叫都能剖析並到達結構描述,各自得到屬於自己的拒絕。對 read_file 沒有提供引數的呼叫,會因 path 被拒絕,錯誤類型為 missing。工具不接受的鍵,在此例中是 lines,會以 extra_forbidden 被拒絕,即使呼叫的其餘部分都沒有問題。以數字給定的 path 則以 string_type 被拒絕。每一則拒絕都會指出欄位、錯誤類型和訊息,因此模型的下一次呼叫只需修改出錯的那一處。欄位使用結構描述本身的用語,也就是 path,而不是 Python 類別的名稱,因為模型處理的正是這些用語。
工具集 v1 使用相同的欄位,但不啟用嚴格模式,所以對於呼叫 2 到 4,它拒絕的是相同的呼叫,欄位和訊息也相同,如輸出中工具集 v1 的各行所示。它的文字省略了錯誤類型,而指出該類型,正是工具集 v2 對這些拒絕所做的唯一補充。請比較呼叫 2 中缺少的 path:工具集 v1 給出 error: invalid arguments: path: Field required,工具集 v2 給出 error: invalid arguments: path (missing): Field required。
這些拒絕各自要求不同的修正,而文字正是告訴模型該做哪一種修正的依據。缺少欄位,要求補上該欄位。多出的鍵,要求將它移除。類型錯誤,則要求依結構描述的規定寫出該值。如果模型只得到「invalid arguments」,就得猜這三者中自己該做哪一種,而每次猜測都要花掉一步。指出欄位和錯誤類型,就能把猜測化為對呼叫的一次修改。
實用原則: 將每一則拒絕都以工具結果送回,並指出欄位、錯誤類型和訊息。不要因為一次錯誤的呼叫就結束執行;唯一的例外是第 2 章的停止規則,在規則啟用且同一個錯誤呼叫一再出現時才適用。剖析器無法讀取的呼叫,以剖析器給出的原因作為拒絕內容,且不會有任何工具對它執行。
每個工具一個名稱
名稱是呼叫交給測試框架(harness)的第一項資訊,而且測試框架在讀取任何引數之前就能檢查它。模型若憑空編造一個工具,或是記錯了工具名稱,所發出的呼叫便沒有任何對應的內容,測試框架必須用模型能夠運用的方式告知這一點。
上一節範例中的最後一次呼叫要求使用 read_files,這是工具集中沒有的工具,所帶的 path 則適用於 read_file。它得到的拒絕訊息列出了工具集中實際存在的名稱,因此模型的下一次呼叫可以從中選用。工具集 v2 的拒絕訊息以 invalid arguments 開頭,因為測試框架是把名稱當作呼叫的一個欄位來檢查,而該欄位名為 name。測試框架會依工具集中各工具的名稱建立一個 Literal 型別,並以它檢查名稱。錯誤的名稱會以 literal_error 的形式失敗,訊息中會列出允許的名稱。工具集 v1 對同一次呼叫給出較短的文字:error: unknown tool: read_files。它只說明該工具未知,卻沒有說明哪些工具是已知的。
名稱位於各工具的參數之外,因此沒有任何參數結構描述(schema)能防止錯誤的名稱。檢查發生在測試框架查找名稱的時候,這正是它應當屬於測試框架,而不是只寫在提示詞裡的原因。
測試框架不會猜測,這項差異很重要。與真實工具相近的名稱,例如以 read_files 代替 read_file,仍然會被拒絕,因為測試框架依據完全相符的名稱來分派,猜測可能會執行模型並未要求的工具。提供協助的是拒絕訊息:它列出實際存在的工具,由模型重新選擇。
名稱對停止工具最為重要。當 finish 或 ask_user 呼叫執行,且其結果帶有結束旗標時,迴圈便結束該次執行。拼錯的停止工具不帶這樣的旗標,它會像其他未知名稱一樣被拒絕,執行會持續到步數上限或停止規則將它終止為止。拒絕 read_files 的同一項完全相符檢查,正是讓 finish 表示 finish 的原因。模型若一再要求工具集中沒有的工具,就是第 2 章的停止規則所要處理的那類執行。
實用原則: 允許的名稱要取自迴圈實際執行的工具,絕不取自另外維護的清單,並且要把它們放進每一則針對未知名稱的拒絕訊息中。工具集中沒有的名稱會得到拒絕,提示詞不應對此作出承諾。只有透過測試框架維護的明確別名對照表才可接受別名,絕不憑猜測。
指出最接近行數的編輯錯誤
編輯會指明它要取代的文字。工具集 v1 的 edit_file 工具會更動檔案中 old 出現的那一處,而當 old 不存在或出現超過一次時,它會拒絕這次呼叫。因此,一次編輯可能只因為幾個引號字元就失敗。模型若是依自己讀取檔案的結果來複製程式碼,就可能把這些引號寫錯,編輯便會被拒絕。
第 1 章中的最初版本,是把整個檔案放進一個 JSON 字串,所以檔案中的每個引號與換行,都必須在模型的回覆中跳脫。編輯的規模較小,它只複製要更動的那幾行,需要寫對的字元因此較少。不過跳脫的問題並未消失,因為複製的內容仍須與檔案完全一致。
任務集的記錄顯示了複製出錯的情形。該記錄收錄同一個開放模型 Qwen3-4B-Instruct-2507 在二十項任務上的回覆,使用工具集 v1、步數上限 16、溫度 0;模型的設定見第 1 章。在 T-01 的第三次回覆中,模型把幾行內容複製到 old,卻漏掉兩個 f-string 的引號,以及 separator = "." 的結尾引號。檔案中是有這些引號的。程式先印出儲存的 old 文字,再把這一次回覆分別以兩個工具集重播,差異便顯現出來:
1"""The edit_file call from step 3 of the task-set recording's T-01 run, read from its stored reply. Its old text drops2the quotes around the f-strings and the closing quote of separator = "."; the printed old text shows it. The point of3the prose rests on the two results: the v2 error names the nearest lines of the file, with their quotes, and the v14error only says the text is missing."""5import json6import shutil78from lib.case import DATA, scratch_copy9from lib.models import ScriptedModel10from lib.tools import V1, V2, Workspace1112rows = [json.loads(line) for line in (DATA / "recorded" / "task-set" / "replies.jsonl").read_text().splitlines()]13stored = next(row for row in rows if row["run"] == "T-01" and row["step"] == 3) # steps count from 114call = ScriptedModel([stored["text"]]).reply([], V2.schemas()).tool_calls[0] # the recorded reply, read back15scratch = scratch_copy()16ws = Workspace(scratch)17print("call:", call["name"], call["arguments"]["path"])18print("old text:")19print(call["arguments"]["old"])20print("v1 result:", V1.call(ws, call["name"], call["arguments"]).text)21v2 = V2.call(ws, call["name"], call["arguments"]).text22print("v2 result:")23print(v2)24assert 'text = f"{whole}{separator}{frac}"' in v225shutil.rmtree(scratch, ignore_errors=True)
python edit-error-nearest-lines.pycall: edit_file unitcraft/format.py
old text:
frac = frac.rstrip("0")
separator = ".
text = f{whole}{separator}{frac}
return f{sign}{text} {q.unit}
v1 result: error: old text not found in unitcraft/format.py
v2 result:
error: old text not found in unitcraft/format.py. The nearest lines of the file, numbered as in the file:
18 | frac = frac.rstrip("0")
19 | separator = "."
20 |
21 | text = f"{whole}{separator}{frac}"
22 |
23 | return f"{sign}{text} {q.unit}"
Copy old from those lines exactly, quotes included, and call edit_file again.
工具集 v1 的文字只說明舊文字不在檔案中,並指出檔案名稱。工具集 v2 的文字則多做了一些事。它給出檔案中最接近的幾行,行號與檔案本身的編號相同,引號也維持原樣,並在結尾說明下一步該做什麼:從這些行複製 old,連引號一併複製,然後再次呼叫。拒絕訊息附上的是一段行數視窗,而不是整個檔案。整個檔案固然能回答模型的疑問,卻要耗費大量 token,而每一筆工具結果,都會計入存放任務的同一份上下文,如第 5 章所計算的。這些行是依相似度找出的。測試框架讓一個與 old 長度相同的視窗沿著檔案逐行滑動,保留比對結果最佳的視窗,遇到同分時選較前面的視窗,因此每次執行的結果都相同。在這個範例中,最佳視窗包含模型正在複製的那一行 f-string,且引號俱在,而範例會斷言該行出現在錯誤訊息中。
如果模型重複同一個失敗的編輯,第 2 章的停止規則會讓這次執行結束,前提是這些規則已啟用。它們預設為關閉,任務集的記錄也沒有啟用。提供最接近的行數,目的是降低這類重複發生的可能。工具集 v1 的文字讓模型還得多花一步:它必須呼叫 read_file 才能看到本該複製的那幾行,而下一次回覆仍可能複製錯誤。工具集 v2 的文字則把這些行直接放進拒絕訊息,所以模型可以立刻重試。輸出內容呈現的是測試框架回傳的文字,並不表示下一次編輯是否成功。那需要實際執行才能得知,執行次數則在第 10 章中統計。本章不報告這兩種次數。
**實用原則:**當編輯的文字不在檔案中時,應回傳檔案中最接近的幾行及其行號,並說明下一步該做什麼。不要只回傳文字缺失,因為那會讓模型去猜是哪個引號有誤。若檔案短到可以整份回傳,則可改為整份回傳,並附上行號。
本章的決定
結構描述(schema)與錯誤訊息都是模型輸入的一部分。更動一個句子、一個欄位或一則錯誤訊息,就會改變請求;本書中的重播會將每個請求與已記錄的請求比對,兩者不同時便拒絕回應。因此,工具集必須連同其記錄一起更動,絕不能原地修改。
本章的承諾會延續到後續各章。模型轉接器對每個轉接器都使用這些相同的結構描述。上下文預算會把每次拒絕當作工具結果來計算,與其他結果無異。測試代理程式以計數比較兩個測試框架版本。它們的工具集就是這兩個;採用工具集 v2 的版本,還包含第 10 章所列的其他更動。
決定如下:
- 工具集中的每個參數模型都禁止未宣告的鍵,因此捏造的鍵會被拒絕,而不是被忽略。
- 工具集 v1 的參數模型沿用 pydantic 寬鬆的預設行為,因為已記錄的任務集執行就是使用這項預設。工具集 v2 的副本則是嚴格的。對本案例的工具而言,它們拒絕的 JSON 值與寬鬆副本相同,因此嚴格與否並未改變該處的任何拒絕結果。
- 本案例的工具沒有非字串的欄位。有界讀取是唯一會顯示該模式的地方,而沒有任何工具使用它。
- 拒絕訊息會指出欄位、其錯誤類型與其訊息。工具集 v1 省略錯誤類型。
- 允許的工具名稱來自迴圈所執行的工具,未知的名稱會連同這些名稱一併被拒絕。
- 在工具集 v1 中,
finish會附上摘要,變更則是透過副本中的edit_file與write_file完成。 - 若編輯所指的文字不存在,則回傳檔案中最接近的幾行,並附上行號。這是工具集 v2 的更動。
- 本章討論的錯誤訊息會由其範例印出,因此訊息的更動會先顯示在輸出中,之後才顯示在執行結果裡。工具程式碼中的其他拒絕,例如案例以外的路徑,並未在此印出。
本章,於本版次中
版次 2026.11.2範例於 2026年11 月 20 通過測試本章 5 個範例 個範例中有 5 個通過
譯自英文書,版次 2026.11.2。