在任务增长时保持上下文有用

阅读约需 30分钟 分钟,10节中含5个示例。

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

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

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

读完本章,你将能够计算一次运行的提示词还剩多少空间,在运行框架无法精确计数时估算提示词的大小,并在压缩一次运行较早的步骤时,不把工具调用与其结果拆开。

模型在每一步都会读取完整的提示词:系统提示词、工具模式、问题描述,以及这次运行到目前为止做过的所有事情。这份提示词必须放进模型加载时所用的窗口,回复也必须放进同一个窗口。一次不断读取文件的运行,最终会耗尽空间。

这个问题出现在该案例中最长的几次运行里。unitcraft 的维护智能体(该库见第 1 章)会读取文件、运行测试并尝试修改,每次读取都会把整个文件加入提示词。在已记录的任务集中,T-16 达到了第 2 章中 16 的步数上限,它的最后一个提示词是整个任务集所有步骤中最大的。按已记录的计数,最后这个提示词还剩 612 个词元的余量,因此已记录的各次运行在此处最接近窗口上限。本章其余部分讲述当提示词放不下时,运行框架必须怎么做。

模型的窗口

所记录的模型是 Qwen3-4B-Instruct-2507,由第 1 章介绍的 GGUF 文件运行。测试框架加载它时使用 8192 个词元的上下文,记录的清单也把同一个值存为 n_ctx。这是测试框架选定的加载设置。模型本身支持的长度要大得多:其模型卡给出的原生上下文长度为 262,144 个词元(模型卡,读取自该卡的主分支)。本书在较小的窗口中运行该模型,因此预算所需的数字是运行时实际加载的那个值。

清单还存有 max_tokens,即回复最多可占用的词元数:1024 个词元。回复与提示占用同一个窗口,所以提示可用的空间就是回复留下的部分。

算式很简短。8192 个词元,减去为回复预留的 1024 个,剩下 7168 个词元,供模型在一步中读取的全部内容使用。提示包含系统提示、工具模式、问题、笔记、先前的各步骤和最近一次的工具结果,这些内容都计入该预算。拒绝信息与其他工具结果一样:测试框架把它的文本作为工具消息返回给模型,所以它同样计入预算。本章称之为提示预算。

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

在打印任何内容之前,代码会检查记录的清单所写的窗口和回复上限是否与测试框架一致,两者不同时则让运行失败。随后它打印预算,以及每次运行中最大的提示与预算的对照。

托管 API 的窗口要大得多。Anthropic API 文档的上下文编辑页面给出 100,000 个输入词元,作为清除旧工具结果的默认触发值(上下文编辑)。在 8192 个词元的窗口上,100,000 个词元的触发值永远不会生效,所以本书的预算取自所记录模型的加载设置,而不取自厂商的默认值。

工作准则: 设定任何预算之前,先从清单所记录的、运行所用的加载设置中取窗口,再减去回复的上限。不要取自模型宣称的长度或厂商的默认值,因为照搬较大模型的预算,会让运行在预算起作用之前就填满窗口。

记录的运行中最接近预算的情形

记录在 replies.jsonl 中保存了模型为每一步报告的提示词计数。适配器按第 4 章对回复的定义,把该计数作为 prompt_tokens 返回,因此这些都是模型自己给出的计数,并非测试框架估算所得。

按这些计数,没有任何一个已记录的步骤达到了提示词预算。在已记录的 220 个步骤中,有 0 个超出预算。最大的一步是 T-16 的最后一步,在为回复留出空间之后,上下文窗口仍剩余 612 个词元。这项检查只读取记录,不加载任何模型,因此没有生成该记录所用的硬件,也能运行。对任何新的记录运行同样的检查,都能立刻看出其中的提示词是否仍在预算之内,所以在更换模型之后,它应当是最先重新运行的检查。

这个结果能说明的,比表面上看到的要少。记录的任务集运行的是 tool set v1,循环与模型之间没有任何环节能够缩短或拒绝一条提示词。没有发生压缩,也没有任何一步为了适应预算而被截断。这些计数只表明这些提示词能够放得下,并不表明提示词放不下时测试框架会怎么做。本章其余部分讨论的正是这种情形。

**工作准则:**在从一次运行中解读出任何结论之前,先把每一步的计数与提示词预算逐一比较。

在测试框架无法计数时估算提示词

精确的计数来自模型自带的分词器,而分词器是模型文件的一部分。本书的示例离线运行,从不打开该文件,它约 2.5 GB,也不在本书中。因此测试框架只能估算。它统计每条消息和工具模式(schema)的字符数,除以三并向上取整:每 3 个字符对应一个词元。

我们是通过查看任务集记录来选定三这个数的。最初尝试的规则是每个词元四个字符。在 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。记录的计数包含聊天模板的词元,而估算并不统计这些词元,因此平均每个词元 3.67 个字符是针对这种提示词格式的比值,而不是仅针对文本本身。

偏向安全一侧的代价也清晰可见。有三个步骤的估算值超过了提示词预算,而这三步中模型自己的计数都在预算之内。信任估算值的测试框架会无故压缩这些步骤。

这条规则是依据任务集步骤选定的,所以这些步骤无法用来检验它。留出检验使用的是 chapter-5-notes 记录。它是在规则确定之后制作的,其计数没有用于选择规则。它的 18 个步骤呈现出相同的规律:没有一步低于计数,比值从 1.22 到 1.29,每个词元 3.74 个字符。它使用的是同一个模型和相似的文本,因此并不能说明这条规则对其他分词器、其他语言或充满符号的代码同样成立。

工作准则: 以每个词元三个字符进行估算,并在任何新模型的最初几次运行中,将估算值与模型报告的计数核对。如果估算值曾低于报告的计数,请先采用更小的每词元字符数,再信任预算。

把最后的结果放在末尾

事实在提示词中的位置,与它是否存在同样重要。在 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 个估算词元。压缩无法削减这一部分,所以低于它的预算无法通过任何压缩来满足。

最后打印了两种切分。仅在最后一个结果之前切分会被拒绝,而在其调用之前切分则是干净的。代码对这两种情况都做了断言,因此任何一种发生变化都会使运行失败。

**工作准则:**把最后一次调用及其结果放在一起,拒绝任何落在工具结果上的切分,并且在依赖压缩让其余部分满足预算之前,先检查固定部分是否在预算之内。

把笔记放在上下文之外

压缩在设计上就会丢失细节。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 个词元,模型报告的最大提示为 3189 个词元。两者都低于提示预算。

每次运行都在上下文接近预算之前就结束了,而且没有一次通过检查。T-01 以 ask_user 结束,当时模型向用户提出了一个问题。T-01 是修复任务,因此这个问题是一次错误的移交。T-02 以 finish 结束,当时模型调用了 finish,而它的检查没有通过。T-06 以 no_progress 结束,这正是第 2 章中的停止规则:连续两次编辑后,测试数量都没有变化。因此,有两次运行是模型自己停止的,而且都停错了,第三次则由停止规则终止。逐次运行打印出的检查结果显示,三次运行中通过的有 0 次。

三个任务上的三次运行,只能说明这些任务上发生了什么,对其余十七个任务则没有任何说明。这些运行既没有检验预算,也没有检验笔记。

工作准则: 在依据一份记录来评判预算或工具之前,先检查每次运行是如何结束的。提前停止的运行从未检验过预算,从不调用工具的模型也从未检验过工具。

测量效果,而不是转述效果

Chroma 在 2025 年 7 月发布了一份技术报告,即 Hong、Troynikov 和 Huber 撰写的《Context Rot》。报告发现,“即使在简单任务上,模型性能也会随输入长度的变化而显著变化”(Context Rot)。该报告在自己设计的任务上评估了来自多家厂商的 18 个 LLM,其中包括 Qwen3。本章不会重新运行这些任务,因此也不引用其中的任何效应量。

本书转而测量自己的运行结果。第 10 章在两个 harness 版本上运行同一任务集,并以完成任务的数量来比较二者。harness v2 在加入预算的同时还有其他若干改动,因此这一比较无法把差异单独归因于预算。第 8 章中的子运行保留各自独立的预算,按其自身的步数计数。

这里的每个示例测量的是别的内容。预算示例测量的是已记录的提示词所处的位置,压缩示例和笔记示例测量的是 harness 保留了什么。没有一个示例测量长度如何影响模型的回答,因此本章不会说长提示词会降低准确率。

**工作准则:**在宣称预算有帮助之前,先用各次运行报告的计数,测量预算对你自己的任务集有何改变。引用已发表的效应时,必须同时给出其实验设置和来源,并且只将其作为该报告的结果。

预算如何出错,以及如何察觉

实践中预算会在四个方面出问题,而每一种问题都可以被察觉。

第一种是模型变更。新模型的窗口、分词器或回复上限可能与旧模型不同。此时预算已经不对,却不会出现任何错误,因为检查仍在运行,并且仍然按旧数值通过。当记录清单(manifest)中的窗口与测试框架使用的常量不再一致时,你就能发现这个问题,因此应当让两者保持关联,并在二者不一致时让运行失败。窗口一节说明了这项检查。

第二种是估算值漂移。估算值的准确程度,取决于针对该模型和当前文本所采用的每词元字符数规则。回复中已经带有模型自己给出的计数,因此在最初的若干次真实运行中,应在每一步比较两者,并记录这些数值对。估算值低于计数是需要采取行动的信号,因为这时测试框架会以为自己有并不存在的余量。

第三种是摘要丢掉了后续步骤所需的内容。经过压缩的运行可能会再次调用同一个工具,因为第一次的结果现在只剩摘要中的一行。第 2 章的停止规则可以捕获完全相同的重复调用,但近似的重复,例如读取同一文件而路径略有不同,则能通过这些规则。应统计一次运行对同一文件的读取次数,并将重复读取视为摘要丢失了信息的迹象。

第四种是笔记块不断增长。笔记在每一步都会发送,压缩从不裁剪它们,也没有任何机制限制单条笔记的长度或笔记的数量。写入大量笔记的运行会使其固定部分不断增大,直到压缩无法满足预算。上下文会在 over_budget 中统计压缩之后仍超出预算的调用次数,该计数大于零就是信号。

工作准则: 在真实运行的每一步记录估算值和报告的计数,并将估算值低于计数视为故障。当一次运行请求的文件已被其自身的摘要涵盖时,应先检查摘要保留了哪些内容,再让运行重新读取该文件。

本章做出的决定

  • 提示词预算等于加载设置减去为回复预留的空间,它取决于加载设置,而不取决于模型对外宣称的长度。
  • 测试框架按每个词元三个字符来估算提示词。任务集的各个步骤选定了这条规则,而后来的 chapter-5-notes 录制并未选择它,却呈现出同样的模式。
  • 压缩在本地进行且是确定性的,因此重放的运行与原始运行的压缩结果完全一致。较早的步骤各压缩为一行,最后一次调用及其结果则原文保留。落在工具结果上的切分会被拒绝。
  • 笔记是模型可以使用的一种工具。它们在每一步都排在议题之后发送,因此压缩不会切掉它们,是否写笔记由模型决定。
  • 本书不使用供应商的服务端压缩。

录制结果表明,提示词都能放入预算,并且在两组步骤上,估算值始终高于实际计数。第 10 章以计数的方式比较了两个测试框架版本,它不能把结果单独归功于预算。

**工作准则:**写明预算或工具在哪些运行上测试过。对于没有任何运行达到过的预算,相关论断说的是设计,而不是模型。

本章,在本版次中

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

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

引用本节

格式

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

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

本页内容

第 5 章,共 12 章: 在任务增长时保持上下文有用

  1. 模型的窗口
  2. 记录的运行中最接近预算的情形
  3. 在测试框架无法计数时估算提示词
  4. 把最后的结果放在末尾
  5. 压缩较早的步骤,保留最后一对
  6. 把笔记放在上下文之外
  7. 被记录的模型如何使用预算
  8. 测量效果,而不是转述效果
  9. 预算如何出错,以及如何察觉
  10. 本章做出的决定

返回顶部全部章节