モデルが誤用できないツールを与える

読了まで約37 分分、6 節 節の 5 例 例。

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

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

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

この章を終えると、ツールが実行される前にハーネスが引数を検査するツールをモデルに与えられるようになり、モデルが対処できる拒否メッセージを書けるようになる。

エージェントの仕事は、量を整形・変換する小さな Python ライブラリであるunitcraftを修正することである。この章の問題は編集の場面に表れる。引用符が1つ欠けるだけで編集が失敗するからである。エージェントはライブラリの作業用コピーで作業する。第1章では、最初に記録された実行が1回の呼び出しで失敗した。録画から再生したオープンモデルの Qwen3-4B は、正しいファイルを読んだ。しかし、課題を「ゼロを削除せよ」という依頼だと誤読した。そのうえで、各変更をファイル全体として、Python の三重引用符を使い、finish呼び出しの JSON の中に書いた。三重引用符は JSON 文字列の中では有効でないため、それらの引数は一度も解析されなかった。ツールは1つも実行されず、実行はステップ上限で終了した。

この章では2つのツールセットを比較する。ツールセット v1 は、タスクセットの録画に使われた7つのツールである。すなわちlist_files、read_file、run_tests、write_file、edit_file、ask_user、finishである。ツールセット v2 は、同じツールを同じ文言と同じシステムプロンプトで備え、3つの変更を加えたものである。厳密な引数モデル、各拒否メッセージに示すエラーの種類、編集に失敗したときの最も近い行のエラーである。

誤読はモデル自身のものであり、ツールの設計では直せない。不正な呼び出しには2つの要素がある。1つは、ハーネスが読み取れない形の呼び出しだったことである。もう1つは、変更がモデルの正しくエスケープすべき文字列の中を通って運ばれたことである。この章は両方を扱う。各ツールには、実行前にハーネスが検査する引数スキーマを与え、拒否はモデルが対処できるテキストとして返す。ツールセット v1 では、変更はfinishからも離れる。モデルはedit_fileとwrite_fileで自分のコピーを編集し、finishは要約だけを運ぶ。小さな編集には固有の引用符の問題があり、これは最後の節で取り上げる。

スキーマは許される内容を定める

モデルは、ツールについて与えられた情報をもとにツール呼び出しを書く。ハーネスが不正な呼び出しを拒否できるのは、同じ記述に照らして検査する場合に限られる。セット内の各ツールは、名前、1文の説明、引数モデルという3つの部分からなる。引数モデルは、そのツールが受け取るフィールドを列挙する小さな pydantic のクラスである。ハーネスは各ツールのスキーマをリクエストとともに送る。スキーマはこのクラスから生成されるので、モデルが読むテキストとハーネスが行う検査は、1つの場所に由来する。

この単一の場所が重要なのは、スキーマがフィールド名以上のものを保持しているからである。スキーマは、モデルが呼び出しの前に記入する書式のようなものと考えられる。書式の各行は、フィールドの名前を示し、どのような種類の答えを求めるかを述べ、答えの大きさの範囲を示すこともある。書式は記入者を導くことはできるが、誤った答えが書かれるのを止めることはできない。ここで書式は防御としては役に立たなくなり、書式にできない検査はハーネスが行わなければならない。

pydantic は、各フィールドの型、説明、デフォルト値、範囲をスキーマに書き出す。この事例のツールが受け取るのはパスと文字列だけなので、本節では別の読み取りツールを使う。行数の上限を持つものであり、セット内のどのツールにもこの上限は使われていない。これは教材用のモデルであり、範囲がどのように見えるかを示すために選んだ。そのスキーマを出力すれば、モデルに何が伝えられるかを最も手早く確認できる。読むべき行は、範囲とデフォルト値の行である。

schema-from-model.py Python 3.12.15 · pydantic 2.14.3 合格
"""The JSON schema pydantic makes for a read with a line limit: its bounds, its default and the descriptions themodel reads before it calls. The point of the prose rests on the max_lines lines: the bounds, the default and thedescription."""from lib.tools import LinesArgsschema = LinesArgs.model_json_schema()limit = schema["properties"]["max_lines"]  # the schema of the one field with a boundprint("required:", ", ".join(schema["required"]))print("max_lines minimum:", limit["minimum"])print("max_lines maximum:", limit["maximum"])print("max_lines default:", limit["default"])print("max_lines description:", limit["description"])print("path description:", schema["properties"]["path"]["description"])# LinesArgs has no extra="forbid", so its schema says nothing about other keys. The tool classes do forbid them.assert "additionalProperties" not in schema
出力python schema-from-model.py
required: path
max_lines minimum: 1
max_lines maximum: 1000
max_lines default: 200
max_lines description: The most lines to return, from 1 to 1000; the default is 200.
path description: A file path relative to the case root, with / as the separator.

出力は、モデルが読むとおりに読む。必須の引数は path だけである。max_lines は 1 から 1000 までの値を取る。

デフォルト値は、そのフィールドのもう一方の半分である。モデルが max_lines を省略すると、値は 200 になる。これらの範囲は、それを検査するコードの中だけでなく、モデルが読むスキーマの中にもある。フィールド自身の説明も、同じことを言葉で述べている。「The most lines to return, from 1 to 1000; the default is 200.」

スキーマ内のデフォルト値は、規則ではなく注記である。JSON Schema validation specification は default を注釈として扱う。注釈は値を与えるだけで、何も検査しない。ハーネスがデフォルト値を補うかどうかはハーネスの選択であり、スキーマだけではそれは実現しない。

モデルが読むもう一方の部分は、各ツールの1文である。これらの文はあらゆるリクエストでスキーマと並んで置かれるため、以下の例ではそれらを出力する。確認する価値のある行は2つある。1つは、第1章のどのツールがこのセットと同じ文を共有しているかを示す行、もう1つは finish が共有していないことを示す行である。

tool-descriptions.py Python 3.12.15 · pydantic 2.14.3 合格
"""The one-sentence description of each tool in the v1 set, the text the model reads beside each schema. The pointrests on the last two printed lines: which chapter 1 tools carry the same sentence in v1, and that finish does not."""from lib.tools import CH1, V1print("v1 tools:", len(V1.tools))for tool in V1.tools:    print(f"v1 {tool.name}: {tool.description}")# The chapter 1 tools whose sentence is exactly the one v1 gives the same tool.shared = [t.name for t in CH1.tools if V1.get(t.name) and V1.get(t.name).description == t.description]print("ch1 tools with the same sentence in v1:", ", ".join(shared))print("ch1 finish has the same sentence in v1:", V1.get("finish").description == CH1.get("finish").description)assert shared == ["read_file", "run_tests"]
出力python tool-descriptions.py
v1 tools: 7
v1 list_files: List the files in the case, by their case-relative paths.
v1 read_file: Read one file in the case, given by its case-relative path.
v1 run_tests: Run the visible test suite on your copy and return the counts of passed and failed tests.
v1 write_file: Create a new file in your copy with this text; it is refused when the file already exists.
v1 edit_file: Replace the one occurrence of old text with new text in a file in your copy.
v1 ask_user: Ask the person a question and end the run; use it when the task needs their decision.
v1 finish: End the run with a summary of what you changed and why.
ch1 tools with the same sentence in v1: read_file, run_tests
ch1 finish has the same sentence in v1: False

ツールセット v1 には 7 個のツールがあり、それぞれに1文が付いている。出力から、第1章のツールはこのセットでも文を保っていることが確認でき、それは read_file, run_tests に当てはまる。変わったのは finish であり、その役割が変わったからである。文は、ツールが何のためにあるかを述べる。ハーネスが検査しない規則を、文に担わせることはできない。

実践ルール: 範囲、型、デフォルト値は、ハーネスが検査する引数モデルの中に書き、各フィールドにはモデルが読める説明を付ける。ツールの文は、そのツールが何のためにあるかにとどめる。文の中にしかない規則は、ハーネスが決して強制しないヒントにすぎない。

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

Lax by default, strict on purpose

A model asked for a number may write "50", and a flag may arrive as true. The harness has to decide whether to take those values as meant, and pydantic answers by mode. In its default, lax mode, a value is converted when the conversion is clear and refused when it is not. In strict mode, a value must already have the declared type. The tool set v1 argument models use the default, and tool set v2's copies of them are strict.

The schema is a hint, not a guarantee. OpenAI's function-calling guide describes a setting also called strict, which constrains what the model generates: with it on, calls follow the schema reliably, and without it they are best effort. Pydantic's strict mode is a different mechanism. It checks a call after it arrives and does not constrain generation. This harness does not constrain what the model writes while it writes it, so every call is checked after it arrives, whatever the schema said.

A model that writes "50" for a line limit most likely means fifty, so refusing it outright would waste a step on a call that was nearly right. A model that sends true for the same field has meant something else entirely, and converting it to a number would hide that. Neither answer is right for every field, so the mode has to be chosen for each argument model that holds those fields. This chapter sets it on each model and not on each field.

The next example sends the same values through both modes. Compare what each mode does with each value.

lax-and-strict.py Python 3.12.15 · pydantic 2.14.3 合格
"""Pydantic's default (lax) mode and strict mode, given the same values for an int field: lax takes the string "50"and the bool True as ints, strict refuses both, and each refusal names its error type. The point of the prose restson the last lines: on a string field the two modes refuse the same values, and the two tool sets' schemas differonly in their titles."""from lib.tools import LinesArgs, PathArg, StrictLinesArgs, StrictPathArg, V1, V2from pydantic import ValidationErrorvalues = [("str 50", "50"), ("int 50", 50), ("bool True", True), ("float 2.0", 2.0), ("float 2.5", 2.5)]outcomes = {}for label, value in values:    for mode, model in (("lax", LinesArgs), ("strict", StrictLinesArgs)):        try:            model.model_validate({"path": "unitcraft/format.py", "max_lines": value})            outcomes[mode, label] = "accepted"        except ValidationError as exc:            outcomes[mode, label] = exc.errors()[0]["type"]  # the first error's type, which a refusal names        print(f"{mode}, max_lines {label}: {outcomes[mode, label]}")assert outcomes["lax", "str 50"] == "accepted" and outcomes["strict", "str 50"] == "int_type"# The case's tools take only strings. On a string field the modes agree, because lax mode does not turn a number,# a flag or nothing into a string.for label, value in [("str a.py", "a.py"), ("int 3", 3), ("float 3.5", 3.5), ("bool True", True), ("None", None),                     ("list", []), ("object", {})]:    results = {}    for mode, model in (("lax", PathArg), ("strict", StrictPathArg)):        try:            model.model_validate({"path": value})            results[mode] = "accepted"        except ValidationError as exc:            results[mode] = exc.errors()[0]["type"]  # the first error's type, which a refusal names        print(f"{mode}, path {label}: {results[mode]}")    assert results["lax"] == results["strict"]def untitled(node):    """A schema with its titles removed, so the two tool sets can be compared on everything else."""    if isinstance(node, dict):        return {key: untitled(value) for key, value in node.items() if key != "title"}    if isinstance(node, list):        return [untitled(item) for item in node]    return nodesame = [untitled(a.schema()) == untitled(b.schema()) for a, b in zip(V1.tools, V2.tools)]print("v1 and v2 schemas differ before titles are removed:", any(a.schema() != b.schema() for a, b in zip(V1.tools, V2.tools)))print("v1 and v2 schemas equal once titles are removed:", all(same))assert all(same)
出力python lax-and-strict.py
lax, max_lines str 50: accepted
strict, max_lines str 50: int_type
lax, max_lines int 50: accepted
strict, max_lines int 50: accepted
lax, max_lines bool True: accepted
strict, max_lines bool True: int_type
lax, max_lines float 2.0: accepted
strict, max_lines float 2.0: int_type
lax, max_lines float 2.5: int_from_float
strict, max_lines float 2.5: int_type
lax, path str a.py: accepted
strict, path str a.py: accepted
lax, path int 3: string_type
strict, path int 3: string_type
lax, path float 3.5: string_type
strict, path float 3.5: string_type
lax, path bool True: string_type
strict, path bool True: string_type
lax, path None: string_type
strict, path None: string_type
lax, path list: string_type
strict, path list: string_type
lax, path object: string_type
strict, path object: string_type
v1 and v2 schemas differ before titles are removed: True
v1 and v2 schemas equal once titles are removed: True

What strict mode changes is the conversions, and nothing else the example shows. A value of the declared type passes in both modes. The string "50" is accepted in lax mode and refused in strict mode, with int_type. A flag is treated the same way: True is accepted in lax mode, and strict mode refuses it with int_type. Lax mode also takes 2.0 for an int, because nothing is lost in the conversion. It refuses 2.5, because the fraction would be lost, and its refusal reads int_from_float.

The tool set v2 copies are written as subclasses of the tool set v1 classes. Each one keeps every field of its parent and changes only the mode, so tool set v1 keeps the classes it had and prints what it printed before. Adding a setting beside the old one, rather than in place of it, lets a tool set change without changing what an earlier run printed. The mode does not appear in the schema the model reads. The example shows that the schemas of the two tool sets differ only in each class's title, StrictPathArg where tool set v1 has PathArg. The class name is the one thing a model could see of strict mode.

Strict mode is not free of cost. It turns a usable call into a refusal, and the model then has to try again. What it buys is that a count the tool receives is a count, and that a flag is never read as a number by accident. Whether that trade is worth it depends on the field, and on the case's tools it changes nothing. Every argument of the case's tools is a string. On a string field, lax and strict refuse the same values. The last lines of the printout try a string, a number, a float, a flag, nothing, a list and an object, and the number, for one, is refused in both modes with string_type. So tool set v2's strict setting changes no refusal that a JSON call can cause on these tools. It guards a field that a later tool might add as a number. Only the bounded read converts, and no tool uses it.

Working rule: Use lax mode where a conversion is what the model meant, and strict mode where a quiet conversion would change what the tool does. Test each model with a value of the wrong type before you rely on it, and read the error type the refusal names, since that is what the model will see.

モデルが読めるエラー

拒否が役に立つのは、モデルが自分の呼び出しのどこが誤っていたかを読み取れる場合に限られる。最初の不正な呼び出しで止まる実行は、モデルに何も教えない。不正な呼び出しを黙って捨てるハーネスは、モデルに次の一手を推測させることになる。そこで、各拒否はツール結果のテキストとして返す。これは他の結果と同じ種類のテキストであり、モデルは次のステップでそれを読む。

不正な呼び出しは異なる時点で失敗するため、ハーネスはそれらを順に検査しなければならない。ステップの途中で届く拒否は、トランスクリプトに加わる 1 件のツール結果にすぎない。実行は続き、モデルの次の返答はその拒否に反応でき、ステップ数の上限も引き続き適用される。したがって、不正な呼び出しはモデルに 1 ステップを費やさせ、そのステップが有益に使われたかどうかは拒否の内容で決まる。

この例の不正な呼び出しは、それぞれ異なる点で誤っている。これらの呼び出しをツールセット v2、続いてツールセット v1 に通す。出力には、各セットが返す内容が示される。

bad-arguments-handed-back.py Python 3.12.15 · pydantic 2.14.3 合格
"""Five bad calls, sent by a ScriptedModel. Each parsed call is run through the v2 tool set and through v1, and eachrefusal is the text the model reads on its next step. The point of the prose rests on the v2 lines and the v1 linesfor calls 2 to 5. A call whose JSON is cut off never reaches a schema, so neither set runs it."""import shutilfrom lib.case import scratch_copyfrom lib.models import ScriptedModelfrom lib.tools import V1, V2, WorkspaceCALLS = [    '<tool_call>{"name": "read_file", "arguments": {"path": "unitcraft/format.py"</tool_call>',    '<tool_call>{"name": "read_file", "arguments": {}}</tool_call>',    '<tool_call>{"name": "read_file", "arguments": {"path": "unitcraft/format.py", "lines": 5}}</tool_call>',    '<tool_call>{"name": "read_file", "arguments": {"path": 3}}</tool_call>',    '<tool_call>{"name": "read_files", "arguments": {"path": "unitcraft/format.py"}}</tool_call>',]scratch = scratch_copy()ws = Workspace(scratch)model = ScriptedModel(CALLS)for number in range(1, len(CALLS) + 1):    reply = model.reply([], V2.schemas())  # the schemas are sent with each request; a scripted model ignores them    if reply.malformed:  # the reply parser's reason for a call whose JSON it cannot read        print(f"call {number}, not run, the JSON is not read: {reply.malformed[0]}")        continue    call = reply.tool_calls[0]    print(f"call {number}, {call['name']}, v2: {V2.call(ws, call['name'], call['arguments']).text}")    print(f"call {number}, {call['name']}, v1: {V1.call(ws, call['name'], call['arguments']).text}")shutil.rmtree(scratch, ignore_errors=True)
出力python bad-arguments-handed-back.py
call 1, not run, the JSON is not read: not JSON (Expecting ',' delimiter)
call 2, read_file, v2: error: invalid arguments: path (missing): Field required
call 2, read_file, v1: error: invalid arguments: path: Field required
call 3, read_file, v2: error: invalid arguments: lines (extra_forbidden): Extra inputs are not permitted
call 3, read_file, v1: error: invalid arguments: lines: Extra inputs are not permitted
call 4, read_file, v2: error: invalid arguments: path (string_type): Input should be a valid string
call 4, read_file, v1: error: invalid arguments: path: Input should be a valid string
call 5, read_files, v2: error: invalid arguments: name (literal_error): Input should be 'list_files', 'read_file', 'run_tests', 'write_file', 'edit_file', 'ask_user' or 'finish'
call 5, read_files, v1: error: unknown tool: read_files

最初の失敗は、スキーマが参照される前に起こる。JSON が途中で切れている呼び出しは、返答パーサがそれを読めないため、ツールに届かない。その理由は not JSON であり、JSON パーサ自身のメッセージが続く。このメッセージは pydantic ではなく Python の標準ライブラリが出したものである。また、この呼び出しは引数が解析されていないので、名前を挙げるべきフィールドがない。

他の呼び出しは解析を通ってスキーマに到達し、それぞれ固有の拒否を受ける。read_file への呼び出しで path がないものは、エラー型 missing で拒否される。ツールが受け付けないキー、ここでは lines は、呼び出しの残りが正しくても extra_forbidden として拒否される。数値で渡された path は string_type として拒否される。どの拒否もフィールド、エラー型、メッセージを挙げるので、モデルは次の呼び出しで誤っていた 1 点だけを直せばよい。フィールドは Python のクラス名ではなく、スキーマ自身の言葉である path で示す。モデルが扱っているのはその言葉だからである。

ツールセット v1 は同じフィールドを厳格モードなしで使うため、呼び出し 2 から 4 については、同じ呼び出しを同じフィールドとメッセージで拒否する。これは出力のツールセット v1 の行に示されるとおりである。そのテキストにはエラー型がなく、この型を示すことが、ツールセット v2 がこれらの拒否に加える唯一の追加である。呼び出し 2 で path が欠けている場合を比べてみよう。ツールセット v1 は error: invalid arguments: path: Field required と返し、ツールセット v2 は error: invalid arguments: path (missing): Field required と返す。

これらの拒否は、それぞれ異なる修正を求めており、モデルにどの修正かを伝えるのはテキストである。フィールドの欠落は、そのフィールドの追加を求める。余分なキーは削除を求め、型の誤りはスキーマが指定する形で値を書くことを求める。「invalid arguments」としか受け取れないモデルは、この 3 つのうちどれを果たすべきかを推測しなければならず、推測は 1 ステップを消費する。フィールドとエラー型を示せば、推測は呼び出しに対する 1 回の編集に変わる。

実践ルール: 各拒否は、フィールド、エラー型、メッセージを挙げたツール結果として返す。不正な呼び出しで実行を終了してはならない。ただし、第 2 章の停止ルールが有効で、同じ不正な呼び出しが繰り返される場合は例外とする。パーサが読めない呼び出しには、パーサの理由を拒否として返し、その呼び出しではツールを実行しない。

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

One name per tool

The name is the first thing a call gives the harness, and the harness can check it before it reads any argument. A model that invents a tool, or remembers one wrongly, makes a call with nothing behind it, and the harness has to say so in terms the model can use.

The last call in the example from the previous section asks for read_files, a tool the set does not have, with a path that would suit read_file. Its refusal lists the names the set does have, so the model's next call can use one of them. The tool set v2 refusal opens with invalid arguments, because the harness checks the name as a field of the call, and the field is called name. The harness builds a Literal type from the names of the tools in the set and checks the name against it. A wrong name fails as literal_error, and the message gives the allowed names. Tool set v1 gives a shorter text for the same call: error: unknown tool: read_files. It says the tool is unknown, and nothing about which tools are.

The name sits outside each tool's parameters, so no parameters schema prevents a wrong name. The check happens when the harness looks the name up, which is why it belongs in the harness and not only in the prompt.

The harness does not guess, and that difference matters. A name close to a real tool, such as read_files for read_file, is still refused, because the harness dispatches on exact names and a guess would run a tool the model did not ask for. The refusal does the helping: it lists what exists, and the model chooses again.

The name matters most for the stop tool. The loop ends a run when a finish or ask_user call runs and its result carries the end flag. A misspelled stop tool carries no such flag. It is refused like any other unknown name, and the run goes on until the step cap or a stop rule ends it. The same exact-name check that refuses read_files is what makes finish mean finish. A model that keeps asking for a tool the set lacks is the kind of run the stop rules in chapter 2 are for.

Working rule: Take the allowed names from the tools the loop actually runs, never from a list kept beside them, and put them in every refusal for an unknown name. A name the set lacks gets a refusal, and the prompt does not promise it. Accept an alias only through an explicit alias map that the harness keeps, never by a guess.

最も近い行を示す編集エラー

編集は、置き換える対象のテキストを名指しする。ツールセット v1 の edit_file ツールは、ファイル内で old が現れる1か所を書き換える。old が存在しない場合や、複数回現れる場合には、呼び出しを拒否する。したがって、編集は引用した数文字の違いだけで失敗しうる。モデルが自分で読み取ったファイルの内容からコードを写すと、その引用符を誤ることがあり、その場合は編集が拒否される。

1章で扱った変更の最初のバージョンでは、ファイル全体を1つの JSON 文字列に入れていた。そのため、ファイル内のすべての引用符と改行を、モデルの返答の中でエスケープする必要があった。編集はそれより小さい。変更する行だけを写すので、誤りうる文字数は少ない。ただし、写したものがファイルと完全に一致しなければならないため、エスケープの問題がなくなるわけではない。

タスクセットの記録には、写しの誤りが残っている。この記録は、同じオープンモデルである Qwen3-4B-Instruct-2507 の返答を20個のタスクにわたって保存したものであり、ツールセット v1、ステップ上限 16、温度 0 で実行した。モデルの設定は1章で説明している。T-01 の3回目の返答で、モデルは数行を old に写したが、2つの f-string の引用符と、separator = "." の閉じ引用符を落とした。ファイルにはそれらの引用符がある。保存された old のテキストを先に表示し、その1つの返答を両方のツールセットで再生するので、違いがわかる。

edit-error-nearest-lines.py Python 3.12.15 · pydantic 2.14.3 合格
"""The edit_file call from step 3 of the task-set recording's T-01 run, read from its stored reply. Its old text dropsthe quotes around the f-strings and the closing quote of separator = "."; the printed old text shows it. The point ofthe prose rests on the two results: the v2 error names the nearest lines of the file, with their quotes, and the v1error only says the text is missing."""import jsonimport shutilfrom lib.case import DATA, scratch_copyfrom lib.models import ScriptedModelfrom lib.tools import V1, V2, Workspacerows = [json.loads(line) for line in (DATA / "recorded" / "task-set" / "replies.jsonl").read_text().splitlines()]stored = next(row for row in rows if row["run"] == "T-01" and row["step"] == 3)  # steps count from 1call = ScriptedModel([stored["text"]]).reply([], V2.schemas()).tool_calls[0]  # the recorded reply, read backscratch = scratch_copy()ws = Workspace(scratch)print("call:", call["name"], call["arguments"]["path"])print("old text:")print(call["arguments"]["old"])print("v1 result:", V1.call(ws, call["name"], call["arguments"]).text)v2 = V2.call(ws, call["name"], call["arguments"]).textprint("v2 result:")print(v2)assert 'text = f"{whole}{separator}{frac}"' in v2shutil.rmtree(scratch, ignore_errors=True)
出力python edit-error-nearest-lines.py
call: edit_file unitcraft/format.py
old text:
    frac = frac.rstrip("0")
    separator = ".

    text = f{whole}{separator}{frac}

    return f{sign}{text} {q.unit}
v1 result: error: old text not found in unitcraft/format.py
v2 result:
error: old text not found in unitcraft/format.py. The nearest lines of the file, numbered as in the file:
   18 |     frac = frac.rstrip("0")
   19 |     separator = "."
   20 |
   21 |     text = f"{whole}{separator}{frac}"
   22 |
   23 |     return f"{sign}{text} {q.unit}"
Copy old from those lines exactly, quotes included, and call edit_file again.

ツールセット v1 のテキストは、古いテキストがファイルにないことと、そのファイル名を述べるだけである。ツールセット v2 のテキストはそれ以上のことを行う。ファイルの最も近い行を、ファイルの行番号のまま、引用符も元のままで示し、最後に次に行うことを述べる。それは、それらの行から old を引用符も含めて写し、もう一度呼び出すことである。拒否に含めるのはファイル全体ではなく、行のウィンドウである。ファイル全体を返せばモデルの疑問には答えられるが、多くのトークンを要する。さらに、すべてのツール結果は、5章で数えるように、タスクを保持している同じコンテキストの消費になる。行は類似度で見つける。ハーネスは old と同じ長さのウィンドウをファイルの先頭から末尾へずらし、最もよく一致するウィンドウを残す。同点の場合は先のウィンドウを選ぶので、実行のたびに同じ答えになる。ここでは、最良のウィンドウにモデルが写そうとしていた f-string の行が引用符つきで含まれており、例はその行がエラーに現れることを検証している。

モデルが失敗した同じ編集を繰り返す場合は、2章の停止ルールが有効になっていれば、実行はそこで終了する。停止ルールは既定では無効であり、タスクセットの記録では有効にしていない。最も近い行は、そのような繰り返しを起こりにくくするためのものである。ツールセット v1 のテキストでは、モデルが使うことになる余分なステップがもう1つ生じる。写すべきだった行を見るために read_file を呼び出す必要があり、その次の返答でもそれらを誤って写すことがありうる。ツールセット v2 のテキストはそれらの行を拒否そのものに含めるので、モデルはすぐにやり直せる。出力が示すのはハーネスが返すテキストであり、次の編集が成功するかどうかではない。それには実行が必要であり、実行の数は10章で数える。この章では、どちらの数も報告しない。

実践ルール: 編集のテキストがファイルにないときは、ファイルの最も近い行を行番号つきで返し、次に行うことを述べる。テキストがないとだけ返してはならない。それではどの引用符が誤りなのかをモデルが推測することになる。全体を返せるほど短いファイルであれば、その代わりに番号つきで全体を返してもよい。

この章での決定事項

スキーマとエラーテキストは、モデルへの入力の一部である。文、フィールド、エラーテキストのいずれかを変更すると、リクエストが変わる。本書のリプレイは、各リクエストを記録済みのリクエストと比較し、両者が異なる場合は応答を拒否する。したがって、ツールセットは記録とともに変更するものであり、その場で書き換えてはならない。

この章での約束は、以降の章にも引き継がれる。モデルアダプタは、すべてのアダプタでこれと同じスキーマを使う。コンテキスト予算は、各拒否を他のツール結果と同じく1件のツール結果として数える。エージェントのテストは、2つのハーネスのバージョンを件数で比較する。比較される2つのハーネスのツールセットは、これらの2つである。ツールセット v2 のバージョンには、第10章に挙げられている他の変更も加わる。

決定事項は次のとおりである。

  • ツールセット内のすべての引数モデルは、宣言していないキーを禁止する。そのため、作り出されたキーは無視されず、拒否される。
  • ツールセット v1 の引数モデルは、記録済みのタスクセットの実行がそれを使っていたため、pydantic の寛容なデフォルトのままにする。ツールセット v2 のコピーは厳格である。このケースのツールでは、厳格なコピーは寛容なコピーと同じ JSON 値を拒否するので、厳格さによって拒否が変わることはない。
  • このケースのツールには、文字列でないフィールドはない。モードが現れるのは範囲指定読み取りだけであり、どのツールもそれを使わない。
  • 拒否では、フィールド、そのエラー型、メッセージを示す。ツールセット v1 はエラー型を省く。
  • 許可されるツール名は、ループが実行するツールから得られ、未知の名前はそれらの名前とともに拒否される。
  • ツールセット v1 では、finishが要約を運び、変更はコピー内でedit_fileとwrite_fileによって行われる。
  • 対象のテキストが見つからない編集では、ファイルの最も近い行が行番号付きで返される。これはツールセット v2 の変更である。
  • この章で論じるエラーテキストは、その例が出力するので、変更は実行に現れる前に出力結果に現れる。ケース外のパスなど、ツールコード内のその他の拒否は、ここでは出力されない。

この版における本章

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

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

この節を引用する

形式

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

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

このページの内容

全12章中の第3章: モデルが誤用できないツールを与える

  1. スキーマは許される内容を定める
  2. Lax by default, strict on purpose
  3. モデルが読めるエラー
  4. One name per tool
  5. 最も近い行を示す編集エラー
  6. この章での決定事項

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