讓上下文在任務變長時仍然有用

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

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

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

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

讀完本章,你將能算出一次執行的提示詞還有多少空間,在測試框架無法精確計數時估算提示詞的大小,並在壓縮一次執行的較早步驟時,不把工具呼叫與其結果拆開。

模型在每一步都會讀取完整的提示詞:系統提示詞、工具結構描述、議題,以及這次執行到目前為止做過的所有事。這份提示詞必須放得進模型載入時所設定的視窗,而回覆也必須放進同一個視窗。一次不斷讀取檔案的執行,最終會用盡空間。

這個問題在案例中最長的幾次執行裡最為明顯。unitcraft 是第 1 章介紹的函式庫,它的維護代理會讀取檔案、執行測試並嘗試修改,而每次讀取都會把整個檔案加進提示詞。在記錄下來的任務集中,T-16 達到了第 2 章所述的步數上限 16,而它的最後一份提示詞是整個任務集所有步驟中最大的。依照記錄的計數,最後一份提示詞還剩下 612 個 token 的餘裕,所以記錄下來的各次執行在這裡最接近視窗的上限。本章其餘部分說明當提示詞放不下時,測試框架必須怎麼做。

模型擁有的視窗

所記錄的模型是 Qwen3-4B-Instruct-2507,由第 1 章介紹的 GGUF 檔案執行。測試框架(harness)載入它時使用 8192 個 token 的上下文,而錄製資料的 manifest 以 n_ctx 儲存同一個值。這是測試框架所選的載入設定。模型本身能支援的長度大得多:其模型卡(model card)載明原生上下文長度為 262,144 個 token(模型卡),此為模型卡主分支上的內容。本書讓模型在較小的視窗中執行,因此預算所需的數字,是該次執行所載入的數字。

manifest 也儲存了 max_tokens,即回覆最多可用的 token 數:1024 個 token。回覆與提示詞佔用同一個視窗,所以提示詞能用的,就是回覆留下的部分。

算式很短。8192 個 token,減去回覆預留的 1024 個,剩下 7168 個 token,供模型在一個步驟中讀取的所有內容使用。提示詞包含系統提示詞、工具結構描述(schema)、issue、筆記、先前的步驟,以及最後一次的工具結果,這些全都計入該預算。拒絕訊息和其他工具結果一樣:測試框架會把它的文字以工具訊息的形式回傳給模型,因此它也計入預算。本章稱之為提示詞預算。

budget-counts-tokens.py Python 3.12.15 · pydantic 2.14.3 通過
"""The context the harness loads the model with, the room the reply keeps, and each run's largest prompt against them.The point rests on the line of steps over the prompt budget: no recorded step reached it."""import jsonfrom lib.context import PROMPT_BUDGET, REPLY, WINDOWfrom lib.models import RECORDEDfolder = RECORDED / "task-set"manifest = json.loads((folder / "manifest.json").read_text(encoding="utf-8"))steps = [json.loads(line) for line in (folder / "replies.jsonl").read_text(encoding="utf-8").splitlines()]assert manifest["n_ctx"] == WINDOW and manifest["max_tokens"] == REPLY, "the budget comes from the recorded load settings"print("load setting, n_ctx, in tokens:", WINDOW)  # the harness's own load setting, not the model's native lengthprint("reply reservation, max_tokens, in tokens:", REPLY)print("prompt budget, in tokens:", PROMPT_BUDGET)print("steps recorded:", len(steps))# ties go to the later run and step, so the same step is named on every runlargest = max(steps, key=lambda s: (s["prompt_tokens"], s["run"], s["step"]))print("largest prompt, in tokens:", largest["prompt_tokens"])print("largest prompt, run:", largest["run"])print("largest prompt, step:", largest["step"])print("room left for the reply at the largest step:", WINDOW - largest["prompt_tokens"] - REPLY)print("steps over the prompt budget:", sum(s["prompt_tokens"] > PROMPT_BUDGET for s in steps))for task in sorted(manifest["tasks"], key=lambda t: t["task"]):    mine = [s["prompt_tokens"] for s in steps if s["run"] == task["task"]]    print(f"{task['task']}: steps {len(mine)}, largest prompt {max(mine)}")    assert len(mine) == task["steps"], "the stored step count must match the replies"
輸出python budget-counts-tokens.py
load setting, n_ctx, in tokens: 8192
reply reservation, max_tokens, in tokens: 1024
prompt budget, in tokens: 7168
steps recorded: 220
largest prompt, in tokens: 6556
largest prompt, run: T-16
largest prompt, step: 16
room left for the reply at the largest step: 612
steps over the prompt budget: 0
T-01: steps 16, largest prompt 4519
T-02: steps 16, largest prompt 4419
T-03: steps 12, largest prompt 3429
T-04: steps 5, largest prompt 2545
T-05: steps 5, largest prompt 2389
T-06: steps 16, largest prompt 6143
T-07: steps 9, largest prompt 4919
T-08: steps 7, largest prompt 3123
T-09: steps 6, largest prompt 2400
T-10: steps 16, largest prompt 5493
T-11: steps 16, largest prompt 3139
T-12: steps 12, largest prompt 3997
T-13: steps 16, largest prompt 4880
T-14: steps 7, largest prompt 2763
T-15: steps 10, largest prompt 3052
T-16: steps 16, largest prompt 6556
T-17: steps 9, largest prompt 2878
T-18: steps 4, largest prompt 1559
T-19: steps 9, largest prompt 4204
T-20: steps 13, largest prompt 4183

在印出任何內容之前,程式碼會先檢查錄製資料的 manifest 所記的視窗與回覆上限是否與測試框架相同,若不同就讓這次執行失敗。接著它會印出預算,以及各次執行中最大的提示詞與該預算的對照。

託管 API 的視窗大得多。Anthropic API 文件的上下文編輯(context editing)頁面,將 100,000 個輸入 token 列為清除舊工具結果的預設觸發點(上下文編輯)。在 8192 個 token 的視窗中,100,000 個 token 的觸發點永遠不會啟動,因此本書的預算取自所記錄模型的載入設定,而不取自廠商的預設值。

實用原則: 視窗大小要取自該次執行所用的載入設定,也就是 manifest 所記錄的值,並在設定任何預算之前先減去回覆的上限。不要取自模型宣稱的長度或廠商的預設值,因為照搬較大模型的預算,會讓執行在預算發揮作用之前就把視窗塞滿。

已記錄的執行最接近預算之處

記錄檔將模型為每個步驟回報的提示詞計數,存放在 replies.jsonl 中。轉接器會將該計數以 prompt_tokens 回傳,如第 4 章對回覆的定義,因此這些都是模型自己的計數,並非測試框架所估算。

依這些計數,沒有任何已記錄的步驟達到提示詞預算。在 220 個已記錄的步驟中,有 0 個超出預算。最大的是 T-16 的最後一個步驟,在預留回覆所需的空間之後,視窗仍剩下 612 個 token。這項檢查只讀取記錄檔,不載入任何模型,因此任何人都能執行,不需要產生該記錄的硬體。對任何新的記錄執行同一項檢查,就能立即得知其提示詞是否仍符合預算,所以更換模型後,這是最先該重新執行的檢查。

這個結果所能說明的,比看起來要少。已記錄的任務集執行的是工具集 v1,迴圈與模型之間沒有任何能縮短或拒絕提示詞的機制。沒有任何壓縮,也沒有任何步驟為了符合限制而被截斷。這些計數顯示這些提示詞符合預算,卻無法顯示當提示詞不符合時,測試框架會怎麼做,而本章其餘部分談的正是這種情況。

**實用原則:**在從一次執行中解讀出任何結論之前,先將每個步驟的計數與提示詞預算比較。

當測試框架無法計算時,估算提示詞的 token 數

精確的 token 數來自模型本身的分詞器(tokenizer),而分詞器是模型檔案的一部分。本書的範例都在離線狀態下執行,不會開啟該檔案,因為它約有 2.5 GB,也未收錄於本書。因此測試框架(harness)改用估算:它計算每則訊息與工具綱要(tool schema)的字元數,除以三並無條件進位,也就是每 3 個字元算一個 token。

我們是參考任務集(task-set)的錄製資料來選定三這個數字。最初嘗試的規則是每個 token 四個字元。在 220 個任務集步驟中,以四估算的結果有 216 個低於實際計數。低於實際計數的估算是危險的方向,因為測試框架會以為還有模型實際上沒有的空間。所以我們改用三。

每個步驟的估算值,都可以與模型在同一步驟回報的計數相比較。

estimate-vs-recorded.py Python 3.12.15 · pydantic 2.14.3 通過
"""The estimate of each recorded request against the prompt count the model reported for it. The rule was chosen ontask-set; chapter-5-notes was recorded after the rule was fixed, so its lines are the held-out check. The point restson the steps below the recorded count: none, in either recording."""import jsonfrom lib.case import load_tasksfrom lib.context import CHARS_PER_TOKEN, PROMPT_BUDGET, Measured, Notes, characters, estimate, notes_toolsetfrom lib.loop import Stops, run_taskfrom lib.models import RECORDED, ReplayModelfrom lib.tools import V1from lib.trace import IdCounterdef replay(recording, tasks, tools, **limits):    """Every request the recorded runs sent: its messages, its tool schemas and the count the model reported."""    ids, requests = IdCounter(), []  # the replay rebuilds each request, so each estimate sees the messages the model saw    for task in tasks:        model = Measured(ReplayModel(recording, task.id))        run_task(model, task, tools, ids=ids, **limits).close()        requests += model.requests    return requestsdef report(name, requests):    """Prints the comparison of the estimate with the count, labelled with the recording's name, and returns the pairs."""    pairs = [(estimate(m, t), n) for m, t, n in requests]    print(f"{name} steps compared:", len(pairs))    print(f"{name} characters per token, recorded (all steps):",          f"{sum(characters(m, t) for m, t, _ in requests) / sum(n for _, n in pairs):.2f}")    print(f"{name} steps where the estimate is above the recorded count:", sum(e > n for e, n in pairs))    print(f"{name} steps where the estimate is below the recorded count:", sum(e < n for e, n in pairs))    print(f"{name} lowest estimate divided by the recorded count: {min(e / n for e, n in pairs):.2f}")    print(f"{name} highest estimate divided by the recorded count: {max(e / n for e, n in pairs):.2f}")    assert all(e >= n for e, n in pairs), f"{name}: the rule should never count fewer tokens than the model did"    return pairsmanifest = json.loads((RECORDED / "chapter-5-notes" / "manifest.json").read_text(encoding="utf-8"))assert manifest["context"]["chars_per_token"] == CHARS_PER_TOKEN, "the held-out recording used the same rule"print(f"estimate rule, characters per token: {CHARS_PER_TOKEN}")task_set = replay("task-set", load_tasks(), V1, max_steps=V1.step_cap)pairs = report("task-set", task_set)# four is the rule a reader would try first: it is the one the comparison is againstprint("task-set with 4 characters per token, steps below the recorded count:",      sum(estimate(m, t, 4) < n for m, t, n in task_set))print("task-set steps whose estimate is over the prompt budget:", sum(e > PROMPT_BUDGET for e, _ in pairs))print("of those, steps whose recorded count is within the budget:",      sum(e > PROMPT_BUDGET and n <= PROMPT_BUDGET for e, n in pairs))report("held-out", replay("chapter-5-notes", load_tasks(only=["T-01", "T-02", "T-06"]), notes_toolset(Notes()),                          max_steps=16, stops=Stops(repeat_limit=3, no_progress_limit=2)))
輸出python estimate-vs-recorded.py
estimate rule, characters per token: 3
task-set steps compared: 220
task-set characters per token, recorded (all steps): 3.67
task-set steps where the estimate is above the recorded count: 220
task-set steps where the estimate is below the recorded count: 0
task-set lowest estimate divided by the recorded count: 1.14
task-set highest estimate divided by the recorded count: 1.35
task-set with 4 characters per token, steps below the recorded count: 216
task-set steps whose estimate is over the prompt budget: 3
of those, steps whose recorded count is within the budget: 3
held-out steps compared: 18
held-out characters per token, recorded (all steps): 3.74
held-out steps where the estimate is above the recorded count: 18
held-out steps where the estimate is below the recorded count: 0
held-out lowest estimate divided by the recorded count: 1.22
held-out highest estimate divided by the recorded count: 1.29

在這 220 個步驟中,估算值全部高於錄製的計數,沒有任何一步低於計數。估算值與計數的比值介於 1.14 到 1.35 之間。錄製的計數包含聊天範本(chat template)的 token,而估算並未計入這些 token,因此平均每個 token 3.67 個字元,是這種提示詞格式的比值,並不是單看文字本身的比值。

選擇安全一側的代價也看得出來。有三個步驟的估算值超過了提示詞預算,但這三個步驟中,模型自己的計數都在預算之內。若測試框架信任估算值,就會無故對這些步驟進行壓縮。

這項規則是依據任務集的步驟選定的,因此那些步驟無法用來檢驗它。保留資料(held-out)的檢驗使用 chapter-5-notes 的錄製資料。它是在規則確定之後才製作的,其計數也未用於選擇規則。它的 18 個步驟呈現相同的模式:沒有任何一步低於計數,比值介於 1.22 到 1.29 之間,每個 token 為 3.74 個字元。它使用相同的模型與相近的文字,所以並不能證明這項規則適用於其他分詞器、其他語言,或充滿符號的程式碼。

**實用原則:**以每個 token 三個字元進行估算,並在任何新模型的最初幾次執行中,將估算值與模型回報的計數相互核對。若估算值曾經低於回報的計數,請先改用較小的每 token 字元數,再信任預算。

把最後的結果放在最後

事實放在提示(prompt)的哪個位置,與它是否存在同樣重要。在 2023 年的一篇論文中,Liu 等人發現,當相關資訊出現在長輸入的開頭或結尾時,表現往往最好;當資訊位於中段時,表現則會下降(Lost in the Middle)。那些模型比本書所記錄的模型更早問世,因此該論文描述的是較舊模型中的一種現象,並不代表 Qwen3-4B-Instruct-2507 處理長提示的方式。

本書的版面配置把議題與筆記放在靠近開頭處,把最後一次工具結果放在結尾,也就是模型在回覆之前最後讀到的位置。這是本書的設計原則。此處沒有任何來源指出最後的結果必須放在最後,本書也沒有在這個模型上測量過這種配置。該論文是做出此選擇的理由。下方的壓縮範例會依序列出最後一次呼叫時送給模型的每則訊息:系統提示、議題、摘要、最後一次呼叫及其結果。

這種配置有代價。壓縮會把較早步驟的摘要放在議題與最後一次呼叫及其結果之間,也就是提示的中段。依該論文描述的現象,模型在這個位置最不容易善用資訊。本書接受這項代價。

實用原則: 把議題與筆記放在最前面,最後一次工具結果放在最後面。把這視為一項設計選擇,只有在你自己的任務上實際執行後看到改善,才宣稱有所提升。

壓縮較舊的步驟,並保留最後一組呼叫與結果

當估計值超過提示預算時,執行框架(harness)就會進行壓縮。這裡的壓縮是在本地端完成的:由執行框架自行撰寫摘要,模型不會看到摘要的撰寫過程。較舊的步驟會合併成一則訊息,每個步驟佔一行:包含呼叫本身、截斷為 60 個字元的引數,以及同樣截斷為 60 個字元的結果第一行。系統提示與議題(issue)維持原樣。最後一個步驟,也就是它的呼叫與結果,會逐字放入,因此模型能完整看到最近的證據。

供應商也在其伺服器上提供壓縮功能。Anthropic 的壓縮指南描述了其中一種:壓縮會「以 Claude 在伺服器端撰寫的摘要,取代對話中較舊的輪次」(compaction)。其隨需使用的形式仍是測試版,需要標頭 compact-2026-09-04。本書不使用伺服器端的形式,本章也沒有任何內容依賴它的行為。我們閱讀了該頁面,但沒有執行它。

切分規則對本地端的執行框架而言才是關鍵。供應商關於保留近期輪次的指南明確寫道:「切分點要落在沒有任何工具呼叫處於未完成狀態的位置,每個工具呼叫與其結果必須在同一側」(keeping recent turns)。若切分點落在工具結果上,該結果就會失去發出請求的呼叫,因此執行框架會拒絕這樣的切分。

在 2000 個估計 token 的預算下,四次讀取加上一次結束就足以超過預算。這個預算刻意設得遠低於真正的 7168,好讓壓縮在小型任務上就會發生。本任務並不會達到真正的預算。

compact-keeps-last-result.py Python 3.12.15 · pydantic 2.14.3 通過
"""Four reads of the case, then finish, under a small budget that the reads cross. The point rests on the callscompacted line and the last two lines: the summary replaces the older steps, and a cut that would leave the lastcall's result on its own is refused."""from lib.case import load_tasksfrom lib.chapter1 import callfrom lib.context import Compacting, Context, Measured, clean_cut, estimatefrom lib.loop import run_taskfrom lib.models import ScriptedModelfrom lib.tools import V2from lib.trace import IdCounter# estimated tokens: above the fixed part and one result, below the full transcript; the chapter's budget is 7168,# which the case's files never reachBUDGET = 2000replies = [call("read_file", path=p) for p in ("unitcraft/convert.py", "unitcraft/units.py", "unitcraft/parse.py",                                                "README.md")] + [call("finish", summary="Read four files.")]ctx = Context(prompt_budget=BUDGET)model = Compacting(Measured(ScriptedModel(replies)), ctx)run = run_task(model, load_tasks(only=["T-01"])[0], V2, max_steps=V2.step_cap, ids=IdCounter())sent, tools, _ = model.inner.requests[-1]# the last request: system prompt, issue, summary, the last call, its resultprint("budget, in estimated tokens:", BUDGET)print("steps:", run.steps)print("ended:", run.ended)print("calls compacted:", ctx.compactions)print("calls still over the budget:", ctx.over_budget)print("fixed part (system prompt, tool schemas, issue), estimated tokens:", estimate(sent[:2], tools))print("messages sent on the last call:", len(sent))for number, message in enumerate(sent, start=1):    print(f"message {number}, {message['role']}:", " ".join(message["content"].split()[:4]))# the summary's first line is its heading, so the steps start at the second lineprint("summary of the older steps:", *sent[2]["content"].splitlines()[1:], sep="\n  ")# the call is wrapped in <tool_call> tags, so its JSON is the second lineprint("kept call:", sent[3]["content"].strip().splitlines()[1][:60])print("kept result, in lines:", len(sent[4]["content"].splitlines()))print("cut before the last result alone, clean:", clean_cut(sent, len(sent) - 1))print("cut before the last call, clean:", clean_cut(sent, len(sent) - 2))assert ctx.compactions > 0 and not clean_cut(sent, len(sent) - 1) and clean_cut(sent, len(sent) - 2)
輸出python compact-keeps-last-result.py
budget, in estimated tokens: 2000
steps: 5
ended: finish
calls compacted: 3
calls still over the budget: 0
fixed part (system prompt, tool schemas, issue), estimated tokens: 1289
messages sent on the last call: 5
message 1, system: You are a maintenance
message 2, user: `format_quantity` drops the trailing
message 3, user: Earlier steps, summarised by
message 4, assistant: <tool_call> {"name": "read_file", "arguments":
message 5, tool: # unitcraft unitcraft parses,
summary of the older steps:
  step 1: read_file({"path": "unitcraft/convert.py"}) -> """convert: change a quantity to another unit of the same di
  step 2: read_file({"path": "unitcraft/units.py"}) -> """The unit table: each symbol with its dimension and its fa
  step 3: read_file({"path": "unitcraft/parse.py"}) -> """parse_quantity: read a quantity written as text, such as
kept call: {"name": "read_file", "arguments": {"path": "README.md"}}
kept result, in lines: 42
cut before the last result alone, clean: False
cut before the last call, clean: True

這次執行壓縮了 3 個較舊的呼叫,而最後一個呼叫與其結果完整保留:那是對 README.md 的一次讀取,結果長達 42 行。固定的部分,也就是系統提示、工具結構描述(schema)與議題,合計 1289 個估計 token。壓縮無法削減這個部分,因此低於它的預算無法靠任何壓縮達成。

最後印出兩種切分。僅在最後一個結果之前切分會被拒絕,而在其呼叫之前切分則是乾淨的。程式碼對這兩種情況都做了斷言,因此任何一項有所改變,執行就會失敗。

**實用原則:**將最後一個呼叫與其結果保留在一起,拒絕任何落在工具結果上的切分,並且在依賴壓縮讓其餘部分符合預算之前,先確認固定的部分本身放得進預算。

將筆記放在上下文之外

壓縮在設計上就會遺失細節。Anthropic 關於上下文工程的技術文章把這點視為一項取捨:「壓縮的技巧在於選擇保留什麼、捨棄什麼,因為過度積極的壓縮,可能會遺失細微但關鍵的上下文,而其重要性要等到之後才會顯現」(Effective context engineering for AI agents)。同一篇文章也提出了繞過這個問題的做法,也就是把筆記保存在視窗之外,但文中沒有報告對這種做法的任何量測。

測試框架新增了 note 工具。模型每個事實寫一行,框架在每一步都會把筆記附在議題之後送出。壓縮不會截斷這些筆記,因為它們不屬於較早的步驟。模型以筆記寫下的事實,能撐過每一次壓縮。只留在較早結果中的事實,最多只會以該結果的第一行被保留下來。

notes-survive.py Python 3.12.15 · pydantic 2.14.3 通過
"""A note the agent writes keeps a fact that an older read result had, after a compaction. The summary keeps only thefirst line of each read, and the fact sits on line 18 of format.py, so the read's summary line lacks it while the notekeeps it whole. The point rests on the last assertions: the fact is in the notes block and not in the read's line."""from lib.case import load_tasksfrom lib.chapter1 import callfrom lib.context import Compacting, Context, Measured, Notes, notes_toolsetfrom lib.loop import run_taskfrom lib.models import ScriptedModelfrom lib.trace import IdCounterBUDGET = 2000  # estimated tokens: the notes and the reads cross it, the last request fits under it# each note states a fact the run has just read in the case, so every note is true of unitcraftnotes = [    "format_quantity strips trailing zeros on line 18 of format.py (frac.rstrip), so 3.50 kg prints as 3.5 kg",    "test_pads_to_two_places in tests/test_format.py expects 3.5 kg to print as 3.50 kg, so the strip fails it",    "round_places goes through float, so 2.675 rounds to 2.67, and test_tie_at_a_binary_float_edge expects 2.68",]replies = [call("read_file", path="unitcraft/format.py"), call("note", text=notes[0]),           call("read_file", path="tests/test_format.py"), call("note", text=notes[1]),           call("read_file", path="unitcraft/rounding.py"), call("note", text=notes[2]),           call("read_file", path="README.md"), call("finish", summary="Read the case and noted the failing tests.")]store = Notes()ctx = Context(notes=store, prompt_budget=BUDGET)  # the notes are kept outside the older steps, so compaction keeps themmodel = Compacting(Measured(ScriptedModel(replies)), ctx)run = run_task(model, load_tasks(only=["T-01"])[0], notes_toolset(store), max_steps=16, ids=IdCounter())sent = model.inner.requests[-1][0]block = next(m["content"] for m in sent if m["content"].startswith("Your notes so far"))summary = next(m["content"] for m in sent if m["content"].startswith("Earlier steps"))read_line = summary.splitlines()[1]  # the first step: the read of format.py, with its first result line cut shortprint("steps:", run.steps)print("ended:", run.ended)print("compactions:", ctx.compactions)print("notes written:", len(store.lines))print("notes whole in the notes block:", sum(line in block for line in store.lines))print("lines in the notes block that name the fact (rstrip):", sum("rstrip" in line for line in block.splitlines()))print("summary line for the read of format.py:", read_line)assert ctx.compactions > 0, "the run should compact"assert all(line in block for line in store.lines), "every note should be whole in the notes block"assert "format.py" in read_line and "rstrip" not in read_line, "the read's summary line must lack the fact"assert "rstrip" in block, "the note must keep the fact"
輸出python notes-survive.py
steps: 8
ended: finish
compactions: 5
notes written: 3
notes whole in the notes block: 3
lines in the notes block that name the fact (rstrip): 1
summary line for the read of format.py: step 1: read_file({"path": "unitcraft/format.py"}) -> """format_quantity: write a quantity as text, such as ``3.50

這個範例是一份腳本,而不是模型。ScriptedModel 會讀取四個檔案並寫下三則筆記,每一則都緊接在它所來自的讀取之後。該事實位於檔案的第 18 行,而摘要只保留檔案的第一行,因此摘要中對應該次讀取的那一行是文件字串,而不是該事實。這次執行共壓縮了 5 次。全部 3 則筆記,在最後一次請求的筆記區塊中都完整無缺,其中有 1 行指出了該事實。每則筆記陳述的都是這次執行在該案例中讀到的內容,因此讀者可以對照案例檔案逐一檢查。

這說明了機制本身,卻沒有說明模型是否會寫下這些筆記。下一節會用模型的錄製紀錄來檢驗這一點。

實用原則: 把後續步驟需要的事實寫進筆記,而不是只寫進摘要。摘要只保留一部分內容,而筆記是本書唯一完整保存事實的地方。

記錄中的模型如何運用預算

錄製檔 chapter-5-notes 是使用第 3 章的工具集 v2、筆記工具,以及第 2 章的停止規則所錄製的。它的三次執行分別是 T-01、T-02 和 T-06。有七次任務集執行達到步數上限 16(T-01, T-02, T-06, T-10, T-11, T-13, T-16),而錄製檔的腳本指明這三次是各自觸及該上限的長時間執行,其餘四次則沒有執行。我們在開啟壓縮的情況下重播這三次執行,以觀察模型如何運用工具與預算。

recorded-context-use.py Python 3.12.15 · pydantic 2.14.3 通過
"""The three recorded runs of chapter 5, replayed with the compaction on: how each ended, whether its check passed,its note calls and compactions, and its largest prompt by the estimate and by the count the model reported. The pointrests on the check lines and the zero counts: no run passed its check, and no run wrote a note or was compacted."""import jsonfrom lib.case import load_tasksfrom lib.context import Compacting, Context, Measured, Notes, estimate, notes_toolsetfrom lib.loop import Stops, run_taskfrom lib.models import RECORDED, ReplayModelfrom lib.trace import IdCountermanifest = json.loads((RECORDED / "chapter-5-notes" / "manifest.json").read_text(encoding="utf-8"))recorded = {t["task"]: t for t in manifest["tasks"]}  # the recording's own check result, stored with each runids, passed, notes_total, compact_total, est_max, rec_max = IdCounter(), 0, 0, 0, 0, 0for task in load_tasks(only=["T-01", "T-02", "T-06"]):    notes = Notes()    context = Context(notes=notes)  # the default budget, 7168 tokens, which no run reaches    model = Compacting(Measured(ReplayModel("chapter-5-notes", task.id)), context)    # the step cap of 16 and the stop rules are those the recording was made with    run = run_task(model, task, notes_toolset(notes), max_steps=16, ids=ids,                   stops=Stops(repeat_limit=3, no_progress_limit=2))    run.close()    print(f"{task.id} kind: {recorded[task.id]['kind']}")    print(f"{task.id} ended: {run.ended}")    print(f"{task.id} check passed: {'yes' if recorded[task.id]['done'] else 'no'}")    print(f"{task.id} note calls: {sum(r['tool'] == 'note' for r in run.trace.records)}")    print(f"{task.id} compactions: {context.compactions}")    passed += recorded[task.id]["done"]    notes_total += sum(r["tool"] == "note" for r in run.trace.records)    compact_total += context.compactions    est_max = max([est_max] + [estimate(m, t) for m, t, _ in model.inner.requests])    rec_max = max([rec_max] + [n for _, _, n in model.inner.requests])print("total note calls:", notes_total)print("total compactions:", compact_total)print("runs whose check passed:", passed)print("largest estimated prompt over the three runs, in tokens:", est_max)print("largest recorded prompt over the three runs, in tokens:", rec_max)assert notes_total == 0, "the recorded runs made no note calls"assert compact_total == 0, "the recorded runs were never compacted"assert passed == 0, "none of the three recorded runs passed its check"
輸出python recorded-context-use.py
T-01 kind: fix
T-01 ended: ask_user
T-01 check passed: no
T-01 note calls: 0
T-01 compactions: 0
T-02 kind: fix
T-02 ended: finish
T-02 check passed: no
T-02 note calls: 0
T-02 compactions: 0
T-06 kind: implement
T-06 ended: no_progress
T-06 check passed: no
T-06 note calls: 0
T-06 compactions: 0
total note calls: 0
total compactions: 0
runs whose check passed: 0
largest estimated prompt over the three runs, in tokens: 4012
largest recorded prompt over the three runs, in tokens: 3189

模型在這三次執行中都沒有寫任何筆記,也沒有任何一次執行被壓縮。估算所見的最大提示為 4012 個 token,模型回報的最大值為 3189。兩者都低於提示預算。

每次執行都在上下文接近預算之前就結束了,而且沒有任何一次通過檢查。T-01 以 ask_user 結束,當時模型向使用者提出了一個問題。T-01 是修復任務,所以這個問題是錯誤的交接。T-02 以 finish 結束,當時模型呼叫了 finish,而它的檢查沒有通過。T-06 以 no_progress 結束,這正是第 2 章的停止規則:連續兩次編輯後,測試數量都沒有改變。因此有兩次執行是模型自己停下的,而且兩次都停錯了,第三次則由停止規則停下。逐次列出檢查結果,三次執行中通過的有 0 次。

三次執行、三項任務,只能說明那幾項任務上發生了什麼,對其餘十七項任務則無從得知。這些執行既沒有測試預算,也沒有測試筆記。

實用原則: 在依據錄製檔判斷預算或工具之前,先檢查每次執行是如何結束的。提早停止的執行從未測試過預算,而從未呼叫工具的模型也從未測試過該工具。

以實測取代引述效果

Chroma 在 2025 年 7 月發表的技術報告〈Context Rot〉(作者為 Hong、Troynikov 與 Huber)指出:「即使是簡單的任務,模型效能也會隨輸入長度變化而有顯著差異」(Context Rot)。該報告以自行設計的任務評估了來自多家廠商的 18 個 LLM,其中包括 Qwen3。本章並未重新執行這些任務,因此不引用其中任何效果量。

本書改為衡量自己的執行結果。第 10 章在兩個 harness 版本上執行同一組任務,並以完成任務的數量比較兩者。Harness v2 除了加入預算之外,還有其他數項變更,因此該比較無法把差異單獨歸功於預算。第 8 章中的子執行(child run)則保有自己的預算,並以自己的步數計算。

這裡的每個範例衡量的都是別的事情。預算範例衡量的是已記錄的提示詞位於何處,而壓縮與筆記範例衡量的是 harness 保留了什麼。沒有任何一個範例衡量長度如何影響模型的回答,因此本章不會斷言較長的提示詞會降低準確度。

**實用原則:**在宣稱預算有幫助之前,先以執行結果所回報的數量,衡量預算如何改變你自己的任務集。引用已發表的效果時,必須連同其實驗設定與出處,並且只能當作該報告的結果來引用。

預算如何出錯,以及如何察覺

實務上,預算會出現四種問題,而且每一種都能被察覺。

第一種是模型更換。新模型可能有不同的視窗、分詞器或回覆上限。此時預算已經不正確,卻不會出現任何錯誤,因為檢查仍會執行,也仍會依照舊的數字通過。當錄製內容的清單檔(manifest)中的視窗大小,與測試框架所用的常數不再相符時,你就能察覺這個問題,因此應讓兩者保持連結,並在兩者不一致時使該次執行失敗。視窗一節說明了這項檢查。

第二種是估計值漂移。估計值的準確度,取決於該模型與眼前文字所適用的每個 token 字元數規則。回覆中本來就附有模型自己的計數,因此在最初幾次真實執行的每個步驟中,都應比較兩者,並記錄這些數對。估計值低於計數,就是必須採取行動的徵兆,因為此時測試框架會誤以為自己還有實際上並不存在的餘裕。

第三種是摘要遺漏了後續步驟所需的內容。經過壓縮的執行可能會再次呼叫同一個工具,因為第一次的結果現在只剩摘要中的一行。第 2 章的停止規則能攔下完全相同的重複呼叫,但近似的重複,例如以略有不同的路徑讀取同一個檔案,則會通過這些規則。請統計一次執行對同一個檔案的讀取次數,並將重複讀取視為摘要遺失了某些內容的徵兆。

第四種是筆記區塊不斷增長。筆記在每個步驟都會被送出,壓縮也從不會裁減它們,而且沒有任何機制限制單則筆記的長度或筆記的數量。若一次執行寫下大量筆記,其固定部分會持續增長,直到壓縮也無法達到預算。情境會在 over_budget 中統計壓縮後仍超出預算的呼叫次數,該計數大於零,就是徵兆。

**實用原則:**在真實執行的每個步驟中,記錄估計值與回報的計數,並將估計值低於計數視為故障。當某次執行要求讀取其自身摘要已涵蓋的檔案時,應先檢查摘要保留了哪些內容,再讓該次執行重新讀取該檔案。

本章的決定

  • 提示預算是載入設定減去回覆所需的空間,它依據的是載入設定,而不是模型對外宣稱的長度。
  • 測試框架以每個 token 三個字元來估算提示。任務集的各個步驟選用了這條規則,而後來的 chapter-5-notes 錄製並未選用這條規則,卻呈現出相同的模式。
  • 壓縮是在本機進行且具確定性的,因此重播的執行會與原始執行以完全相同的方式壓縮。較早的步驟各濃縮為一行,最後一次呼叫及其結果則逐字保留。若切點落在工具結果上,該切割會被拒絕。
  • 筆記是模型可以使用的一項工具。筆記在每個步驟中都接在議題之後送出,因此壓縮絕不會切到它們,而是否寫入筆記則由模型決定。
  • 本書不使用供應商的伺服器端壓縮。

錄製的結果顯示提示都能容納於預算內,而且在兩組步驟中,估算值都維持在實際計數之上。第 10 章以計數比較兩個測試框架版本,並且無法單獨將成效歸功於預算。

實用原則: 要說明預算或工具是在哪些執行上測試的。若某項預算的主張沒有任何執行達到過,那就是關於設計的主張,而不是關於模型的主張。

本章,於本版次中

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

譯自英文書,版次 2026.11.2。

引用本節

格式

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

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

本頁內容

第 5 章,共 12 章: 讓上下文在任務變長時仍然有用

  1. 模型擁有的視窗
  2. 已記錄的執行最接近預算之處
  3. 當測試框架無法計算時,估算提示詞的 token 數
  4. 把最後的結果放在最後
  5. 壓縮較舊的步驟,並保留最後一組呼叫與結果
  6. 將筆記放在上下文之外
  7. 記錄中的模型如何運用預算
  8. 以實測取代引述效果
  9. 預算如何出錯,以及如何察覺
  10. 本章的決定

返回頂端所有章節