给模型一套无法误用的工具

阅读约需 40分钟 分钟,6节中含5个示例。

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

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

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

读完本章,你将能够为模型提供一套工具:在任何工具运行之前,由运行框架(harness)先检查其参数;你还将能够写出模型可以据以行动的拒绝信息。

智能体的任务是修复 unitcraft,这是一个用于格式化和转换数量的小型 Python 库。本章要讨论的问题恰好出现在它的编辑操作中,因为少一个引号就会让一次编辑失败。智能体在该库的一份临时副本上工作。在第 1 章中,它的首次记录运行因一次调用而中断。这个开源模型是 Qwen3-4B,从其记录中回放。它读取了正确的文件,却把问题误解为要求去掉零,然后把每处改动都写成整个文件,用 Python 的三引号包裹,放在一次 finish 调用的 JSON 里。三引号在 JSON 字符串中不是合法写法,因此这些参数始终无法解析。没有任何工具运行,运行在达到步数上限时结束。

本章比较两套工具。工具集 v1 是录制任务集记录时所用的七个工具:list_files、read_file、run_tests、write_file、edit_file、ask_user 和 finish。工具集 v2 的工具相同,描述语句和系统提示也相同,只有三处改动:严格的参数模型、在每条拒绝信息中写明错误类型,以及编辑失败时给出最接近的行的错误信息。

误解出自模型本身,任何工具设计都无法纠正。这些格式错误的调用有两个方面。其一,调用的形态是测试框架无法读取的;其二,改动本身放在一个字符串里,模型必须对它正确转义。本章对这两方面都做处理。每个工具都有一份参数模式,测试框架在运行前先检查;拒绝信息则以模型可以据以行动的文本返回给它。在工具集 v1 中,改动也不再经由 finish 传递:模型用 edit_file 和 write_file 修改自己的副本,而 finish 只携带一份摘要。小改动自有其引号方面的麻烦,最后一节会讨论。

模式规定了什么是允许的

模型根据别人告知它的工具信息来编写工具调用,而测试框架要拒绝一个错误的调用,只能把它与同一份描述进行核对。工具集中的每个工具都有三个部分:名称、一句话描述,以及参数模型。参数模型是一个小型的 pydantic 类,列出该工具接受的字段。测试框架在请求中附带每个工具的模式,而模式由这个类生成,因此模型读到的文字和测试框架执行的检查出自同一处。

这个唯一的来源之所以重要,是因为模式包含的不只是字段名。可以把它看作模型在发出调用之前要填写的表格。表格的每一行都给出一个字段名,说明需要哪种类型的答案,还可以说明答案的大小范围。表格可以引导填写者,却不能阻止错误的答案被写下来。到这一步,表格就不再能充当防护,测试框架必须完成表格无法完成的检查。

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 验证规范把 default 视为一种注解:它提供一个值,但不检查任何内容。测试框架是否填入默认值由测试框架自行决定,仅凭模式并不能使其发生。

模型所读内容的另一半是每个工具的那句话。这些句子在每个请求中都与各自的模式并排出现,因此下面的示例把它们打印出来。有两行值得核对:一行说明第 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 章的工具在本工具集中保留了各自的句子,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.

模型能读懂的错误

只有当模型能读懂调用错在哪里时,拒绝才有帮助。一次运行如果在第一个错误调用处就停止,模型什么也学不到;而如果测试框架悄悄丢弃错误调用,模型在下一步就只能靠猜。因此,每次拒绝都作为工具结果的文本返回,与其他任何结果是同一类文本,模型在下一步中会读到它。

错误调用会在不同的环节失败,测试框架必须按顺序逐项检查。在某一步中收到的拒绝,就是记录中多出的一条工具结果。运行继续,模型的下一次回复可以对它作出反应,步数上限依然有效。所以,一次错误调用会让模型多花一步,而拒绝的文本决定这一步是否花得有价值。

本示例中的每个错误调用,错误的方式各不相同。它们先通过工具集 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

第一种失败发生在查阅任何模式(schema)之前。JSON 被截断的那个调用永远到不了工具,因为回复解析器无法读取它。它的原因是 not JSON,后面跟着 JSON 解析器自己的报错信息。该信息来自 Python 标准库,而不是 pydantic,并且这个调用没有可指明的字段,因为它的参数根本没有被解析。

其余的调用都能解析并到达模式,每个调用得到各自的拒绝。read_file 的调用没有给出参数,因 path 被拒绝,错误类型为 missing。工具不接受的键,这里是 lines,即使调用的其余部分没有问题,也会因 extra_forbidden 被拒绝。以数字形式给出的 path 因 string_type 被拒绝。每次拒绝都会指明字段、错误类型和报错信息,因此模型的下一次调用只需改动出错的那一处。字段使用模式自身的措辞来命名,即 path,而不是 Python 类的名称,因为模型处理的正是这些措辞。

工具集 v1 使用相同的字段,但不启用严格模式,所以对于调用 2 到 4,它拒绝的是同样的调用,字段和报错信息也相同,正如输出中工具集 v1 的各行所示。它的文本省略了错误类型,而写明该类型,正是工具集 v2 对这些拒绝所做的唯一补充。比较调用 2 中缺失的 path:工具集 v1 给出 error: invalid arguments: path: Field required,工具集 v2 给出 error: invalid arguments: path (missing): Field required。

这些拒绝各自要求不同的修正,而文本就是告诉模型该做哪一种修正的依据。缺少字段,要求补上该字段;多出键,要求删除该键;类型错误,要求按模式规定的方式写出该值。如果模型得到的只是“参数无效”,就必须猜测这三种修正里该做哪一种,而每次猜测都要花一步。写明字段和错误类型,就把猜测变成了对调用的一次修改。

工作准则: 把每次拒绝作为工具结果返回,其中写明字段、错误类型和报错信息。不要因为一次错误调用而结束运行;唯一的例外是 第 2 章 中的停止规则,即规则已开启,并且同一个错误调用不断重复出现时。解析器无法读取的调用,其拒绝内容为解析器给出的原因,并且不会对它运行任何工具。

每个工具一个名称

名称是一次调用交给运行框架(harness)的第一项内容,运行框架在读取任何参数之前就可以检查它。模型若虚构了一个工具,或记错了某个工具的名称,发出的调用就没有任何实物与之对应,运行框架必须用模型能够利用的措辞指出这一点。

上一节示例中的最后一次调用请求的是 read_files,工具集中并没有这个工具,所带的 path 却适用于 read_file。它得到的拒绝信息列出了工具集中实际存在的名称,因此模型的下一次调用可以从中选用一个。工具集 v2 的拒绝信息以 invalid arguments 开头,原因是运行框架把名称当作调用的一个字段来检查,而这个字段名为 name。运行框架根据工具集中各工具的名称构造一个 Literal 类型,并用它检查名称。错误的名称会以 literal_error 的形式失败,消息中给出允许使用的名称。工具集 v1 对同一次调用给出的文本更短:error: unknown tool: read_files。它只说明该工具未知,却没有说明哪些工具是已知的。

名称位于各工具的参数之外,因此没有任何参数模式(schema)能够阻止错误的名称。检查发生在运行框架查找名称之时,这就是检查应当放在运行框架中,而不能只写在提示词里的原因。

运行框架不做猜测,这一区别很重要。与真实工具相近的名称,例如用 read_files 代替 read_file,依然会被拒绝,因为运行框架按精确名称分派,猜测可能会运行一个模型并未请求的工具。起帮助作用的是拒绝信息:它列出实际存在的工具,由模型重新选择。

名称对停止工具最为重要。当 finish 或 ask_user 调用被执行,且其结果带有结束标志时,循环就会结束运行。拼写错误的停止工具不带这样的标志。它与其他未知名称一样被拒绝,运行会继续,直到步数上限或某条停止规则将其终止。拒绝 read_files 的那个精确名称检查,也正是使 finish 表示 finish 的原因。模型若不断请求工具集中没有的工具,就属于第 2 章的停止规则所要应对的那类运行。

工作准则: 允许使用的名称应取自循环实际运行的工具,不要取自与之并列维护的清单,并将这些名称写入每一条针对未知名称的拒绝信息。工具集中没有的名称会得到拒绝,提示词不对它作出承诺。只有通过运行框架维护的显式别名映射才接受别名,绝不通过猜测来接受。

指出最接近行的编辑错误信息

一次编辑会指明它要替换的文本。工具集 v1 的 edit_file 工具会修改文件中 old 出现的那一处位置,而当 old 不存在或出现多次时,它会拒绝这次调用。因此,一次编辑可能仅仅因为几个引用字符不对而失败。模型根据自己对文件的读取来复制代码时,可能会把这些引号写错,这时编辑就会被拒绝。

第 1 章中该改动的第一个版本把整个文件放进一个 JSON 字符串,所以文件中的每个引号和换行都必须在模型的回复中转义。编辑则小得多。它只复制发生变化的那几行,需要写对的字符因此更少。不过转义问题并没有消失,因为复制的内容仍然必须与文件完全一致。

任务集记录显示了复制出错的情形。记录中保存的是同一个开放模型 Qwen3-4B-Instruct-2507 在二十个任务上的回复,运行时使用工具集 v1、步数上限 16 以及温度 0;模型的设置见第 1 章。在 T-01 的第三次回复中,模型把几行代码复制到 old 中,漏掉了两个 f-string 周围的引号,也漏掉了 separator = "." 的结尾引号。而文件中是有这些引号的。下面先打印所存的 old 文本,再把这一次回复分别用两个工具集重放,差别便显现出来:

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 的文本给模型留下了一个要多花的步骤:它必须调用 read_file 才能看到本应复制的那些行,而下一次回复仍可能把它们复制错。工具集 v2 的文本把这些行直接放进拒绝信息,模型可以立即重试。打印结果显示的是测试框架返回的文本,而不是下一次编辑是否成功。要知道后者需要实际运行,第 10 章统计了这些运行。本章不报告这两类计数。

工作准则: 当编辑所用的文本不在文件中时,返回文件中最接近的几行及其行号,并说明下一步该做什么。不要只返回文本缺失,因为那会让模型去猜哪个引号写错了。如果文件短到可以整个返回,则可以改为返回带行号的整个文件。

本章的决定

模式(schema)和错误文本都是模型输入的一部分。改动一句话、一个字段或一条错误文本,就会改变请求。本书中的回放会把每个请求与已记录的请求比对,两者不同时便拒绝应答。因此,工具集总是连同它的录制记录一起更改,而不会原地修改。

本章的约定会延续到后面。模型适配器对所有适配器使用这些相同的模式。上下文预算把每次拒绝都当作一条工具结果来计数,与其他工具结果相同。测试智能体以计数的方式比较两个框架版本。它们的工具集就是这两个;使用工具集 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。

引用本节

格式

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

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

本页内容

第 3 章,共 12 章: 给模型一套无法误用的工具

  1. 模式规定了什么是允许的
  2. Lax by default, strict on purpose
  3. 模型能读懂的错误
  4. 每个工具一个名称
  5. 指出最接近行的编辑错误信息
  6. 本章的决定

返回顶部全部章节