追蹤一個請求,再問時間花在哪裡

閱讀約 34 分鐘,7 節 中共有 6 個範例。

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

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

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

Labs

透過實作學習本章

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

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

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

正在檢查您的時數…

正在尋找您的 Lab…

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

讀完本章,你可以親手建立一則訊息的追蹤紀錄(trace),把它印成樹狀結構,並說明這則訊息的時間與 token 花在哪裡。接著,你可以對一整天的訊息做同樣的加總,並指出哪一個步驟耗時最多。

Ambrewick 是一個個人助理應用程式的後端,為本書而寫。使用者傳送一則訊息,助理會從知識庫、從工具,或以固定回覆來回答。它的日誌為每則訊息記錄一行,為每則回覆也記錄一行,兩者之間什麼都沒有。在開發日,也就是本章重播的 2026-12-07 當天的二十則訊息中,最慢的訊息是訊息 3271。從收到訊息到回覆,花了 36,230.7 ms。訊息 809 是本章追蹤的第一則。它的內容是「brew coffee at noon」,從收到訊息到回覆的時間是 11,520.7 ms。日誌無法說明這段時間如何分配在選擇路由、搜尋知識庫與撰寫答案之間。追蹤紀錄會記下這樣的分配,一次記錄一個計時的步驟。

一則訊息,一條追蹤

追蹤是以每則訊息為單位保存的,因為關於使用者體驗的問題,正是以訊息為單位提出的。若有人問為什麼訊息 809 很慢,就需要看到它的各個步驟集中在一起;若有人問一天的時間花在哪裡,則需要把二十則訊息的追蹤並排比較。沒有鍵值的話,每個事件一行的日誌無法這樣分組,而 trace ID 就是這個鍵值。同一則訊息的每個 span 都帶有它,因此這兩個問題各用一次查詢就能回答,不必在文字中搜尋。

追蹤是一則使用者訊息所做工作的紀錄:為它建立的每個 span 都共用同一個 trace ID。這些 span 以父子連結串成一棵樹,而父 span 遺失的 span 仍屬於該追蹤。span 是一個有名稱、有計時的操作,帶有屬性和一個父 span,唯有根 span 沒有父 span。根 span 涵蓋整則訊息,助理所採取的每個步驟則是其下的一個 span,各有自己的開始與結束時間。

《Agent Harnesses》一書同樣為每個步驟保存紀錄,並稱這份紀錄為追蹤。在該書中,追蹤是每行一個 JSON 物件的檔案,也就是代理程式一次執行的逐字紀錄,如 One line per event 所述。在本書中,追蹤指的是 OpenTelemetry 的 span,每則訊息一條追蹤,其樹狀結構由父子連結構成。兩本書對追蹤的用途看法一致,只是形式不同。

Ambrewick 以最多五個步驟處理一則訊息。路由步驟進行一次模型呼叫,從七條路由中選出一條。其中三條路由 messages、devices 與 media,會在回答之前先搜尋知識庫,這個搜尋就是擷取步驟。回答步驟進行一次模型呼叫來撰寫回覆。回答呼叫可能要求使用工具而不是直接回覆;工具步驟會執行該工具,之後再由一次回答呼叫撰寫回覆。被路由到 fallback 的訊息會得到固定的回覆,不進行模型呼叫。訊息 809 執行了五個步驟中的三個:路由、擷取與回答。它的追蹤有四個 span,一個名為 message 的根 span,以及每個步驟各一個子 span。

這些訊息來自 Amazon 的 MASSIVE 資料集 1.1 版。其英文地區設定 en-US 是本書流量的來源。資料集中的一列是一句話語,話語一旦進入流量,就成為一則訊息。MASSIVE 的資料以 CC BY 4.0 授權,該資料集由 FitzGerald 等人,2023 描述,發表於 ACL 2023 會議論文集。MASSIVE 有 52 個地區設定檔,其中之一是英文種子資料。該種子是 SLURP,一個口語語言資料集,其英文文字由群眾外包工作者根據提示撰寫,如 Bastianelli 等人,2020 所述。SLURP 的文字同樣採用 CC BY 4.0。群眾外包工作者為這些資料集撰寫文字,口吻如同對助理說話的人。它們並非來自任何真實助理的日誌。Ambrewick、它的工具與知識庫都是本書自行建立的。

實用原則: 每則使用者訊息建立一條追蹤,根 span 涵蓋該訊息的全部時間,其工作經歷的每個步驟各有一個 span。涵蓋多則訊息、或只涵蓋部分步驟的追蹤,無法回答關於單一訊息的問題;缺少 trace ID 的日誌行,也無法與其他日誌行串接。

重播與虛擬時鐘

訊息 809 的追蹤需要每個步驟的時間,而這裡的時間來自一份錄製紀錄,不是來自時鐘。重播會為每次模型呼叫提供紀錄中保存的回覆,連同該次呼叫所記錄的時間與其 token 數量。這裡沒有任何東西在等待模型,也沒有任何東西被量測。OpenTelemetry Specification, Trace API(v1.52.0)預期 span 的時間戳記反映該操作實際經過的真實時間,因此本書的時間是錄製紀錄的時間,經重播而來,這是刻意的選擇。重播會依每次呼叫的錄製時間推進一個虛擬時鐘。這個時鐘是自 Unix epoch 起算、以 UTC 表示的奈秒整數計數,並從訊息抵達時開始。重播執行完畢後,時鐘就會顯示該訊息花了多久。同一份錄製紀錄在每次執行時,都會讓時鐘前進相同的量。

dev day 是包含二十則訊息的一天,也是本章唯一使用的一天。其中每次模型呼叫都在錄製機器上錄製過一次,這部機器是 2.10 GHz 的 4 vCPU Intel Xeon,執行的是 Q4_K_M GGUF 檔案的 Qwen3-4B-Instruct-2507。各範例重播的就是這份紀錄:每次模型呼叫都取得該次執行給出的回覆,以及其錄製時間與 token 數量,沒有任何範例會執行模型。託管模型的回應時間會不同。下文的方法可以沿用到託管模型,但數字不能。

呼叫的 token 數量不是時間,所以不會推進時鐘。它們是錄製紀錄為每次呼叫保存的屬性,並由 span 攜帶。快取輸入 token是推導而來,並非直接回報:它等於 prompt token 減去 llama.cpp 依其效能計數器所評估的 token。第 6 章會說明這個推導。

重播訊息 809 需要兩次模型呼叫,重播會印出每一次的結果以及兩者的總和:

replay-one-message.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 通過
"""Replay one dev-day message through the assistant, answering each model call from the recording, and print what eachcall cost on the virtual clock. The printed times and token counts are the recording's; the point rests on the routecall and the answer call of this one message."""from lib.dayrun import run_dev_dayfrom lib.report import fmt_int, fmt_ms(run,) = run_dev_day(["809"])                          # a device request: route, retrieve, answeroutcome = run.outcomeprint("message text:", run.message.text)print("route chosen:", outcome.route)print("reply source:", outcome.source)print("steps:", ", ".join(step.step for step in outcome.steps))calls = [step for step in outcome.steps if step.step in ("route", "answer")]   # retrieve takes no model timefor step in calls:    print(f"{step.step} call, time:", fmt_ms(step.end_ns - step.start_ns))    print(f"{step.step} call, input tokens:", fmt_int(step.prompt_tokens))    print(f"{step.step} call, cached input tokens:", fmt_int(step.cached_tokens))    print(f"{step.step} call, output tokens:", fmt_int(step.completion_tokens))print("message, time in model calls:", fmt_ms(sum(s.end_ns - s.start_ns for s in calls)))# The clock moved by exactly the steps' times, so the steps account for all of the message's time.assert run.replied_ns - run.arrived_ns == sum(step.end_ns - step.start_ns for step in outcome.steps)assert outcome.source == "model"
輸出python replay-one-message.py
message text: brew coffee at noon
route chosen: devices
reply source: model
steps: route, retrieve, answer
route call, time: 3,336.3 ms
route call, input tokens: 142
route call, cached input tokens: 6
route call, output tokens: 6
answer call, time: 8,184.4 ms
answer call, input tokens: 331
answer call, cached input tokens: 192
answer call, output tokens: 38
message, time in model calls: 11,520.7 ms
習題 1.1

為什麼步驟檢查看不出空隙

+10 則證明

即使錄製內容在路由呼叫與回答呼叫之間有一段空隙,而重播會捨棄這段空隙,第 22 行在本書的資料上仍然通過。為什麼這項檢查仍會通過?

為什麼步驟檢查看不出空隙:選出正確的說明
在 Python 3.13.16 上執行
route call, time: 3,336.3 ms
route call, input tokens: 142
route call, cached input tokens: 6
route call, output tokens: 6
answer call, time: 8,184.4 ms
answer call, input tokens: 331
answer call, cached input tokens: 192
answer call, output tokens: 38
message, time in model calls: 11,520.7 ms

路由呼叫耗時 3,336.3 ms,回答呼叫耗時 8,184.4 ms。兩者合計,就是該訊息花在模型呼叫上的 11,520.7 ms。重播不給 retrieve 步驟任何時間,因為錄製紀錄中沒有搜尋的時間。錄製的那次執行在路由呼叫結束與回答呼叫開始之間花了 7.3 ms,而重播捨棄了這段間隔。針對時鐘的斷言只檢查重播的程式碼:時鐘只會依各步驟的時間前進,因此無法發現錄製紀錄所捨棄的間隔。

實用原則: 讓錄製紀錄推動時鐘,絕不要手動加上某個步驟的時間。在時鐘旁放一個斷言,依各步驟檢查時鐘的移動量,這樣遺漏時間的步驟會使該次執行失敗,而不會以偏短的總和呈現在讀者面前。

手動建立 span

有了重播的步驟與時間(重播與虛擬時鐘),SDK 就能建立 span。本章的程式碼使用 Python 版 OpenTelemetry SDK,版本為 1.45.2。SDK 的 tracer 負責建立 span,而它所設定的兩個元件決定 span 的去向。span processor 會在每個 span 開始與結束時被呼叫,並在結束時把 span 交給 exporter,由 exporter 將它送往某處:記憶體、檔案或 OTLP 端點。此處的程式碼使用 SimpleSpanProcessor,它會在每個 span 結束的當下就匯出。相對地,批次 processor 會在之後依計時器分批匯出,因此在清空(flush)之前就列印的程式碼可能找不到任何 span,而佇列滿了之後 span 也會被丟棄(OpenTelemetry Specification, Trace SDK,v1.52.0)。我們使用簡易 processor,是為了讓每個 span 在列印時都已匯出。在正式環境中,我們建議使用批次 processor,因為簡易 processor 會在結束 span 的執行緒上呼叫 exporter,所以速度慢的 exporter 會拖慢請求。SDK 在 1.45.2 中 SimpleSpanProcessor.on_end 的原始碼就是直接進行這項呼叫。這裡的 exporter 是記憶體內的實作,它把 span 保存在行程內的一個串列中。

SDK 會在 span 開啟時取得開始時間。它的 start_span 呼叫沒有結束時間的參數,所以結束時間要交給另一個呼叫。lib/tracing.py 中的輔助函式會依照收到的時間完成這兩件事:

recorded = tracer.start_span(name, context=context, kind=kind, start_time=start_ns, attributes=attributes)
recorded.end(end_time=end_ns)

每個時間都是以奈秒為單位的整數,並且都來自虛擬時鐘,重播一節對此有說明。這裡的程式碼完全不讀取機器本身的時鐘,所以同一份錄製內容每次執行都會產生相同的 span。

把結束時間交給 SDK 並不會出錯。span 會在呼叫 end() 時以機器時鐘結束,而該時鐘在每次執行時的速度都不同。於是同一則訊息每次會印出不同的持續時間,而且這個持續時間與錄製內容毫無關係。輔助函式的做法是由呼叫端提供結束時間,並拒絕早於開始時間的結束時間,因為那會印出負的持續時間。

trace ID 是同一條 trace 的每個 span 所帶的編號,span ID 則是單一 span 的編號。SDK 預設的產生器會隨機產生這兩者,所以 lib/ids.py 改為以計數方式產生,依序為 1、2、3,並在每次執行時重新開始。span 的父 span 是它所屬工作的上層 span;span context 主要包含 trace ID、span ID 與 trace flags,讓其他程式碼與其他行程能指稱該 span。輔助函式會接收一個父 span 並將它放入 context,使子 span 能指明它的父 span。

resource 描述產生遙測資料的來源,同一個 tracer provider 所建立的每個 span 都相同:service.name、service.version、service.instance.id。本書中的服務是 ambrewick-assistant,版本為錄製時所用的版本,其執行個體 ID 是手動設定的固定字串,因為 SDK 的預設值是每次執行都產生新的隨機 UUID。

屬性(attribute)是記錄在 span 或 resource 上的鍵與值,例如 gen_ai.request.model。本章的屬性是本書自訂的。每個步驟的 span 都帶有 ambrewick.step,用來標明它來自哪個步驟。根 span 沒有 ambrewick.step;它帶有 ambrewick.route 與 ambrewick.reply.source,所以樹狀輸出會在它的位置印出 (root)。兩次模型呼叫還帶有 ambrewick.tokens.input、ambrewick.tokens.cached 與 ambrewick.tokens.output。這些 span 依步驟命名,分別為 route、retrieve 與 answer,根 span 則命名為 message。它們沿用 SDK 預設的 span kind。這些名稱刻意取得粗略;第 2 章會加以取代。

build-one-trace.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 通過
"""Build one dev-day message's trace by hand: a span per step, each with its explicit start and end times, from sequentialIDs, a synchronous processor and an in-memory exporter. The steps and their times come from the replay; the printedlines rest on the span count and on every child span's parent."""from lib.dayrun import RELEASE, run_dev_dayfrom lib.export import spans_to_rowsfrom lib.ids import SequentialIdsfrom lib.report import fmt_intfrom lib.tracing import make_provider, spanfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter(run,) = run_dev_day(["809"])outcome = run.outcome# The resource names the service; service.instance.id is set, not drawn at random. Spans export as they end.exporter = InMemorySpanExporter()provider = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", run.clock, SequentialIds(),                         exporter, "https://opentelemetry.io/schemas/1.44.0")tracer = provider.get_tracer("ambrewick.assistant")# The root is the message. Its span is made first, and each step's span names it as parent.root = span(tracer, "message", run.arrived_ns, run.replied_ns,            attributes={"ambrewick.route": outcome.route, "ambrewick.reply.source": outcome.source})for step in outcome.steps:    name = f"tool {step.name}" if step.step == "tool" else step.step      # named by step, not by the standard    attributes = {"ambrewick.step": step.step}    if step.step in ("route", "answer"):                                  # model calls carry their token counts        attributes |= {"ambrewick.tokens.input": step.prompt_tokens, "ambrewick.tokens.cached": step.cached_tokens,                       "ambrewick.tokens.output": step.completion_tokens}    span(tracer, name, step.start_ns, step.end_ns, parent=root, attributes=attributes)rows = spans_to_rows(exporter)                 # sorted by (trace, start, span), so the order is fixedroot_row = next(row for row in rows if row["parent_span_id"] is None)children = [row for row in rows if row["parent_span_id"] is not None]assert len({row["trace_seq"] for row in rows}) == 1                       # one message, one traceassert all(row["parent_span_id"] == root_row["span_id"] for row in children)print("spans in the trace:", fmt_int(len(rows)))print("spans under the root:", fmt_int(len(children)))route = next(row for row in children if row["name"] == "route")print("route span, input tokens on the span:", fmt_int(route["attributes"]["ambrewick.tokens.input"]))
輸出python build-one-trace.py
spans in the trace: 4
spans under the root: 3
route span, input tokens on the span: 142

訊息 809 的四個 span 就來自這些呼叫。每個子 span 都以根 span 作為父 span,只需一行程式碼:

span(tracer, name, step.start_ns, step.end_ns, parent=root, attributes=attributes)

接著腳本會驗證四個 span 共用同一個 trace ID,且每個子 span 都指明根 span 為其父 span。輸出會回報該 trace 中有 4 個 span,其中 3 個位於根 span 之下,並回報 route span 上的輸入 token為 142。

正式環境中出的問題比數字錯誤更隱微。span 只有在結束時才會匯出,因為簡易 processor 會在 span 完成後立即把它交給 exporter,規格的 SDK 頁面對此有說明,所以工作從未執行到 end() 呼叫的 span 根本不會被匯出。在實際執行的程式碼中,根 span 涵蓋整則訊息,因此最後才結束;行程若在處理訊息中途當機,就會遺失根 span 以及當時正在執行的步驟。這條 trace 送達時會只有已完成的步驟,而它們的父 span 始終沒有送達;若使用批次 processor,仍在佇列中的 span 也會遺失。範例先結束根 span,只是因為它們是在重播之後才建立 span,而實際執行的程式碼絕不會如此。找出唯一沒有父 span 的那個 span 的檢查,就能抓出這類 trace。

實用原則: 在重播中,以重播時鐘提供的明確結束時間來結束每個 span。在實際執行的程式碼中,則讓 SDK 從機器時鐘取得這兩個時間。無論哪種情況,都要檢查每條 trace 是否有根 span,也就是恰好一個沒有父 span 的 span,因為沒有根 span 的 trace 正是當機留下的結果,而且它看起來只是幾個短暫的步驟,而不像是失敗。

單一追蹤的樹狀結構

手動建立 span為訊息 809 建立的四個 span,依其父子連結形成一棵樹,接著腳本會檢查它們的時間如何相加。這棵樹列出根 span 與它的三個步驟,其後幾行則給出各自的時間與檢查結果:

習題 1.2

為什麼訊息時間與各步驟的時間相符

+10 則證明

第 45 行在比較訊息時間與各步驟的時間時印出 yes。對這次重播而言,下列哪一項說明成立?

為什麼訊息時間與各步驟的時間相符:選出正確的說明
在 Python 3.13.16 上執行
message  step: (root)
  route  step: route
  retrieve  step: retrieve
  answer  step: answer
message span, time: 11,520.7 ms
steps, time added up: 11,520.7 ms
steps overlap in time: no
message time equals the sum of its steps: yes

縮排表示父子連結,因此訊息 809 的三個步驟位於根 span 的下一層。OpenTelemetry Specification將追蹤稱為由 span 組成的有向無環圖,而父子連結使這張圖成為一棵樹,每個 span 只有一個父 span。這棵樹並未給出時間,所以時間來自後面幾行。

子 span 可以在其父 span 之後才結束。規格的概觀就畫出了這樣的例子,也沒有訂定禁止這種情況的規則(OpenTelemetry Specification, Overview: Traces, Spans, SpanContext,標籤 v1.52.0)。因此,當子 span 互相重疊時,父 span 的持續時間並不等於子 span 時間的總和;當子 span 之間留有空隙時,兩者也可能不同。在這次重播中,訊息 809 的各步驟既不重疊,也沒有空隙:路由結束時,回答隨即開始。腳本會測試這一點,輸出中訊息的時間為 11,520.7 ms,各步驟的時間為 11,520.7 ms,兩者是同一個數字。

讀者很容易把父 span 的長條視為其子 span 所做的工作。長條只顯示父 span 何時開始與停止,而空隙則是沒有任何子 span 記錄的工作。這次重播中沒有這兩種情況。

圖 1.1將同一個追蹤畫成瀑布圖。瀑布圖是在時間軸上為每個 span 畫一條長條的檢視方式,也是追蹤工具所繪製的檢視,規格的概觀也勾勒過它;規格並未將它定義為一種格式,這張圖是本書自行繪製的版本。圖中每個 span 各有一條長條,從 span 的開始到結束,單位為訊息抵達後的秒數。最上方是整則訊息的長條,其次是從抵達時起算的路由長條,檢索步驟是路由結束處的一個刻度,再來是從該處延伸到訊息結束的較長回答長條。

024681012seconds after the message arrivesmessagerouteretrieveanswer
圖 1.1 訊息 809 的各個 span,單位為抵達後的秒數
figure-dev-day-waterfall.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 one dev-day message's trace as a waterfall: each span a bar from its start to its end, after the message arrives.The bars are the spans of build-one-trace, from the replay's recorded times, so the figure shows the order and length ofthe steps. The printed lines are the values the figure's text quotes."""from lib.dayrun import run_dev_dayfrom lib.figures import ACCENT, INK, MUTED, new_figure, savefrom lib.report import fmt_ms(run,) = run_dev_day(["809"])outcome, arrived = run.outcome, run.arrived_ns# One bar per span: the message first, then its steps in order. The answer is the accent; the route is ink.bars = [("message", arrived, run.replied_ns, MUTED)]bars += [(s.step, s.start_ns, s.end_ns, ACCENT if s.step == "answer" else INK) for s in outcome.steps]fig, ax = new_figure(height=2.4)for row, (label, start, end, colour) in enumerate(bars):    left, width = (start - arrived) / 1e9, (end - start) / 1e9             # seconds after arrival    if width > 0:        ax.barh(row, width, left=left, height=0.6, color=colour)    else:                                                                  # a step with no time is a tick, not a bar        ax.plot([left], [row], marker="|", markersize=10, color=colour)ax.set_yticks(range(len(bars)), [label for label, _, _, _ in bars])ax.invert_yaxis()ax.set_xlabel("seconds after the message arrives")save(fig, "dev-day-waterfall")steps = {s.step: s for s in outcome.steps}                                 # one span per step in this messageroute, answer = steps["route"], steps["answer"]print("message, time from arrival to reply:", fmt_ms(run.replied_ns - arrived))print("route span, time:", fmt_ms(route.end_ns - route.start_ns))print("retrieve span, time:", fmt_ms(steps["retrieve"].end_ns - steps["retrieve"].start_ns))print("answer span, time:", fmt_ms(answer.end_ns - answer.start_ns))print("answer span starts, after arrival:", fmt_ms(answer.start_ns - arrived))# The steps run one after another: the answer starts exactly when the route ends, so the bars do not overlap.assert answer.start_ns == route.end_ns
輸出python figure-dev-day-waterfall.py
figure: figures/dev-day-waterfall.svg
message, time from arrival to reply: 11,520.7 ms
route span, time: 3,336.3 ms
retrieve span, time: 0.0 ms
answer span, time: 8,184.4 ms
answer span starts, after arrival: 3,336.3 ms

回答 span 在抵達後 3,336.3 ms 開始,也就是路由結束的時刻。圖中的順序就是各步驟執行的順序,圖中的長度就是時鐘記錄的時間。

**實用原則:**將追蹤印成父子連結的樹狀結構,並在相加子 span 的時間之前,先檢查它們是否互不重疊且沒有空隙。若有重疊或空隙,請分別回報父 span 的時間與各子 span 的時間。

二十則訊息的時間花在哪裡

訊息 809 是一條追蹤(trace),而開發日共有二十條。一則訊息、一條追蹤把每則訊息的各個步驟放在一起,因此可以把一天的步驟加總。備援回覆(fallback reply)是路由器選擇 fallback 時,Ambrewick 傳送的固定文字;沒有任何模型撰寫它,它的 span 也如此標示。在開發日當天,有 6 of 20 則訊息收到備援回覆。只有在沒有任何工具或文章能解決訊息時,備援回覆才是正確的答案。

sum-dev-day-steps.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 通過
"""Replay all 20 dev-day messages and add up each model step over the day: its calls, its recorded time, its tokens, and itsshare of the day's model time and tokens. Tool time is not in the recording (the tools are modelled), so it is countedand left out of the shares; retrieve and fallback take no time. The route-to-answer gap is the recorder's, not the replay's."""from collections import Counterfrom lib.dayrun import recorded_gap_ns, run_dev_dayfrom lib.report import fmt_int, fmt_ms, fmt_shareMODEL_STEPS = ("route", "answer")runs = run_dev_day()                                   # all 20 messages, in arrival ordercalls, time_ns, tokens = Counter(), Counter(), Counter()cached, overlapping, fallbacks = Counter(), 0, 0for run in runs:    ordered = sorted(run.outcome.steps, key=lambda s: s.start_ns)    overlapping += any(later.start_ns < earlier.end_ns for earlier, later in zip(ordered, ordered[1:]))    fallbacks += run.outcome.source == "fallback"    for step in run.outcome.steps:        calls[step.step] += 1        if step.step in MODEL_STEPS:       # the recording's times and tokens; input counts cached tokens too            time_ns[step.step] += step.end_ns - step.start_ns            tokens[step.step] += step.prompt_tokens + step.completion_tokens            cached[step.step] += step.cached_tokens            tokens[f"{step.step} input"] += step.prompt_tokensslowest = max(runs, key=lambda run: run.replied_ns - run.arrived_ns)     # the first of the slowest, if two tietotal_time, total_tokens = sum(time_ns[s] for s in MODEL_STEPS), sum(tokens[s] for s in MODEL_STEPS)input_total = sum(tokens[f"{s} input"] for s in MODEL_STEPS)print("messages in the dev day:", fmt_int(len(runs)))print("messages whose steps overlap in time:", f"{overlapping} of {len(runs)}")print("messages answered by the fallback reply:", f"{fallbacks} of {len(runs)}")print("slowest message:", slowest.message.message_id)print("slowest message time:", fmt_ms(slowest.replied_ns - slowest.arrived_ns))print("slowest message route:", slowest.outcome.route)for step in MODEL_STEPS:    print(f"{step} calls:", fmt_int(calls[step]))    print(f"{step}, recorded time:", fmt_ms(time_ns[step]))    print(f"{step}, share of model time:", fmt_share(time_ns[step], total_time))    print(f"{step}, share of tokens (input plus output):", fmt_share(tokens[step], total_tokens))print("tool calls:", fmt_int(calls["tool"]))print("retrieve calls:", fmt_int(calls["retrieve"]))print("route to answer gap, message 809:", fmt_ms(recorded_gap_ns("809", "route", "answer")))print("input tokens, total:", fmt_int(input_total))print("cached input tokens, total:", fmt_int(sum(cached[s] for s in MODEL_STEPS)))print("output tokens, total:", fmt_int(total_tokens - input_total))assert calls["route"] == len(runs)               # every message is routed onceassert overlapping == 0                          # the steps never overlap in the replay
輸出python sum-dev-day-steps.py
messages in the dev day: 20
messages whose steps overlap in time: 0 of 20
messages answered by the fallback reply: 6 of 20
slowest message: 3271
slowest message time: 36,230.7 ms
slowest message route: alarms
route calls: 20
route, recorded time: 35,500.6 ms
route, share of model time: 16.7%
route, share of tokens (input plus output): 21.2%
answer calls: 17
answer, recorded time: 176,519.9 ms
answer, share of model time: 83.3%
answer, share of tokens (input plus output): 78.8%
tool calls: 3
retrieve calls: 8
route to answer gap, message 809: 7.3 ms
input tokens, total: 13,417
cached input tokens, total: 8,299
output tokens, total: 775
習題 1.3

計算每個模型步驟的輸入與輸出 token

+10 則證明

第 20 行只加總了每次模型呼叫所寫出的內容,因此 token 占比漏掉了當天的輸入。請修正第 20 行,讓每個模型步驟的 token 等於其輸入加上其輸出。

        calls[step.step] += 1        if step.step in MODEL_STEPS:       # the recording's times and tokens; input counts cached tokens too            time_ns[step.step] += step.end_ns - step.start_ns            cached[step.step] += step.cached_tokens            tokens[f"{step.step} input"] += step.prompt_tokens
在 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 上執行

這個指令碼依序重播全部二十則訊息,並加總一天中每個模型步驟。當天的工具呼叫都送往行程內(in-process)工具,也就是行事曆、鬧鐘與清單工具;它們的耗時是依本書設定中的一張表建模而來,並非實際記錄,因此各項占比不含這些工具,只把它們算作呼叫次數。檢索(Retrieve)同樣沒有記錄時間。指令碼也會計算步驟在時間上重疊的訊息數,結果是 0 of 20。因此,一天的總和是各步驟時間的總和,並不是把每則訊息的根時間(root time)拆開的結果。

回答(answer)步驟占了一天模型時間的大部分,為 83.3%;而路由(route)步驟占 token 的 21.2%,占時間的 16.7%。回答呼叫的次數多於模型有回答的訊息數,因為每則呼叫過工具的訊息,在工具回傳後還需要再一次回答呼叫,所以回答步驟共執行了 17 次。各項占比是相對於一天的模型時間及其 token(輸入加輸出)而言,輸出會印出這兩個總量。

圖 1.2畫出每個模型步驟的這兩種占比。如圖所示,時間與 token 的分布形狀並不相同。

routeanswer020406080100percent of the dev day16.7%83.3%21.2%78.8%share of model timeshare of tokens
圖 1.2 每次模型呼叫在開發日中占模型時間與 token 的比例,共 20 則訊息
figure-dev-day-step-shares.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 each model step's share of the dev day's model time, beside its share of the tokens (input plus output), over all20 messages. Each bar is labelled with the share the example prints, so the figure and the printed lines are one set ofnumbers. Tool time is not in the recording, so the tool step is not drawn."""from collections import Counterfrom lib.dayrun import run_dev_dayfrom lib.figures import ACCENT, INK, new_figure, savefrom lib.report import fmt_int, fmt_ms, fmt_shareMODEL_STEPS = ("route", "answer")runs = run_dev_day()calls, time_ns, tokens = Counter(), Counter(), Counter()for run in runs:    for step in (s for s in run.outcome.steps if s.step in MODEL_STEPS):        calls[step.step] += 1        time_ns[step.step] += step.end_ns - step.start_ns        tokens[step.step] += step.prompt_tokens + step.completion_tokens      # input plus outputtotal_time, total_tokens = sum(time_ns.values()), sum(tokens.values())time_labels = [fmt_share(time_ns[s], total_time) for s in MODEL_STEPS]token_labels = [fmt_share(tokens[s], total_tokens) for s in MODEL_STEPS]fig, ax = new_figure(height=2.6)positions = list(range(len(MODEL_STEPS)))time_bars = ax.bar([p - 0.2 for p in positions], [100 * time_ns[s] / total_time for s in MODEL_STEPS], width=0.4,                   color=ACCENT, label="share of model time")token_bars = ax.bar([p + 0.2 for p in positions], [100 * tokens[s] / total_tokens for s in MODEL_STEPS], width=0.4,                    color=INK, label="share of tokens")ax.bar_label(time_bars, labels=time_labels, padding=2)ax.bar_label(token_bars, labels=token_labels, padding=2)ax.set_xticks(positions, list(MODEL_STEPS))ax.set_ylim(0, 100)ax.set_ylabel("percent of the dev day")ax.legend(loc="upper left")          # the route bars reach only about 21 percent, so the top left is clear of labelssave(fig, "dev-day-step-shares")print("messages in the dev day:", fmt_int(len(runs)))for step, time_label, token_label in zip(MODEL_STEPS, time_labels, token_labels):    print(f"{step} calls:", fmt_int(calls[step]))    print(f"{step}, recorded time:", fmt_ms(time_ns[step]))    print(f"{step}, share of model time:", time_label)    print(f"{step}, tokens, input plus output:", fmt_int(tokens[step]))    print(f"{step}, share of tokens:", token_label)print("model time, total:", fmt_ms(total_time))print("tokens, input plus output, total:", fmt_int(total_tokens))assert sum(calls.values()) == 37     # 20 route calls and 17 answer calls, as the recording holds
輸出python figure-dev-day-step-shares.py
figure: figures/dev-day-step-shares.svg
messages in the dev day: 20
route calls: 20
route, recorded time: 35,500.6 ms
route, share of model time: 16.7%
route, tokens, input plus output: 3,003
route, share of tokens: 21.2%
answer calls: 17
answer, recorded time: 176,519.9 ms
answer, share of model time: 83.3%
answer, tokens, input plus output: 11,189
answer, share of tokens: 78.8%
model time, total: 212,020.5 ms
tokens, input plus output, total: 14,192
習題 1.4

將輸入與輸出 token 一併計算

+10 則證明

第 16 行只計算每次呼叫的完成 token,但各項占比是以輸入加輸出計算的 token 為基礎計算的。請修正第 16 行,使每次呼叫同時加入其輸入與輸出 token。

    for step in (s for s in run.outcome.steps if s.step in MODEL_STEPS):        calls[step.step] += 1        time_ns[step.step] += step.end_ns - step.start_nstotal_time, total_tokens = sum(time_ns.values()), sum(tokens.values())time_labels = [fmt_share(time_ns[s], total_time) for s in MODEL_STEPS]
在 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 上執行
習題 1.5

寫出各比例所除以的總數

+10 則證明

第 18 行是空白的。請寫出這一行,使兩個分母分別為當天的模型時間,以及當天的輸入與輸出 token 總和,兩者都是將第 11 行 time_ns 與 tokens 計數器中各模型步驟的數值加總而得。

        time_ns[step.step] += step.end_ns - step.start_ns        tokens[step.step] += step.prompt_tokens + step.completion_tokens      # input plus outputtime_labels = [fmt_share(time_ns[s], total_time) for s in MODEL_STEPS]token_labels = [fmt_share(tokens[s], total_tokens) for s in MODEL_STEPS]fig, ax = new_figure(height=2.6)
在 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 上執行

步驟的時間占比說明一天的等待花在哪裡,token 占比則說明一天的輸入與輸出來自哪裡。這是兩個不同的問題,本章兩者都回答;哪個步驟花費最多金錢則是第 6 章的問題,除了 token 之外還需要價格。

**實用原則:**將各步驟在所有訊息上的記錄時間與 token 加總,並在每個占比旁印出其分母。指出任何沒有記錄時間的步驟,並把它排除在占比之外,讓讀者能看出這些總和沒有涵蓋一天中的哪一部分。

這個版本尚未做到的事

這個版本還很粗略,其中每個部分,後面都有一章會把它做得穩固。依序如下:

  • 名稱。 span 目前是依本書自己的步驟命名。第 2 章會依標準的名稱為每個 span 命名、設定其種類,並以驗證器檢查;這裡的每個 span 都無法通過該驗證。
  • 模型呼叫。 span 目前是手動建立的。第 3 章會說明 openai 用戶端函式庫的官方檢測(instrumentation)針對同類呼叫會送出什麼內容。
  • 第二個行程。 這份追蹤只是單一行程的紀錄。第 4 章會把聯絡人團隊伺服器(以獨立行程執行)的 span 接到這份追蹤上。
  • 儲存。 span 存放在記憶體中,行程結束後就會消失。第 5 章會把它們送到負責儲存的後端。
  • 尾端。 二十則訊息無法提供具有可信度的尾端百分位數。第 7 章會提供附有筆數與區間的百分位數。
  • 取樣。 目前每一條追蹤都會保留。第 11 章會決定要保留哪些追蹤,以及原因。
  • 提示詞。 span 刻意不記錄提示詞文字。第 3 章會指出可以記錄它的開關,第 12 章則說明該開關會洩漏什麼。
  • 錯誤的路由。 有 6 of 20 則開發日訊息得到了備援回覆,而本章並未檢查每一次路由是否正確。第 8 章會處理這件事。

本章所做的決定

這些決定會影響本書其餘的部分:

  • 目前 span 依步驟命名。從第 2 章起,本書改用標準的名稱。
  • 每個耗時都是記錄下來的值,而不是即時量測的結果,因此每一個印出的時間都能重新執行並得到相符的結果。
  • span 在結束的當下由同步處理器匯出,因此每個 span 在印出時都已經匯出。
  • 占比會連同分母一併印出;若某個步驟的時間沒有記錄,就不納入占比的計算,而不是加以估計。
  • 每條 trace 只屬於一則訊息,而一整天的加總,是依記錄所載把各則訊息的步驟相加,不另用 span 建構其他的量測值。

實用原則: 要回答關於某一則訊息的問題,只依該訊息的 trace 作答。該訊息的每個 span 都共用同一個 trace ID,根 span 涵蓋其全部時間,所以這條 trace 只包含該訊息的步驟,不含其他訊息的步驟。沒有 ID 的 span 或日誌行無法歸入答案,應將它排除並加以說明,而不要猜測它屬於哪一則訊息。猜測會把一則訊息的時間算進另一則訊息的總計。

本章,於本版次中

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

譯自英文書,版次 2026.11.2。

開始 Labs

本書仍可免費閱讀。

查看價格

引用本節

格式

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

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

本頁內容

第 1 章,共 12 章: 追蹤一個請求,再問時間花在哪裡

  1. 一則訊息,一條追蹤
  2. 重播與虛擬時鐘
  3. 手動建立 span
  4. 單一追蹤的樹狀結構
  5. 二十則訊息的時間花在哪裡
  6. 這個版本尚未做到的事
  7. 本章所做的決定

返回頂端所有章節