追蹤每次執行並計算其成本

閱讀約需 31 分鐘 分鐘,8 節 中共有 4 個範例。

版次 2026.11.2 範例於 2026年11 月 20 通過測試 64 個範例中有 64 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.2。 閱讀原文

讀完本章後,你能讓每次執行為每個步驟寫出一筆記錄,存入日後的讀者可以解析的檔案;為每筆記錄加上 ID,將它與所屬的執行和呼叫連結起來;並說明該次執行耗用了多少 token。這裡的成本指的是計數,絕不是金額。

維護代理在 unitcraft 的暫存副本中進行執行。一次執行可能順利結束、失敗結束,或是根本沒有結束,而停止原因只說明它如何結束。以第 1 章中對 T-01 的執行為例,T-01 是任務集中的任務之一。該次執行讀取了正確的檔案並執行測試,接著連續發出一串格式錯誤的呼叫,直到達到步數上限。停止原因寫的是 step_cap,而停止原因所能說明的也僅止於此。它沒有說明這些格式錯誤的呼叫有何共通之處、框架如何處理其中每一個呼叫,也沒有說明每個步驟用了多少 token。這些答案都在各個步驟之中,因此框架必須保存這些步驟。

每個步驟的記錄就是追蹤記錄。第 10 章的評分已經讀取儲存下來的計數,而想知道某次執行為何停止的讀者,需要看到停止之前的步驟。本章將追蹤記錄寫成資料,為其 ID 訂定固定的格式,並計算其中所含的內容。這裡的每個計數,都是從錄製內容讀取,或由腳本印出。沒有任何一個取自即時模型,因此這些計數是儲存下來的計數,而能從模型重新推導這些計數的那項檢查尚未執行。

每個事件一行

追蹤記錄(trace)是一個檔案,每行存放一個 JSON 物件。這種格式有個名稱,叫 JSON Lines,定義也很簡短:每行存放一個 JSON 值,檔案採用 UTF-8,每行以換行字元(line feed)結尾。該頁面也建議最後一行之後再加一個換行字元,但並不強制要求,同時也接受回車字元加換行字元的組合。JSON Lines format 指出,不得包含位元組順序標記(byte order mark)。測試框架(harness)寫出每筆記錄時,會將鍵排序、不加空格,並且只使用 ASCII,因此相同的記錄一定會輸出為相同的位元組。這件事重要的原因,與印出的輸出內容重要的原因相同:讀者可以逐行比對兩份追蹤記錄。

重播(replay)第 1 章在 T-01 上的執行,會以這種形式寫出它的各個步驟。重播時會讀取每個步驟已記錄的回覆,因此每次執行的追蹤記錄都相同。

trace-one-run.py Python 3.12.15 · pydantic 2.14.3 通過
"""The chapter 1 recorded run of T-01 as JSON lines: one record per step, with run-scoped IDs and the recorded tokencounts. The lines are written to a file and read back, and the reader counts the empty pieces it skips."""import jsonimport tempfilefrom pathlib import Pathfrom lib.case import load_tasksfrom lib.loop import run_taskfrom lib.models import ReplayModelfrom lib.tools import CH1from lib.trace import IdCounter, StepRecorder, dumps, read_lines, step_recordstask = load_tasks(only=["T-01"])[0]model = StepRecorder(ReplayModel("chapter-1-t01", "T-01"))run = run_task(model, task, CH1, max_steps=CH1.step_cap, ids=IdCounter())records = step_records(run, model)for record in records:    print(dumps(record))print("records:", len(records))print("first call ID:", records[0]["calls"][0])print("results:", ", ".join(f"step {r['step']} {r['result']}" for r in records))print("prompt tokens, summed over the records:", sum(r["prompt_tokens"] for r in records))print("completion tokens, summed over the records:", sum(r["completion_tokens"] for r in records))try:    json.loads("")  # a blank line is not a JSON valueexcept json.JSONDecodeError as error:    print("blank line:", error)with tempfile.TemporaryDirectory() as folder:    path = Path(folder) / "trace.jsonl"    path.write_text("".join(dumps(record) + "\n" for record in records), encoding="utf-8")    read_back, skipped = read_lines(path.read_text(encoding="utf-8"))print("lines read back:", len(read_back))print("empty pieces skipped:", skipped)assert read_back == records and skipped == 1  # the one piece after the last line feedassert run.ended == "step_cap" and len(records) == CH1.step_cap and records[-1]["stop"] == "step_cap"assert sum(r["prompt_tokens"] for r in records) == run.prompt_tokensrun.close()
輸出python trace-one-run.py
{"arguments":{"path":"unitcraft/format.py"},"brief":"23 lines","calls":["run-0001-c1"],"completion_tokens":22,"gate":[],"malformed":[],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":501,"result":"ok","run":"run-0001","step":1,"stop":"","tool":"read_file"}
{"arguments":{},"brief":"8 failed, 22 passed","calls":["run-0001-c2"],"completion_tokens":70,"gate":[],"malformed":[],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":713,"result":"ok","run":"run-0001","step":2,"stop":"","tool":"run_tests"}
{"arguments":null,"brief":"error: malformed call","calls":["run-0001-c3"],"completion_tokens":560,"gate":[],"malformed":["not JSON (Expecting ',' delimiter)"],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":941,"result":"refused","run":"run-0001","step":3,"stop":"","tool":"malformed"}
{"arguments":null,"brief":"error: malformed call","calls":["run-0001-c4"],"completion_tokens":292,"gate":[],"malformed":["not JSON (Expecting ',' delimiter)"],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":1528,"result":"refused","run":"run-0001","step":4,"stop":"","tool":"malformed"}
{"arguments":null,"brief":"error: malformed call","calls":["run-0001-c5"],"completion_tokens":296,"gate":[],"malformed":["not JSON (Expecting ',' delimiter)"],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":1847,"result":"refused","run":"run-0001","step":5,"stop":"","tool":"malformed"}
{"arguments":null,"brief":"error: malformed call","calls":["run-0001-c6"],"completion_tokens":296,"gate":[],"malformed":["not JSON (Expecting ',' delimiter)"],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":2170,"result":"refused","run":"run-0001","step":6,"stop":"","tool":"malformed"}
{"arguments":null,"brief":"error: malformed call","calls":["run-0001-c7"],"completion_tokens":296,"gate":[],"malformed":["not JSON (Expecting ',' delimiter)"],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":2493,"result":"refused","run":"run-0001","step":7,"stop":"","tool":"malformed"}
{"arguments":null,"brief":"error: malformed call","calls":["run-0001-c8"],"completion_tokens":296,"gate":[],"malformed":["not JSON (Expecting ',' delimiter)"],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":2816,"result":"refused","run":"run-0001","step":8,"stop":"step_cap","tool":"malformed"}
records: 8
first call ID: run-0001-c1
results: step 1 ok, step 2 ok, step 3 refused, step 4 refused, step 5 refused, step 6 refused, step 7 refused, step 8 refused
prompt tokens, summed over the records: 13009
completion tokens, summed over the records: 2128
blank line: Expecting value: line 1 column 1 (char 0)
lines read back: 8
empty pieces skipped: 1

這次執行有 8 筆記錄,每個步驟一筆,最後一筆記錄帶有停止原因 step_cap。每筆記錄包含步驟編號、工具、引數、對回傳內容的一行摘要、結果類別、呼叫 ID、當時提供的工具、關卡(gate)針對該步驟產生的行,以及該步驟的 token 數。第一次呼叫的 ID 是 run-0001-c1。

後面的步驟是格式錯誤的呼叫。模型的回覆不是有效的 JSON,所以測試框架沒有執行該呼叫。它將該步驟記錄為 refused,並把剖析錯誤放進 malformed 欄位。refused 涵蓋測試框架未執行的每一種呼叫,以及工具在執行前就拒絕的呼叫:無法剖析或被截斷的回覆、測試框架並未提供的工具名稱、與工具不符的引數、被關卡擋下的變更,以及工具自身檢查所拒絕的路徑。第三個類別 error 則不同,它表示工具已經執行並回報失敗。若把 refused 當成工具錯誤,會讓讀者去一個從未被呼叫的工具裡尋找錯誤。

將各筆記錄加總,重播的這次執行使用了 13009 個提示 token 與 2128 個完成 token。這些是錄製時為每個步驟儲存的計數,而不是重播期間取得的計數。

這個檔案有一個陷阱,範例在最後展示了它。JSON Lines 不允許空白行,因為空白行不是一個值。剖析空行會失敗,Python 會將它回報為 Expecting value: line 1 column 1 (char 0)。這些記錄會寫入檔案,再透過讀取器讀回。以換行字元分割文字時,最後一個換行字元之後會留下一個空片段,因此讀取器會刻意跳過該片段並加以計數。這裡讀回了 8 筆記錄,跳過了 1 個片段。若讀取器不跳過它,就會在每個檔案的結尾停下來。

實用原則: 追蹤記錄的讀取器只在有意為之時才跳過空行,並且會計算跳過的行數。否則它會在第一個空行處停止。寫入端絕不在記錄之間加入空白行。

不依賴時鐘的 ID

追蹤中的每個步驟都必須能被再次找到:依它所屬的執行、它所回應的呼叫,以及它在順序中的位置。追蹤的 ID 只取自呼叫端傳入的計數器,不取自其他任何來源。一次執行的 ID 是 run-0001,從一開始編號。工具呼叫的 ID 是其所屬執行的 ID 加上 c 與一個數字,因此該次執行的第一個呼叫是 run-0001-c1,這與重播該次執行時第一筆記錄所帶的 ID 相同。步驟依發生的順序,從 1 開始編號。

沒有任何記錄帶有時間。時間戳記在每次執行都會不同,任何顯示它的範例,其輸出也會不同。每個範例都會與它在錄製時印出的輸出相比對,因此時間戳記會使每次執行的比對都失敗。追蹤中只保存計數、簡短的結果與 ID,不含任何來自時鐘的內容。

ID 之所以重要,還有第二個原因。執行 ID 與呼叫 ID 會放進 harness 送給模型的 requests 之中,所以只有當重播對執行的編號方式與錄製時相同,重播送出的請求才會與錄製的相同。任務的重播程式碼會從該任務在錄製中所在的位置接續它的計數器,這就是子範例依錄製的順序,而不是從自己的起點為它的執行編號的原因。

實用原則: 執行與呼叫的編號一律取自傳入的計數器,絕不取自時鐘或隨機產生器。在不同執行之間會改變的 ID 會改變請求,而該次執行的重播會在第一個無法與錄製相比對的請求處停止。

以計數表示的 token

追蹤紀錄中的每一筆記錄都帶有兩個 token 計數,以第 1 章所定義的、固定版本模型的 token 為單位。提示計數是模型讀入的 token 數,完成計數則是模型寫出的 token 數。錄製在執行時取得這兩個計數。它把每個步驟的計數連同該步驟的回覆一併存入 replies.jsonl,並把每項任務的總數存入其資訊清單(manifest)。重播只讀取已儲存的計數,不會再次進行 token 化,因此重播不可能產生錄製時未寫下的計數。

依任務以及就整個任務集加總已儲存的步驟計數,是下一個範例的工作。它會將每項任務的加總與資訊清單為該任務所存的總數相互核對,也會將整個任務集的提示加總與這些任務總數之和相互核對。

token-counts-from-recording.py Python 3.12.15 通過
"""The token counts of the task-set recording, summed per task and for the set, read from the stored counts. Replaynever tokenizes, so these are the counts the recording wrote; the live check against a tokenizer is not run."""from lib.models import load_recordingfrom lib.trace import OTEL_TOKEN_FIELDSmanifest, rows = load_recording("task-set")  # rows: one per step, from replies.jsonl; the manifest has task totalssums: dict[str, list[int]] = {}for row in rows:    total = sums.setdefault(row["run"], [0, 0, 0])    total[0] += row["prompt_tokens"]    total[1] += row["completion_tokens"]    total[2] += 1  # each row is one step, so the third sum counts stepsfor task in sorted(manifest["tasks"], key=lambda t: t["task"]):    prompt, completion, steps = sums[task["task"]]    print(f"{task['task']} prompt tokens: {prompt} completion tokens: {completion} steps: {steps}")    assert (prompt, completion, steps) == (task["prompt_tokens"], task["completion_tokens"], task["steps"])set_prompt = sum(total[0] for total in sums.values())set_completion = sum(total[1] for total in sums.values())print("set tasks:", len(sums))print("set prompt tokens:", set_prompt)print("set completion tokens:", set_completion)print("live count check: not run")for field, name in sorted(OTEL_TOKEN_FIELDS.items()):  # the mapping table; the book's own names stay in the trace    print(f"field {field} would map to {name} (data only; OpenTelemetry is not used)")assert set_prompt == sum(t["prompt_tokens"] for t in manifest["tasks"])
輸出python token-counts-from-recording.py
T-01 prompt tokens: 44836 completion tokens: 2025 steps: 16
T-02 prompt tokens: 43904 completion tokens: 2059 steps: 16
T-03 prompt tokens: 27562 completion tokens: 1463 steps: 12
T-04 prompt tokens: 8809 completion tokens: 1054 steps: 5
T-05 prompt tokens: 8494 completion tokens: 906 steps: 5
T-06 prompt tokens: 55109 completion tokens: 4670 steps: 16
T-07 prompt tokens: 24989 completion tokens: 3468 steps: 9
T-08 prompt tokens: 13713 completion tokens: 1154 steps: 7
T-09 prompt tokens: 10324 completion tokens: 701 steps: 6
T-10 prompt tokens: 51056 completion tokens: 3549 steps: 16
T-11 prompt tokens: 33951 completion tokens: 817 steps: 16
T-12 prompt tokens: 30787 completion tokens: 1617 steps: 12
T-13 prompt tokens: 49249 completion tokens: 942 steps: 16
T-14 prompt tokens: 12651 completion tokens: 972 steps: 7
T-15 prompt tokens: 20409 completion tokens: 1254 steps: 10
T-16 prompt tokens: 57696 completion tokens: 4621 steps: 16
T-17 prompt tokens: 17601 completion tokens: 1511 steps: 9
T-18 prompt tokens: 5122 completion tokens: 304 steps: 4
T-19 prompt tokens: 22713 completion tokens: 2154 steps: 9
T-20 prompt tokens: 33630 completion tokens: 2065 steps: 13
set tasks: 20
set prompt tokens: 572605
set completion tokens: 37306
live count check: not run
field completion_tokens would map to gen_ai.usage.output_tokens (data only; OpenTelemetry is not used)
field prompt_tokens would map to gen_ai.usage.input_tokens (data only; OpenTelemetry is not used)

每項任務的加總都與其資訊清單一致,因此下列任務集的總數就是錄製本身的計數。該任務集共有 20 項任務,合計使用了 572605 個提示 token 與 37306 個完成 token。輸出中的即時計數檢查會以固定版本的模型對已錄製的提示進行 token 化,其回報為 not run。

函式庫的原始碼顯示了這類計數是如何產生的。llama-cpp-python 的原始碼是依錄製所固定的版本閱讀的,並未在此執行。它的非串流補全會回報提示 token 串列的長度與補全 token 串列的長度,並以兩者之和作為總數(llama.py at v0.3.36)。它的 tokenize 方法接收 UTF-8 位元組,並回傳整數 token ID 的串列。除非指定不要,否則它會加上序列起始 token,因此提示的計數除了取決於模型的詞彙表,也取決於這項設定。

不同 tokenizer 所得的計數不能相互比較。這是經驗法則,而非實測結果:token 是某一個詞彙表的單位,同一段文字在另一個詞彙表下可能切分成不同數量的單位。讀者若要比較兩個計數,必須先確認模型檔案與設定都相符。

錄製的資訊清單儲存了模型檔案及其 SHA-256,但沒有儲存會影響提示計數的設定:函式庫所套用的對話模板,以及序列起始 token 的設定。錄製對這兩者都使用函式庫的預設值,而本書目前尚未將它們寫下。

實用原則: 儲存每個計數時,應一併記下它所來自的模型檔案,以及任何會改變它的設定,例如序列起始 token。不要比較來自不同 tokenizer 的計數。尚未經任何檢查重新推導的計數,應報告為已儲存的計數,而不是即時計數。

子代的紀錄位於其父代的呼叫之下

第 8 章把子任務交給子迴圈,並取回一份摘要與一個停止原因。該章也把子代自己的紀錄保留在子代那裡,因此父代的摘要不會是發生過程的唯一軌跡。本節在追蹤紀錄中實現這項承諾。子代的各個步驟會寫成它們自己的一次執行,並有各自的執行 ID 與呼叫 ID。子代的每一筆紀錄都帶有 parent,也就是啟動該子代的那次呼叫的 ID。子代的紀錄會緊接在啟動它們的父代呼叫之後印出。

在這個範例中,父代針對 T-04 啟動一個子代,T-04 是要求提供英寸單位的任務。子代所記錄的執行以一個會變更檔案的結束動作作結。一位照腳本行事的人對這項變更說不,於是閘門攔下該結束動作,子代則以一個問題交還控制權。

child-trace-under-parent.py Python 3.12.15 · pydantic 2.14.3 通過
"""A parent starts a child on T-04, whose recorded run ends with a finish that changes files. The gate holds that finishbecause the person says no, so the child hands back with ask_user. The child's records sit under the parent's start call;the parent is scripted, so its records carry zero tokens."""from lib.case import load_tasksfrom lib.chapter1 import callfrom lib.models import ReplayModel, load_recordingfrom lib.permissions import Gate, library_copy, replay_ids, scriptedfrom lib.subagents import START_CHILDfrom lib.tasks import snapshotfrom lib.tools import V1from lib.trace import StepRecorder, child_under_parent, dumpstask = load_tasks(only=["T-04"])[0]manifest, _ = load_recording("task-set")stored = next(t for t in manifest["tasks"] if t["task"] == "T-04")with library_copy() as library:    before = snapshot(library, "unitcraft")    gate = Gate(library, scripted((False, "not this change")))  # the scripted person says no, with this reason    child_model = StepRecorder(ReplayModel("task-set", "T-04"), gate)    replies = [call(START_CHILD, task_id="T-04"), call("ask_user", question="The child's change was held. Pass it on?")]    parent, child, records = child_under_parent(task, replies, child_model, gate, library, replay_ids("T-04"))    for record in records:        print(dumps(record))    print("child budget:", V1.step_cap)    print("child ended:", child.handoff.ended)    print("gate refusals:", gate.counts["refused"])    print("parent ended:", parent.ended)    print("copy unchanged by the held finish:", before == snapshot(library, "unitcraft"))    child_records = [r for r in records if r["run"] == child.run.id]    parent_records = [r for r in records if r["run"] != child.run.id]    print("child run:", child.run.id)    print("parent call of the child:", child_records[0]["parent"])    print("held step:", next(r["step"] for r in child_records if r["result"] == "refused"))    print("parent tokens, summed:", sum(r["prompt_tokens"] + r["completion_tokens"] for r in parent_records))    child_prompt = sum(r["prompt_tokens"] for r in child_records)    child_completion = sum(r["completion_tokens"] for r in child_records)    print("child prompt tokens, summed:", child_prompt)    print("child completion tokens, summed:", child_completion)    assert child.handoff.ended == "ask_user" and sum(r["result"] == "refused" for r in records) == 1    assert parent.ended == "ask_user" and before == snapshot(library, "unitcraft")    assert (child_prompt, child_completion) == (stored["prompt_tokens"], stored["completion_tokens"])    parent.close()
輸出python child-trace-under-parent.py
{"arguments":{"task_id":"T-04"},"brief":"child ask_user at step 5","calls":["run-0001-c1"],"completion_tokens":0,"gate":[],"malformed":[],"offered":["ask_user","start_child"],"parent":null,"prompt_tokens":0,"result":"ok","run":"run-0001","step":1,"stop":"","tool":"start_child"}
{"arguments":{},"brief":"25 files","calls":["run-0004-c1"],"completion_tokens":51,"gate":[],"malformed":[],"offered":["ask_user","edit_file","finish","list_files","read_file","run_tests","write_file"],"parent":"run-0001-c1","prompt_tokens":1049,"result":"ok","run":"run-0004","step":1,"stop":"","tool":"list_files"}
{"arguments":{"path":"unitcraft/units.py"},"brief":"36 lines","calls":["run-0004-c2"],"completion_tokens":108,"gate":[],"malformed":[],"offered":["ask_user","edit_file","finish","list_files","read_file","run_tests","write_file"],"parent":"run-0001-c1","prompt_tokens":1253,"result":"ok","run":"run-0004","step":2,"stop":"","tool":"read_file"}
{"arguments":{"new":"Unit(\"m\", \"length\", Decimal(1)),\n        Unit(\"km\", \"length\", Decimal(1000)),\n        Unit(\"cm\", \"length\", Decimal(\"0.01\")),\n        Unit(\"mm\", \"length\", Decimal(\"0.001\")),\n        Unit(\"ft\", \"length\", Decimal(\"0.3048\")),\n        Unit(\"in\", \"length\", Decimal(\"0.0254\")),\n        Unit(\"kg\", \"mass\", Decimal(1)),\n        Unit(\"g\", \"mass\", Decimal(\"0.001\")),\n        Unit(\"lb\", \"mass\", Decimal(\"0.45359237\")),\n        Unit(\"s\", \"time\", Decimal(1)),\n        Unit(\"min\", \"time\", Decimal(60)),\n        Unit(\"h\", \"time\", Decimal(3600)),\n        Unit(\"C\", \"temperature\", None),\n        Unit(\"F\", \"temperature\", None),\n        Unit(\"K\", \"temperature\", None),","old":"Unit(\"m\", \"length\", Decimal(1)),\n        Unit(\"km\", \"length\", Decimal(1000)),\n        Unit(\"cm\", \"length\", Decimal(\"0.01\")),\n        Unit(\"mm\", \"length\", Decimal(\"0.001\")),\n        Unit(\"ft\", \"length\", Decimal(\"0.3048\")),\n        Unit(\"kg\", \"mass\", Decimal(1)),\n        Unit(\"g\", \"mass\", Decimal(\"0.001\")),\n        Unit(\"lb\", \"mass\", Decimal(\"0.45359237\")),\n        Unit(\"s\", \"time\", Decimal(1)),\n        Unit(\"min\", \"time\", Decimal(60)),\n        Unit(\"h\", \"time\", Decimal(3600)),\n        Unit(\"C\", \"temperature\", None),\n        Unit(\"F\", \"temperature\", None),\n        Unit(\"K\", \"temperature\", None),","path":"unitcraft/units.py"},"brief":"edited unitcraft/units.py","calls":["run-0004-c3"],"completion_tokens":570,"gate":[],"malformed":[],"offered":["ask_user","edit_file","finish","list_files","read_file","run_tests","write_file"],"parent":"run-0001-c1","prompt_tokens":1686,"result":"ok","run":"run-0004","step":3,"stop":"","tool":"edit_file"}
{"arguments":{},"brief":"8 failed, 22 passed","calls":["run-0004-c4"],"completion_tokens":111,"gate":[],"malformed":[],"offered":["ask_user","edit_file","finish","list_files","read_file","run_tests","write_file"],"parent":"run-0001-c1","prompt_tokens":2276,"result":"ok","run":"run-0004","step":4,"stop":"","tool":"run_tests"}
{"arguments":{"summary":"Added the inch unit ('in') with a factor of 0.0254 to the units dictionary in unitcraft/units.py. This allows parse_quantity('2 in') to work correctly and enables the convert function to handle inch-to-meter conversions. The test suite failures indicate other issues in the codebase that are outside the scope of this specific task."},"brief":"p-1 was not applied: the person said no: not this change","calls":["run-0004-c5"],"completion_tokens":214,"gate":["p-1 1 files, diff 06ee73fd984f: asked","p-1 answer no, bound to p-1 and 06ee73fd984f","p-1 not applied: the person said no: not this change"],"malformed":[],"offered":["ask_user","edit_file","finish","list_files","read_file","run_tests","write_file"],"parent":"run-0001-c1","prompt_tokens":2545,"result":"refused","run":"run-0004","step":5,"stop":"ask_user","tool":"finish"}
{"arguments":{"question":"The child's change was held. Pass it on?"},"brief":"ask_user","calls":["run-0001-c2"],"completion_tokens":0,"gate":[],"malformed":[],"offered":["ask_user","start_child"],"parent":null,"prompt_tokens":0,"result":"ok","run":"run-0001","step":2,"stop":"ask_user","tool":"ask_user"}
child budget: 16
child ended: ask_user
gate refusals: 1
parent ended: ask_user
copy unchanged by the held finish: True
child run: run-0004
parent call of the child: run-0001-c1
held step: 5
parent tokens, summed: 0
child prompt tokens, summed: 8809
child completion tokens, summed: 1054

子代的執行採用錄製內容賦予 T-04 的編號,也就是其中的第四次執行,因此它的請求與錄製的請求相符。這次執行是 run-0004,其第一筆紀錄在 parent 中指出父代的呼叫:run-0001-c1。

子代的紀錄帶有錄製內容為 T-04 儲存的計數,即 8809 個提示詞 token 與 1054 個完成 token,腳本會依清單對這些數字進行斷言。父代是照腳本行事的,所以它的紀錄不帶任何 token:0。

那個人的拒絕就是子代執行結束之處。閘門在步驟 5 攔下該結束動作,這是子代的最後一筆紀錄,而子代改為交還一個問題。

子代以 ask_user 停止,閘門拒絕了 1 次呼叫。這次停止來自閘門,而不是來自 16 個步驟的預算。同樣照腳本行事的父代,向那個人提出它自己的問題,並以 ask_user 停止。執行之後,程式庫副本並未改變,這正是閘門的全部意義:被攔下的變更從未到達該庫。

這個範例沒有展示用盡預算的子代。第 8 章討論了那種情況,其停止原因來自預算,而不是來自被攔下的變更。

實用原則: 為每個子代指定它自己的執行 ID 與自己的紀錄,且每筆紀錄的 parent 都設為啟動它的那次呼叫。回報父代執行的成本時,請加總其子代的計數,並說明你這樣做了。這份追蹤紀錄把它們分開印出,沒有把任何一項加總到父代之中。

以計數而非金額衡量成本

有了依任務加總的已儲存計數,一次執行的成本就是三個數字:步數、工具呼叫次數與 token 數。本書只報告這三項,不報告其他項目。價格表會過時,以美元表示的數字在第一次調價之後就不再正確,因此本書不會把計數乘上價格。需要金額的讀者,可以自行把計數乘上其供應商目前收取的價格,而書中的數字不會因價格變動而失準。

依每次執行的結束方式將已儲存的計數分組,就能把達到步數上限的執行與其他執行並列,使各種停止原因的成本顯示在同一份輸出中。

cost-as-counts.py Python 3.12.15 通過
"""The cost of the task-set runs as counts only: steps, tool calls and tokens, summed per way a run ended. The cost istokens, never money, and the tokens are the recording's stored counts; the groups are sorted, so the output is stable."""from lib.models import load_recordingmanifest, rows = load_recording("task-set")tasks = sorted(manifest["tasks"], key=lambda t: (t["task"], t["kind"]))for ending in sorted({t["ended"] for t in tasks}):    group = [t for t in tasks if t["ended"] == ending]    print(f"ended {ending}: runs {len(group)}, done {sum(t['done'] for t in group)}, "          f"steps {sum(t['steps'] for t in group)}, tool calls {sum(t['tool_calls'] for t in group)}, "          f"prompt tokens {sum(t['prompt_tokens'] for t in group)}, "          f"completion tokens {sum(t['completion_tokens'] for t in group)}")    print("  tasks:", ", ".join(t["task"] for t in group))    print("  done:", ", ".join(t["task"] for t in group if t["done"]) or "none")print(f"all: runs {len(tasks)}, done {sum(t['done'] for t in tasks)}, steps {sum(t['steps'] for t in tasks)}, "      f"tool calls {sum(t['tool_calls'] for t in tasks)}, prompt tokens {sum(t['prompt_tokens'] for t in tasks)}, "      f"completion tokens {sum(t['completion_tokens'] for t in tasks)}")capped = [t for t in tasks if t["ended"] == "step_cap"]print(f"step-capped runs done: {sum(t['done'] for t in capped)} of {len(capped)}")print(f"step-capped runs, steps: {sum(t['steps'] for t in capped)} of {sum(t['steps'] for t in tasks)}")print(f"step-capped runs, prompt tokens: {sum(t['prompt_tokens'] for t in capped)} of "      f"{sum(t['prompt_tokens'] for t in tasks)}")prompts: dict[str, list[int]] = {}for row in sorted(rows, key=lambda r: (r["run"], r["step"])):  # the stored step rows, in step order    prompts.setdefault(row["run"], []).append(row["prompt_tokens"])rising = [t["task"] for t in capped if all(b > a for a, b in zip(prompts[t["task"]], prompts[t["task"]][1:]))]print(f"step-capped runs whose prompt count rises at every step: {len(rising)} of {len(capped)}")assert all(t["tool_calls"] == t["steps"] for t in tasks), "one tool call per step in this recording"
輸出python cost-as-counts.py
ended ask_user: runs 7, done 1, steps 69, tool calls 69, prompt tokens 157824, completion tokens 10368
  tasks: T-03, T-12, T-15, T-17, T-18, T-19, T-20
  done: T-18
ended finish: runs 6, done 4, steps 39, tool calls 39, prompt tokens 78980, completion tokens 8255
  tasks: T-04, T-05, T-07, T-08, T-09, T-14
  done: T-04, T-05, T-09, T-14
ended step_cap: runs 7, done 0, steps 112, tool calls 112, prompt tokens 335801, completion tokens 18683
  tasks: T-01, T-02, T-06, T-10, T-11, T-13, T-16
  done: none
all: runs 20, done 5, steps 220, tool calls 220, prompt tokens 572605, completion tokens 37306
step-capped runs done: 0 of 7
step-capped runs, steps: 112 of 220
step-capped runs, prompt tokens: 335801 of 572605
step-capped runs whose prompt count rises at every step: 7 of 7

達到步數上限的執行共花了 112 of 220 步與 335801 of 572605 個提示 token。達到步數上限的那一行顯示為 runs 7, done 0, steps 112, tool calls 112, prompt tokens 335801, completion tokens 18683。所有執行的那一行顯示為 runs 20, done 5, steps 220, tool calls 220, prompt tokens 572605, completion tokens 37306,它涵蓋上方的每一個分組。另有一項斷言檢查記錄是否正確:每次執行在每一步都只呼叫一次工具,因此工具呼叫次數與步數是同一個數字。

達到步數上限的執行沒有任何一次算完成:計數顯示為 0 of 7。達到步數上限的執行既沒有 finish,也沒有交接,所以不論其檔案內容為何,零這個結果都依完成規則而來。ask_user 群組中唯一完成的一次是 T-18,其計數是透過路徑比對得出(第 10 章)。這個零並未說明任何達到步數上限的執行距離完成有多近,本章也不把它當作關於這些任務的發現。

判斷,而非量測:達到步數上限的那一行,是花光 token 卻未完成的執行所付出的成本。若對執行的總 token 數設定 token 預算,而不是第 5 章中每次請求的提示預算,這些執行本可更早停止。其代價是可能中止原本會在後續某一步完成的執行,而這份記錄無法顯示這種可能性,因為每次達到步數上限的執行都停在上限處,沒有寫下之後的步驟。使成本增加的是提示計數:迴圈在每一步都會重新送出整份對話記錄。統計提示計數在每一步都上升的達到步數上限的執行,結果為 7 of 7。步數預算只計算步數,因此對於長時間的執行,它對成本的說明不如 token 數。若設定了 token 預算,測試框架應以自己的停止原因與自己的計數結束該次執行,以便區分因預算而中止與因步數上限而中止。

第 12 章以這些相同的單位比較代理與固定管線,而這些單位唯有在每次執行都以相同方式回報時才有用。

實用原則: 以每次執行的步數、工具呼叫次數與 token 數來回報成本,依結束方式分組,並將各組並列印出。不要引用金額。將達到步數上限的群組視為花費 token 卻未完成,在第二項衡量另有說明之前,不要把它當作關於任務的證據。

保留自己的欄位名稱,並在邊界處對應

本書紀錄中的 token 欄位是 prompt_tokens 與 completion_tokens,這兩個名稱是本書自行訂定的。OpenTelemetry 專案發布了生成式 AI 系統遙測資料的慣例。在語意慣例 v1.37.0 版中,其 GenAI spans 頁面將同樣這兩項計數命名為 gen_ai.usage.input_tokens 與 gen_ai.usage.output_tokens(the semantic conventions, GenAI spans)。在該版本中,此頁面將其狀態標示為「Development」,因此這些名稱可能會變動。本書並不使用 OpenTelemetry。token 計數範例僅以資料形式,將這兩個名稱與本書的欄位並列印出,本章也不主張 OpenTelemetry 工具會如何讀取追蹤紀錄。

本書保留自己的名稱,是出於實務上的考量。若讀者要把追蹤紀錄匯出到其他工具,只需要一張對應表,而這張表是唯一依賴該標準的地方。標準改變時,本書的欄位名稱不會跟著改變。對應並不會改動計數本身。提示計數與完成計數在兩組名稱下是相同的數字,追蹤紀錄中的各筆紀錄也維持原本寫入時的樣子。

實用原則: 在自己的專案中,依欄位所計數的內容為追蹤紀錄的欄位命名。在邊界處以一張表將它們對應到標準的名稱,並在表旁寫明所依據的標準版本。標準的版本更動時,請重新檢查這張表。

哪裡會出錯,以及如何察覺

第一個錯誤出在 result 欄位。refused 的呼叫從未執行,讀者若把 refused 當成工具的錯誤,就會找錯地方。你可以從記錄中察覺:result 是 refused,malformed 給出解析錯誤,工具欄位顯示的是 malformed,而不是工具的名稱,閘門的各行也都是空的。這類步驟的指示以 error: 開頭,讀起來像是工具失敗,所以請閱讀 result 與 malformed,而不要看指示。

第二個錯誤是為了除錯而加入的時間戳記。它會讓印出的輸出在每次執行時都不同,因此範例與其記錄的輸出之間的比對,在修改後第一次執行就會失敗。修正方式是移除時間戳記,改用步驟編號。步驟編號在每次執行時都相同,足以讓各行排出順序。

第三個錯誤是 第一節 中的空白行。讀取器若把空行交給 JSON 解析器,就會在該處失敗,而檔案本身並沒有問題,失敗卻看起來像檔案損毀。你會在解析因空字串而失敗時察覺。修正方式是訂定一條規則,刻意略過空的片段並計算略過的次數,如同範例所做的。

第四個錯誤是把追蹤當成控制機制。追蹤記錄的是閘門與沙箱所做的決定。它本身不做任何決定,也無法復原已經執行的呼叫。子範例 中被擋下的結束動作,是由閘門擋下的,第 6 章 對此有所說明。指令的限制則來自 第 7 章 的沙箱。在一次不良的執行之後閱讀追蹤,只能告訴你框架允許了什麼,除此之外別無其他。

第五點是本章的一項限制。本章只追蹤內建工具。這裡沒有追蹤任何 MCP 伺服器,因此本章不對 MCP 呼叫在追蹤中如何呈現做任何說明。第 9 章 則涵蓋工具本身。

實用原則: 在依據追蹤做出決定之前,先閱讀它的 result 與 stop 欄位,再將其印出的總和與儲存的總計相互核對。追蹤若與其總計不符,代表寫入它的程式有錯誤,而它所記錄的那次執行,還不能算是關於代理程式的發現。

本章的決定

  • 每次執行為每個步驟依步驟順序寫入一行 JSON,鍵依排序,不含空格,且僅使用 ASCII。不寫入空白行。
  • ID 來自呼叫端傳入的計數器:執行以 run-0001 表示,呼叫以 run-0001-c1 表示。追蹤紀錄中不會出現時鐘或隨機值。
  • 詞元數量採用錄製檔所儲存的數值。即時的數量檢查並未執行,本章在相關之處會加以說明。
  • 子執行的紀錄帶有自己的執行 ID 和 parent 欄位。只有在報告明確說明時,父執行的成本才包含其子執行的數量。
  • 成本以步驟、工具呼叫和詞元計算,並依各次執行的結束方式分組。本書不列出金額。
  • 本書的欄位名稱是自行定義的。OpenTelemetry 的名稱只作為資料印出,並未使用。

追蹤紀錄每個步驟花費一行,換得的是停止原因無法回答的問題的答案:哪一個步驟出了錯、框架拒絕了什麼,以及每個步驟用了多少詞元。停止原因、分數和成本,可檢驗的程度只取決於用來計數的那些行。請保留這些行,保留其 ID,並保留錄製檔所寫入的數量。

實用原則: 對於你所報告的每一次執行,每個步驟都保留一行,並附上其 ID 與所儲存的詞元數量。無法追溯到這些行的數字,不予報告。

本章,於本版次中

版次 2026.11.2範例於 2026年11 月 20 通過測試本章 4 個範例 個範例中有 4 個通過

譯自英文書,版次 2026.11.2。

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 11 章,共 12 章: 追蹤每次執行並計算其成本

  1. 每個事件一行
  2. 不依賴時鐘的 ID
  3. 以計數表示的 token
  4. 子代的紀錄位於其父代的呼叫之下
  5. 以計數而非金額衡量成本
  6. 保留自己的欄位名稱,並在邊界處對應
  7. 哪裡會出錯,以及如何察覺
  8. 本章的決定

返回頂端所有章節