각 단계에 토큰과 비용 귀속하기

읽는 데 약 46분, 9절에 8개 예제이(가) 있음.

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

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

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

Labs

직접 해 보며 이 장을 배운다

모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. 약 30초 안에 열린다.

모든 예제를 책에서 한 그대로 실행하고, 코드를 바꿔 결과를 확인하며, 책의 코드와 데이터에 자신의 아이디어를 적용해 본다. 설치할 것은 없으며 작업 내용은 저장된다. Labs가 실행을 대신한다: 월 40시간.

Lab에서 열기, 새 탭에서

이용 시간을 확인하는 중…

Lab을 찾는 중…

자신의 컴퓨터에서, 무료로: 이 책의 노트북 내려받기, 코드와 데이터를 포함해 GitHub에서 받을 수 있다.

이 장을 마치면 하루치 모델 호출을 입력 토큰, 캐시된 입력 토큰, 출력 토큰으로 나누고, 어떤 토큰도 두 번 세지 않고 합산하며, 비용이 어느 단계, 경로, 사용자에게 갔는지 말할 수 있다. 또한 그 수치 가운데 어느 것이 가격표에 의존하고 어느 것이 의존하지 않는지도 말할 수 있다.

Ambrewick의 재무팀은 어시스턴트의 트레이스에 두 가지를 묻는다. 첫째는 메시지 하나의 비용이 경로별, 사용자별로 얼마인가 하는 것이다. 스팬을 모두 더하면 될 것처럼 들리지만, 가장 먼저 잘못되는 질문이 바로 이것이다. 사용량은 둘 이상의 종류의 스팬에 기록되어 있어서, 모든 스팬을 합산하면 값이 지나치게 높아진다. 둘째는 같은 메시지가 다른 언어로 들어오면 비용이 얼마가 되는가 하는 것이다. 이 책의 어시스턴트는 영어만 지원하지만, 데이터셋의 다른 로케일에도 같은 발화가 들어 있고, 같은 발화라도 언어마다 토큰 수가 다르다. 이 장은 기준선 1일차인 2026-12-08, 하루치 데이터로 두 가지를 모두 측정한다. 이 날에는 메시지 200개가 있다. 각 메시지는 기준선 릴리스의 어시스턴트를 거쳤고, 모델은 Qwen3-4B-Instruct-2507이었다. 각 모델 호출은 1장에서 설명한 대로 한 번 기록되었고 가상 시계 위에서 재생되었다.

토큰이 먼저인 이유는 토큰이 모델이 실제로 한 일이기 때문이다. 돈은 그다음인데, 돈에는 가격이 필요하고 그 가격은 이 책이 선택하고 날짜를 붙이는 것이기 때문이다.

호출마다 세 가지 개수

토큰 수는 모델이 한 번의 호출에서 읽거나 쓰는 토큰의 개수이며, 그 모델 자체의 어휘를 기준으로 센다. 이 책은 호출마다 세 가지 개수를 기록한다. 입력 토큰은 모델이 읽은 프롬프트 전체이며 캐시된 부분을 포함한다. 캐시된 입력 토큰은 그중 모델의 캐시에 들어 있던 부분이다. 출력 토큰은 모델이 쓴 것이다. 버전 0.1.0의 GenAI 규약도 입력 총량을 같은 방식으로 정의한다. gen_ai.usage.input_tokens는 캐시된 토큰을 포함한다. 따라서 캐시된 개수는 입력 개수 안에 들어 있으며, 두 값을 더하면 캐시된 부분이 두 번 계산된다.

Agent Harnesses의 프롬프트 개수와 완성 개수는 이 가운데 입력과 출력의 두 개수와 가깝고, 캐시된 부분이 없다. 이 책은 캐시된 부분을 추가하며, 이 장의 뒤에서 개수에 가격도 더한다.

메시지마다 라우팅 호출이 한 번 일어나고, fallback 외의 경로로 가는 메시지는 답변 호출을 한 번 이상 일으킨다. 이날 한 메시지가 일으킨 호출의 최댓값은 3이다. 도구의 요청이 응답보다 먼저 오는 경우로, 라우팅 호출 한 번과 답변 호출 두 번이다. 아래 스크립트는 이날의 모든 호출을 세 가지 개수와 단계별로 분류한다.

token-counts-per-step.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 통과
"""Tokens per model call (a request), per message, per resolved message and per route, over baseline day 1's 200messages. Each rate names its denominator (PL-11): a resolved message is one the model answered, not the fallback reply.The input count includes the cached part, so the cached share is printed beside it."""from lib.dayrun import run_dayfrom lib.report import fmt_int, fmt_shareruns = run_day("2026-12-08")model_steps = {run.message.message_id: [s for s in run.outcome.steps if s.name == "chat"] for run in runs}def totals(steps):    """Input (cached part included), cached input (derived) and output tokens, summed over some model steps."""    return (sum(s.prompt_tokens for s in steps), sum(s.cached_tokens for s in steps),            sum(s.completion_tokens for s in steps))requests = [s for steps in model_steps.values() for s in steps]inp, cached, out = totals(requests)print("messages:", fmt_int(len(runs)))print("requests (model calls):", fmt_int(len(requests)))print("input tokens, total:", fmt_int(inp))print("cached input tokens, derived, total:", fmt_int(cached))print("output tokens, total:", fmt_int(out))print("cached share of input tokens:", fmt_share(cached, inp))print("input tokens per request:", f"{inp / len(requests):.1f}")print("output tokens per request:", f"{out / len(requests):.1f}")print("input tokens per message:", f"{inp / len(runs):.1f}")# Every message makes a route call first; a fallback message stops there, so it has no answer call.for step in ("route", "answer"):    steps = [s for s in requests if s.step == step]    print(f"{step} requests:", fmt_int(len(steps)))    print(f"{step} requests, input tokens per request:", f"{totals(steps)[0] / len(steps):.1f}")model_calls = {run.message.message_id: len(model_steps[run.message.message_id]) for run in runs}assert all(sum(s.step == "route" for s in model_steps[m]) == 1 for m in model_calls)   # one route call per messageprint("most model calls in one message:", max(model_calls.values()))   # the route call and up to two answer callsresolved = [run for run in runs if run.outcome.source == "model"]r_inp, _, r_out = totals([s for run in resolved for s in model_steps[run.message.message_id]])print("resolved messages:", fmt_int(len(resolved)))print("input tokens per resolved message:", f"{r_inp / len(resolved):.1f}")print("output tokens per resolved message:", f"{r_out / len(resolved):.1f}")for route in sorted({run.outcome.route for run in runs}):    mine = [run for run in runs if run.outcome.route == route]    route_inp, _, route_out = totals([s for run in mine for s in model_steps[run.message.message_id]])    print(f"route {route}, messages:", fmt_int(len(mine)))    print(f"route {route}, input tokens per message:", f"{route_inp / len(mine):.1f}")    print(f"route {route}, output tokens per message:", f"{route_out / len(mine):.1f}")assert sum(totals(steps)[0] for steps in model_steps.values()) == inp   # every request belongs to exactly one message
출력python token-counts-per-step.py
messages: 200
requests (model calls): 321
input tokens, total: 104,811
cached input tokens, derived, total: 61,460
output tokens, total: 4,996
cached share of input tokens: 58.6%
input tokens per request: 326.5
output tokens per request: 15.6
input tokens per message: 524.1
route requests: 200
route requests, input tokens per request: 145.5
answer requests: 121
answer requests, input tokens per request: 625.6
most model calls in one message: 3
resolved messages: 111
input tokens per resolved message: 827.7
output tokens per resolved message: 40.2
route alarms, messages: 16
route alarms, input tokens per message: 883.6
route alarms, output tokens per message: 43.4
route calendar, messages: 27
route calendar, input tokens per message: 903.5
route calendar, output tokens per message: 38.8
route devices, messages: 17
route devices, input tokens per message: 627.9
route devices, output tokens per message: 44.5
route fallback, messages: 89
route fallback, input tokens per message: 145.4
route fallback, output tokens per message: 6.0
route lists, messages: 13
route lists, input tokens per message: 936.5
route lists, output tokens per message: 29.0
route media, messages: 31
route media, input tokens per message: 663.9
route media, output tokens per message: 41.6
route messages, messages: 7
route messages, input tokens per message: 1415.4
route messages, output tokens per message: 42.1
연습문제 6.1

입력의 캐시된 비율

+10 증명

24행은 비어 있다. 18행에서 계산한 합계와 5행에서 가져온 fmt_share 도우미를 사용하여, 입력 토큰 중 캐시된 비율을 출력하는 행을 작성하라.

print("input tokens, total:", fmt_int(inp))print("cached input tokens, derived, total:", fmt_int(cached))print("output tokens, total:", fmt_int(out))print("input tokens per request:", f"{inp / len(requests):.1f}")print("output tokens per request:", f"{out / len(requests):.1f}")print("input tokens per message:", f"{inp / len(runs):.1f}")
Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3에서 실행된다
연습문제 6.2

메시지당 입력 비율이 더 낮은 이유

+10 증명

출력에서 메시지당 입력 토큰 줄이 해결된 메시지당 입력 토큰 줄보다 작은 이유는 무엇인가?

메시지당 입력 비율이 더 낮은 이유: 올바른 설명을 고른다
Python 3.13.16에서 실행된다

이날 입력의 대부분은 캐시되어 있다. 이날 모델 호출 전체의 입력 토큰 104,811개 가운데 61,460개가 캐시되었으며, 이는 입력의 58.6%에 해당한다. 출력은 이에 비해 적어서 모두 4,996개 토큰이다.

두 단계는 크기가 다르다. 라우팅 요청은 평균 145.5개의 입력 토큰을 읽고, 답변 요청은 625.6개를 읽는다. 답변 호출이 검색된 문서나 도구의 결과 같은 프롬프트를 더 많이 담기 때문이다.

입력 토큰은 호출의 메시지를 모델의 GGUF 파일에 있는 채팅 템플릿으로 렌더링한 뒤, 그 모델 자체의 토크나이저로 다시 토큰화한 것이다. 출력 토큰은 응답을 모델 자체의 토크나이저로 다시 토큰화한 것이다. 캐시된 입력은 1장에서 설명했듯이 보고된 값이 아니라 유도한 값이며, 그 뺄셈은 아래의 캐시된 입력 절에서 보인다.

이날의 입력을 메시지 수로 나누면 메시지당 524.1개 토큰이다. 해결된 메시지당으로는 입력 827.7개, 출력 40.2개 토큰이다. 해결된 메시지란 어시스턴트가 대체 응답이 아니라 모델의 응답으로 답한 메시지이다. 여기서 각 비율은 분모를 밝힌다. 요청당 개수와 메시지당 개수는 서로 다른 질문에 답하기 때문이다.

작업 규칙: 호출의 입력은 캐시된 부분을 포함한 프롬프트 전체로 보고하고, 캐시된 입력은 그 옆에 따로 보고하되 입력에 더하지 않는다. 출력은 따로 제시한다. 토큰 총량 옆에는 항상 그 개수의 출처를 밝힌다. 같은 텍스트라도 어휘가 다르면 토큰 수가 달라지기 때문이다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Summing spans double counts

The obvious way to total a day's tokens is to add the usage on every span. That is the sum a backend's query would run first, and here it is wrong. The conventions' note on aggregating token usage says not to sum gen_ai.usage.* over all spans without filtering by operation name, because the same tokens can be reported on more than one type of span, such as an agent span and an inference span. Usage sits on each model call's inference span, and the assistant also sets the message's total on its agent span, as the conventions allow. Chapter 2 names both span types.

Adding the usage up three ways over the same day shows where the extra comes from.

totals-metric-against-spans.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 통과
"""Summing usage over every span counts each input token twice, because the agent span carries its message's usage as well asits model calls do (the registry's aggregation note). The assistant's live meter counts each call once, as the call ends,and matches the inference spans. The two asserts are the facts the prose relies on."""from lib.dayrun import RELEASE, run_day_tracedfrom lib.metrics import PER_OPERATION, USAGE, make_meter_provider, totalsfrom lib.names_map import NAMES, REGISTRY_VERSIONfrom lib.report import fmt_intfrom opentelemetry.sdk.metrics.export import InMemoryMetricReaderDAY = "2026-12-08"INPUT = "gen_ai.usage.input_tokens"reader = InMemoryMetricReader()provider = make_meter_provider(reader, service_instance_id=f"{DAY}-metrics", service_version=RELEASE.service_version)traced = run_day_traced(DAY, live=False, meter_provider=provider)   # the assistant records each call's tokens as it endsattributes = [s["attributes"] for s in traced.spans]inference = [a for a in attributes if a.get("gen_ai.operation.name") == "chat"]agents = [a for a in attributes if a.get("gen_ai.operation.name") == "invoke_agent"]   # one per messagedef summed(rows, key):    """The sum of one usage attribute over span attributes; a span without it adds zero."""    return sum(row.get(key, 0) for row in rows)got = totals(reader)spans_input = summed(inference, INPUT)every_span_input = summed(attributes, INPUT)counter_input = int(got[USAGE["input"]]["sum"])print("messages:", fmt_int(len(traced.runs)))print("inference spans, one per model call:", fmt_int(len(inference)))print("agent spans, invoke_agent, one per message:", fmt_int(len(agents)))print("input tokens, summed over the inference spans:", fmt_int(spans_input))print("input tokens, summed over every span:", fmt_int(every_span_input))print("input tokens, token counter total:", fmt_int(counter_input))print("input tokens, per-operation histogram sum:", fmt_int(int(got[PER_OPERATION["input"]]["sum"])))print("per-operation histogram, count of operations:", fmt_int(got[PER_OPERATION["input"]]["count"]))print("output tokens, token counter total:", fmt_int(int(got[USAGE["output"]]["sum"])))print("GenAI conventions version:", REGISTRY_VERSION)print("package token histogram, gen_ai.client.token.usage, v0.1.0 names:", ", ".join(NAMES["gen_ai.client.token.usage"]))assert every_span_input == 2 * spans_input      # the agent spans repeat every inference token once moreassert counter_input == spans_input             # the counter reads each call's usage once, as the call ends
출력python totals-metric-against-spans.py
messages: 200
inference spans, one per model call: 321
agent spans, invoke_agent, one per message: 200
input tokens, summed over the inference spans: 104,811
input tokens, summed over every span: 209,622
input tokens, token counter total: 104,811
input tokens, per-operation histogram sum: 104,811
per-operation histogram, count of operations: 321
output tokens, token counter total: 4,996
GenAI conventions version: 0.1.0
package token histogram, gen_ai.client.token.usage, v0.1.0 names: gen_ai.client.inference.operation.input_tokens, gen_ai.client.inference.operation.output_tokens

The assistant records each model call's tokens on its meter as the call ends, and the book reads two instruments from that meter. A metric is a measurement the SDK aggregates over many operations and exports without each one's detail; a counter only adds, and a histogram counts values into buckets with their sum and count. The input-token counter, gen_ai.client.inference.usage.input_tokens, gives one total for the day. The per-operation histogram records one value for each model call, its input tokens, and keeps their sum and their count.

Summed over the inference spans, the input is 104,811 tokens. Summed over every span, it is 209,622. The second figure is the first with the agent spans' copy added, so it is too high by exactly that copy. The token counter, which the assistant adds to on each model call, gives 104,811, the same total as the inference spans. The point to keep is that the counter and the inference spans agree, and the sum over every span does not.

The per-operation histogram's sum is 104,811 over 321 operations, the model calls, which matches the counter. The output counter gives 4,996 output tokens.

The package this book uses writes an older token metric: one histogram, gen_ai.client.token.usage, that splits by gen_ai.token.type. Chapter 3 shows its names beside the registry's, and in v0.1.0 that histogram's names are gen_ai.client.inference.operation.input_tokens, gen_ai.client.inference.operation.output_tokens. The counters split by gen_ai.token.modality instead, and for each operation the modality counts add up to the total. The conventions' note says that the token counters are not affected by trace sampling, so a total read from them survives a sampler that drops spans, and a total read from spans does not. A counter filled at each call counts every call whatever a sampler keeps; a total rebuilt from sampled spans falls with the sample, and must be scaled up, with an error, as chapter 11 shows.

Working rule: Take a day's token total from the counters, or sum usage over inference spans only, filtered by operation name. Usage on an agent span is that agent's total over its calls, so never add it to the calls' usage. In production we read totals from the counters, because a sampler cannot thin them.

카운터에서 도출한 캐시 입력

런타임은 재사용된 토큰 수를 보고하지 않으므로, 이 책은 그 값을 직접 도출한다. 캐시 입력은 프롬프트 토큰에서 런타임이 평가한 토큰을 뺀 값이다. 재사용은 두 곳에서 일어난다. 런타임은 마지막 프롬프트에서 평가한 접두부를 보관하며, 프롬프트가 같은 토큰으로 시작하는 호출은 새로 추가된 접미부만 평가한다. 기준선은 RAM 캐시도 켜 둔다. 이 캐시는 PromptCache(LlamaRAMCache)이며 cache_prompt: true와 함께 쓴다. 컨텍스트 자체의 접두부가 덮어쓰인 뒤에는, 이전 프롬프트 가운데 공유하는 접두부가 가장 긴 것의 저장된 상태를 복원한다. 어시스턴트의 시스템 프롬프트와 도구 목록은 모든 프롬프트의 맨 앞에 있으므로, 대부분의 호출이 이를 재사용한다.

고정된 버전인 llama-cpp-python 0.3.37은 Python API에도, 함께 제공되는 성능 카운터에도 캐시된 토큰 필드가 없다. 기록기는 카운터가 누적되므로, 평가한 프롬프트 토큰인 n_p_eval를 호출 사이의 차이로 구한다. n_reused 카운터는 같은 구조에 있지만 토큰이 아니라 그래프 재사용을 센다. 따라서 이 책은 이 값을 캐시된 토큰 수로 읽지 않는다. 재사용된 접두부 토큰을 도출한 값은 gen_ai.usage.cache_read.input_tokens와 캐시 읽기 카운터에 속한다고 판단하며, 아무것도 재사용되지 않으면 0을 기록한다. 레지스트리는 이 속성을 제공자가 관리하는 캐시에서 제공된 토큰으로, 제공자가 보고한 대로 정의한다. 따라서 이 수는 제공자의 보고가 아니라 이 책 자체의 판단이다.

여기서는 기준선 1일 차에서 시드를 고정해 뽑은 같은 60개 메시지를 두 번 실행한다. 한 번은 기준선 릴리스인 r0에서, 다른 한 번은 캐시를 끈 릴리스인 r4에서 실행한다. 릴리스 r4은 r0과 두 가지가 다르다. RAM 캐시가 꺼져 있고, llm.reset()가 각 호출 전에 런타임의 상태를 지운다. 이 책의 기록기는 이런 방식으로 각 호출에 새 상태를 준다. 캐시를 none으로 설정하는 것만으로는 충분하지 않다. 고정된 버전에서 이 책의 탐침이 확인했듯이, 다음 호출이 여전히 직전 호출의 접두부를 재사용하기 때문이다.

cached-tokens-from-replay.py Python 3.13.16 · bm25s 0.3.16 · huggingface-hub 2.4.0 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3 통과
"""Cached input tokens for each model call, derived as prompt tokens minus the tokens llama.cpp evaluated (PL-21), on baselineday 1 and on the same 60 messages with the prompt cache reset before each call (release r4). The reset leaves the inputtokens the model reads unchanged; what it removes is the cached part, so the same tokens are all evaluated again. Each callis priced at its own start on the replay clock."""from decimal import Decimalfrom lib.case import load_messagesfrom lib.dayrun import run_dayfrom lib.prices import PriceTablefrom lib.report import fmt_int, fmt_share, fmt_usdfrom lib.tokens import derived_cached, recorded_callsDAY, MODEL = "2026-12-08", "Qwen3-4B-Instruct-2507"paired = {m.message_id for m in load_messages("2026-12-08-paired")}   # the 60 messages r1, r3 and r4 replayday = recorded_calls("baseline-day-1")day_input, _, day_cached = derived_cached(day)print("baseline day 1, model calls:", fmt_int(len(day)))print("baseline day 1, input tokens, total:", fmt_int(day_input))print("baseline day 1, cached input tokens, derived, total:", fmt_int(day_cached))print("baseline day 1, cached share of input:", fmt_share(day_cached, day_input))# The recorder's own derived field is the same subtraction, call by call.assert all(c["cached_tokens_derived"] == c["prompt_tokens"] - c["tokens_evaluated"] for c in day)base = recorded_calls("baseline-day-1", paired)cache_off = recorded_calls("release-cache-off", paired)assert [(c["message_id"], c["step"]) for c in base] == [(c["message_id"], c["step"]) for c in cache_off]  # the same callsb_input, b_evaluated, b_cached = derived_cached(base)o_input, o_evaluated, o_cached = derived_cached(cache_off)print("same 60 messages, model calls:", fmt_int(len(base)))print("r0, input tokens:", fmt_int(b_input))print("r0, tokens evaluated:", fmt_int(b_evaluated))print("r0, cached input tokens, derived:", fmt_int(b_cached))print("r4, input tokens:", fmt_int(o_input))print("r4, tokens evaluated:", fmt_int(o_evaluated))print("r4, cached input tokens, derived:", fmt_int(o_cached))print("tokens evaluated, r4 minus r0:", fmt_int(o_evaluated - b_evaluated))assert o_input == b_input and o_cached == 0          # same input tokens; the cache reset leaves no cached partassert o_evaluated - b_evaluated == b_cached         # every cached token is evaluated again without the cache# The same calls at the book's rates. A recorded call has no clock of its own, so each takes the start the baseline replay# gave its message and step, and r4 makes the same calls, so its calls take the same starts.starts = {(run.message.message_id, s.step): s.start_ns for run in run_day(DAY, paired)          for s in run.outcome.steps if s.name == "chat"}price = PriceTable()def money(calls):    """The money of recorded calls at the book's rates, each at its own start."""    return sum((price.cost(MODEL, c["prompt_tokens"], c["cached_tokens_derived"], c["completion_tokens"],                           starts[(c["message_id"], c["step"])]) for c in calls), Decimal(0))print(f"cost difference, r4 minus r0, same 60 messages, {price.version}:", fmt_usd(money(cache_off) - money(base)))
출력python cached-tokens-from-replay.py
baseline day 1, model calls: 321
baseline day 1, input tokens, total: 104,811
baseline day 1, cached input tokens, derived, total: 61,460
baseline day 1, cached share of input: 58.6%
same 60 messages, model calls: 93
r0, input tokens: 29,107
r0, tokens evaluated: 11,682
r0, cached input tokens, derived: 17,425
r4, input tokens: 29,107
r4, tokens evaluated: 29,107
r4, cached input tokens, derived: 0
tokens evaluated, r4 minus r0: 17,425
cost difference, r4 minus r0, same 60 messages, book-2026-11-02: $0.001394

기준선에서 60개 메시지는 입력 토큰 29,107개를 읽었고, 그중 11,682개만 평가되었다. 나머지는 캐시된 것이다. 캐시를 끈 릴리스에서는 같은 29,107개 토큰을 읽었고, 모두 평가되었다. 상태를 초기화해도 모델이 읽은 내용은 달라지지 않았다. 달라진 것은 런타임이 평가해야 하는 양이며, 그 결과 17,425개의 토큰이 더 평가되었다.

그 차이가 곧 비용이다. 이 책의 요금표로 보면 캐시를 끈 릴리스는 이 60개 메시지에서 $0.001394만큼 더 든다. 캐시된 토큰은 캐시 요율로, 평가된 토큰은 입력 요율로 청구되기 때문이다. 캐시를 바꾸는 릴리스는 비용을 바꾸지만 입력 토큰은 그대로 두므로, 입력 토큰만 비교해서는 그 변화를 놓친다.

작업 규칙: 캐시 입력은 릴리스의 라벨이 아니라 런타임의 카운터에서 호출마다 도출한다. 릴리스가 캐시를 바꿀 때는 입력 수가 움직이지 않으므로, 같은 메시지에 대한 비용을 비교한다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

The same utterances in other languages

Tokens are counted per vocabulary, and the same text can take very different numbers of tokens in different languages. Petrov and colleagues measured the gap for several tokenizers, found differences of up to fifteen times in some language pairs, and found the gap persisted in tokenizers built for many languages, as their NeurIPS 2023 paper reports. This section measures the gap for the dataset's utterances.

Only the English messages ran through the assistant. The other five locales are the same 200 utterances in the dataset's other locale files, joined by id. No model read them and no assistant served them, so each cost is an input rate on that text. The six locales are English (en-US), German (de-DE), Japanese (ja-JP), Hindi (hi-IN), Arabic (ar-SA) and Chinese (zh-CN). The example counts all six with the tokenizer file of the model the book uses, and prices the counts at the book's table.

Each locale's count is the tokenizer file's count: the utterance's text alone, normalised to NFC and tokenized by tokenizers 0.23.3 with the 4B's tokenizer.json; no model read it, and it is not a whole prompt.

count-locales-with-the-tokenizer.py Python 3.13.16 · huggingface-hub 2.4.0 · numpy 2.5.5 · tokenizers 0.23.3 통과
"""Count the same 200 baseline utterances in six locales with the 4B's own tokenizer file, and price the counts at the book'sinput rate. The printed hi-IN ratio is the point the prose rests on: the same request takes several times the Englishtokens. Each count is the utterance's text alone, not a whole prompt."""from decimal import Decimalfrom lib.case import load_locale, load_messagesfrom lib.clock import VirtualClockfrom lib.prices import PriceTablefrom lib.report import fmt_int, fmt_usdfrom lib.tokens import LocaleCounter, is_nfcDAY = "2026-12-08"MODEL = "Qwen3-4B-Instruct-2507"LOCALES = ("en-US", "de-DE", "ja-JP", "hi-IN", "ar-SA", "zh-CN")messages = load_messages(DAY)ids = [m.message_id for m in messages]texts = {m.message_id: m.text for m in messages}by_id = sorted(messages, key=lambda m: int(m.message_id))   # the order load_locale returns each locale's utterances inarrivals = [VirtualClock(DAY, start_ns=m.arrival_ns).now_ns for m in by_id]   # each message's own arrival, on the day's clockcounter, price = LocaleCounter(), PriceTable()print("price table:", price.version)print("utterances, the baseline day's messages joined by id:", fmt_int(len(ids)))means = {}for locale in LOCALES:    utterances = load_locale(locale, ids)   # the same messages, in ascending ID order, so the locales line up    counts = [counter.count(text) for text in utterances]    total = sum(counts)    means[locale] = total / len(counts)    # The text is not cached, so every token bills at the input rate, each utterance at its message's arrival.    per_thousand = sum((price.cost(MODEL, n, 0, 0, at) for n, at in zip(counts, arrivals)), Decimal(0)) * 1000 / len(counts)    print(f"{locale}, tokens, total:", fmt_int(total))    print(f"{locale}, tokens per utterance:", f"{means[locale]:.1f}")    print(f"{locale}, input cost per 1,000 utterances, {price.version}:", fmt_usd(per_thousand))print("hi-IN tokens per utterance, as a multiple of en-US:", f"{means['hi-IN'] / means['en-US']:.1f}")hindi = load_locale("hi-IN", ids)# NFC is applied by the tokenizer file, so only text that is not already NFC can count differently under another counter.print(f"hi-IN utterances not in NFC, of {len(hindi)}:", sum(not is_nfc(text) for text in hindi))assert [texts[i] for i in sorted(ids, key=int)] == load_locale("en-US", ids)  # the English texts are the traffic's ownassert all(is_nfc(t) for locale in LOCALES if locale != "hi-IN" for t in load_locale(locale, ids))
출력python count-locales-with-the-tokenizer.py
price table: book-2026-11-02
utterances, the baseline day's messages joined by id: 200
en-US, tokens, total: 1,508
en-US, tokens per utterance: 7.5
en-US, input cost per 1,000 utterances, book-2026-11-02: $0.000754
de-DE, tokens, total: 2,194
de-DE, tokens per utterance: 11.0
de-DE, input cost per 1,000 utterances, book-2026-11-02: $0.001097
ja-JP, tokens, total: 1,979
ja-JP, tokens per utterance: 9.9
ja-JP, input cost per 1,000 utterances, book-2026-11-02: $0.000990
hi-IN, tokens, total: 6,864
hi-IN, tokens per utterance: 34.3
hi-IN, input cost per 1,000 utterances, book-2026-11-02: $0.003432
ar-SA, tokens, total: 2,015
ar-SA, tokens per utterance: 10.1
ar-SA, input cost per 1,000 utterances, book-2026-11-02: $0.001008
zh-CN, tokens, total: 1,314
zh-CN, tokens per utterance: 6.6
zh-CN, input cost per 1,000 utterances, book-2026-11-02: $0.000657
hi-IN tokens per utterance, as a multiple of en-US: 4.6
hi-IN utterances not in NFC, of 200: 8

The same 200 utterances cost 4.6 times as many tokens in Hindi as in English. The table gives each locale's count per utterance, and the input cost of 1,000 utterances at the book's table.

Locale Tokens per utterance Input cost per 1,000 utterances
English, en-US 7.5 $0.000754
German, de-DE 11.0 $0.001097
Japanese, ja-JP 9.9 $0.000990
Hindi, hi-IN 34.3 $0.003432
Arabic, ar-SA 10.1 $0.001008
Chinese, zh-CN 6.6 $0.000657

The English utterances take 7.5 tokens each, and the Hindi ones take 34.3. A budget for input tokens written in English tokens is therefore wrong for a Hindi user, and the same holds for the cost of a request. The counts are of the utterance alone, so they understate a whole prompt in every locale. What carries into a budget is the ratio between locales, and that ratio should be measured on the traffic that will run.

Some of the Hindi text is not in the normal form the tokenizer expects. 8 of the 200 Hindi utterances are not in Unicode normalisation form NFC, as the Unicode report on normalisation defines it. The tokenizer file normalises them before counting. The GGUF tokenizer that llama.cpp uses applies no normalisation, so its count can differ from this one on those utterances, and at most 8 of the 200 can differ; the GGUF count was not run. This chapter prints the file's count and no other, and it says which counter each number comes from. The chapter quotes no utterance text, because no example prints it.

Working rule: Count each locale with the tokenizer that serves it, after the same normalisation, and name the counter beside every figure. Budget input in the locale's own tokens, and measure the locale's ratio on your own traffic before you rely on a multiple.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

The price table

Every money figure in this chapter comes from one file, the book's price table, examples/data/case/prices.toml, at version book-2026-11-02. The price table is a dated, versioned file of rates per million tokens, read at each call's virtual timestamp. For each model it gives rates in US dollars for input, cached input and output, and a date from which each row applies. The rows were written for this book, not quoted from any provider; each row says what a hosted endpoint would charge at those rates. The ratios matter most: on the 4B row, output costs 4.0 times input, and cached input 0.2 of input.

Hosted providers do not all report input the same way. Anthropic's input_tokens excludes cached tokens, and the conventions' Anthropic note asks instrumentation to add them in, so a reader pricing such a provider normalises its fields to the registry's input total before pricing. Cache writes are counted apart, in gen_ai.usage.cache_write.input_tokens. The book's runtime writes no cache, so its table has no cache-write rate.

A self-hosted model is billed by its machine, not by its tokens. The table therefore attaches a money figure to a token count so that the book can compare requests. It is not a bill for the local model, and Small Open Models works out a machine's bill against per-token prices.

The nearest real price is the genai-prices listing, and it differs from the book's rows in three ways: it names a provider, it has no cache price, and it carries no date. genai-prices 0.2.5 lists the repository Qwen/Qwen3-4B-Instruct-2507 under the provider huggingface_nscale, with an input rate and an output rate. With no cache price, the listing bills cached input at the input rate. The rates are the snapshot the library bundles, and the library makes no network call unless its updater is started. A lookup needs both the full repository name and provider_id="huggingface_nscale": without the provider it raises LookupError, and so does a provider it does not list, as the example asserts. The listing has no text-model row for Qwen3-0.6B, so the book's 0.6B row has no source. The library's 4B row has no start date, and the book's probe at the pinned version found that it prices the same request the same on 2026-11-01, 2026-11-02 and 2026-12-08. So the 2026-11-02 date in the book's table is the book's own, and the library does not supply it.

One answer request from the day, priced three ways, shows how the tables differ.

price-one-request.py Python 3.13.16 · bm25s 0.3.16 · genai-prices 0.2.5 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 통과
"""Price one answer call twice: at the book's own rates, and at the genai-prices 0.2.5 listing for the 4B, which needs itsprovider and a virtual timestamp (B-59). The two prices differ because the rates differ; the book's rates were writtenfor the book and the listing is the real one, so the prose names which is which. Money prints with its table's version."""from decimal import Decimalfrom lib.dayrun import run_dayfrom lib.prices import PriceTable, datetime_offrom lib.report import fmt_int, fmt_usdfrom genai_prices import Usage, calc_priceMODEL, LISTED = "Qwen3-4B-Instruct-2507", "Qwen/Qwen3-4B-Instruct-2507"   # the book's name, and the listing's repo nameruns = run_day("2026-12-08")call = next(s for run in runs for s in run.outcome.steps if s.step == "answer")   # the day's first answer callprint("request, input tokens, total:", fmt_int(call.prompt_tokens))print("request, cached input tokens, derived:", fmt_int(call.cached_tokens))print("request, output tokens:", fmt_int(call.completion_tokens))book = PriceTable()money = book.cost(MODEL, call.prompt_tokens, call.cached_tokens, call.completion_tokens, call.start_ns)no_cache = book.cost(MODEL, call.prompt_tokens, 0, call.completion_tokens, call.start_ns)print(f"book's table, cached input at its own rate, {book.version}:", fmt_usd(money))print(f"book's table, the same request with no cached input, {book.version}:", fmt_usd(no_cache))row = book.row(MODEL, call.start_ns)   # the row in force at the call's startprint("book's table, output rate to input rate:", f"{Decimal(row['output_per_mtok']) / Decimal(row['input_per_mtok']):.1f}")print("book's table, cached input rate to input rate:",      f"{Decimal(row['cache_read_per_mtok']) / Decimal(row['input_per_mtok']):.1f}")usage = Usage(input_tokens=call.prompt_tokens, cache_read_tokens=call.cached_tokens, output_tokens=call.completion_tokens)when = datetime_of(call.start_ns)   # the call's virtual time, never the machine's clocklisted = calc_price(usage, LISTED, provider_id="huggingface_nscale", genai_request_timestamp=when)print("genai-prices listing, huggingface_nscale, the same request:", fmt_usd(listed.total_price))def lookup_fails(*args, **kwargs) -> bool:    """True when genai-prices cannot find a price for the call: a LookupError, not a price from another model."""    try:        calc_price(*args, **kwargs)    except LookupError:        return True    return False# The listing has no cache price, so cached input bills at the input rate: the total does not change with the cache.assert calc_price(Usage(input_tokens=call.prompt_tokens, output_tokens=call.completion_tokens), LISTED,                  provider_id="huggingface_nscale", genai_request_timestamp=when).total_price == listed.total_priceassert lookup_fails(usage, LISTED, genai_request_timestamp=when)          # no provider given: no priceassert lookup_fails(usage, LISTED, provider_id="openai", genai_request_timestamp=when)   # the span's provider: no priceassert lookup_fails(usage, "Qwen/Qwen3-0.6B", provider_id="huggingface_nscale", genai_request_timestamp=when)
출력python price-one-request.py
request, input tokens, total: 212
request, cached input tokens, derived: 201
request, output tokens: 27
book's table, cached input at its own rate, book-2026-11-02: $0.000016
book's table, the same request with no cached input, book-2026-11-02: $0.000032
book's table, output rate to input rate: 4.0
book's table, cached input rate to input rate: 0.2
genai-prices listing, huggingface_nscale, the same request: $0.000003
연습문제 6.3

캐시를 제거한 요청의 가격 계산

+10 증명

20번째 줄은 캐시 없이 요청의 가격을 계산하기 전에 입력 토큰 수에서 캐시된 토큰을 뺀다. 같은 요청의 모든 입력이 입력 요율로 계산되고 캐시된 입력은 없도록 이 줄을 고쳐라.

book = PriceTable()money = book.cost(MODEL, call.prompt_tokens, call.cached_tokens, call.completion_tokens, call.start_ns)print(f"book's table, cached input at its own rate, {book.version}:", fmt_usd(money))print(f"book's table, the same request with no cached input, {book.version}:", fmt_usd(no_cache))row = book.row(MODEL, call.start_ns)   # the row in force at the call's start
Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · genai-prices 0.2.5 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3에서 실행된다

The request reads 212 input tokens, most of them cached, and writes 27 output tokens. At the book's table it costs $0.000016. With the cache removed from the same request it would cost $0.000032, so the cache is what brings the bill down for this call.

The listing prices the same request at $0.000003. The gap between the two is the gap between the rate rows, since the tokens are the same in both.

A cost tool needs one more guard. The book's spans record gen_ai.provider.name as openai, because the assistant's client speaks OpenAI's API to a local server, as chapter 2 explains. A cost tool that reads that value could look up OpenAI's rates for a model OpenAI does not serve, and price the local model at OpenAI's rates. The listing fails loudly on that lookup, since it raises LookupError for the 4B under openai, so the risk is a tool that falls back to a default model or a fuzzy match. The book's table is keyed by model and does not read the provider value, and the listing is queried with its provider named by hand. A query that prices spans should do the same, and should never take the provider from the span. MLflow is one such tool: it prices a span only when its catalog knows the span's model, which is why it stored no cost for the 4B in chapter 5, and a self-hosted model reported under a hosted model's name could be priced at that model's rates.

The table's version and dates matter once a price changes. The release comparison in chapter 10 reads its money from this same table version, so one version holds every money figure that is compared.

Working rule: Attach a price table's version and its date to every money figure. Price each call at its own timestamp, and name the provider when you use a listing. Never take a provider from a span to choose the price. We key the book's table by model, and never by the span's provider.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Cost by route and step

A call's cost is its tokens priced by a named, dated price table, and cost attribution assigns each call's cost to the step, route and user that caused it. Agent Harnesses stops its cost at counts on purpose; this book adds money, tokens first. The book computes cost at query time, from each call's tokens and the table, and does not store cost on the spans. A price change then reprices the query and leaves the stored spans as they were. Chapter 1 asked which step costs the most money, and this section answers it.

cost-by-route-and-user.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 통과
"""Cost by step, by route, per resolved message and per user on baseline day 1, at the book's rates. Each call is priced atits own start, and the price row in force at that time is the one used (PL-20). Every rate names its denominator (PL-11):messages sent to the route, messages the model resolved, or users. The fallback route makes a route call and no answer call."""from collections import Counterfrom decimal import Decimalfrom lib.dayrun import run_dayfrom lib.prices import PriceTablefrom lib.report import fmt_int, fmt_share, fmt_usdMODEL = "Qwen3-4B-Instruct-2507"runs = run_day("2026-12-08")price = PriceTable()cost, by_step = Counter(), Counter()   # Decimal money per message ID, and per step namefor run in runs:    for step in (s for s in run.outcome.steps if s.name == "chat"):        money = price.cost(MODEL, step.prompt_tokens, step.cached_tokens, step.completion_tokens, step.start_ns)        cost[run.message.message_id] += money        by_step[step.step] += moneytotal = sum(cost.values(), Decimal(0))print("messages:", fmt_int(len(runs)))print(f"cost, all messages, {price.version}:", fmt_usd(total))for step in ("route", "answer"):    print(f"{step} requests, cost, {price.version}:", fmt_usd(by_step[step]))    print(f"{step} requests, share of cost:", fmt_share(by_step[step], total))assert sum(by_step.values(), Decimal(0)) == total   # the two steps make up the whole costfor route in sorted({run.outcome.route for run in runs}):    mine = [run for run in runs if run.outcome.route == route]    route_cost = sum((cost[run.message.message_id] for run in mine), Decimal(0))    print(f"route {route}, messages:", fmt_int(len(mine)))    print(f"route {route}, cost per 1,000 messages, {price.version}:", fmt_usd(route_cost * 1000 / len(mine)))resolved = [run for run in runs if run.outcome.source == "model"]resolved_total = sum((cost[run.message.message_id] for run in resolved), Decimal(0))print("resolved messages:", fmt_int(len(resolved)))print(f"cost of a resolved message, its own calls, {price.version}:", fmt_usd(resolved_total / len(resolved)))by_user = Counter()                          # Decimal money per user IDfor run in runs:    by_user[run.message.user_id] += cost[run.message.message_id]assert sum(by_user.values(), Decimal(0)) == total   # the users make up the whole costcostliest = max(sorted(by_user), key=by_user.get)   # ties go to the lower ID, so the choice is stableprint("users with a message:", fmt_int(len(by_user)))print(f"cost per user, mean over users with a message, {price.version}:", fmt_usd(total / len(by_user)))print("costliest user, messages:", fmt_int(sum(run.message.user_id == costliest for run in runs)))print("costliest user, share of cost:", fmt_share(by_user[costliest], total))
출력python cost-by-route-and-user.py
messages: 200
cost, all messages, book-2026-11-02: $0.007563
route requests, cost, book-2026-11-02: $0.001379
route requests, share of cost: 18.2%
answer requests, cost, book-2026-11-02: $0.006184
answer requests, share of cost: 81.8%
route alarms, messages: 16
route alarms, cost per 1,000 messages, book-2026-11-02: $0.063688
route calendar, messages: 27
route calendar, cost per 1,000 messages, book-2026-11-02: $0.057486
route devices, messages: 17
route devices, cost per 1,000 messages, book-2026-11-02: $0.056201
route fallback, messages: 89
route fallback, cost per 1,000 messages, book-2026-11-02: $0.006630
route lists, messages: 13
route lists, cost per 1,000 messages, book-2026-11-02: $0.074429
route media, messages: 31
route media, cost per 1,000 messages, book-2026-11-02: $0.057041
route messages, messages: 7
route messages, cost per 1,000 messages, book-2026-11-02: $0.101463
resolved messages: 111
cost of a resolved message, its own calls, book-2026-11-02: $0.000063
users with a message: 121
cost per user, mean over users with a message, book-2026-11-02: $0.000063
costliest user, messages: 3
costliest user, share of cost: 3.0%
연습문제 6.4

각 경로의 비용을 해당 경로의 메시지 수로 나눈다

+10 증명

32행은 각 경로의 비용을 그 경로의 메시지 수가 아니라 하루 전체의 메시지 수로 나눈다. 각 경로의 비율이 그 경로 자체의 메시지 수를 사용하도록 고쳐라.

    mine = [run for run in runs if run.outcome.route == route]    route_cost = sum((cost[run.message.message_id] for run in mine), Decimal(0))    print(f"route {route}, messages:", fmt_int(len(mine)))resolved = [run for run in runs if run.outcome.source == "model"]resolved_total = sum((cost[run.message.message_id] for run in resolved), Decimal(0))
Python 3.13.16 · bm25s 0.3.16 · duckdb 2.0.1 · httpx 0.28.1 · huggingface-hub 2.4.0 · matplotlib 3.11.2 · mcp 2.3.0 · mlflow 3.18.0 · mlflow-skinny 3.18.0 · mlflow-tracing 3.18.0 · numpy 2.5.5 · openai 3.57.0 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 · tokenizers 0.23.3에서 실행된다
연습문제 6.5

폴백 경로의 비용이 가장 낮은 이유

+10 증명

폴백 경로는 모든 경로 중 메시지 1,000건당 비용이 가장 낮게 출력된다. 이 수치를 설명하는 진술은 무엇인가?

폴백 경로의 비용이 가장 낮은 이유: 올바른 설명을 고른다
Python 3.13.16에서 실행된다

The answer step costs most. Over the day's 200 messages, the answer requests cost $0.006184, which is 81.8% of the day's cost. The route requests cost $0.001379, or 18.2%. The route call is smaller, but every message makes one, so it still holds nearly a fifth of the money.

The routes differ in what a message costs. The table gives each route's messages, its tokens per message from the same day, and its cost per 1,000 messages. The denominator is the messages on each route.

Route Messages Input tokens per message Output tokens per message Cost per 1,000 messages
alarms 16 883.6 43.4 $0.063688
calendar 27 903.5 38.8 $0.057486
devices 17 627.9 44.5 $0.056201
fallback 89 145.4 6.0 $0.006630
lists 13 936.5 29.0 $0.074429
media 31 663.9 41.6 $0.057041
messages 7 1415.4 42.1 $0.101463

The messages route costs the most per message. It rests on 7 messages, though, so read it as one day's sample and not as a settled rate. The fallback route costs the least. Its reply is the fixed one that chapter 1 describes, and its span records that no model wrote it. The route makes its one route call and no answer call, so its row carries the route call alone.

figure-route-token-mix.py Python 3.13.16 · bm25s 0.3.16 · matplotlib 3.11.2 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 통과
"""Draw the input, cached and output tokens per message on each route, over baseline day 1's 200 messages. The cached part isdrawn inside the input bar, hatched, so no reader adds it to input; output stands beside it. Every bar is printed by routewith its message count, since a tokens-per-message rate names its denominator (PL-11)."""from lib.dayrun import run_dayfrom lib.figures import ACCENT, INK, MUTED, new_figure, savefrom lib.report import fmt_intruns = run_day("2026-12-08")routes = sorted({run.outcome.route for run in runs})per_message = {}                            # route: (input, cached, output) tokens per message, as floatsfor route in routes:    mine = [run for run in runs if run.outcome.route == route]    steps = [s for run in mine for s in run.outcome.steps if s.name == "chat"]   # model calls only; no tool time here    averages = tuple(sum(values) / len(mine) for values in (        [s.prompt_tokens for s in steps], [s.cached_tokens for s in steps], [s.completion_tokens for s in steps]))    per_message[route] = averages    print(f"route {route}, messages:", fmt_int(len(mine)))    print(f"route {route}, input tokens per message:", f"{averages[0]:.1f}")    print(f"route {route}, cached input tokens per message:", f"{averages[1]:.1f}")    print(f"route {route}, output tokens per message:", f"{averages[2]:.1f}")fig, ax = new_figure(height=2.8)positions, width = list(range(len(routes))), 0.36left, right = [p - width / 2 for p in positions], [p + width / 2 for p in positions]cached = [per_message[r][1] for r in routes]uncached = [per_message[r][0] - per_message[r][1] for r in routes]   # input minus its cached part, stacked on top of itax.bar(left, cached, width=width, color=MUTED, hatch="///", edgecolor=INK, label="cached input, part of input")ax.bar(left, uncached, bottom=cached, width=width, color=ACCENT, label="input not cached")ax.bar(right, [per_message[r][2] for r in routes], width=width, color=INK, label="output tokens")ax.set_xticks(positions, routes)ax.set_ylabel("tokens per message")ax.set_ylim(0, 1.35 * max(v[0] for v in per_message.values()))   # headroom above the tallest bar for the legendax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.16), ncol=3, frameon=False)   # below the plot, clear of the top ticksave(fig, "route-token-mix")
출력python figure-route-token-mix.py
route alarms, messages: 16
route alarms, input tokens per message: 883.6
route alarms, cached input tokens per message: 525.3
route alarms, output tokens per message: 43.4
route calendar, messages: 27
route calendar, input tokens per message: 903.5
route calendar, cached input tokens per message: 604.9
route calendar, output tokens per message: 38.8
route devices, messages: 17
route devices, input tokens per message: 627.9
route devices, cached input tokens per message: 305.1
route devices, output tokens per message: 44.5
route fallback, messages: 89
route fallback, input tokens per message: 145.4
route fallback, cached input tokens per message: 128.9
route fallback, output tokens per message: 6.0
route lists, messages: 13
route lists, input tokens per message: 936.5
route lists, cached input tokens per message: 385.3
route lists, output tokens per message: 29.0
route media, messages: 31
route media, input tokens per message: 663.9
route media, cached input tokens per message: 325.1
route media, output tokens per message: 41.6
route messages, messages: 7
route messages, input tokens per message: 1415.4
route messages, cached input tokens per message: 711.7
route messages, output tokens per message: 42.1
figure: figures/route-token-mix.svg

그림 6.1 shows each route's input tokens per message, with the cached part inside the input bar, and its output tokens beside it. A route can be cheap in output and still expensive in prompt.

alarmscalendardevicesfallbacklistsmediamessages050010001500tokens per messagecached input, part of inputinput not cachedoutput tokens
그림 6.1 Input, cached input and output tokens per message, by route. The fallback route's bars are its route call alone.

그림 6.1 shows that the lists route writes the least output of any route but the fallback route, 29.0 tokens per message, and still reads 936.5 input tokens per message. The messages route reads 1415.4 input tokens per message, of which 711.7 are cached. Every route reads far more than it writes.

Two per-unit figures close the section, each with its denominator. A resolved message costs $0.000063 in its own calls, over the 111 messages the model answered. Per user, the day costs $0.000063 on average, over the 121 users who sent a message that day.

The costliest of those users sent 3 messages and holds 3.0% of the day's cost.

Working rule: Attribute each call's cost to its step, route and user from each call's recorded counts, print each share beside its total, and name the denominator of every per-unit rate. Read a route's rate with its message count beside it, because a route with a handful of messages can move a lot from one day to the next. For the finance question we report each route's rate, not one mean over the day, because the money differs by route.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

The expensive tail

An average hides the few messages that cost much more than the rest. The check is to rank the messages by cost and ask what share of the day's money the top 1% holds. With 200 messages, the top 1% is two messages.

expensive-tail-share.py Python 3.13.16 · bm25s 0.3.16 · mcp 2.3.0 · numpy 2.5.5 · opentelemetry-api 1.45.2 · opentelemetry-exporter-http-transport 0.66b2 · opentelemetry-exporter-otlp-common 0.66b2 · opentelemetry-exporter-otlp-proto-common 1.45.2 · opentelemetry-exporter-otlp-proto-http 1.45.2 · opentelemetry-instrumentation 0.66b2 · opentelemetry-instrumentation-genai-openai 1.3b0 · opentelemetry-proto 1.45.2 · opentelemetry-sdk 1.45.2 · opentelemetry-semantic-conventions 0.66b2 · opentelemetry-util-genai 1.3b0 · pydantic 2.14.4 통과
"""The most expensive 1% of baseline day 1's messages, and their share of the day's cost at the book's rates. The count isexact over the day's 200 messages, with no interval: an interval for another day is chapter 7's. The count is thenearest-rank count for 1% of n (PL-5), and equal costs are ordered by message ID so the choice is stable."""import mathfrom decimal import Decimalfrom fractions import Fractionfrom lib.dayrun import run_dayfrom lib.prices import PriceTablefrom lib.report import fmt_int, fmt_share, fmt_usdMODEL = "Qwen3-4B-Instruct-2507"runs = run_day("2026-12-08")price = PriceTable()cost = {}                                   # Decimal money per message IDfor run in runs:    cost[run.message.message_id] = sum((price.cost(MODEL, s.prompt_tokens, s.cached_tokens, s.completion_tokens,                                                   s.start_ns)                                        for s in run.outcome.steps if s.name == "chat"), Decimal(0))ranked = sorted(runs, key=lambda run: (-cost[run.message.message_id], int(run.message.message_id)))k = math.ceil(Fraction(1, 100) * len(runs))  # 1% of 200 is 2 messagestail = ranked[:k]total = sum(cost.values(), Decimal(0))tail_money = sum((cost[run.message.message_id] for run in tail), Decimal(0))print("messages:", fmt_int(len(runs)))print("messages in the most expensive 1%:", fmt_int(k))print(f"cost of the day, {price.version}:", fmt_usd(total))print(f"cost of the most expensive 1%, {price.version}:", fmt_usd(tail_money))print("share of the day's cost, most expensive 1%:", fmt_share(tail_money, total))print("most expensive message, route:", tail[0].outcome.route)print(f"most expensive message, cost, {price.version}:", fmt_usd(cost[tail[0].message.message_id]))print("most expensive 1%, messages resolved by the model:", fmt_int(sum(run.outcome.source == "model" for run in tail)))assert tail_money * len(runs) > total * k        # the tail costs more per message than the day does on average
출력python expensive-tail-share.py
messages: 200
messages in the most expensive 1%: 2
cost of the day, book-2026-11-02: $0.007563
cost of the most expensive 1%, book-2026-11-02: $0.000234
share of the day's cost, most expensive 1%: 3.1%
most expensive message, route: messages
most expensive message, cost, book-2026-11-02: $0.000118
most expensive 1%, messages resolved by the model: 2

On this day there is no concentrated expensive tail. The two most expensive messages cost $0.000234 of the day's $0.007563, which is 3.1% of the cost. The most expensive of them, on the messages route, cost $0.000118. Both of the top two were resolved by the model, so the tail is an answer tail, not a fallback one.

The count is exact over one day, so it says what this day's messages cost and nothing about another day. How far another day would move the share needs a method this chapter does not use. The method is the bootstrap, which applies to any per-message statistic, and chapter 7 introduces it. Until then, a tail on one day is a count to report with its denominator, and not a rate to plan a budget on.

Working rule: Report the top 1% of messages as a count and as a share of the day's total, with the day named. Do not call a share small or large until a second day gives something to compare it with.

운영 환경에서 무엇이 잘못되는가

게이트웨이나 롤업이 그 아래 호출들의 사용량을 함께 싣기 시작하면 대시보드의 토큰 합계가 두 배가 될 수 있으며, 파이프라인의 다른 부분은 아무것도 바뀌지 않는다. 스팬을 합산하면 그 토큰을 두 번 센다. 합계는 카운터에서 읽거나, 규약의 주석이 말하는 대로 스팬을 작업 이름으로 걸러서 읽어야 한다.

백엔드가 트레이스의 절반만 보관하기 시작하면 스팬에서 읽은 대시보드 합계도 절반이 된다. 스팬이 표본과 함께 사라지기 때문이다. 카운터는 영향을 받지 않는다. 합계에는 카운터를 쓰고, 메시지가 어떤 경로를 거쳤는지처럼 카운터로 답할 수 없는 질문에는 스팬을 쓴다. 11장에서는 표본 추출된 합계를 오차와 함께 원래 규모로 환산한다.

릴리스가 프롬프트 중 캐시된 부분의 크기를 바꾸면, 입력 토큰 수는 그대로인데 청구액이 달라진다. 입력 토큰만 추적하는 대시보드는 이 변화를 놓친다. 비용을 입력 토큰 및 캐시된 입력 토큰과 나란히 추적하고, 캐시된 토큰 수는 그것이 속한 릴리스와 대조하여 읽어야 한다.

비용 도구가 스팬에서 제공자를 가져오는데 그 스팬에 openai라고 적혀 있으면, 로컬 모델이 호스팅 제공자의 요금으로 계산된다. 이 책의 목록은 그 조회에서 오류를 내며 실패하므로, 위험한 쪽은 기본 모델로 대체하거나 유사 일치를 쓰는 도구이다. 이 책의 표는 모델을 키로 하고, 목록은 제공자를 명시하여 조회한다. 스팬에 가격을 매기는 도구라면 모두 같은 방식을 따라야 한다.

어떤 메시지도 바뀌지 않았는데 가격이 바뀐 날에 한 달 치 비용이 달라진다. 이 책의 표에서 각 행은 유효 시작일을 갖고, 각 호출은 자기 타임스탬프의 가격으로 계산된다. 스팬에 저장한 비용은 이전 가격을 그대로 유지하므로, 이 책은 비용을 쿼리 시점에 계산한다.

영어 토큰 기준으로 정한 예산은 힌디어 사용자에게서 어긋나며, 그 차이는 트래픽이 아니라 어휘에서 비롯된다. 로캘별 비율은 실제로 처리될 트래픽으로 측정하고, 해당 로캘을 처리하는 토크나이저로 센다.

작업 규칙: 합계는 카운터에, 비용은 버전이 붙은 표에, 각 로캘의 토큰 수는 그 로캘 자체의 토크나이저에 맡긴다. 릴리스가 프롬프트나 캐시를 바꾸면 비용을 토큰 수와 나란히 읽는다. 둘이 서로 다르게 움직일 수 있기 때문이다.

이 장에서 결정한 것

  • 토큰을 먼저 다루고 금액은 그다음에 다룬다. 금액을 제시할 때마다 가격표의 버전인 book-2026-11-02과 그 날짜를 함께 밝힌다.
  • 입력 토큰에는 캐시된 부분이 포함된다. 캐시된 입력은 런타임의 카운터에서 도출하며, 입력에 따로 더하지 않는다.
  • 합계는 카운터에서 구한다. 스팬에 대한 합은 추론 스팬만 대상으로 하되 연산 이름으로 걸러서 구한다. 에이전트 스팬의 사용량은 해당 에이전트의 총량이므로 호출들의 사용량에 더하지 않는다.
  • 비용은 질의 시점에 가격표와 각 호출의 타임스탬프로 계산한다. 스팬에는 저장하지 않는다.
  • 캐시를 끈 릴리스는 호출마다 초기화라고 부른다. 고정한 런타임에는 캐시를 끄는 스위치가 없기 때문이다.
  • 로케일별 개수는 NFC 정규화를 거친 뒤 토크나이저 파일로 센다. 이 장은 GGUF 개수를 싣지 않는다. 발화 텍스트는 어떤 예제도 출력하지 않으므로 인용하지 않는다.
  • 이 장은 구간을 쓰지 않는다. 하루치 개수는 정확하여 구간이 필요하지 않기 때문이다. 다른 날의 변동 폭을 구하는 방법은 7장에서 다룬다.
  • 가격은 이 책의 판단이다. 날짜와 버전이 있으며 견적이 아니다. 다른 가격을 선호하는 독자는 가격표를 바꾸고 개수는 그대로 두면 되며, 토큰에 관한 모든 문장은 여전히 성립한다. 이 장이 토큰을 먼저 다루는 이유가 이러한 분리에 있다.

이 판의 이 장

2026.11.2판예제 통과 2026년 11월 238 of 8개 예제 in this chapter pass

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

Labs 시작

도서는 계속 무료로 읽을 수 있다.

요금 보기

이 절 인용

형식

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

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

이 페이지의 내용

12장 중 6장: 각 단계에 토큰과 비용 귀속하기

  1. 호출마다 세 가지 개수
  2. Summing spans double counts
  3. 카운터에서 도출한 캐시 입력
  4. The same utterances in other languages
  5. The price table
  6. Cost by route and step
  7. The expensive tail
  8. 운영 환경에서 무엇이 잘못되는가
  9. 이 장에서 결정한 것

맨 위로 돌아가기전체 장