モデルにツールとループを与える

読了まで約35 分分、8 節 節の 4 例 例。

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

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

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

本章を終えると、モデルを3つのツールを持つループの中で実行できるようになる。1つ目のツールはファイルを読み、2つ目はテストを実行し、3つ目は変更したファイルを提出して終了する。ループは、モデルが終了したとき、ステップを使い切ったとき、呼び出しをやめたときに停止する。このループを、課題を解く台本付きモデルで実行し、次に課題を解けない記録済みのオープンモデルで実行して、そのモデルがどこで誤るかを確認する。

本章のエージェントが保守するのは unitcraft である。これは、3.5 kg のようにテキストで書かれた物理量を読み取り、変換し、整形する小さな Python ライブラリである。エージェントは、メンテナが登録した issue を受け取り、ライブラリのコードに対する変更を提案する。エージェントは自分のコピー上で公開テストを実行できるが、変更が完了と見なされるかどうかを決める非公開の検査は見られない。この分離は意図的なものである。自分の採点基準を読めるエージェントは、その採点基準を学習してしまい、第10章での本書の測定は意味を失う。

Andrew Ng による 2026年11月13日付の書簡 The Batch, issue 379 は、エージェントハーネスを、LLM を包み込み、コンテキスト、ツール、ガードレールを与えるコードとして説明している。本書でもこの語を同じ意味で用いる。判断を下すのはモデルである。ハーネスは、ループ、ツール、そしてそれらのツールに許される動作の制限を提供する。本書の大半は、この後者について述べるものである。

最初の課題 T-01 は1ファイルの修正であり、変更は unitcraft/format.py に加える。公開テスト群は tests/test_format.py で失敗しており、issue には次のように書かれている。「format_quantity は末尾のゼロを落とす。3.5 kg は 3.5 kg と出力されるが、既定は小数点以下2桁である。」したがって、3.5 kg の期待される出力は 3.50 kg である。人間であれば、unitcraft/format.py を開いて読み、変更を加え、テストをもう一度実行するだろう。エージェントは同じことを順番に行わなければならない。しかも、手順の間に人間は介在しない。そしてハーネスは、モデルが誤ったときでも、この順序が守られるようにしなければならない。

本章は1つの課題を最初から最後まで扱う。エージェントが何を持って始めるか、それを動かすループ、呼び出すツール、そしてそれを止める最初の規則を説明する。その後、ループを2回実行する。1回は台本付きモデルで、もう1回は記録済みモデルで行い、何が起きたかを数える。

エージェントが1つのタスクで行うこと

エージェントは2つのメッセージから始める。1つは、使えるツールとその引数を示すシステムプロンプトであり、もう1つは issue の本文である。タスクについてモデルに届くものは、これ以外にない。エージェントはケースそのものには決して触れない。ハーネスは実行ごとにライブラリの作業用コピーを作り、エージェントが行う書き込みはすべてそのコピーにだけ反映される。実行が終わるとコピーは採点された後に破棄されるので、ある実行が次の実行に変更を残すことはない。

修正が完了したと見なされるのは、2つの条件が満たされたときである。1つは、コピーに対して隠しチェックが通ること、もう1つは、実行が finish 呼び出しで終わっていることである。T-01 の隠しチェックは H-01 であり、issue の本文をもとに書かれた pytest ファイルである。これが検証するのは1点だけで、format_quantity が 3.5、0、12 kg を小数第2位までそろえ、3.50 kg、0.00 kg、12.00 kg として返すことである。ハーネスは実行後にこのファイルをライブラリの新しいコピーへ配置するので、エージェントがこれを読むことはない。第10章は、同じ規則をタスクセット全体に適用する。変更をケースのライブラリに反映するかどうかは別の判断であり、承認ゲートがそれを担うのは第6章である。

この規則は、モデルが取りうる近道を1つ塞ぐ役目も果たす。見えているテストを、通るまで書き換えるという近道である。T-01 のタスクファイルは tests フォルダを変更してはならないと定めており、採点器はそのフォルダをケースとバイト単位で比較する。そのためテストを書き換えると、隠しチェックが通っても、その実行は完了とは見なされない。修正を手探りしているモデルは、不正を働くつもりがなくてもこの近道に手を伸ばすことがある。それを数えないようにするのがこの規則である。

T-01 をタスクファイルから読み込み、ケースのファイルを一覧表示するには、短い例が1つあれば足りる。

read-the-issue.py Python 3.12.15 合格
"""The issue the agent starts from, task T-01, and the case's files in sorted order. The model reads only theissue and the system prompt, so these are what its first request holds about the task."""from lib.case import CASE, case_files, load_taskstask = load_tasks(only=["T-01"])[0]print("task:", task.id)print("issue:", task.issue)files = case_files(CASE)print("case files:", len(files))for name in files:    print(" ", name)
出力python read-the-issue.py
task: T-01
issue: `format_quantity` drops the trailing zeros: 3.5 kg prints as `3.5 kg`, and the default is two places. CI is red on `tests/test_format.py`.
case files: 25
  .github/workflows/test.yml
  README.md
  pyproject.toml
  tests/test_arith.py
  tests/test_cli.py
  tests/test_convert.py
  tests/test_format.py
  tests/test_parse.py
  tests/test_rounding.py
  tests/test_table.py
  tests/test_temperature.py
  unitcraft/__init__.py
  unitcraft/__main__.py
  unitcraft/arith.py
  unitcraft/cli.py
  unitcraft/convert.py
  unitcraft/errors.py
  unitcraft/format.py
  unitcraft/parse.py
  unitcraft/prefixes.py
  unitcraft/quantity.py
  unitcraft/rounding.py
  unitcraft/table.py
  unitcraft/temperature.py
  unitcraft/units.py

出力では、まず issue が表示され、続いてケースのファイルがソート順に表示される。issue は、モデルへの最初のリクエストに含まれる唯一のタスク固有のテキストである。したがって、以後のすべてのステップは、その最初のリクエストに何が含まれていたかに左右される。ケースには 25 のファイルがあり、エージェントはそのどれでも自分のコピーから読める。

実践ルール: 実行の採点は、その実行自身のコピーと、そのタスクのチェックだけに対して行う。ケースそのものに対しては決して採点しない。ケースに反映された変更は、それに値しない実行の成果として数えられてしまうからである。

この部分はまだ翻訳されていないため、英語で表示している。

A loop in about seventy lines

A model produces text, and the harness turns some of that text into actions. Each step sends the messages so far, along with the tool schemas, to the model. The reply comes back as text. The harness reads the tool call inside it, runs the tool on the scratch copy, appends the result to the messages, and goes around again. The model never runs anything itself. Anthropic's documentation for tool use states the contract in those terms: the model emits a structured request, the application runs the operation, and the result goes back into the conversation (How tool use works).

The loop is _loop in examples/lib/loop.py, about seventy lines. The file also holds rules for later chapters: the optional stops in Stops are off by default, and a reply cut off at the token limit is refused whatever the settings. None of this chapter's runs reach either. A step is one model call. A tool call is one request inside a step, and a reply can hold more than one. The loop acts on the first request and answers each other one with an error that says it was not run. Each request gets an ID from a counter, and the ID goes on the tool-result message that answers it. The assistant message that holds the reply carries no ID, and the trace keeps none. The trace, in lib/trace.py, holds one line per step: the step's number, the tool it called and what came back. Every reply stays in the messages too, which is why the model sees its own earlier steps on the next call, and why the request grows with each step.

The model's reply is plain text, and its tool call has a fixed shape: JSON inside <tool_call> tags. The chat template in the model file asks for that shape, a JSON object with a function name and arguments inside the tags (the model file at its pinned revision). The recorded replies use this shape, and the harness reads only what is inside the tags:

<tool_call>
{"name": "read_file", "arguments": {"path": "<case-relative path>"}}
</tool_call>

Text outside the tags is ignored, so a reply may carry prose before the call. A block that doesn't parse isn't run. The harness records it as a malformed call and hands the reason back to the model as an error result, so the model can try again.

Across the run the messages grow in a fixed order: the system prompt, the issue, then each reply followed by the result of its call. Nothing is summarised and nothing is dropped. That makes the transcript readable, and it makes the cost of each step grow with the one before it. Chapter 5 takes up what to do when that growth reaches the model's window. The runs in this chapter are short, and they don't need that yet.

ReAct interleaves written reasoning with actions, and Yao and colleagues reported that the reasoning helps a model keep and revise a plan, and handle exceptions (Yao et al., ReAct). This loop keeps the actions and asks the model for no reasoning between them. Its system prompt says "Reply with a tool call only," and the parser passes over any prose the model writes anyway.

Working rule: Keep every request and its result in the messages, and give each result the ID of the request it answers. A loop that drops a result leaves the model without an answer to its request, and the messages are where that gap shows.

二つのツールと一つの終了ツール

エージェントは読み取り、テスト、変更を行う必要があるため、本章ではそれぞれの作業に一つずつツールを与える。変更ツールは終了ツールを兼ねる。この設計では、変更を行うと実行が終わるからである。

ツール 引数 返るもの 実行を終了するか
read_file path。実行ごとに用意されたケースの作業用コピーの内部のパス ファイルのテキスト、またはエラー いいえ
run_tests なし コピー上の可視スイートによる件数と、失敗したテストの名前 いいえ
finish path と text(新しいファイル全体) 変更を書き込んだ後の件数と、失敗したテスト はい

read_file はファイル全体を返し、コピーの外にあるパスは拒否される。run_tests はコピー内で可視スイートを実行し、全出力ではなく、件数と失敗したテストの名前を返す。制限時間を超えて動き続けるスイートは、そのプロセスグループとともに停止される。finish は一つのファイルの新しいテキストを受け取り、それをコピーに書き込み、可視スイートを実行して、実行を終了する。書き込みが拒否された場合、エラーはツールの結果として返され、実行は続くため、モデルはもう一度試すことができる。

本章では、ツールはハーネス自身のプロセス内で、コピーに対して動作する。第7章では、これらのツールが起動する唯一のコマンドであるテストの実行を、サンドボックス内で行う。

ファイルを読むツールは、どのパスを読み取るかを決めておく必要がある。ケースの外にある二つのパスを指定して read_file を呼び出すと、モデルが外部のパスを要求したときに何が返るかがわかる。

tool-refusal.py Python 3.12.15 · pydantic 2.14.3 合格
"""The read tool refuses a path outside the case, and the refusal comes back as text the model can read. Only readsare tried, and a refused path never reaches the disk."""from lib.case import CASEfrom lib.tools import CH1, WorkspaceABSOLUTE = "/etc/secret.txt"ws = Workspace(CASE)for path in ("../secret.txt", ABSOLUTE):    result = CH1.call(ws, "read_file", {"path": path})    # An absolute path differs on every machine, so the output shows a placeholder for it.    print("refused:", result.text.replace(ABSOLUTE, "<absolute path>"))
出力python tool-refusal.py
refused: error: path outside the case: ../secret.txt
refused: error: path outside the case: <absolute path>

どちらのパスも拒否され、それぞれの拒否はツールの結果として返される。モデルは次のステップで、ほかの結果と同じようにこれを読むため、パスを修正して再試行できる。拒否された二つの読み取りは、どちらもディスクに触れない。

実践ルール: 各ツールには一つの役割だけを与え、実行を終了させるのは終了ツールだけにする。拒否された読み取りや書き込みは、モデルが対処できるエラーとして返し、ループを止めてはならない。

終了するのは、作業が完了したときか、予算が尽きたときである

終了条件のないループは、誰かが止めるまで動き続け、1 ステップごとにトークンを消費する。そのため、実行は 3 通りのいずれかで終了し、実行はそのどれであるかを ended として記録する。1 つ目は、モデルが finish を呼び出し、実行がその変更とともに終了する場合である。2 つ目は、実行がステップ予算に達する場合である。この章のツールセットではステップ予算は 8 ステップであり、実行は step_cap として終了する。3 つ目は、モデルがツール呼び出しをまったく行わない応答を 2 回続けて返す場合である。最初のそのような応答には再試行が与えられ、ツール呼び出しを 1 回求めるメッセージが送られる。2 回目の応答で、実行は no_tool_call として終了する。

存在しないツールの呼び出しはエラー結果として返され、実行は続く。ループは不正な呼び出しがあっても停止しない。その呼び出しを数え、エラーを返し、次のステップを待つ。不正な呼び出しを繰り返し続けるモデルが永久に動き続けないようにするのが、予算である。予算が数えるのは秒数ではなくモデルの呼び出し回数であるため、同じ実行はどのマシンでも同じステップで終了する。また、予算はコンテキストのサイズとは別の制限である。実行はウィンドウに余裕が残ったままステップ予算に達することもあれば、先にウィンドウを使い切ることもある。ウィンドウは、この章が強制する制限ではない。

第 2 章では、残りの停止規則を追加する。同じ呼び出しを繰り返す実行、テスト件数が変わらないまま編集を重ねる実行、続行せずに人へ質問すべき実行が対象である。この章のループにはそれらの規則がないため、ループに陥ったモデルは 8 ステップ目まで繰り返し続ける。

実践ルール: ステップ予算は実行を開始する前に設定し、厳格な上限として扱うこと。予算に達した実行は、最後のステップがどのように見えても完了しておらず、未完了として報告すること。

スクリプト化したモデルで実行する

ループ、そのツール、そして予算が揃ったところで、最初の実行には、返答を自分で書いたモデルを使う。スクリプト化したモデルは、与えられた返答を順番どおりに返すだけで、それ以外のことは何もしない。これはループの純粋なテストになる。実行中の不具合はモデルではなくループに原因があり、実行結果からは、モデルが何を選ぶかではなく、正しい返答に対してループが何をするかが分かる。T-01 のための四つのスクリプト化した返答は、実装を読み、そのテストを読み、可視のスイートを実行し、修正したファイルを出して終了する。

scripted-loop.py Python 3.12.15 · pydantic 2.14.3 合格
"""Four scripted replies solve T-01 through the step loop: read the file, read its test, run the visible suite,then finish with the fixed file. The model is scripted, so the output shows the loop's steps and not a model's choices."""from lib.case import load_tasksfrom lib.chapter1 import SOLUTION, call, reportfrom lib.models import ScriptedModelfrom lib.tools import CH1task = load_tasks(only=["T-01"])[0]model = ScriptedModel([    call("read_file", path="unitcraft/format.py"),    call("read_file", path="tests/test_format.py"),    call("run_tests"),    call("finish", path="unitcraft/format.py", text=SOLUTION.read_text(encoding="utf-8")),])run, done = report(model, task, CH1)  # CH1: three tools, their system prompt and a budget of eight steps; report prints the trace and scores the runassert done, "the scripted run should solve T-01"
出力python scripted-loop.py
step 1: read_file: 23 lines
step 2: read_file: 27 lines
step 3: run_tests: 8 failed, 22 passed
step 4: finish: 7 failed, 23 passed
steps: 4
tool calls: 4
ended: finish

この実行は T-01 を四つのステップで解く。スクリプト化した実行で証明できるのはここまでであり、ループが正しい返答を、合格するチェックに至るまで運ぶということである。修正したファイルは、ケースデータとともに保管されている本書独自の解答であり、例ではこの実行が完了と見なされることを検証している。

出力は順に読む。各行は一つの呼び出しとその結果を示しているので、行をまとめて見れば、モデルが各ステップで何を手元に持っていたかが分かる。件数はステップ 3 とステップ 4 の間で変化する。修正により、可視のスイートは 8 件の失敗から 7 件の失敗になり、issue が述べているテストは合格するようになる。残る 7 件は、同じ可視のスイートにある別のテストの失敗である。T-01 で意味を持つチェックは H-01 であり、これは合格する。この実行は 4 ステップを要し、ステップごとに一つ、合計 4 回のツール呼び出しを行い、finish として終了する。

実践ルール: どのモデルで実行するよりも先に、スクリプト化したモデルでループを実行する。スクリプト化した実行が失敗するなら、不具合はハーネスにあり、モデルでの実行はそれを隠すだけである。スクリプト化した実行が合格し、モデルでの実行が失敗するなら、不具合はモデルかプロンプトにある。

この部分はまだ翻訳されていないため、英語で表示している。

Run it on the recorded model

The recorded run comes from Qwen3-4B-Instruct-2507, an open model quantised to Q4_K_M and run on a CPU at temperature 0 with a fixed seed. Its replies were saved as the raw text it produced, in a recording whose manifest names the model, its revision, the prompt's hash and the token counts. Replay checks that each request matches the one the recording holds, where a request is the messages and tool schemas sent at that step, and then returns the recorded reply.

recorded-run.py Python 3.12.15 · pydantic 2.14.3 合格
"""The recorded run of T-01, replayed step by step: each request must match the one recorded, and the replies arethe recorded text, mistakes included. The run stops at the step cap without a finish, so the task is not done."""from lib.case import load_tasksfrom lib.chapter1 import Recorder, reportfrom lib.models import ReplayModelfrom lib.tools import CH1from collections import Countertask = load_tasks(only=["T-01"])[0]model = Recorder(ReplayModel("chapter-1-t01", "T-01"))run, done = report(model, task, CH1)assert not done, "the recorded run should not solve T-01"reasons = [reason for reply in model.replies for reason in reply.malformed]print("malformed calls:", len(reasons))for reason, count in sorted(Counter(reasons).items()):    print(f"  {count} x {reason}")assert all('"text": """' in reply.text for reply in model.replies[2:]), "from step 3 the call's text opens with triple quotes"print("prompt tokens:", run.prompt_tokens)print("completion tokens:", run.completion_tokens)
出力python recorded-run.py
step 1: read_file: 23 lines
step 2: run_tests: 8 failed, 22 passed
step 3: malformed: error: malformed call
step 4: malformed: error: malformed call
step 5: malformed: error: malformed call
step 6: malformed: error: malformed call
step 7: malformed: error: malformed call
step 8: malformed: error: malformed call
steps: 8
tool calls: 8
ended: step_cap
malformed calls: 6
  6 x not JSON (Expecting ',' delimiter)
prompt tokens: 13009
completion tokens: 2128

The recorded model never finishes. Its first two steps are valid calls: a read_file, then a run_tests. From the third step on, each reply is a finish call that carries a whole new file, and each of those calls fails to parse. That happens 6 times, all with one reason, and the run ends as step_cap after 8 steps and 8 tool calls. The harness returns each failure as an error result, and the model answers it with a finish call of the same shape.

The shape of each failing call looks like this. The file is left out, and the call's text is shown with ...:

<tool_call>
{"name": "finish", "arguments": {"path": "unitcraft/format.py", "text": """ ...the whole file...\""}}
</tool_call>

The value opens with three quotes. JSON reads the first two as an empty string, so the parser stops at the third, where it expects a comma. The value also closes with a single quote, after an escaped one.

The model's reading of the issue is wrong from step 2, and the format failure hides it. At step 2 the model writes that format_quantity "drops trailing zeros in the fractional part, which is correct" (the model's words, from step 2 of the recording's replies.jsonl). The file at step 3 keeps the bug: it still strips zeros from the fraction with frac.rstrip("0"). No finish call parses in this run, so that file never reaches the hidden check. A probe outside the book's examples ran the step 3 file, copied from its code block, in a copy of the case against H-01, using the pinned pytest 9.2.0:

FAILED test_t01.py::test_pads_to_two_places - AssertionError: assert '3.5 kg'...

The book's own solution passes the same check. So the change the model proposed was wrong, and only the format failure kept it from being checked.

The example asserts that the run did not count as done, and that from the third step on every reply carries its file in triple quotes inside the call. The stop tool is the one tool that carries a whole file, so the format failure sits there. Chapter 3 returns to that tool and changes how a change is sent, which removes the triple-quoted file, though small edits bring quoting trouble of their own. It does not answer the misreading at step 2: a change sent in the right form can still be wrong.

Working rule: Replay a recording the same way on every run, and never edit it to make a run pass. A failing recording shows what the model really did. The fix belongs in the harness, the prompt or the model choice, and the result of that fix is a new recording.

何が失敗し、何を数えるか

再生された実行で示した記録された実行は、二通りの形で失敗している。第一の失敗はループが捕捉するが、修復はしない。不正な形式の呼び出しはどれも、モデルが読めるエラー結果として返され、ステップ予算によって実行が終了した。第二の失敗は誤った変更である。これはループには見えない。finish の呼び出しが一つも解析されないため、変更が実行されないからである。この記録では、モデルが誤ったツールを呼ぶことはなく、呼び出しを伴わない返答で早期に停止することもなかった。形式の失敗は予算が尽きるまで繰り返され、そのために読み違いが見えなくなっていた。

この本のすべての実行は、四つの数で記述される。ステップ数はモデル呼び出しの回数を数え、ツール呼び出し数は不正な形式のものも含めてリクエストを数える。二つのトークン数は、実行中のすべてのリクエストにわたって合計したプロンプトトークン数と、モデルが生成した補完トークン数である。トークンは、記録を作成する時点で、固定されたモデル自身のトークナイザーによって数えられ、その数は記録のマニフェストに保存される。再生では保存された数を読み取り、再度トークン化することはしない。記録された実行では、プロンプトトークン数は 13009、補完トークン数は 2128 である。各ステップが会話の記録全体をあらためて送るため、プロンプトの合計は大きくなる。

実践ルール: ステップ数とツール呼び出し数は、どの実行でも同じ方法で数え、二つの実行を比較できるようにする。実行が予算で終了したときは、プロンプトやモデルを変更する前に、そのエラー行を読む。エラー行を見れば、モデルが同じ誤りを繰り返しているかどうかが分かり、ハーネスのどの部分を調べるべきかが分かる。

この章での決定

  • ツールはハーネス自身のプロセス内で、作業用のコピーに対して実行される。 これはループを示すには十分であるが、防御にはならない。サンドボックスがツールを保持するようになるまで、このコピーは書き込みが行われる場所にすぎない。
  • 停止ツールは、1 つのファイルの新しい全文を受け取る。 これは停止ツールが担える最も単純な変更である。ただし、記録されたモデルは、この変更をパーサが読める形式で送ることに失敗する。別の停止ツールを使うには、新しい記録が必要になる。
  • ステップ予算は 8 である。 この数が小さいのは、この章のタスクに必要なステップが約 4 であるためである。タスクに合った予算であれば、迷走する実行が目立つようになる。
  • 記録された実行は、起きたとおりに示される。 形式の失敗と読み違いは、どちらも本に残してある。合格するように編集した記録は、実在しないモデルを示すことになるからである。記録の生の応答は集計結果の隣に保存してあるので、パーサがそれぞれの応答をどう解釈したかを誰でも確認できる。

実践ルール: これらの決定のいずれかを変更する前に、その変更がこの章の出力する数値に何をもたらすかを確かめる。新しいステップ予算はステップ数を変え、新しい停止ツールは新しい記録を必要とし、サンドボックスはツールが到達できる範囲を変える。変更はその章自身の枠組みの中で行い、結果を信頼する前に、スクリプトによる例と記録による例を再実行する。

この版における本章

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

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

この節を引用する

形式

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

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

このページの内容

全12章中の第1章: モデルにツールとループを与える

  1. エージェントが1つのタスクで行うこと
  2. A loop in about seventy lines
  3. 二つのツールと一つの終了ツール
  4. 終了するのは、作業が完了したときか、予算が尽きたときである
  5. スクリプト化したモデルで実行する
  6. Run it on the recorded model
  7. 何が失敗し、何を数えるか
  8. この章での決定

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