모델이 오용할 수 없는 도구를 제공하라
읽는 데 약 30분분 걸린다, 6절에 5개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.2판을 번역한 것이다. 원문 읽기
이 장을 마치면 도구가 실행되기 전에 하네스가 인자를 검사하는 도구를 모델에 제공할 수 있고, 모델이 따라 행동할 수 있는 거부 메시지를 작성할 수 있다.
에이전트가 맡은 일은 수량을 형식화하고 변환하는 작은 Python 라이브러리인 unitcraft를 고치는 것이다. 이 장의 문제는 에이전트의 편집에서 드러나는데, 따옴표 하나가 빠지면 편집 하나가 실패하기 때문이다. 에이전트는 라이브러리의 임시 복사본에서 작업한다. 1장에서 첫 번째로 기록된 실행은 호출 하나에서 깨졌다. 녹화본에서 재생한 공개 모델 Qwen3-4B는 올바른 파일을 읽었지만, 이슈를 0을 없애라는 요구로 잘못 이해했다. 그런 다음 각 변경을 파일 전체로 작성했고, 이를 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은 각 필드의 타입, 설명, 기본값, 범위를 스키마에 기록한다. 이 사례의 도구들은 경로와 문자열만 받으므로, 이 절에서는 세트의 어떤 도구도 쓰지 않는, 줄 수 제한이 있는 다른 읽기 도구를 사용한다. 이것은 범위가 어떤 모습인지 보여 주려고 고른 교육용 모델이다. 스키마를 출력해 보는 것이 모델이 전달받는 내용을 가장 빠르게 확인하는 방법이며, 읽어야 할 줄은 범위와 기본값이다.
1"""The JSON schema pydantic makes for a read with a line limit: its bounds, its default and the descriptions the2model reads before it calls. The point of the prose rests on the max_lines lines: the bounds, the default and the3description."""4from lib.tools import LinesArgs56schema = LinesArgs.model_json_schema()7limit = schema["properties"]["max_lines"] # the schema of the one field with a bound8print("required:", ", ".join(schema["required"]))9print("max_lines minimum:", limit["minimum"])10print("max_lines maximum:", limit["maximum"])11print("max_lines default:", limit["default"])12print("max_lines description:", limit["description"])13print("path description:", schema["properties"]["path"]["description"])14# LinesArgs has no extra="forbid", so its schema says nothing about other keys. The tool classes do forbid them.15assert "additionalProperties" not in schema
python schema-from-model.pyrequired: 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이 공유하지 않음을 알려 주는 줄이다.
1"""The one-sentence description of each tool in the v1 set, the text the model reads beside each schema. The point2rests on the last two printed lines: which chapter 1 tools carry the same sentence in v1, and that finish does not."""3from lib.tools import CH1, V145print("v1 tools:", len(V1.tools))6for tool in V1.tools:7 print(f"v1 {tool.name}: {tool.description}")8# The chapter 1 tools whose sentence is exactly the one v1 gives the same tool.9shared = [t.name for t in CH1.tools if V1.get(t.name) and V1.get(t.name).description == t.description]10print("ch1 tools with the same sentence in v1:", ", ".join(shared))11print("ch1 finish has the same sentence in v1:", V1.get("finish").description == CH1.get("finish").description)12assert shared == ["read_file", "run_tests"]
python tool-descriptions.pyv1 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.
1"""Pydantic's default (lax) mode and strict mode, given the same values for an int field: lax takes the string "50"2and the bool True as ints, strict refuses both, and each refusal names its error type. The point of the prose rests3on the last lines: on a string field the two modes refuse the same values, and the two tool sets' schemas differ4only in their titles."""5from lib.tools import LinesArgs, PathArg, StrictLinesArgs, StrictPathArg, V1, V26from pydantic import ValidationError78values = [("str 50", "50"), ("int 50", 50), ("bool True", True), ("float 2.0", 2.0), ("float 2.5", 2.5)]9outcomes = {}10for label, value in values:11 for mode, model in (("lax", LinesArgs), ("strict", StrictLinesArgs)):12 try:13 model.model_validate({"path": "unitcraft/format.py", "max_lines": value})14 outcomes[mode, label] = "accepted"15 except ValidationError as exc:16 outcomes[mode, label] = exc.errors()[0]["type"] # the first error's type, which a refusal names17 print(f"{mode}, max_lines {label}: {outcomes[mode, label]}")18assert outcomes["lax", "str 50"] == "accepted" and outcomes["strict", "str 50"] == "int_type"1920# The case's tools take only strings. On a string field the modes agree, because lax mode does not turn a number,21# a flag or nothing into a string.22for label, value in [("str a.py", "a.py"), ("int 3", 3), ("float 3.5", 3.5), ("bool True", True), ("None", None),23 ("list", []), ("object", {})]:24 results = {}25 for mode, model in (("lax", PathArg), ("strict", StrictPathArg)):26 try:27 model.model_validate({"path": value})28 results[mode] = "accepted"29 except ValidationError as exc:30 results[mode] = exc.errors()[0]["type"] # the first error's type, which a refusal names31 print(f"{mode}, path {label}: {results[mode]}")32 assert results["lax"] == results["strict"]333435def untitled(node):36 """A schema with its titles removed, so the two tool sets can be compared on everything else."""37 if isinstance(node, dict):38 return {key: untitled(value) for key, value in node.items() if key != "title"}39 if isinstance(node, list):40 return [untitled(item) for item in node]41 return node424344same = [untitled(a.schema()) == untitled(b.schema()) for a, b in zip(V1.tools, V2.tools)]45print("v1 and v2 schemas differ before titles are removed:", any(a.schema() != b.schema() for a, b in zip(V1.tools, V2.tools)))46print("v1 and v2 schemas equal once titles are removed:", all(same))47assert all(same)
python lax-and-strict.pylax, 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을 거치며, 출력은 각 세트가 돌려주는 내용을 보여 준다.
1"""Five bad calls, sent by a ScriptedModel. Each parsed call is run through the v2 tool set and through v1, and each2refusal is the text the model reads on its next step. The point of the prose rests on the v2 lines and the v1 lines3for calls 2 to 5. A call whose JSON is cut off never reaches a schema, so neither set runs it."""4import shutil56from lib.case import scratch_copy7from lib.models import ScriptedModel8from lib.tools import V1, V2, Workspace910CALLS = [11 '<tool_call>{"name": "read_file", "arguments": {"path": "unitcraft/format.py"</tool_call>',12 '<tool_call>{"name": "read_file", "arguments": {}}</tool_call>',13 '<tool_call>{"name": "read_file", "arguments": {"path": "unitcraft/format.py", "lines": 5}}</tool_call>',14 '<tool_call>{"name": "read_file", "arguments": {"path": 3}}</tool_call>',15 '<tool_call>{"name": "read_files", "arguments": {"path": "unitcraft/format.py"}}</tool_call>',16]17scratch = scratch_copy()18ws = Workspace(scratch)19model = ScriptedModel(CALLS)20for number in range(1, len(CALLS) + 1):21 reply = model.reply([], V2.schemas()) # the schemas are sent with each request; a scripted model ignores them22 if reply.malformed: # the reply parser's reason for a call whose JSON it cannot read23 print(f"call {number}, not run, the JSON is not read: {reply.malformed[0]}")24 continue25 call = reply.tool_calls[0]26 print(f"call {number}, {call['name']}, v2: {V2.call(ws, call['name'], call['arguments']).text}")27 print(f"call {number}, {call['name']}, v1: {V1.call(ws, call['name'], call['arguments']).text}")28shutil.rmtree(scratch, ignore_errors=True)
python bad-arguments-handed-back.pycall 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로 거부된다. 모든 거부는 필드, 오류 유형, 메시지를 밝히므로 모델은 다음 호출에서 잘못된 한 곳만 바꾸면 된다. 필드는 Python 클래스의 이름이 아니라 스키마 자체의 용어인 path로 지목한다. 모델이 다루는 말이 바로 그 용어이기 때문이다.
도구 세트 v1은 같은 필드를 엄격 모드 없이 사용하므로, 호출 2에서 4까지는 도구 세트 v1도 같은 호출을 같은 필드와 메시지로 거부한다. 출력의 도구 세트 v1 줄이 이를 보여 준다. 다만 v1의 텍스트에는 오류 유형이 빠져 있으며, 이 유형을 밝히는 것이 도구 세트 v2가 이 거부들에 더하는 유일한 추가 사항이다. 호출 2에서 누락된 path에 대한 거부를 비교해 보자. 도구 세트 v1은 error: invalid arguments: path: Field required라고 하고, 도구 세트 v2는 error: invalid arguments: path (missing): Field required라고 한다.
이 거부들은 각각 다른 수정을 요구하며, 어느 수정인지 알려 주는 것은 텍스트다. 누락된 필드는 그 필드를 추가하라는 요구이다. 불필요한 키는 제거하라는 요구이고, 잘못된 유형은 스키마가 정한 방식으로 값을 쓰라는 요구이다. "invalid arguments"만 받은 모델은 이 세 가지 중 무엇을 해야 하는지 추측해야 하고, 추측은 한 단계를 소모한다. 필드와 오류 유형을 밝히면 추측이 호출에 대한 한 번의 수정으로 바뀐다.
작업 규칙: 각 거부는 필드, 오류 유형, 메시지를 밝히는 도구 결과로 돌려보낸다. 잘못된 호출로 실행을 끝내서는 안 된다. 단, 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가 나타나는 한 곳을 바꾸며, old가 없거나 두 번 이상 나타나면 호출을 거부한다. 따라서 편집은 따옴표 몇 글자 때문에 실패할 수 있다. 모델이 파일을 읽은 내용에서 코드를 베껴 올 때 이 따옴표를 틀리게 쓸 수 있고, 그러면 편집이 거부된다.
1장에서 다룬 변경의 첫 번째 버전은 파일 전체를 JSON 문자열 하나에 넣었기 때문에, 파일의 모든 따옴표와 줄바꿈을 모델의 응답에서 이스케이프해야 했다. 편집은 더 작다. 바뀌는 줄만 복사하므로 틀릴 수 있는 글자가 적다. 그래도 이스케이프 문제가 사라지지는 않는다. 복사한 내용이 파일과 정확히 일치해야 하기 때문이다.
작업 집합 기록에서 복사가 잘못되는 모습을 볼 수 있다. 이 기록에는 같은 공개 모델인 Qwen3-4B-Instruct-2507이 스무 개 작업에서 낸 응답이 들어 있으며, 도구 집합 v1, 단계 상한 16, 온도 0으로 실행했다. 모델의 설정은 1장에서 설명한다. T-01의 세 번째 응답에서 모델은 몇 줄을 old에 복사하면서 f-문자열 두 개의 따옴표와 separator = "."의 닫는 따옴표를 빠뜨렸다. 파일에는 이 따옴표들이 있다. 저장된 old 텍스트를 먼저 출력한 다음, 그 응답 하나를 두 도구 집합에 모두 다시 실행하므로 차이가 드러난다.
1"""The edit_file call from step 3 of the task-set recording's T-01 run, read from its stored reply. Its old text drops2the quotes around the f-strings and the closing quote of separator = "."; the printed old text shows it. The point of3the prose rests on the two results: the v2 error names the nearest lines of the file, with their quotes, and the v14error only says the text is missing."""5import json6import shutil78from lib.case import DATA, scratch_copy9from lib.models import ScriptedModel10from lib.tools import V1, V2, Workspace1112rows = [json.loads(line) for line in (DATA / "recorded" / "task-set" / "replies.jsonl").read_text().splitlines()]13stored = next(row for row in rows if row["run"] == "T-01" and row["step"] == 3) # steps count from 114call = ScriptedModel([stored["text"]]).reply([], V2.schemas()).tool_calls[0] # the recorded reply, read back15scratch = scratch_copy()16ws = Workspace(scratch)17print("call:", call["name"], call["arguments"]["path"])18print("old text:")19print(call["arguments"]["old"])20print("v1 result:", V1.call(ws, call["name"], call["arguments"]).text)21v2 = V2.call(ws, call["name"], call["arguments"]).text22print("v2 result:")23print(v2)24assert 'text = f"{whole}{separator}{frac}"' in v225shutil.rmtree(scratch, ignore_errors=True)
python edit-error-nearest-lines.pycall: 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의 텍스트는 old 텍스트가 파일에 없다는 것만 알려 주고, 파일 이름을 밝힌다. 도구 집합 v2의 텍스트는 더 많은 것을 한다. 파일에서 가장 가까운 줄을 파일이 매긴 번호 그대로, 따옴표도 있는 그대로 보여 주고, 다음에 할 일을 알려 주며 끝난다. 그 줄들에서 old를 따옴표까지 포함해 복사하고 다시 호출하라는 것이다. 거부 메시지에 담기는 것은 파일 전체가 아니라 몇 줄의 범위다. 파일 전체를 주면 모델의 의문은 풀리겠지만 토큰을 많이 쓰게 되며, 모든 도구 결과는 작업을 담고 있는 같은 맥락에 포함된다. 이는 5장에서 계산한 방식과 같다. 줄은 유사도로 찾는다. 하니스는 old와 길이가 같은 창을 파일 아래로 밀면서 가장 잘 일치하는 창을 고르고, 동점이면 앞쪽 창을 택하므로 실행할 때마다 답이 같다. 여기서는 가장 좋은 창에 모델이 복사하던 f-문자열 줄이 따옴표와 함께 들어 있으며, 예제는 그 줄이 오류에 나타난다고 단언한다.
모델이 실패한 같은 편집을 반복하면 2장의 중단 규칙이 실행을 끝낸다. 단, 규칙을 켜 두었을 때의 이야기다. 규칙은 기본적으로 꺼져 있고, 작업 집합 기록에서도 켜지 않았다. 가장 가까운 줄은 이런 반복이 일어날 가능성을 낮추려는 것이다. 도구 집합 v1의 텍스트는 모델에게 쓸 단계를 하나 더 남긴다. 복사했어야 할 줄을 보려면 read_file를 호출해야 하고, 그다음 응답에서도 그 줄을 다시 잘못 복사할 수 있다. 도구 집합 v2의 텍스트는 그 줄을 거부 메시지에 직접 담으므로 모델이 곧바로 다시 시도할 수 있다. 출력 결과는 하니스가 돌려주는 텍스트를 보여 줄 뿐, 다음 편집이 성공하는지는 보여 주지 않는다. 그것을 알려면 실행이 필요하며, 실행 횟수는 10장에서 센다. 이 장은 어느 쪽의 횟수도 보고하지 않는다.
작업 규칙: 편집할 텍스트가 파일에 없으면 파일에서 가장 가까운 줄을 번호와 함께 돌려주고, 다음에 할 일을 알려 준다. 텍스트가 없다는 사실만 돌려주지 않는다. 그러면 어느 따옴표가 틀렸는지 모델이 짐작해야 하기 때문이다. 통째로 돌려줄 만큼 짧은 파일은 그 대신 번호를 붙여 전체를 돌려줄 수 있다.
이 장의 결정 사항
스키마와 오류 문구는 모델 입력의 일부다. 문장 하나, 필드 하나, 오류 문구 하나를 바꾸면 요청이 바뀐다. 이 책의 재생(replay)은 각 요청을 기록된 요청과 비교하며, 둘이 다르면 응답을 거부한다. 따라서 도구 집합은 기록과 함께 바뀌어야 하며, 기존 상태 그대로 바뀌어서는 안 된다.
이 장의 약속은 이후로 이어진다. 모델 어댑터는 모든 어댑터에 이 스키마를 그대로 사용한다. 컨텍스트 예산은 거부된 호출 하나하나를 다른 도구 결과와 똑같이 도구 결과로 센다. 에이전트 테스트는 두 하니스 버전을 횟수로 비교한다. 두 버전의 도구 집합은 이 장의 두 가지(v1과 v2)이며, 도구 집합 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판을 번역한 것이다.