タスクが長くなってもコンテキストを有用に保つ

読了まで約29 分分、10 節 節の 5 例 例。

第2026.11.2版 2026年11月20日時点で例が通過 64 例中 64 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.2)から翻訳した。 原文を読む

この章を読み終えると、実行(run)のプロンプトにどれだけの余裕があるかを求め、ハーネスが正確に数えられないときにプロンプトの大きさを見積もり、ツール呼び出しとその結果を切り離さずに、実行の古いステップを圧縮できるようになる。

モデルは、ステップごとにプロンプト全体を読む。プロンプトは、システムプロンプト、ツールのスキーマ、課題、そしてそれまでに実行が行ったすべてのことからなる。このプロンプトは、モデルが読み込まれたときのウィンドウに収まらなければならず、応答も同じウィンドウに収まらなければならない。ファイルを読み続ける実行は、やがて余裕を使い果たす。

この問題は、この事例で最も長い実行に現れる。unitcraftは第1章のライブラリであり、そのメンテナンスエージェントは、ファイルを読み、テストを実行し、編集を試みる。読み込みのたびに、ファイル全体がプロンプトに加わる。記録されたタスクセットでは、T-16が第2章のステップ上限である16に達し、その最後のプロンプトはセット内のどのステップよりも大きかった。記録された数値では、その最後のプロンプトに残った余裕は612トークンであり、記録された実行がウィンドウに最も近づいたのはこの箇所だった。この章の残りでは、プロンプトが収まらないときにハーネスが何をしなければならないかを扱う。

モデルが持つウィンドウ

記録に使ったモデルは Qwen3-4B-Instruct-2507 であり、第1章で紹介した GGUF ファイルから実行している。ハーネスはこのモデルを 8192 トークンのコンテキストでロードし、記録のマニフェストにも同じ値が n_ctx として保存されている。これはハーネスが選んだロード設定である。モデル自体はそれよりはるかに長いコンテキストに対応しており、モデルカードには 262,144 トークンというネイティブのコンテキスト長が示されている(モデルカード、カードの main ブランチで確認した)。本書ではこのモデルをより小さなウィンドウで実行するため、予算に必要な数値は、実行時にロードした値のほうである。

マニフェストには max_tokens も保存されている。これは返信が使える最大量であり、1024 トークンである。返信はプロンプトと同じウィンドウから出力されるため、プロンプトに割り当てられるのは、返信の分を除いた残りである。

計算は短い。8192 トークンから返信用の 1024 トークンを引くと、モデルが1ステップで読むすべてのために 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 トークンが示されている(コンテキスト編集)。100,000 トークンのトリガーは、8192 トークンのウィンドウでは決して作動しない。そのため本書は、ベンダーの既定値ではなく、記録対象のモデルのロード設定から予算を決める。

実践ルール: ウィンドウは、実行で使われたロード設定から、マニフェストの記録どおりに取り、予算を設定する前に返信の上限を差し引くこと。モデルの公称の長さやベンダーの既定値は使ってはならない。より大きなモデルから写した予算では、予算が働く前に実行がウィンドウを使い切ってしまうからである。

記録された実行が予算に最も近づいた箇所

記録には、モデルが各ステップについて報告したプロンプトのトークン数が replies.jsonl に保存されている。アダプタはこの数を prompt_tokens として返す。返信は第4章の定義に従う。したがって、これらの数はモデル自身が数えたものであり、ハーネスが推定したものではない。

これらの数で見ると、プロンプト予算に達した記録済みステップはなかった。記録された 220 ステップのうち、予算を超えたものは 0 であった。最大のものは T-16 の最後のステップであり、返信用の余地を除いても、コンテキストウィンドウには 612 トークンの余裕が残っていた。この検査は記録を読むだけで、モデルを読み込まない。そのため、記録を作ったハードウェアがなくても誰でも実行できる。新しい記録に対して同じ検査を実行すれば、そのプロンプトが依然として予算に収まっているかどうかがすぐに分かる。このため、モデルを変更した後に最初に再実行すべき検査である。

この結果が示す内容は、見かけよりも少ない。記録されたタスク群はツールセット v1 で実行されており、ループとモデルの間には、プロンプトを短縮したり拒否したりするものが何もなかった。圧縮は行われず、収めるために切り詰められたステップもなかった。この数が示すのは、これらのプロンプトが収まるということだけである。プロンプトが収まらないときにハーネスがどう動くかは示していない。この章の残りは、その場合を扱う。

実践ルール: 実行から何かを読み取る前に、すべてのステップの数をプロンプト予算と比べること。

ハーネスがプロンプトを数えられない場合の推定

正確なトークン数は、モデル自身のトークナイザから得られる。トークナイザはモデルファイルの一部である。本書の例はオフラインで動作し、このファイルを開くことはない。ファイルは約 2.5 GB あり、本書には含まれていない。そこでハーネスは推定を行う。すべてのメッセージとツールスキーマの文字数を数え、3 で割って切り上げる。つまり、3 文字につき 1 トークンとして扱う。

3 という値は、タスクセットの記録を調べて選んだ。最初に試した規則は 1 トークンあたり 4 文字であった。220 個のタスクセットのステップのうち、4 文字の規則による推定が真のトークン数を下回ったものは 216 であった。推定がトークン数を下回るのは危険な方向である。モデルにはない余裕があるとハーネスが思い込んでしまうからである。そこで 3 に改めた。

各ステップの推定は、同じステップについてモデルが報告したトークン数と突き合わせることができる。

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 の範囲であった。記録されたトークン数にはチャットテンプレートのトークンが含まれるが、推定はそれを数えない。したがって、1 トークンあたり平均 3.67 文字という値は、テキストだけの比ではなく、このプロンプト形式における比である。

安全側に倒すことの代償も見て取れる。3 つのステップでは、推定がプロンプト予算を超えていたが、3 つのすべてでモデル自身の数え方によるトークン数は予算の範囲内であった。推定を信頼するハーネスであれば、これらのステップを理由なく圧縮していたことになる。

この規則はタスクセットのステップで選んだものなので、それらのステップで規則を検証することはできない。ホールドアウト検証は、chapter-5-notes の記録で行う。この記録は規則を確定した後に作成したものであり、そのトークン数は規則の選択には使っていない。18 個のステップでも同じ傾向が見られた。下回るものはなく、比は 1.22 から 1.29 の範囲で、1 トークンあたり 3.74 文字であった。モデルは同じで、テキストも似ている。したがって、別のトークナイザ、別の言語、記号の多いコードに対してこの規則が成り立つかどうかは、この結果からは分からない。

実践ルール: 1 トークンあたり 3 文字で推定し、新しいモデルでは最初の実行時に、その推定をモデルが報告するトークン数と照らし合わせて確認する。推定が報告されたトークン数を下回ることが一度でもあれば、予算を信頼する前に、1 トークンあたりの文字数をより小さい値にする。

最後の結果を末尾に置く

プロンプトでは、事実が含まれているかどうかだけでなく、それがどこにあるかも重要である。2023年の論文で Liu らは、関連する情報が長い入力の先頭または末尾にあるときに性能が最も高くなることが多く、中央にあるときには低下することを見いだした(Lost in the Middle)。これらのモデルは本書が記録するモデルより古いため、この論文が述べているのは古いモデルに見られる傾向であり、Qwen3-4B-Instruct-2507 が長いプロンプトをどう扱うかを示すものではない。

本書のレイアウトでは、課題(issue)とメモを先頭近くに置き、最後のツール結果を末尾に置く。末尾は、モデルが応答する前に最後に読む位置だからである。これは本書の設計上のルールである。最後の結果を最後に置かなければならないと述べる資料はここにはなく、本書もこのモデルでこのレイアウトを計測してはいない。この選択の根拠は、この論文である。後述の圧縮の例では、最後の呼び出しでモデルに送られる各メッセージを順に出力している。システムプロンプト、課題、要約、最後の呼び出しとその結果の順である。

このレイアウトにはコストがある。圧縮を行うと、古いステップの要約が、課題と、最後の呼び出しおよびその結果との間に入る。そこはプロンプトの中央である。論文が述べる傾向に従えば、モデルが情報を最も使いにくい位置にあたる。本書はこのコストを受け入れる。

実践ルール: 課題とメモを先頭に、最後のツール結果を末尾に置く。これは設計上の選択として扱い、自分のタスクでの実行によって効果が示された場合にのみ、効果があると主張すること。

古いステップを圧縮し、最後の呼び出しと結果の組は残す

見積もりがプロンプト予算を超えると、ハーネスは圧縮を行う。ここでの圧縮はローカルで行われる。要約はハーネス自身が書き、モデルが要約の作成過程を見ることはない。古いステップは、1件のメッセージにまとめられ、1ステップが1行になる。1行には、呼び出し、60文字で切り詰めた引数、そして同じく60文字で切り詰めた結果の最初の行が入る。システムプロンプトと課題はそのまま残る。最後のステップは、呼び出しも結果も一字一句そのまま入れる。そのため、モデルは直近の証拠を省略なしで見ることができる。

ベンダーも、自社のサーバー上で圧縮を提供している。Anthropic の圧縮ガイドにその一例がある。圧縮とは、会話の「古いターンを、Claude がサーバー上で書いた要約に置き換える」ものである(compaction)。オンデマンド形式はベータ版であり、ヘッダー compact-2026-09-04 を必要とする。本書ではサーバー形式を使わず、この章の内容もその挙動には依存しない。このページは読んだが、実行はしていない。

ローカルのハーネスにとって重要なのは、切断の規則である。直近のターンを残す方法についてのベンダーのガイドは、これを明確に述べている。「ツール呼び出しが未完了のまま残らない位置で切る。各ツール呼び出しとその結果は同じ側に置く」(keeping recent turns)。ツール結果の位置で切ると、その結果を求めた呼び出しが失われて結果だけが残る。そのためハーネスはそのような切断を拒否する。

予算を見積もりトークン 2000 とすると、4回の読み取りと1回の終了で予算を超えるには十分である。この予算は、実際の 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 行の長さであった。固定部分、すなわちシステムプロンプト、ツールスキーマ、課題は、見積もりで 1289 トークンであった。圧縮はこの部分を切り詰められない。したがって、これを下回る予算は、どのような圧縮でも満たせない。

最後に2つの切断が出力される。最後の結果だけの手前での切断は拒否され、その呼び出しの手前での切断は問題なく行われる。コードは両方をアサートしているので、どちらかが変わると実行は失敗する。

実践ルール: 最後の呼び出しとその結果は組にして残し、ツール結果の位置にかかる切断はすべて拒否し、残りを圧縮で収めようとする前に、固定部分が予算に収まるかを確認する。

ノートをコンテキストの外に置く

圧縮は設計上、細部を失う。Anthropic のコンテキストエンジニアリングに関する技術記事は、これを一つの選択として述べている。「圧縮の技術は、何を残し何を捨てるかの選択にある。圧縮が過度に積極的であると、重要性が後になってはじめて明らかになる、微妙だが決定的なコンテキストが失われかねない」(Effective context engineering for AI agents)。同じ記事は、ウィンドウの外にノートを保持するという回避策も述べているが、その効果の測定は報告していない。

ハーネスに note ツールを加える。モデルは事実ごとに1行を書き、ハーネスはステップごとに、課題の後ろにそのノートを送る。ノートは古いステップの一部ではないため、圧縮で切り取られない。モデルがノートとして書いた事実は、すべての圧縮を越えて残る。古い結果の中にしか残っていない事実は、残るとしても、せいぜいその結果の最初の1行としてである。

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 は4つのファイルを読み、3つのノートを書く。各ノートは、その元になった読み取りの直後に書かれる。事実はファイルの18行目にあり、要約はファイルの最初の1行しか残さないので、その読み取りに対する要約の行にあるのは docstring であって事実ではない。この実行では圧縮が 5 回行われた。3 件のノートはすべて、最後のリクエストのノートブロックに欠けることなく入っており、その行のうち 1 行が事実を挙げている。各ノートは、実行がそのケースで読んだ内容を述べているので、読者は各ノートをケースのファイルと照合できる。

これは仕組みを示すものである。モデルがノートを書くかどうかは示していない。それは次の節で、モデルの記録を使って確かめる。

実践ルール: 後のステップが必要とする事実は、要約だけでなくノートにも書く。要約は選んだ内容だけを残す。本書が事実を欠けることなく保つ場所は、ノートだけである。

記録されたモデルがバジェットをどう使ったか

記録 chapter-5-notes は、第3章のツールセット v2、ノートツール、および第2章の停止ルールを使って作成した。この記録の3つの実行は T-01、T-02、T-06 である。タスクセットの7つの実行がステップ上限 16 に達しており(T-01, T-02, T-06, T-10, T-11, T-13, T-16)、記録のスクリプトは、上限に達した長い実行としてこの3つを挙げている。残りの4つは実行しない。モデルがツールとバジェットをどう使ったかを調べるため、圧縮を有効にしてこの3つの実行を再生した。

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

3つの実行のいずれでも、モデルはノートを書かず、圧縮された実行もなかった。見積もりで確認された最大のプロンプトは 4012 トークンであり、モデルが報告した最大のプロンプトは 3189 トークンであった。どちらもプロンプトバジェットを下回っている。

どの実行も、コンテキストがバジェットに近づく前に終了しており、チェックに合格した実行もなかった。T-01 は、モデルが人に質問をした時点で ask_user として終了した。T-01 は修正タスクであるため、この質問は誤った引き継ぎであった。T-02 は、モデルが finish を呼び出した時点で finish として終了したが、そのチェックには合格しなかった。T-06 は no_progress として終了した。これは第2章の停止ルールによるものであり、2回連続の編集でテスト数が変わらなかったのである。つまり、モデル自身が2つの実行を止めたが、どちらも誤りであり、3つ目は停止ルールが止めた。実行ごとに出力したチェック結果では、3つのうち合格は 0 件である。

3つのタスクにおける3回の実行が示すのは、それらのタスクで起きたことだけであり、残りの17件のタスクについては何も示さない。これらの実行は、バジェットもノートも検証していない。

実践ルール: 記録をもとにバジェットやツールを評価する前に、各実行がどのように終了したかを確認すること。早期に停止する実行はバジェットを検証せず、ツールを一度も呼び出さないモデルはそのツールを検証しない。

効果は引用せず測定する

2025年7月に Chroma が公開した技術報告書「Context Rot」(Hong、Troynikov、Huber)は、「単純なタスクであっても、入力長が変わるとモデルの性能は大きく変動する」と報告している(Context Rot)。この報告書は、Qwen3 を含む複数のベンダーの 18 個の LLM を、報告書独自のタスクで評価している。本章はそれらのタスクを再実行していないため、そこから効果量を引用することはしない。

そこで本書は、自前の実行結果を測定する。第10章では、2 つのハーネスのバージョンでタスクセットを実行し、完了したタスクの件数として両者を比較する。ハーネス v2 は予算のほかにもいくつかの変更を加えているため、この比較では効果を予算だけに帰することはできない。第8章の子の実行は、自身のステップ数で数える固有の予算を持つ。

ここで扱う各例が測定するものは、それぞれ異なる。予算の例は、記録されたプロンプトがどの位置にあったかを測定し、圧縮とノートの例は、ハーネスが何を保持するかを測定する。いずれも、長さがモデルの回答にどう影響するかは測定していない。したがって本章は、長いプロンプトが精度を損なうとは述べない。

実践ルール: 予算が有効だと主張する前に、実行が報告する件数を用いて、予算が自分のタスクセットをどう変えるかを測定する。公表された効果を引用するのは、その設定と出典を添えた場合に限り、しかもその報告書の結果としてのみ引用する。

予算が誤るしくみと、その気づき方

実際には予算に関して四つの問題が起こり、いずれも気づくことができる。

一つ目は、モデルの変更である。新しいモデルでは、ウィンドウ、トークナイザー、応答の上限が異なる場合がある。その場合、予算は誤ったものになるが、エラーは出ない。検査は実行され、古い数値に対して合格し続けるためである。録画のマニフェストにあるウィンドウが、ハーネスの使う定数と一致しなくなったときに、これに気づける。そのため、両者を結び付けておき、食い違えば実行を失敗させる。この検査についてはウィンドウの節で説明している。

二つ目は、見積もりのずれである。見積もりの精度は、そのモデルとその文章に対する、トークン当たりの文字数の規則の精度を超えない。応答にはモデル自身の数えた値がすでに含まれているので、最初の実際の実行では毎ステップで両者を比べ、その組を記録する。見積もりが実測値を下回るときは、対処すべき兆候である。ハーネスが、実際にはない余裕があると思い込むからである。

三つ目は、後のステップに必要な情報を要約が落とすことである。圧縮された実行では、最初の結果が要約の中の一行になっているため、同じツールを再び呼び出すことがある。第2章の停止規則は完全な繰り返しを捕らえるが、同じファイルをわずかに異なるパスで読むような、ほぼ同じ繰り返しはこれを通り抜ける。一つの実行が同じファイルを何回読むかを数え、繰り返しがあれば、要約が何かを失った兆候として扱う。

四つ目は、ノートのブロックが増え続けることである。ノートは毎ステップ送られ、圧縮でも削られることがなく、ノートの長さや数に上限を設けるものもない。多くのノートを書く実行では、固定部分が増え続け、ついには圧縮でも予算を満たせなくなる。コンテキストは、圧縮後もなお予算を超えている呼び出しの数をover_budgetに数えており、その値がゼロを超えていれば、それが兆候である。

実践ルール: 実際の実行では毎ステップで見積もりと報告されたトークン数を記録し、見積もりが報告値を下回る場合は障害として扱う。実行が、自身の要約ですでに扱われているファイルを求めたときは、再びファイルを読む前に、要約が何を残したかを確認する。

本章で下した判断

  • プロンプトの予算は、負荷設定から応答の余地を引いた値である。予算は、モデルが公称する長さではなく、負荷設定に従う。
  • ハーネスは、プロンプトを1トークンあたり3文字として見積もる。この規則を選んだのはタスクセットのステップであり、この規則を選んでいない後の chapter-5-notes の記録にも、同じ傾向が現れる。
  • 圧縮はローカルで決定的に行われるため、再生した実行は元の実行と全く同じように圧縮される。古いステップは1行ずつにまとめられ、直近の呼び出しとその結果は一語一句そのまま残される。ツールの結果の位置にかかる切断は拒否される。
  • ノートは、モデルが使ってよいツールである。ノートは毎ステップ、課題の後に送られるため、圧縮によって切られることはなく、ノートを書くかどうかはモデルが決める。
  • 本書は、ベンダーのサーバー側の圧縮を使わない。

記録からは、プロンプトが収まったこと、そして両方のステップ群で見積もりが実測の数を上回ったままだったことが分かる。第10章は、2つのハーネスのバージョンを件数として比較しており、予算だけを原因とみなすことはできない。

実践ルール: 予算やツールを試した実行に名前を付けること。どの実行も達しなかった予算についての主張は、モデルについての主張ではなく、設計についての主張である。

この版における本章

第2026.11.2版2026年11月20日時点で例が通過この章の5 例件のうち5件が合格

英語版の書籍(版2026.11.2)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全12章中の第5章: タスクが長くなってもコンテキストを有用に保つ

  1. モデルが持つウィンドウ
  2. 記録された実行が予算に最も近づいた箇所
  3. ハーネスがプロンプトを数えられない場合の推定
  4. 最後の結果を末尾に置く
  5. 古いステップを圧縮し、最後の呼び出しと結果の組は残す
  6. ノートをコンテキストの外に置く
  7. 記録されたモデルがバジェットをどう使ったか
  8. 効果は引用せず測定する
  9. 予算が誤るしくみと、その気づき方
  10. 本章で下した判断

ページの先頭に戻るすべての章