將 token 與成本歸屬到每個步驟

閱讀約 52 分鐘,9 節 中共有 8 個範例。

版次 2026.11.2 範例於 2026年11 月 23 通過測試 80 個範例中有 80 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.2。 閱讀原文

Labs

透過實作學習本章

完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。約 30 秒內開啟。

完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。由 Labs 為你執行:每月 40 小時。

在 Lab 中開啟,於新分頁開啟

正在檢查您的時數…

正在尋找您的 Lab…

於您自己的電腦,免費: 下載本書的筆記本,連同其程式碼與資料,皆取自 GitHub。

讀完本章,你可以把一天的模型呼叫拆成輸入 token、快取輸入 token 與輸出 token,在不重複計算任何 token 的情況下加總,並說明這些費用花在哪個步驟、哪條路由、哪位使用者身上。你也可以說明這些數字中,哪些取決於價格表,哪些不取決於價格表。

Ambrewick 的財務團隊對助理的追蹤記錄提出兩個問題。第一個是一則訊息的成本是多少,要依路由與使用者分別計算。這聽起來像是對所有 span 加總,卻是最先出錯的問題:用量記錄在不只一種 span 上,所以對全部 span 加總會得到過高的結果。第二個問題是,同樣的訊息換成其他語言要花多少成本。本書的助理只服務英文,但資料集的其他語系含有相同的語句,而同一句話在每種語言中所需的 token 數並不相同。本章以一天的資料來衡量這兩件事,即基準第 1 天,2026-12-08,共有 200 則訊息。每則訊息都在基準版本上經過助理處理,模型為 Qwen3-4B-Instruct-2507,每次模型呼叫都記錄一次,並在虛擬時鐘上重播,如第 1 章所述。

先談 token,因為 token 反映了模型實際做了什麼。再談金額,因為金額需要價格,而價格是本書做出並標註日期的選擇。

每次呼叫的三種計數

詞元計數(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 行目前是空白。請寫出一行程式,印出快取的輸入 token 佔比,並使用第 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 則證明

在輸出中,為什麼「每則訊息的輸入 token 數」那一行,比「每則已解決訊息的輸入 token 數」那一行小?

為什麼每則訊息的輸入率較低:選出正確的說明
在 Python 3.13.16 上執行

當天的輸入大部分來自快取。在當天所有模型呼叫的 104,811 個輸入詞元中,有 61,460 個來自快取,占輸入的 58.6%。相較之下,輸出很少,總共只有 4,996 個詞元。

兩個步驟的規模並不相同。路由請求平均讀取 145.5 個輸入詞元,回答請求則讀取 625.6 個,因為回答呼叫攜帶了更多提示內容,例如檢索到的文章與工具的結果。

輸入詞元是將該次呼叫的訊息,經由模型 GGUF 檔案中的聊天範本轉譯,再以該模型自身的分詞器重新分詞而得。輸出詞元則是將回覆以該模型自身的分詞器重新分詞而得。快取輸入是推算而來,並非由模型回報,如第 1 章所述,下方的快取輸入一節會示範這項減法。

以訊息數相除,當天的輸入為每則訊息 524.1 個詞元。若以已解決的訊息計算,則每則為 827.7 個輸入詞元與 40.2 個輸出詞元。已解決的訊息是指助理以模型回覆作答、而非以後備回覆作答的訊息。這裡的每個比率都註明其分母,因為每個請求的計數與每則訊息的計數,回答的是不同的問題。

實用原則: 回報一次呼叫的輸入時,以完整提示為準,包含快取的部分,並在旁邊另列快取輸入,切勿與其相加。輸出則單獨列出。任何詞元總數旁都要註明計數的來源,因為同一段文字在不同的詞彙表中,詞元數量並不相同。

加總 span 會重複計算

要計算一天的 token 總量,最直觀的做法是把每個 span 上的用量加起來。這正是後端查詢最先會執行的加總,而在這裡它是錯的。關於彙總 token 用量的慣例說明指出,不要在未依操作名稱篩選的情況下,對所有 span 加總 gen_ai.usage.*,因為同樣的 token 可能會在不只一種類型的 span 上回報,例如 agent span 與推論 span。用量記錄在每次模型呼叫的推論 span 上,而助理也依慣例允許的做法,把該則訊息的總量設在其 agent span 上。第 2 章說明了這兩種 span 類型。

以三種方式加總同一天的用量,便可看出多出來的部分從何而來。

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

助理在每次模型呼叫結束時,把該次呼叫的 token 記錄到它的 meter 上,本書從這個 meter 讀取兩種 instrument。指標(metric)是 SDK 對多次操作進行彙總、並在不附帶各次操作細節的情況下匯出的量測值;counter 只會累加,而 histogram 則把數值歸入各個 bucket,並保留其總和與次數。輸入 token 的 counter,也就是 gen_ai.client.inference.usage.input_tokens,給出當天的單一總量。每次操作的 histogram 則為每次模型呼叫記錄一個值,即其輸入 token,並保留這些值的總和與次數。

對推論 span 加總,輸入為 104,811 個 token。對所有 span 加總,則為 209,622。第二個數字等於第一個數字再加上 agent span 的那一份副本,因此偏高的量正好就是那份副本。token counter 在每次模型呼叫時累加,給出 104,811,與推論 span 的總量相同。要記住的重點是:counter 與推論 span 的結果一致,而對所有 span 的加總則不然。

每次操作 histogram 的總和是 104,811,涵蓋 321 次操作,也就是那些模型呼叫,與 counter 相符。輸出 counter 則給出 4,996 個輸出 token。

本書使用的套件寫入的是較舊的 token 指標:單一 histogram gen_ai.client.token.usage,並依 gen_ai.token.type 區分。第 3 章把它的名稱與規格登錄中的名稱並列顯示,在 v0.1.0 中,該 histogram 的名稱是 gen_ai.client.inference.operation.input_tokens, gen_ai.client.inference.operation.output_tokens。counter 則改為依 gen_ai.token.modality 區分,且對每個操作而言,各模態的計數加總後等於總量。慣例說明指出,token counter 不受追蹤取樣影響,因此從 counter 讀取的總量不受會丟棄 span 的取樣器影響,而從 span 讀取的總量則會受影響。在每次呼叫時累加的 counter,不論取樣器保留了什麼,都會計入每一次呼叫;由取樣後的 span 重建的總量會隨取樣而減少,必須向上放大,並附上誤差,如第 11 章所示。

實用原則: 一天的 token 總量應取自 counter,或只對推論 span 加總用量,並依操作名稱篩選。agent span 上的用量是該 agent 在其各次呼叫中的總量,因此切勿把它與各次呼叫的用量相加。在正式環境中,我們從 counter 讀取總量,因為取樣器無法使它們變少。

從計數器推導快取輸入

執行環境並不回報重複使用的數量,因此本書自行推導:快取輸入等於提示詞的 token 數減去執行環境實際評估的 token 數。重複使用發生在兩個地方。執行環境會保留上一個提示詞已評估的前綴,若某次呼叫的提示詞開頭與其相同,就只評估新增的後綴;基準版本另外開啟了 RAM 快取,即 PromptCache(LlamaRAMCache),並搭配 cache_prompt: true。當上下文本身的前綴已被覆寫時,它會還原先前某個提示詞的已儲存狀態,並選取共同前綴最長者。助理的系統提示詞與工具清單位於每個提示詞的最前面,因此大多數呼叫都能重複使用這部分。

鎖定版本 llama-cpp-python 0.3.37 在其 Python API 與隨附的效能計數器中,都沒有快取 token 的欄位。記錄器取得 n_p_eval,也就是已評估的提示詞 token 數,做法是計算相鄰呼叫之間的差值,因為這些計數器是累加的。計數器 n_reused 位於同一個結構中,但它計算的是計算圖的重複使用,而不是 token,所以本書不把它當作快取數量。我們判斷,推導出的重複使用前綴 token 數應記入 gen_ai.usage.cache_read.input_tokens 與快取讀取計數器;在沒有任何重複使用時,則記錄為零。登錄表將該屬性定義為由供應商管理的快取所提供的 token 數,且依供應商所回報者為準,因此這個數量是本書自己的判斷,而不是供應商的回報。

這裡將同樣的 60 則訊息執行兩次,樣本取自基準版本第 1 天的隨機種子抽樣:一次使用基準版本 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 個輸入 token,其中只有 11,682 個被評估,其餘皆來自快取。在關閉快取的版本下,它們讀入相同的 29,107 個 token,且全部都被評估。重設狀態並沒有改變模型所讀入的內容,改變的是執行環境必須評估其中的多少部分,因此多評估了 17,425 個 token。

這個差異就是成本。依本書的價目表,關閉快取的版本在這 60 則訊息上多花費 $0.001394,因為快取 token 依快取費率計費,已評估的 token 則依輸入費率計費。變更快取的版本會改變成本,卻不會改變輸入 token 數,所以只比較輸入 token 數會漏掉這項變化。

實用原則: 應在每次呼叫時由執行環境的計數器推導快取輸入,絕不依據版本的標籤。當某個版本變更了快取,我們會在相同的訊息上比較成本,因為輸入數量不會改變。

其他語言中的相同語句

詞元是依各自的詞彙表計算的,同一段文字在不同語言中所需的詞元數可能差異很大。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 行在計算無快取請求的價格之前,先從輸入數量中扣除了快取的 token。請修正這一點,讓同一個請求的所有輸入都以輸入費率計價,且不含任何快取輸入。

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.

依路由與步驟計算成本

一次呼叫的成本,是其 token 數依具名且標有日期的價格表計價的結果;成本歸屬則是把每次呼叫的成本指派給引發它的步驟、路由與使用者。Agent Harnesses刻意讓成本停在計數;本書則加上金額,並以 token 為先。本書在查詢時,依每次呼叫的 token 數與價格表計算成本,並不把成本存放在 span 上。價格變動時,只需重新計價查詢,已儲存的 span 維持原樣。第 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 上執行

answer 步驟的成本最高。在當日的 200 則訊息中,answer requests 的成本為 $0.006184,占當日成本的 81.8%。route requests 的成本為 $0.001379,占 18.2%。route 呼叫較小,但每則訊息都會發出一次,因此仍占近五分之一的金額。

各路由處理一則訊息的成本並不相同。下表列出各路由的訊息數、同一天中每則訊息的 token 數,以及每 1,000 則訊息的成本。分母是各路由上的訊息數。

路由 訊息數 每則訊息的輸入 token 每則訊息的輸出 token 每 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 章所述的固定回覆,其 span 也記錄了這不是由模型寫出的。這條路由只發出一次 route 呼叫,沒有 answer 呼叫,因此它的資料列只含 route 呼叫。

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顯示各路由每則訊息的輸入 token,其中快取的部分包含在輸入長條內,輸出 token 則列在旁邊。某條路由的輸出可能很便宜,提示詞卻仍然昂貴。

alarmscalendardevicesfallbacklistsmediamessages050010001500tokens per messagecached input, part of inputinput not cachedoutput tokens
圖 6.1 依路由列出每則訊息的輸入、快取輸入與輸出 token。fallback 路由的長條僅為其 route 呼叫。

圖 6.1顯示,lists 路由的輸出是除 fallback 路由外所有路由中最少的,每則訊息 29.0 個 token,但每則訊息仍讀入 936.5 個輸入 token。messages 路由每則訊息讀入 1415.4 個輸入 token,其中 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% 的訊息以計數及占當日總額的比例來報告,並註明是哪一天。在第二天提供可比較的資料之前,不要稱某個比例為小或大。

正式環境中會出什麼問題

當閘道或彙總層開始帶上其下各次呼叫的用量時,儀表板上的 token 總數可能翻倍,而管線中的其他部分並未改變。對 span 加總會把這些 token 算兩次。請從計數器讀取總數,或如慣例中的說明所述,依操作名稱篩選 span。

當後端開始只保留一半的追蹤資料時,從 span 讀取的儀表板總數會減半,因為 span 會隨取樣而減少。計數器則不受影響。總數請以計數器為準,span 則留給計數器無法回答的問題,例如某則訊息走了哪一條路由。第 11 章會說明如何把取樣後的總數放大還原,並附上其誤差。

帳單金額會變動,而輸入數量卻持平,原因是某次發行改變了提示中被快取的比例。只追蹤輸入 token 的儀表板會漏掉這項變化。請把成本與輸入量和快取輸入量並列追蹤,並對照該快取數量所屬的發行版本來解讀。

當成本工具從 span 取得供應商,而該 span 寫的是 openai 時,本地模型會被以代管供應商的費率計價。該清單在這項查詢上會明確報錯失敗,因此危險在於工具退而使用預設模型或模糊比對。本書的表格以模型作為鍵值,查詢清單時則會指明其供應商。任何為 span 計價的工具都應比照辦理。

某個月的成本會在價格變動當天改變,即使沒有任何訊息改變。本書表格中的每一列都帶有生效起始日期,每次呼叫都依其自身的時間戳記計價。儲存在 span 上的成本會沿用舊價格,因此本書在查詢時才計算成本。

以英文 token 設定的預算,對印地語使用者會失效,差異來自詞彙表,而不是流量。請在實際會運行的流量上量測各語系的比率,並使用服務該語系的分詞器來計數。

實用原則: 總數以計數器為準,成本以附版本的表格為準,各語系的計數則使用其自己的分詞器。當某次發行改變了提示或快取時,請把它的成本與 token 並列解讀,因為兩者可能背離。

本章的決定

  • 先算 token,再算金額。每個金額數字都會標明價格表的版本 book-2026-11-02 及其日期。
  • 輸入 token 包含快取的部分。快取輸入由執行階段的計數器推得,絕不加到輸入上。
  • 總量取自計數器。對 span 加總時,只對推論 span 加總,並依操作名稱篩選。代理程式 span 的用量就是該代理程式的總量,絕不與各次呼叫的用量相加。
  • 成本在查詢時依價格表與每次呼叫的時間戳記計算,不儲存在 span 上。
  • 關閉快取的版本稱為「每次呼叫重設」,因為固定版本的執行階段沒有快取開關。
  • 各語系的計數使用分詞器檔案,並在 NFC 正規化之後進行;本章不印出 GGUF 的計數。語句文字不予引用,因為沒有任何範例印出它。
  • 本章不使用區間,因為單日的計數是精確值,不需要區間。其他日期的變動幅度,其方法見第 7 章。
  • 價格是本書的判斷:標明日期與版本,並非報價。偏好其他價格的讀者可以修改價格表並保留計數,而每一句關於 token 的敘述依然成立。這樣的區分,正是本章先處理 token 的原因。

本章,於本版次中

版次 2026.11.2範例於 2026年11 月 23 通過測試8 of 8 個範例 in this chapter pass

譯自英文書,版次 2026.11.2。

開始 Labs

本書仍可免費閱讀。

查看價格

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 6 章,共 12 章: 將 token 與成本歸屬到每個步驟

  1. 每次呼叫的三種計數
  2. 加總 span 會重複計算
  3. 從計數器推導快取輸入
  4. 其他語言中的相同語句
  5. The price table
  6. 依路由與步驟計算成本
  7. 高成本的尾端
  8. 正式環境中會出什麼問題
  9. 本章的決定

返回頂端所有章節