각 실행을 추적하고 그 비용을 세기

읽는 데 약 22분분 걸린다, 8절에 4개 예제이(가) 있음.

2026.11.2판 예제 통과 2026년 11월 20 64개 예제 중 64개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.2판을 번역한 것이다. 원문 읽기

이 장을 마치면 모든 실행이 단계마다 레코드 하나를 나중에 읽는 사람이 파싱할 수 있는 파일에 쓰도록 만들 수 있다. 각 레코드에 그 실행과 해당 호출을 연결하는 ID를 부여할 수 있으며, 실행에 든 비용을 토큰 수로 말할 수 있다. 여기서 비용은 개수를 뜻한다. 금액을 뜻하지 않는다.

유지보수 에이전트는 임시 복사본에서 unitcraft 위에서 실행한다. 실행은 잘 끝날 수도, 잘못 끝날 수도, 끝나지 않을 수도 있으며, 종료 사유는 그 실행이 어떻게 끝났는지만 알려 준다. 작업 세트의 작업 중 하나인 T-01에 대한 1장의 실행을 보자. 이 실행은 올바른 파일을 읽고 테스트를 돌린 뒤, 단계 상한에 이를 때까지 잘못된 형식의 호출을 연달아 한다. 종료 사유는 step_cap이며, 종료 사유가 알려 주는 것은 그것이 전부다. 잘못된 호출들의 공통점이 무엇인지, 하네스가 각 호출을 어떻게 처리했는지, 각 단계가 토큰을 몇 개 썼는지는 알려 주지 않는다. 이 답들은 단계 안에 있으므로, 하네스는 단계를 보관해야 한다.

각 단계의 기록이 트레이스다. 10장의 점수는 이미 저장된 개수를 읽으며, 실행이 왜 멈췄는지 묻는 독자에게는 멈추기 전의 단계들이 필요하다. 이 장은 트레이스를 데이터로 작성하고, ID에 고정된 형식을 주고, 트레이스에 담긴 것을 센다. 여기의 모든 개수는 녹화본에서 읽거나 스크립트가 출력한 것이다. 라이브 모델에서 가져온 것은 하나도 없으므로 이 개수는 저장된 개수이며, 모델에서 이를 다시 도출하는 검증은 아직 수행하지 않았다.

이벤트당 한 줄

트레이스는 한 줄에 JSON 객체 하나를 담은 파일이다. 이 형식에는 JSON Lines라는 이름과 짧은 정의가 있다. 각 줄은 JSON 값 하나를 담고, 파일은 UTF-8이며, 각 줄은 줄 바꿈(line feed)으로 끝난다. 해당 문서는 마지막 줄 뒤에도 줄 바꿈을 둘 것을 권장하지만 요구하지는 않으며, 캐리지 리턴과 줄 바꿈의 조합도 허용한다. JSON Lines format은 바이트 순서 표식(byte order mark)을 포함해서는 안 된다고 밝힌다. 하니스는 각 레코드를 키를 정렬하고, 공백 없이, ASCII만으로 기록한다. 그래서 같은 레코드는 언제나 같은 바이트로 나온다. 이는 출력 결과가 중요한 것과 같은 이유로 중요하다. 독자가 두 트레이스를 줄 단위로 비교할 수 있기 때문이다.

1장의 T-01 실행을 재생하면 그 단계들이 이 형식으로 기록된다. 재생은 각 단계에 대해 기록된 응답을 읽으므로 트레이스는 실행할 때마다 같다.

trace-one-run.py Python 3.12.15 · pydantic 2.14.3 통과
"""The chapter 1 recorded run of T-01 as JSON lines: one record per step, with run-scoped IDs and the recorded tokencounts. The lines are written to a file and read back, and the reader counts the empty pieces it skips."""import jsonimport tempfilefrom pathlib import Pathfrom lib.case import load_tasksfrom lib.loop import run_taskfrom lib.models import ReplayModelfrom lib.tools import CH1from lib.trace import IdCounter, StepRecorder, dumps, read_lines, step_recordstask = load_tasks(only=["T-01"])[0]model = StepRecorder(ReplayModel("chapter-1-t01", "T-01"))run = run_task(model, task, CH1, max_steps=CH1.step_cap, ids=IdCounter())records = step_records(run, model)for record in records:    print(dumps(record))print("records:", len(records))print("first call ID:", records[0]["calls"][0])print("results:", ", ".join(f"step {r['step']} {r['result']}" for r in records))print("prompt tokens, summed over the records:", sum(r["prompt_tokens"] for r in records))print("completion tokens, summed over the records:", sum(r["completion_tokens"] for r in records))try:    json.loads("")  # a blank line is not a JSON valueexcept json.JSONDecodeError as error:    print("blank line:", error)with tempfile.TemporaryDirectory() as folder:    path = Path(folder) / "trace.jsonl"    path.write_text("".join(dumps(record) + "\n" for record in records), encoding="utf-8")    read_back, skipped = read_lines(path.read_text(encoding="utf-8"))print("lines read back:", len(read_back))print("empty pieces skipped:", skipped)assert read_back == records and skipped == 1  # the one piece after the last line feedassert run.ended == "step_cap" and len(records) == CH1.step_cap and records[-1]["stop"] == "step_cap"assert sum(r["prompt_tokens"] for r in records) == run.prompt_tokensrun.close()
출력python trace-one-run.py
{"arguments":{"path":"unitcraft/format.py"},"brief":"23 lines","calls":["run-0001-c1"],"completion_tokens":22,"gate":[],"malformed":[],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":501,"result":"ok","run":"run-0001","step":1,"stop":"","tool":"read_file"}
{"arguments":{},"brief":"8 failed, 22 passed","calls":["run-0001-c2"],"completion_tokens":70,"gate":[],"malformed":[],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":713,"result":"ok","run":"run-0001","step":2,"stop":"","tool":"run_tests"}
{"arguments":null,"brief":"error: malformed call","calls":["run-0001-c3"],"completion_tokens":560,"gate":[],"malformed":["not JSON (Expecting ',' delimiter)"],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":941,"result":"refused","run":"run-0001","step":3,"stop":"","tool":"malformed"}
{"arguments":null,"brief":"error: malformed call","calls":["run-0001-c4"],"completion_tokens":292,"gate":[],"malformed":["not JSON (Expecting ',' delimiter)"],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":1528,"result":"refused","run":"run-0001","step":4,"stop":"","tool":"malformed"}
{"arguments":null,"brief":"error: malformed call","calls":["run-0001-c5"],"completion_tokens":296,"gate":[],"malformed":["not JSON (Expecting ',' delimiter)"],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":1847,"result":"refused","run":"run-0001","step":5,"stop":"","tool":"malformed"}
{"arguments":null,"brief":"error: malformed call","calls":["run-0001-c6"],"completion_tokens":296,"gate":[],"malformed":["not JSON (Expecting ',' delimiter)"],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":2170,"result":"refused","run":"run-0001","step":6,"stop":"","tool":"malformed"}
{"arguments":null,"brief":"error: malformed call","calls":["run-0001-c7"],"completion_tokens":296,"gate":[],"malformed":["not JSON (Expecting ',' delimiter)"],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":2493,"result":"refused","run":"run-0001","step":7,"stop":"","tool":"malformed"}
{"arguments":null,"brief":"error: malformed call","calls":["run-0001-c8"],"completion_tokens":296,"gate":[],"malformed":["not JSON (Expecting ',' delimiter)"],"offered":["finish","read_file","run_tests"],"parent":null,"prompt_tokens":2816,"result":"refused","run":"run-0001","step":8,"stop":"step_cap","tool":"malformed"}
records: 8
first call ID: run-0001-c1
results: step 1 ok, step 2 ok, step 3 refused, step 4 refused, step 5 refused, step 6 refused, step 7 refused, step 8 refused
prompt tokens, summed over the records: 13009
completion tokens, summed over the records: 2128
blank line: Expecting value: line 1 column 1 (char 0)
lines read back: 8
empty pieces skipped: 1

이 실행에는 단계마다 하나씩 모두 8개의 레코드가 있고, 마지막 레코드에는 중단 사유 step_cap가 담겨 있다. 각 레코드는 단계 번호, 도구, 인자, 돌아온 결과의 한 줄 요약, 결과 분류, 호출 ID, 제공된 도구, 해당 단계에 대한 게이트의 줄, 해당 단계의 토큰 수를 담는다. 첫 번째 호출의 ID는 run-0001-c1이다.

뒤쪽 단계들은 형식이 잘못된 호출이다. 모델의 응답이 유효한 JSON이 아니었으므로 하니스는 그 호출을 실행하지 않았다. 하니스는 그 단계를 refused로 기록했고, 파싱 오류는 malformed 필드에 넣었다. refused는 하니스가 실행하지 않았거나 실행 전에 도구가 거부한 모든 호출을 포괄한다. 파싱할 수 없거나 잘린 응답, 하니스가 제공하지 않는 도구 이름, 도구에 맞지 않는 인자, 게이트가 보류한 변경, 도구 자체의 검사가 거부한 경로가 여기에 해당한다. 세 번째 분류인 error는 다르다. 이것은 도구가 실행되었고 실패를 보고했다는 뜻이다. refused를 도구 오류로 읽으면, 한 번도 호출되지 않은 도구에서 버그를 찾게 된다.

레코드 전체를 합하면 재생된 실행은 프롬프트 토큰 13009개와 완성 토큰 2128개를 사용했다. 이 수치는 재생 중에 센 값이 아니라 기록이 각 단계마다 저장해 둔 값이다.

이 파일에는 함정이 하나 있으며, 예제는 끝부분에서 그것을 보여 준다. JSON Lines는 빈 줄을 허용하지 않는다. 빈 줄은 값이 아니기 때문이다. 빈 줄을 파싱하면 실패하며, Python은 이를 Expecting value: line 1 column 1 (char 0)로 보고한다. 레코드는 파일로 기록되고 리더를 통해 다시 읽힌다. 텍스트를 줄 바꿈으로 나누면 마지막 줄 바꿈 뒤에 빈 조각이 하나 남는데, 리더는 이 조각을 의도적으로 건너뛰고 그 수를 센다. 여기서는 레코드 8개가 다시 읽히고, 건너뛴 조각은 1개이다. 이 조각을 건너뛰지 않는 리더는 모든 파일의 끝에서 멈추게 된다.

작업 규칙: 트레이스를 읽는 리더는 빈 줄을 의도적으로만 건너뛰며, 건너뛴 줄의 수를 센다. 그렇지 않으면 첫 번째 빈 줄에서 멈춘다. 기록하는 쪽은 레코드 사이에 빈 줄을 절대 넣지 않는다.

시계 없는 ID

트레이스의 한 단계는 그 단계가 속한 실행, 그 단계가 응답하는 호출, 그리고 순서상의 위치로 다시 찾을 수 있어야 한다. 트레이스는 ID를 호출자가 넘겨 준 카운터에서만 얻고, 다른 곳에서는 얻지 않는다. 실행은 run-0001처럼 1부터 번호를 매긴다. 도구 호출의 ID는 해당 실행의 ID에 c와 번호를 붙인 것이다. 따라서 그 실행의 첫 번째 호출은 run-0001-c1이며, 이는 재생된 실행의 첫 번째 레코드가 가지는 ID와 같다. 단계는 일어난 순서대로 1부터 번호를 매긴다.

어떤 레코드도 시각을 담지 않는다. 타임스탬프는 실행할 때마다 달라지고, 이를 보여 주는 예제가 출력하는 결과도 달라진다. 각 예제는 기록될 때 출력된 결과와 비교되므로, 타임스탬프가 있으면 실행할 때마다 이 비교가 실패한다. 트레이스에는 횟수, 짧은 결과, ID만 담기며 시계에서 나오는 값은 담기지 않는다.

ID가 중요한 이유는 하나 더 있다. 실행 ID와 호출 ID는 하니스가 모델에 보내는 requests에 들어가므로, 재생은 기록과 같은 방식으로 실행에 번호를 매길 때에만 기록과 같은 요청을 보낸다. 한 작업의 재생 코드는 기록에서 그 작업이 놓인 위치에서 카운터를 이어받는다. 자식 예제가 자신의 시작 지점이 아니라 기록의 순서에 따라 실행 번호를 매기는 것도 이 때문이다.

작업 규칙: 실행과 호출의 번호는 넘겨받은 카운터에서 매기고, 시계나 난수 생성기에서 매기지 않는다. 실행마다 달라지는 ID는 요청을 바꾸며, 그런 실행을 재생하면 기록과 맞출 수 없는 첫 요청에서 멈춘다.

토큰 수

추적 기록의 각 레코드에는 두 가지 토큰 수가 들어 있다. 이 수는 1장에서 정의한 대로 고정된 모델의 토큰을 기준으로 센다. 프롬프트 수는 모델이 읽은 토큰의 수이고, 완성 수는 모델이 쓴 토큰의 수이다. 녹화는 실행될 때 두 수를 모두 구한다. 녹화는 각 단계의 수를 그 응답과 함께 replies.jsonl에 저장하고, 각 과제의 합계는 매니페스트에 저장한다. 재생은 저장된 수를 읽을 뿐 다시 토큰화하지 않으므로, 재생이 녹화에 기록되지 않은 수를 만들어 낼 수는 없다.

저장된 단계별 수를 과제별로, 그리고 집합 전체에 대해 합산하는 일은 다음 예제가 맡는다. 이 예제는 각 과제의 합을 매니페스트가 그 과제에 대해 저장한 합계와 대조하고, 집합의 프롬프트 합을 그 과제 합계들의 합과 대조한다.

token-counts-from-recording.py Python 3.12.15 통과
"""The token counts of the task-set recording, summed per task and for the set, read from the stored counts. Replaynever tokenizes, so these are the counts the recording wrote; the live check against a tokenizer is not run."""from lib.models import load_recordingfrom lib.trace import OTEL_TOKEN_FIELDSmanifest, rows = load_recording("task-set")  # rows: one per step, from replies.jsonl; the manifest has task totalssums: dict[str, list[int]] = {}for row in rows:    total = sums.setdefault(row["run"], [0, 0, 0])    total[0] += row["prompt_tokens"]    total[1] += row["completion_tokens"]    total[2] += 1  # each row is one step, so the third sum counts stepsfor task in sorted(manifest["tasks"], key=lambda t: t["task"]):    prompt, completion, steps = sums[task["task"]]    print(f"{task['task']} prompt tokens: {prompt} completion tokens: {completion} steps: {steps}")    assert (prompt, completion, steps) == (task["prompt_tokens"], task["completion_tokens"], task["steps"])set_prompt = sum(total[0] for total in sums.values())set_completion = sum(total[1] for total in sums.values())print("set tasks:", len(sums))print("set prompt tokens:", set_prompt)print("set completion tokens:", set_completion)print("live count check: not run")for field, name in sorted(OTEL_TOKEN_FIELDS.items()):  # the mapping table; the book's own names stay in the trace    print(f"field {field} would map to {name} (data only; OpenTelemetry is not used)")assert set_prompt == sum(t["prompt_tokens"] for t in manifest["tasks"])
출력python token-counts-from-recording.py
T-01 prompt tokens: 44836 completion tokens: 2025 steps: 16
T-02 prompt tokens: 43904 completion tokens: 2059 steps: 16
T-03 prompt tokens: 27562 completion tokens: 1463 steps: 12
T-04 prompt tokens: 8809 completion tokens: 1054 steps: 5
T-05 prompt tokens: 8494 completion tokens: 906 steps: 5
T-06 prompt tokens: 55109 completion tokens: 4670 steps: 16
T-07 prompt tokens: 24989 completion tokens: 3468 steps: 9
T-08 prompt tokens: 13713 completion tokens: 1154 steps: 7
T-09 prompt tokens: 10324 completion tokens: 701 steps: 6
T-10 prompt tokens: 51056 completion tokens: 3549 steps: 16
T-11 prompt tokens: 33951 completion tokens: 817 steps: 16
T-12 prompt tokens: 30787 completion tokens: 1617 steps: 12
T-13 prompt tokens: 49249 completion tokens: 942 steps: 16
T-14 prompt tokens: 12651 completion tokens: 972 steps: 7
T-15 prompt tokens: 20409 completion tokens: 1254 steps: 10
T-16 prompt tokens: 57696 completion tokens: 4621 steps: 16
T-17 prompt tokens: 17601 completion tokens: 1511 steps: 9
T-18 prompt tokens: 5122 completion tokens: 304 steps: 4
T-19 prompt tokens: 22713 completion tokens: 2154 steps: 9
T-20 prompt tokens: 33630 completion tokens: 2065 steps: 13
set tasks: 20
set prompt tokens: 572605
set completion tokens: 37306
live count check: not run
field completion_tokens would map to gen_ai.usage.output_tokens (data only; OpenTelemetry is not used)
field prompt_tokens would map to gen_ai.usage.input_tokens (data only; OpenTelemetry is not used)

모든 과제의 합이 매니페스트와 일치하므로, 아래의 집합 합계는 녹화가 직접 기록한 수이다. 과제 집합은 과제 20개로 이루어져 있으며, 이들이 사용한 토큰은 프롬프트 토큰 572605개와 완성 토큰 37306개이다. 기록된 프롬프트를 고정된 모델로 토큰화해 보는 출력의 실시간 수 점검은 not run(이)라고 보고한다.

이런 수가 어떻게 만들어지는지는 라이브러리의 소스에서 볼 수 있다. llama-cpp-python의 소스는 녹화가 고정한 릴리스에서 읽었으며, 여기서 실행하지는 않았다. 스트리밍하지 않는 완성은 프롬프트의 토큰 목록 길이와 완성의 토큰 목록 길이를 보고하고, 그 합을 전체 수로 보고한다(llama.py at v0.3.36). 이 라이브러리의 tokenize 메서드는 UTF-8 바이트를 받아 정수 토큰 ID의 목록을 반환한다. 이 메서드는 지시하지 않는 한 문장 시작 토큰을 추가하므로, 프롬프트의 수는 모델의 어휘뿐 아니라 이 설정에도 좌우된다.

서로 다른 토크나이저에서 나온 수는 비교할 수 없다. 이것은 측정값이 아니라 경험칙이다. 토큰은 하나의 어휘에 속한 단위이며, 같은 텍스트도 다른 어휘에서는 다른 개수의 단위로 나뉠 수 있다. 두 수를 비교하려는 독자는 먼저 모델 파일과 설정이 일치하는지 확인해야 한다.

녹화의 매니페스트에는 모델 파일과 그 SHA-256이 저장되어 있지만, 프롬프트의 수를 결정하는 설정은 저장되어 있지 않다. 그 설정은 라이브러리가 적용한 채팅 템플릿과 문장 시작 토큰 설정이다. 녹화는 둘 다 라이브러리의 기본값을 사용했으며, 이 책은 아직 그 값을 적어 두지 않았다.

작업 규칙: 각 수는 그것이 나온 모델 파일, 그리고 문장 시작 토큰처럼 그 수를 바꾸는 모든 설정과 함께 저장한다. 서로 다른 토크나이저에서 나온 수는 비교하지 않는다. 어떤 점검으로도 다시 구하지 않은 수는 저장된 수로 보고하며, 실시간 수로 보고하지 않는다.

자식의 기록은 부모의 호출 아래에 놓인다

8장은 하위 작업을 자식 루프에 넘기고 요약과 종료 사유를 돌려받는다. 또한 부모의 요약이 일어난 일의 유일한 흔적이 되지 않도록, 자식 자신의 기록도 자식 쪽에 보관한다. 이 절은 그 약속을 트레이스에서 지킨다. 자식의 단계는 고유한 실행 ID와 고유한 호출 ID를 가진 별도의 실행으로 기록된다. 자식의 각 기록에는 그 실행을 시작한 호출의 ID인 parent가 들어 있다. 자식의 기록은 그것을 시작한 부모의 호출 바로 뒤에 출력된다.

여기서는 부모가 인치 단위를 요구하는 작업인 T-04에 자식을 시작한다. 자식의 기록된 실행은 파일을 변경하는 finish로 끝난다. 스크립트로 정해진 사람이 그 변경을 거부하므로 게이트는 finish를 보류하고, 자식은 질문 하나와 함께 제어를 돌려준다.

child-trace-under-parent.py Python 3.12.15 · pydantic 2.14.3 통과
"""A parent starts a child on T-04, whose recorded run ends with a finish that changes files. The gate holds that finishbecause the person says no, so the child hands back with ask_user. The child's records sit under the parent's start call;the parent is scripted, so its records carry zero tokens."""from lib.case import load_tasksfrom lib.chapter1 import callfrom lib.models import ReplayModel, load_recordingfrom lib.permissions import Gate, library_copy, replay_ids, scriptedfrom lib.subagents import START_CHILDfrom lib.tasks import snapshotfrom lib.tools import V1from lib.trace import StepRecorder, child_under_parent, dumpstask = load_tasks(only=["T-04"])[0]manifest, _ = load_recording("task-set")stored = next(t for t in manifest["tasks"] if t["task"] == "T-04")with library_copy() as library:    before = snapshot(library, "unitcraft")    gate = Gate(library, scripted((False, "not this change")))  # the scripted person says no, with this reason    child_model = StepRecorder(ReplayModel("task-set", "T-04"), gate)    replies = [call(START_CHILD, task_id="T-04"), call("ask_user", question="The child's change was held. Pass it on?")]    parent, child, records = child_under_parent(task, replies, child_model, gate, library, replay_ids("T-04"))    for record in records:        print(dumps(record))    print("child budget:", V1.step_cap)    print("child ended:", child.handoff.ended)    print("gate refusals:", gate.counts["refused"])    print("parent ended:", parent.ended)    print("copy unchanged by the held finish:", before == snapshot(library, "unitcraft"))    child_records = [r for r in records if r["run"] == child.run.id]    parent_records = [r for r in records if r["run"] != child.run.id]    print("child run:", child.run.id)    print("parent call of the child:", child_records[0]["parent"])    print("held step:", next(r["step"] for r in child_records if r["result"] == "refused"))    print("parent tokens, summed:", sum(r["prompt_tokens"] + r["completion_tokens"] for r in parent_records))    child_prompt = sum(r["prompt_tokens"] for r in child_records)    child_completion = sum(r["completion_tokens"] for r in child_records)    print("child prompt tokens, summed:", child_prompt)    print("child completion tokens, summed:", child_completion)    assert child.handoff.ended == "ask_user" and sum(r["result"] == "refused" for r in records) == 1    assert parent.ended == "ask_user" and before == snapshot(library, "unitcraft")    assert (child_prompt, child_completion) == (stored["prompt_tokens"], stored["completion_tokens"])    parent.close()
출력python child-trace-under-parent.py
{"arguments":{"task_id":"T-04"},"brief":"child ask_user at step 5","calls":["run-0001-c1"],"completion_tokens":0,"gate":[],"malformed":[],"offered":["ask_user","start_child"],"parent":null,"prompt_tokens":0,"result":"ok","run":"run-0001","step":1,"stop":"","tool":"start_child"}
{"arguments":{},"brief":"25 files","calls":["run-0004-c1"],"completion_tokens":51,"gate":[],"malformed":[],"offered":["ask_user","edit_file","finish","list_files","read_file","run_tests","write_file"],"parent":"run-0001-c1","prompt_tokens":1049,"result":"ok","run":"run-0004","step":1,"stop":"","tool":"list_files"}
{"arguments":{"path":"unitcraft/units.py"},"brief":"36 lines","calls":["run-0004-c2"],"completion_tokens":108,"gate":[],"malformed":[],"offered":["ask_user","edit_file","finish","list_files","read_file","run_tests","write_file"],"parent":"run-0001-c1","prompt_tokens":1253,"result":"ok","run":"run-0004","step":2,"stop":"","tool":"read_file"}
{"arguments":{"new":"Unit(\"m\", \"length\", Decimal(1)),\n        Unit(\"km\", \"length\", Decimal(1000)),\n        Unit(\"cm\", \"length\", Decimal(\"0.01\")),\n        Unit(\"mm\", \"length\", Decimal(\"0.001\")),\n        Unit(\"ft\", \"length\", Decimal(\"0.3048\")),\n        Unit(\"in\", \"length\", Decimal(\"0.0254\")),\n        Unit(\"kg\", \"mass\", Decimal(1)),\n        Unit(\"g\", \"mass\", Decimal(\"0.001\")),\n        Unit(\"lb\", \"mass\", Decimal(\"0.45359237\")),\n        Unit(\"s\", \"time\", Decimal(1)),\n        Unit(\"min\", \"time\", Decimal(60)),\n        Unit(\"h\", \"time\", Decimal(3600)),\n        Unit(\"C\", \"temperature\", None),\n        Unit(\"F\", \"temperature\", None),\n        Unit(\"K\", \"temperature\", None),","old":"Unit(\"m\", \"length\", Decimal(1)),\n        Unit(\"km\", \"length\", Decimal(1000)),\n        Unit(\"cm\", \"length\", Decimal(\"0.01\")),\n        Unit(\"mm\", \"length\", Decimal(\"0.001\")),\n        Unit(\"ft\", \"length\", Decimal(\"0.3048\")),\n        Unit(\"kg\", \"mass\", Decimal(1)),\n        Unit(\"g\", \"mass\", Decimal(\"0.001\")),\n        Unit(\"lb\", \"mass\", Decimal(\"0.45359237\")),\n        Unit(\"s\", \"time\", Decimal(1)),\n        Unit(\"min\", \"time\", Decimal(60)),\n        Unit(\"h\", \"time\", Decimal(3600)),\n        Unit(\"C\", \"temperature\", None),\n        Unit(\"F\", \"temperature\", None),\n        Unit(\"K\", \"temperature\", None),","path":"unitcraft/units.py"},"brief":"edited unitcraft/units.py","calls":["run-0004-c3"],"completion_tokens":570,"gate":[],"malformed":[],"offered":["ask_user","edit_file","finish","list_files","read_file","run_tests","write_file"],"parent":"run-0001-c1","prompt_tokens":1686,"result":"ok","run":"run-0004","step":3,"stop":"","tool":"edit_file"}
{"arguments":{},"brief":"8 failed, 22 passed","calls":["run-0004-c4"],"completion_tokens":111,"gate":[],"malformed":[],"offered":["ask_user","edit_file","finish","list_files","read_file","run_tests","write_file"],"parent":"run-0001-c1","prompt_tokens":2276,"result":"ok","run":"run-0004","step":4,"stop":"","tool":"run_tests"}
{"arguments":{"summary":"Added the inch unit ('in') with a factor of 0.0254 to the units dictionary in unitcraft/units.py. This allows parse_quantity('2 in') to work correctly and enables the convert function to handle inch-to-meter conversions. The test suite failures indicate other issues in the codebase that are outside the scope of this specific task."},"brief":"p-1 was not applied: the person said no: not this change","calls":["run-0004-c5"],"completion_tokens":214,"gate":["p-1 1 files, diff 06ee73fd984f: asked","p-1 answer no, bound to p-1 and 06ee73fd984f","p-1 not applied: the person said no: not this change"],"malformed":[],"offered":["ask_user","edit_file","finish","list_files","read_file","run_tests","write_file"],"parent":"run-0001-c1","prompt_tokens":2545,"result":"refused","run":"run-0004","step":5,"stop":"ask_user","tool":"finish"}
{"arguments":{"question":"The child's change was held. Pass it on?"},"brief":"ask_user","calls":["run-0001-c2"],"completion_tokens":0,"gate":[],"malformed":[],"offered":["ask_user","start_child"],"parent":null,"prompt_tokens":0,"result":"ok","run":"run-0001","step":2,"stop":"ask_user","tool":"ask_user"}
child budget: 16
child ended: ask_user
gate refusals: 1
parent ended: ask_user
copy unchanged by the held finish: True
child run: run-0004
parent call of the child: run-0001-c1
held step: 5
parent tokens, summed: 0
child prompt tokens, summed: 8809
child completion tokens, summed: 1054

자식의 실행은 기록이 T-04에 부여한 번호, 즉 기록에서 네 번째 실행의 번호를 사용하므로 자식의 요청은 기록된 요청과 일치한다. 이 실행은 run-0004이고, 첫 기록은 parent에 부모의 호출을 명시한다. 그 값은 run-0001-c1이다.

자식의 기록에는 녹화본이 T-04에 대해 저장한 횟수, 즉 프롬프트 토큰 8809개와 완성 토큰 1054개가 담기며, 스크립트는 이를 매니페스트와 대조해 검증한다. 부모는 스크립트로 동작하므로 부모의 기록에는 토큰이 없다. 그 값은 0이다.

사람의 거부가 자식의 실행이 끝나는 지점이다. 게이트는 자식의 마지막 기록인 단계 5에서 finish를 보류하고, 자식은 대신 질문을 넘겨준다.

자식은 ask_user로 멈추며, 게이트는 호출 1건을 거부했다. 이 정지는 16단계의 예산이 아니라 게이트에서 비롯된다. 마찬가지로 스크립트로 동작하는 부모는 사람에게 자신의 질문을 하고 ask_user로 멈춘다. 실행 후에도 라이브러리 사본은 그대로이며, 이것이 게이트의 핵심이다. 보류된 변경은 라이브러리에 도달하지 못했다.

이 예제는 예산을 소진하는 자식을 보여 주지 않는다. 그 경우는 8장에서 다루며, 그 종료 사유는 보류된 변경이 아니라 예산에서 비롯된다.

작업 규칙: 각 자식에게 고유한 실행 ID와 고유한 기록을 주고, 각 기록의 parent를 그것을 시작한 호출로 설정한다. 부모 실행의 비용을 보고할 때는 자식들의 횟수를 더하고, 더했다는 사실을 밝힌다. 이 트레이스는 자식의 횟수를 따로 출력하며 어느 것도 부모에 합산하지 않는다.

비용은 금액이 아니라 횟수로 센다

저장된 횟수를 작업별로 합산하면 한 실행의 비용은 세 가지 수로 나타난다. 단계 수, 도구 호출 수, 토큰 수이다. 이 책은 이 세 가지만 보고하고 다른 것은 보고하지 않는다. 가격표는 시간이 지나면 낡고, 달러로 적은 수치는 가격이 한 번 바뀌면 틀린 값으로 남는다. 그래서 이 책은 횟수에 가격을 곱하지 않는다. 금액이 필요한 독자는 제공자가 오늘 청구하는 가격을 횟수에 곱하면 되며, 가격이 바뀌어도 이 책의 수치는 그대로 맞는다.

저장된 횟수를 각 실행이 끝난 방식별로 묶으면 단계 상한에 걸린 실행이 다른 실행과 나란히 놓이므로, 종료 사유별 비용이 같은 출력에 드러난다.

cost-as-counts.py Python 3.12.15 통과
"""The cost of the task-set runs as counts only: steps, tool calls and tokens, summed per way a run ended. The cost istokens, never money, and the tokens are the recording's stored counts; the groups are sorted, so the output is stable."""from lib.models import load_recordingmanifest, rows = load_recording("task-set")tasks = sorted(manifest["tasks"], key=lambda t: (t["task"], t["kind"]))for ending in sorted({t["ended"] for t in tasks}):    group = [t for t in tasks if t["ended"] == ending]    print(f"ended {ending}: runs {len(group)}, done {sum(t['done'] for t in group)}, "          f"steps {sum(t['steps'] for t in group)}, tool calls {sum(t['tool_calls'] for t in group)}, "          f"prompt tokens {sum(t['prompt_tokens'] for t in group)}, "          f"completion tokens {sum(t['completion_tokens'] for t in group)}")    print("  tasks:", ", ".join(t["task"] for t in group))    print("  done:", ", ".join(t["task"] for t in group if t["done"]) or "none")print(f"all: runs {len(tasks)}, done {sum(t['done'] for t in tasks)}, steps {sum(t['steps'] for t in tasks)}, "      f"tool calls {sum(t['tool_calls'] for t in tasks)}, prompt tokens {sum(t['prompt_tokens'] for t in tasks)}, "      f"completion tokens {sum(t['completion_tokens'] for t in tasks)}")capped = [t for t in tasks if t["ended"] == "step_cap"]print(f"step-capped runs done: {sum(t['done'] for t in capped)} of {len(capped)}")print(f"step-capped runs, steps: {sum(t['steps'] for t in capped)} of {sum(t['steps'] for t in tasks)}")print(f"step-capped runs, prompt tokens: {sum(t['prompt_tokens'] for t in capped)} of "      f"{sum(t['prompt_tokens'] for t in tasks)}")prompts: dict[str, list[int]] = {}for row in sorted(rows, key=lambda r: (r["run"], r["step"])):  # the stored step rows, in step order    prompts.setdefault(row["run"], []).append(row["prompt_tokens"])rising = [t["task"] for t in capped if all(b > a for a, b in zip(prompts[t["task"]], prompts[t["task"]][1:]))]print(f"step-capped runs whose prompt count rises at every step: {len(rising)} of {len(capped)}")assert all(t["tool_calls"] == t["steps"] for t in tasks), "one tool call per step in this recording"
출력python cost-as-counts.py
ended ask_user: runs 7, done 1, steps 69, tool calls 69, prompt tokens 157824, completion tokens 10368
  tasks: T-03, T-12, T-15, T-17, T-18, T-19, T-20
  done: T-18
ended finish: runs 6, done 4, steps 39, tool calls 39, prompt tokens 78980, completion tokens 8255
  tasks: T-04, T-05, T-07, T-08, T-09, T-14
  done: T-04, T-05, T-09, T-14
ended step_cap: runs 7, done 0, steps 112, tool calls 112, prompt tokens 335801, completion tokens 18683
  tasks: T-01, T-02, T-06, T-10, T-11, T-13, T-16
  done: none
all: runs 20, done 5, steps 220, tool calls 220, prompt tokens 572605, completion tokens 37306
step-capped runs done: 0 of 7
step-capped runs, steps: 112 of 220
step-capped runs, prompt tokens: 335801 of 572605
step-capped runs whose prompt count rises at every step: 7 of 7

단계 상한에 걸린 실행은 112 of 220단계와 프롬프트 토큰 335801 of 572605개를 사용했다. 단계 상한에 걸린 실행의 줄은 runs 7, done 0, steps 112, tool calls 112, prompt tokens 335801, completion tokens 18683이다. 전체 실행의 줄은 runs 20, done 5, steps 220, tool calls 220, prompt tokens 572605, completion tokens 37306이며, 그 위의 모든 그룹을 포함한다. 추가 단언 하나는 기록을 검사한다. 모든 실행이 단계마다 도구를 한 번씩 호출했으므로 도구 호출 수와 단계 수는 같은 수이다.

단계 상한에 걸린 실행 중 완료된 것은 하나도 없다. 그 수는 0 of 7이다. 단계 상한에 걸린 실행은 finish로도 인계로도 끝나지 않으므로, 파일에 무엇이 들어 있든 0이라는 값은 완료 규칙에서 그대로 따라 나온다. ask_user 그룹에서 완료된 하나는 T-18이며, 이 수는 경로 일치를 통해 얻어진다(10장). 이 0은 단계 상한에 걸린 실행이 얼마나 가까이 갔는지에 대해서는 아무것도 말해 주지 않으며, 이 장은 이를 작업에 대한 발견으로 읽지 않는다.

판단이며 측정은 아니다. 단계 상한 줄은 토큰을 쓰고도 끝내지 못한 실행의 비용이다. 5장의 요청당 프롬프트 예산이 아니라 실행의 전체 토큰에 거는 토큰 예산이었다면 그 실행들을 더 일찍 멈추었을 것이다. 그 대가는 이후 단계에서 끝났을 수도 있는 실행을 멈출 가능성이며, 이 기록은 그 가능성을 보여 줄 수 없다. 단계 상한에 걸린 각 실행은 상한에서 멈췄고 그 뒤의 단계를 쓰지 않았기 때문이다. 비용을 키우는 것은 프롬프트 토큰 수이다. 루프는 단계마다 전체 대화 기록을 다시 보낸다. 프롬프트 수가 매 단계 증가하는 단계 상한 실행을 세면 7 of 7이 나온다. 단계 예산은 단계를 세므로, 긴 실행에서는 토큰이 비용에 대해 말해 주는 바보다 적게 말해 준다. 토큰 예산을 두는 경우 하니스는 실행을 자체 종료 사유와 자체 횟수와 함께 끝내야 하며, 그래야 예산에 의한 중단과 단계 상한에 의한 중단을 구별할 수 있다.

12장은 에이전트와 고정 파이프라인을 이와 같은 단위로 비교하는데, 이 단위는 모든 실행이 같은 방식으로 보고할 때에만 쓸모가 있다.

작업 규칙: 비용은 각 실행의 단계, 도구 호출, 토큰으로 보고하고, 끝난 방식별로 묶어 그룹을 나란히 출력한다. 금액은 인용하지 않는다. 단계 상한 그룹은 끝내지 못하고 소비한 토큰으로 읽으며, 두 번째 측정이 달리 말해 주기 전에는 작업에 대한 증거로 읽지 않는다.

자신의 필드 이름을 유지하고, 경계에서 대응시킨다

이 레코드의 토큰 필드는 prompt_tokens과 completion_tokens이며, 이 책이 자체적으로 정한 이름이다. OpenTelemetry 프로젝트는 생성형 AI 시스템의 텔레메트리에 대한 규약을 공개한다. 시맨틱 규약 v1.37.0 개정판의 GenAI 스팬 페이지는 같은 두 개수를 gen_ai.usage.input_tokens과 gen_ai.usage.output_tokens라는 이름으로 부른다(시맨틱 규약, GenAI 스팬). 이 개정판에서 해당 페이지는 상태를 "Development"로 표시하므로 이름이 바뀔 수 있다. 이 책은 OpenTelemetry를 사용하지 않는다. 토큰 개수 예제는 두 이름을 이 책의 필드 옆에 데이터로만 출력하며, 이 장은 OpenTelemetry 도구가 트레이스를 어떻게 읽는지에 대해서는 어떤 주장도 하지 않는다.

이 책이 자체 이름을 유지하는 이유는 실용적이다. 트레이스를 다른 도구로 내보내는 독자에게는 대응표 하나가 필요하고, 표준에 의존하는 곳은 그 표뿐이다. 표준이 바뀌어도 이 책의 필드 이름은 바뀌지 않는다. 대응시켜도 개수에는 아무것도 더해지지 않는다. 프롬프트 개수와 완성 개수는 두 이름 체계에서 같은 숫자이며, 트레이스의 레코드는 기록된 그대로 남는다.

작업 규칙: 자신의 프로젝트에서는 트레이스의 필드에 그것이 세는 대상에 맞는 이름을 붙인다. 표준의 이름으로는 경계에서 표 하나로 대응시키고, 표 옆에 표준의 개정판을 적어 둔다. 표준의 개정판이 바뀌면 표를 다시 확인한다.

무엇이 잘못되며 어떻게 알아차리는가

첫 번째 실수는 result 필드에 있다. refused 호출은 실행된 적이 없는데, refused를 도구의 오류로 받아들이는 독자는 엉뚱한 곳을 살핀다. 이 실수는 기록에서 알아차릴 수 있다. result가 refused이고, malformed가 파싱 오류를 알려 주며, 도구 필드에는 도구의 이름 대신 malformed가 적혀 있고, 게이트의 줄은 비어 있다. 이런 단계의 브리프는 error:로 시작하는데, 이는 도구의 실패처럼 읽히므로 브리프가 아니라 result와 malformed를 읽어야 한다.

두 번째 실수는 디버깅을 위해 추가한 타임스탬프다. 타임스탬프는 실행할 때마다 출력을 바꾸므로, 변경 후 처음 실행하면 예제의 출력과 기록된 출력의 비교가 실패한다. 해결책은 타임스탬프를 없애고 단계 번호를 쓰는 것이다. 단계 번호는 실행마다 같으며, 줄의 순서를 잡는 데 충분하다.

세 번째 실수는 첫 번째 절에 있는 빈 줄이다. 빈 줄을 JSON 파서에 넘기는 리더는 거기서 실패하며, 파일에는 문제가 없는데도 그 실패는 파일이 손상된 것처럼 보인다. 이 실수는 빈 문자열에서 파싱이 실패할 때 알아차릴 수 있다. 해결책은 예제가 하는 것처럼 빈 조각을 의도적으로 건너뛰고 건너뛴 횟수를 세는 규칙이다.

네 번째 실수는 트레이스를 통제 수단으로 여기는 것이다. 트레이스는 게이트와 샌드박스가 내린 결정을 기록한다. 트레이스가 무언가를 결정하지는 않으며, 이미 실행된 호출을 되돌릴 수도 없다. 자식 예제에서 보류된 종료는 게이트가 보류한 것이며, 게이트는 6장에서 설명한다. 명령에 대한 제한은 7장의 샌드박스에서 나온다. 잘못된 실행 뒤에 트레이스를 읽으면 하네스가 무엇을 허용했는지 알 수 있을 뿐, 그 이상은 알 수 없다.

다섯 번째는 이 장의 한계다. 이 장은 내장 도구만 추적한다. 여기서는 MCP 서버를 추적하지 않으므로, MCP 호출이 트레이스에 어떻게 나타나는지에 대해서는 아무 주장도 하지 않는다. 도구 자체는 9장에서 다룬다.

작업 규칙: 트레이스를 믿고 결정을 내리기 전에 result 필드와 stop 필드를 읽고, 출력된 합계를 저장된 총계와 대조한다. 총계와 맞지 않는 트레이스는 기록하는 쪽에 버그가 있는 것이며, 그것이 기록한 실행은 아직 에이전트에 관한 결론이 아니다.

이 장에서 결정한 것

  • 각 실행은 단계마다 JSON 한 줄을 단계 순서대로 기록한다. 키는 정렬하고, 공백은 두지 않으며, ASCII만 사용한다. 빈 줄은 기록하지 않는다.
  • ID는 호출자가 넘겨 주는 카운터에서 만든다. 실행은 run-0001, 호출은 run-0001-c1 형식이다. 시계나 난수 값은 트레이스에 들어가지 않는다.
  • 토큰 수는 녹화본에 저장된 값을 그대로 쓴다. 실시간 토큰 수 검사는 실행하지 않으며, 이 점이 중요한 곳에서는 본문에서 밝힌다.
  • 자식 실행의 레코드에는 자신의 실행 ID와 parent 필드가 있다. 부모의 비용에 자식의 토큰 수가 포함되는 경우는 보고서가 그렇다고 밝힐 때뿐이다.
  • 비용은 단계 수, 도구 호출 수, 토큰 수이며, 각 실행이 어떻게 끝났는지에 따라 묶는다. 이 책은 금액을 제시하지 않는다.
  • 이 책의 필드 이름은 책 고유의 것이다. OpenTelemetry의 이름은 데이터로만 출력하며 사용하지 않는다.

트레이스에 드는 비용은 단계당 한 줄이다. 그 대가로 종료 사유만으로는 답할 수 없는 질문에 답할 수 있다. 어느 단계가 잘못되었는지, 하네스가 무엇을 거부했는지, 각 단계가 토큰을 얼마나 썼는지가 그것이다. 종료 사유, 점수, 비용은 그것을 집계한 줄만큼만 검증할 수 있다. 줄을 보존하고, 줄의 ID를 보존하며, 녹화본이 기록한 대로 수치를 보존한다.

작업 규칙: 보고하는 모든 실행에 대해 단계마다 한 줄씩, ID와 저장된 수치를 함께 보존한다. 이 줄들로 거슬러 추적할 수 없는 수치는 보고하지 않는다.

이 판의 이 장

2026.11.2판예제 통과 2026년 11월 20이 장에서 4개 예제개 중 4개가 통과한다

영어판 2026.11.2판을 번역한 것이다.

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

12장 중 11장: 각 실행을 추적하고 그 비용을 세기

  1. 이벤트당 한 줄
  2. 시계 없는 ID
  3. 토큰 수
  4. 자식의 기록은 부모의 호출 아래에 놓인다
  5. 비용은 금액이 아니라 횟수로 센다
  6. 자신의 필드 이름을 유지하고, 경계에서 대응시킨다
  7. 무엇이 잘못되며 어떻게 알아차리는가
  8. 이 장에서 결정한 것

맨 위로 돌아가기전체 장