将词元与成本归因到每一步

阅读约 56分钟,9节中含8个示例。

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

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

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

实验室

通过动手实践学习本章

完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。约 30 秒后打开。

完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。Labs 为你运行:每月 40小时。

正在查找您的 Lab…

在你自己的机器上,免费: 下载本书的笔记本,附其代码和数据,来源为 GitHub。

读完本章,你可以把一天的模型调用拆分为输入词元、缓存输入词元和输出词元,在不重复计算任何词元的前提下求和,并说明费用流向了哪一步、哪条路由和哪位用户。你还可以说明这些数字中哪些依赖价格表,哪些不依赖。

Ambrewick 的财务团队向助手的追踪记录提出两个问题。第一个是一条消息的成本是多少,按路由和按用户分别计算。这听起来像是对各个 span 求和,但它恰恰是最先出错的问题:用量记录在不止一种 span 上,因此对所有 span 求和会偏高。第二个是同样的消息换成其他语言会花多少钱。本书中的助手只服务英语,但数据集的其他语言区域包含相同的话语,而同一句话在不同语言中占用的词元数各不相同。本章在同一天的数据上测量这两个问题,即基线第 1 天,2026-12-08,共有 200 条消息。每条消息都在基线版本上经助手运行,模型为 Qwen3-4B-Instruct-2507,每次模型调用只记录一次,并在虚拟时钟上重放,如第 1 章所述。

词元排在最前,因为它们是模型实际做的事。金钱排在其次,因为它需要价格,而价格是本书做出并标明日期的一个选择。

每次调用的三个计数

词元计数(token count)是模型在一次调用中,按其自身词表读入或写出的词元数量。本书为每次调用保留三个计数。输入词元是模型读入的整个提示词,其中包含缓存部分;缓存输入词元是模型缓存所保存的那一部分;输出词元是模型写出的内容。GenAI 约定在版本 0.1.0 中以同样的方式定义输入总数: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 个输出词元。已解决的消息是指助手以模型回复作答、而非以兜底回复作答的消息。这里的每个比率都注明了分母,因为按请求计数和按消息计数回答的是不同的问题。

工作准则: 将一次调用的输入报告为整个提示词,包含缓存部分,并在旁边报告缓存输入,不要把两者相加。输出单独给出。在任何词元总数旁注明该计数的来源,因为同一段文本在不同的词表下会得到不同的词元数。

对跨度求和会重复计数

统计一天的词元总量,最直观的做法是把每个跨度上的用量相加。后端的查询通常首先会执行这种求和,而在这里它是错的。规范中关于汇总词元用量的说明指出,不要在未按操作名称过滤的情况下对所有跨度的 gen_ai.usage.* 求和,因为同样的词元可能会在不止一种类型的跨度上被报告,例如智能体跨度和推理跨度。用量记录在每次模型调用的推理跨度上,而助手也按规范允许的方式,在其智能体跨度上设置了该消息的总量。第 2 章给出了这两种跨度类型的名称。

对同一天的用量用三种方式相加,可以看出多出的部分来自哪里。

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

助手在每次模型调用结束时,把该次调用的词元记录到它的计量器上,本书从这个计量器读取两种仪表。指标是 SDK 对大量操作进行聚合后导出的测量值,不带每次操作的细节;计数器只增不减,直方图则把数值计入各个分桶,并保留其总和与计数。输入词元计数器 gen_ai.client.inference.usage.input_tokens 给出这一天的一个总数。按操作记录的直方图为每次模型调用记录一个值,即它的输入词元数,并保留这些值的总和与计数。

对推理跨度求和,输入为 104,811 个词元。对所有跨度求和,则为 209,622。第二个数字是在第一个数字之上加了智能体跨度上的副本,因此恰好高出这份副本。词元计数器在每次模型调用时累加,给出 104,811,与推理跨度的总量相同。需要记住的要点是:计数器与推理跨度相符,而对所有跨度的求和则不相符。

按操作记录的直方图,其总和为 104,811,涉及 321 次操作,也就是模型调用,这与计数器一致。输出计数器给出 4,996 个输出词元。

本书使用的软件包写出的是较旧的词元指标:一个直方图 gen_ai.client.token.usage,按 gen_ai.token.type 拆分。第 3 章把它的名称与注册表中的名称并列展示,在 v0.1.0 中,该直方图的名称为 gen_ai.client.inference.operation.input_tokens, gen_ai.client.inference.operation.output_tokens。计数器则改为按 gen_ai.token.modality 拆分,对每种操作,各模态的计数之和等于总数。规范中的说明指出,词元计数器不受追踪采样的影响,因此从计数器读出的总量在采样器丢弃跨度时依然成立,而从跨度得出的总量则不然。在每次调用时累加的计数器,无论采样器保留什么,都会计入每一次调用;由采样后的跨度重建的总量会随样本减少,必须按比例放大,并附带误差,如第 11 章所示。

工作准则: 一天的词元总量取自计数器,或者只对推理跨度上的用量求和,并按操作名称过滤。智能体跨度上的用量是该智能体在其各次调用中的总量,因此绝不要把它与各次调用的用量相加。在生产环境中,我们从计数器读取总量,因为采样器无法使计数器变稀。

这部分尚未翻译,因此以英文显示。

Cached input, derived from the counters

The runtime does not report the reused count, so the book derives it: cached input is the prompt tokens minus the tokens the runtime evaluated. Reuse happens in two places. The runtime keeps the evaluated prefix of the last prompt, and a call whose prompt starts with the same tokens evaluates only the new suffix; the baseline also turns on a RAM cache, PromptCache(LlamaRAMCache) with cache_prompt: true, which restores the saved state of an earlier prompt with the longest shared prefix once the context's own prefix has been overwritten. The assistant's system prompt and its tool list sit at the front of every prompt, so most calls reuse them.

The pinned llama-cpp-python 0.3.37 has no cached-token field in its Python API or in the performance counters it ships. The recorder takes n_p_eval, the prompt tokens evaluated, as a difference between calls, because the counters accumulate. The counter n_reused sits in the same structure, but it counts graph reuse, not tokens, so this book does not read it as the cached count. We judge that a derived count of reused prefix tokens belongs in gen_ai.usage.cache_read.input_tokens and the cache-read counter, and we record a zero when nothing is reused. The registry defines that attribute as tokens served from a provider-managed cache, as the provider reports them, so the count is the book's own judgement and not a provider's report.

The same 60 messages run twice here, a seeded sample of baseline day 1: once on the baseline release, r0, and once on the cache-off release, r4. Release r4 differs from r0 in two ways. Its RAM cache is off, and llm.reset() clears the runtime's state before each call, which is the way the book's recorder gives each call a fresh state. Setting the cache to none is not enough, because the next call still reuses the prefix of the last one, as the book's probe at the pinned version found.

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

Under the baseline the 60 messages read 29,107 input tokens, and only 11,682 of them were evaluated; the rest were cached. Under the cache-off release they read the same 29,107 tokens, and all of them were evaluated. Resetting the state did not change what the model read; it changed how much of it the runtime had to evaluate, so 17,425 more tokens were evaluated.

That difference is the money. At the book's table the cache-off release costs $0.001394 more on those 60 messages, because cached tokens are billed at the cached rate and evaluated ones at the input rate. A release which changes the cache changes cost and leaves input tokens alone, so a comparison of input tokens would miss that change.

Working rule: Derive cached input at each call from the runtime's counters, never from a release's label. When a release changes the cache, we compare cost on the same messages, because the input count will not move.

其他语言中的同一批话语

词元是按词表计数的,同一段文本在不同语言中所需的词元数量可能相差很大。Petrov 等人对多个分词器测量了这一差距,发现某些语言对之间的差异最高可达十五倍,并且发现在为多种语言构建的分词器中,这一差距依然存在,详见他们的 NeurIPS 2023 论文。本节针对该数据集中的话语测量这一差距。

只有英文消息经过了助手处理。另外五个语言区域是数据集中其他语言区域文件里的同样 200 条话语,按 id 关联。没有模型读过这些文本,也没有助手为它们提供服务,因此每项成本都只是对该文本按输入价格计算的结果。这六个语言区域是英语(en-US)、德语(de-DE)、日语(ja-JP)、印地语(hi-IN)、阿拉伯语(ar-SA)和中文(zh-CN)。该示例使用本书所用模型的分词器文件对六者全部计数,并按本书的价格表对计数结果计价。

每个语言区域的计数都是分词器文件给出的计数:只针对话语文本本身,先规范化为 NFC,再由 tokenizers 0.23.3 配合 4B 模型的 tokenizer.json 进行分词;没有模型读过它,它也不是完整的提示词。

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

同样的 200 条话语,印地语所需的词元数是英语的 4.6 倍。下表给出每个语言区域每条话语的词元数,以及按本书价格表计算的 1,000 条话语的输入成本。

语言区域 每条话语的词元数 每 1,000 条话语的输入成本
英语,en-US 7.5 $0.000754
德语,de-DE 11.0 $0.001097
日语,ja-JP 9.9 $0.000990
印地语,hi-IN 34.3 $0.003432
阿拉伯语,ar-SA 10.1 $0.001008
中文,zh-CN 6.6 $0.000657

英语话语每条需要 7.5 个词元,印地语话语则需要 34.3 个。因此,以英语词元为单位编写的输入词元预算对印地语用户是错误的,请求的成本也是如此。这些计数只针对话语本身,所以在每个语言区域中都低估了完整提示词的词元数。能够带入预算的是各语言区域之间的比值,而且这一比值应当在将要运行的流量上测量。

部分印地语文本不符合分词器所期望的规范形式。200 条印地语话语中有 8 条不属于 Unicode 规范化形式 NFC,该形式的定义见 Unicode 规范化报告。分词器文件在计数之前会先对它们做规范化。llama.cpp 使用的 GGUF 分词器不做任何规范化,因此在这些话语上,它的计数可能与此处的计数不同,200 条中最多有 8 条可能不同;GGUF 的计数没有运行。本章只给出分词器文件的计数,不给出其他计数,并且会说明每个数字来自哪一种计数器。本章不引用任何话语文本,因为没有示例输出这些文本。

工作准则: 对每个语言区域,使用为其提供服务的分词器,并在相同的规范化之后计数,同时在每个数字旁标明所用的计数器。以该语言区域自身的词元为单位编制输入预算,并在依赖某个倍数之前,先在你自己的流量上测量该语言区域的比值。

这部分尚未翻译,因此以英文显示。

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.

按路由和步骤划分的成本

一次调用的成本,是其词元数按一份有名称、有日期的价格表计价的结果;成本归因则把每次调用的成本分配给引起它的步骤、路由和用户。Agent Harnesses有意让成本止步于计数;本书在此基础上加入金额,并且先从词元算起。本书在查询时根据每次调用的词元数和价格表计算成本,不把成本存入跨度。这样,价格变动只会让查询按新价重算,已存储的跨度保持原样。第 1 章曾问哪个步骤花钱最多,本节给出答案。

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

回答步骤的成本最高。在当天的 200 条消息中,回答请求的成本为 $0.006184,占当天成本的 81.8%。路由请求的成本为 $0.001379,占 18.2%。路由调用较小,但每条消息都会发起一次,因此它仍占去近五分之一的费用。

各路由处理一条消息的成本不同。下表给出每个路由的消息数、同一天内每条消息的词元数,以及每 1,000 条消息的成本。分母是各路由上的消息数。

路由 消息数 每条消息的输入词元数 每条消息的输出词元数 每 1,000 条消息的成本
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

messages 路由每条消息的成本最高。不过它只基于 7 条消息,应将其视为一天的样本,而不是确定的费率。fallback 路由的成本最低。它的回复是第 1 章所述的固定回复,其跨度记录了回复并非由模型写成。该路由只发起一次路由调用,不发起回答调用,因此它的一行只包含路由调用。

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展示了每个路由每条消息的输入词元数(缓存部分位于输入柱内)以及并列的输出词元数。一个路由可能输出很少,提示词却依然很贵。

alarmscalendardevicesfallbacklistsmediamessages050010001500tokens per messagecached input, part of inputinput not cachedoutput tokens
图 6.1 按路由划分的每条消息的输入词元、缓存输入词元和输出词元。fallback 路由的柱仅为其路由调用。

图 6.1表明,lists 路由的输出量在除 fallback 路由之外的所有路由中最少,每条消息为 29.0 个词元,而每条消息仍要读取 936.5 个输入词元。messages 路由每条消息读取 1415.4 个输入词元,其中 711.7 个来自缓存。每个路由读取的都远多于写出的。

本节以两个单位数字收尾,每个都附有分母。一条已解决的消息在其自身的调用中花费 $0.000063,分母是模型回答的 111 条消息。按用户计,当天平均每人花费 $0.000063,分母是当天发送过消息的 121 位用户。

这些用户中花费最多的一位发送了 3 条消息,占当天成本的 3.0%。

**工作准则:**根据每次调用记录的计数,把其成本归因到所属的步骤、路由和用户;在每个总额旁打印其占比,并为每个单位费率写明分母。读取某个路由的费率时,要同时看它的消息数,因为只有寥寥几条消息的路由,每天之间可能波动很大。对于财务问题,我们报告每个路由的费率,而不是全天的单一均值,因为各路由的费用并不相同。

昂贵的尾部

平均值会掩盖少数成本远高于其余消息的情况。检查的办法是按成本对消息排序,然后问成本最高的 1% 占当天总花费的多少份额。若有 200 条消息,最高的 1% 就是两条消息。

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

这一天没有集中的昂贵尾部。成本最高的两条消息花费 $0.000234,当天总成本为 $0.007563,占成本的 3.1%。其中最贵的一条走的是 messages 路由,成本为 $0.000118。最贵的两条都由模型解答,因此这个尾部是回答尾部,而不是回退尾部。

这个计数只在这一天内是精确的,所以它只能说明这一天的消息花了多少,对其他日子没有任何说明。换一天份额会变动多少,需要本章没有使用的方法。这个方法是自助法(bootstrap),适用于任何按消息计算的统计量,第 7 章会介绍它。在此之前,一天中的尾部是应连同分母一起报告的计数,而不是可据以制定预算的比率。

工作准则: 将成本最高的 1% 消息报告为计数,并报告其占当天总额的份额,同时写明是哪一天。在第二天提供可供比较的数据之前,不要说某个份额是小还是大。

生产环境中会出什么问题

网关或汇总层开始携带其下各次调用的用量之后,仪表盘上的词元总数可能翻倍,而管道中的其他环节并没有变化。对跨度求和,会把这些词元计算两次。应当从计数器读取总数,或者按操作名称过滤跨度,正如这些约定中的注释所述。

当后端开始只保留一半的追踪数据时,从跨度读取的仪表盘总数会减半,因为跨度会随采样一同减少。计数器不受影响。总数应以计数器为准,跨度则留给计数器无法回答的问题,例如某条消息走了哪条路由。第 11 章会讲解如何把采样得到的总数按比例放大,并给出其误差。

账单发生变化,而输入数量保持不变,原因是某次发布改变了提示词被缓存的比例。只跟踪输入词元的仪表盘会漏掉这一变化。应当把成本与输入、缓存输入并列跟踪,并把缓存数量对照其所属的发布来读。

当成本工具从跨度中取得提供方,而该跨度写的是 openai 时,本地模型会被按托管提供方的费率计价。清单在这种查询上会明确报错,所以危险在于那些退回到默认模型或模糊匹配的工具。本书的价格表以模型为键,查询清单时会指明其提供方。任何为跨度计价的工具都应当这样做。

价格变动的那一天,一个月的成本会随之改变,尽管没有任何消息发生变化。本书价格表中的每一行都带有生效起始日期,每次调用按其自身的时间戳计价。若把成本存储在跨度上,就会沿用旧价格,所以本书在查询时计算成本。

按英语词元设定的预算,对印地语用户会失效,差异来自词表,而不是流量。应当在将要运行的流量上测量每个语言区域的比率,并用服务该语言区域的分词器来计数。

工作准则: 总数以计数器为准,成本以带版本的价格表为准,各语言区域的计数用其自己的分词器。当某次发布改变了提示词或缓存时,应把它的成本与词元数放在一起读,因为二者可能背离。

本章的决定

  • 先算词元,后算金额。每个金额数字都注明价格表的版本 book-2026-11-02 及其日期。
  • 输入词元包含缓存部分。缓存的输入由运行时的计数器推导得出,绝不与输入相加。
  • 总量来自计数器。对跨度求和时,只对推理跨度求和,并按操作名称过滤。智能体跨度的用量就是该智能体的总用量,绝不与各次调用的用量相加。
  • 成本在查询时根据价格表和每次调用的时间戳计算,不存储在跨度上。
  • 关闭缓存的版本称为“每次调用重置”,因为所固定的运行时没有缓存开关。
  • 各语言区域的计数使用分词器文件,并在 NFC 规范化之后进行;本章不给出 GGUF 的计数。话语文本不予引用,因为没有任何示例打印它。
  • 本章不使用区间,因为一天的计数是精确的,无需区间。另一天的波动范围,其方法见第 7 章。
  • 价格是本书的判断:有日期、有版本,而不是报价。若读者倾向于另一种价格,可以修改价格表并保留计数,所有关于词元的论述依然成立。这一区分正是本章先算词元的原因。

本章,在本版次中

版次 2026.11.2示例于 2026年11月23日 通过8 of 8个示例 in this chapter pass

译自英文版图书,版次 2026.11.2。

开始实验室

图书始终免费阅读。

查看价格

引用本节

格式

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

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

本页内容

第 6 章,共 12 章: 将词元与成本归因到每一步

  1. 每次调用的三个计数
  2. 对跨度求和会重复计数
  3. Cached input, derived from the counters
  4. 其他语言中的同一批话语
  5. The price table
  6. 按路由和步骤划分的成本
  7. 昂贵的尾部
  8. 生产环境中会出什么问题
  9. 本章的决定

返回顶部全部章节