追蹤一個請求,再問時間花在哪裡
閱讀約 34 分鐘,7 節 中共有 6 個範例。
Labs
透過實作學習本章
完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。約 30 秒內開啟。
完全照書中的方式執行每個範例,修改程式碼觀察結果,並在書中的程式碼與資料上嘗試你自己的想法。無須安裝,你的工作會自動儲存。由 Labs 為你執行:每月 40 小時。
於您自己的電腦,免費: 下載本書的筆記本,連同其程式碼與資料,皆取自 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 需要兩次模型呼叫,重播會印出每一次的結果以及兩者的總和:
1"""Replay one dev-day message through the assistant, answering each model call from the recording, and print what each2call cost on the virtual clock. The printed times and token counts are the recording's; the point rests on the route3call and the answer call of this one message."""4from lib.dayrun import run_dev_day5from lib.report import fmt_int, fmt_ms67(run,) = run_dev_day(["809"]) # a device request: route, retrieve, answer8outcome = run.outcome910print("message text:", run.message.text)11print("route chosen:", outcome.route)12print("reply source:", outcome.source)13print("steps:", ", ".join(step.step for step in outcome.steps))14calls = [step for step in outcome.steps if step.step in ("route", "answer")] # retrieve takes no model time15for step in calls:16 print(f"{step.step} call, time:", fmt_ms(step.end_ns - step.start_ns))17 print(f"{step.step} call, input tokens:", fmt_int(step.prompt_tokens))18 print(f"{step.step} call, cached input tokens:", fmt_int(step.cached_tokens))19 print(f"{step.step} call, output tokens:", fmt_int(step.completion_tokens))20print("message, time in model calls:", fmt_ms(sum(s.end_ns - s.start_ns for s in calls)))21# The clock moved by exactly the steps' times, so the steps account for all of the message's time.22assert run.replied_ns - run.arrived_ns == sum(step.end_ns - step.start_ns for step in outcome.steps)23assert outcome.source == "model"
python replay-one-message.pymessage 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
為什麼步驟檢查看不出空隙
+10 則證明即使錄製內容在路由呼叫與回答呼叫之間有一段空隙,而重播會捨棄這段空隙,第 22 行在本書的資料上仍然通過。為什麼這項檢查仍會通過?
為何有效
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 章會加以取代。
1"""Build one dev-day message's trace by hand: a span per step, each with its explicit start and end times, from sequential2IDs, a synchronous processor and an in-memory exporter. The steps and their times come from the replay; the printed3lines rest on the span count and on every child span's parent."""4from lib.dayrun import RELEASE, run_dev_day5from lib.export import spans_to_rows6from lib.ids import SequentialIds7from lib.report import fmt_int8from lib.tracing import make_provider, span9from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1011(run,) = run_dev_day(["809"])12outcome = run.outcome1314# The resource names the service; service.instance.id is set, not drawn at random. Spans export as they end.15exporter = InMemorySpanExporter()16provider = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", run.clock, SequentialIds(),17 exporter, "https://opentelemetry.io/schemas/1.44.0")18tracer = provider.get_tracer("ambrewick.assistant")19# The root is the message. Its span is made first, and each step's span names it as parent.20root = span(tracer, "message", run.arrived_ns, run.replied_ns,21 attributes={"ambrewick.route": outcome.route, "ambrewick.reply.source": outcome.source})22for step in outcome.steps:23 name = f"tool {step.name}" if step.step == "tool" else step.step # named by step, not by the standard24 attributes = {"ambrewick.step": step.step}25 if step.step in ("route", "answer"): # model calls carry their token counts26 attributes |= {"ambrewick.tokens.input": step.prompt_tokens, "ambrewick.tokens.cached": step.cached_tokens,27 "ambrewick.tokens.output": step.completion_tokens}28 span(tracer, name, step.start_ns, step.end_ns, parent=root, attributes=attributes)2930rows = spans_to_rows(exporter) # sorted by (trace, start, span), so the order is fixed31root_row = next(row for row in rows if row["parent_span_id"] is None)32children = [row for row in rows if row["parent_span_id"] is not None]33assert len({row["trace_seq"] for row in rows}) == 1 # one message, one trace34assert all(row["parent_span_id"] == root_row["span_id"] for row in children)35print("spans in the trace:", fmt_int(len(rows)))36print("spans under the root:", fmt_int(len(children)))37route = next(row for row in children if row["name"] == "route")38print("route span, input tokens on the span:", fmt_int(route["attributes"]["ambrewick.tokens.input"]))
python build-one-trace.pyspans 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"""Print one dev-day message's trace as a tree, with each span's step, then check how its times add up. The spans are the2ones build-one-trace makes. The steps run one after another, so none overlap and the message's time is their sum. Where3spans do overlap, a parent's duration is not the sum of its children's; this trace shows no overlap."""4from lib.dayrun import RELEASE, run_dev_day5from lib.export import spans_to_rows6from lib.ids import SequentialIds7from lib.report import fmt_ms8from lib.tracing import make_provider, span9from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter1011(run,) = run_dev_day(["809"])12outcome = run.outcome1314exporter = InMemorySpanExporter()15provider = make_provider("ambrewick-assistant", RELEASE.service_version, "dev-day-replay", run.clock, SequentialIds(),16 exporter, "https://opentelemetry.io/schemas/1.44.0")17tracer = provider.get_tracer("ambrewick.assistant")18root = span(tracer, "message", run.arrived_ns, run.replied_ns,19 attributes={"ambrewick.route": outcome.route, "ambrewick.reply.source": outcome.source})20for step in outcome.steps:21 name = f"tool {step.name}" if step.step == "tool" else step.step22 span(tracer, name, step.start_ns, step.end_ns, parent=root, attributes={"ambrewick.step": step.step})2324rows = spans_to_rows(exporter)25root_row = next(row for row in rows if row["parent_span_id"] is None)26children = [row for row in rows if row["parent_span_id"] is not None]272829def print_tree(row, depth):30 """Print a span, then its children one level further in. Shows the shape of the trace, not its times."""31 print(" " * depth + f"{row['name']} step: {row['attributes'].get('ambrewick.step', '(root)')}")32 for child in (r for r in rows if r["parent_span_id"] == row["span_id"]):33 print_tree(child, depth + 1)343536print_tree(root_row, 0)37# Sorted by start, two steps overlap exactly when a step starts before the one before it has ended.38ordered = sorted(children, key=lambda row: row["start_ns"])39overlap = any(later["start_ns"] < earlier["end_ns"] for earlier, later in zip(ordered, ordered[1:]))40root_time = root_row["end_ns"] - root_row["start_ns"]41steps_time = sum(row["end_ns"] - row["start_ns"] for row in children)42print("message span, time:", fmt_ms(root_time))43print("steps, time added up:", fmt_ms(steps_time))44print("steps overlap in time:", "yes" if overlap else "no")45print("message time equals the sum of its steps:", "yes" if root_time == steps_time else "no")46assert not overlap and root_time == steps_time
python print-trace-tree.pymessage 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
為什麼訊息時間與各步驟的時間相符
+10 則證明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 的開始到結束,單位為訊息抵達後的秒數。最上方是整則訊息的長條,其次是從抵達時起算的路由長條,檢索步驟是路由結束處的一個刻度,再來是從該處延伸到訊息結束的較長回答長條。
1"""Draw one dev-day message's trace as a waterfall: each span a bar from its start to its end, after the message arrives.2The bars are the spans of build-one-trace, from the replay's recorded times, so the figure shows the order and length of3the steps. The printed lines are the values the figure's text quotes."""4from lib.dayrun import run_dev_day5from lib.figures import ACCENT, INK, MUTED, new_figure, save6from lib.report import fmt_ms78(run,) = run_dev_day(["809"])9outcome, arrived = run.outcome, run.arrived_ns1011# One bar per span: the message first, then its steps in order. The answer is the accent; the route is ink.12bars = [("message", arrived, run.replied_ns, MUTED)]13bars += [(s.step, s.start_ns, s.end_ns, ACCENT if s.step == "answer" else INK) for s in outcome.steps]14fig, ax = new_figure(height=2.4)15for row, (label, start, end, colour) in enumerate(bars):16 left, width = (start - arrived) / 1e9, (end - start) / 1e9 # seconds after arrival17 if width > 0:18 ax.barh(row, width, left=left, height=0.6, color=colour)19 else: # a step with no time is a tick, not a bar20 ax.plot([left], [row], marker="|", markersize=10, color=colour)21ax.set_yticks(range(len(bars)), [label for label, _, _, _ in bars])22ax.invert_yaxis()23ax.set_xlabel("seconds after the message arrives")24save(fig, "dev-day-waterfall")2526steps = {s.step: s for s in outcome.steps} # one span per step in this message27route, answer = steps["route"], steps["answer"]28print("message, time from arrival to reply:", fmt_ms(run.replied_ns - arrived))29print("route span, time:", fmt_ms(route.end_ns - route.start_ns))30print("retrieve span, time:", fmt_ms(steps["retrieve"].end_ns - steps["retrieve"].start_ns))31print("answer span, time:", fmt_ms(answer.end_ns - answer.start_ns))32print("answer span starts, after arrival:", fmt_ms(answer.start_ns - arrived))33# The steps run one after another: the answer starts exactly when the route ends, so the bars do not overlap.34assert answer.start_ns == route.end_ns
python figure-dev-day-waterfall.pyfigure: 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 則訊息收到備援回覆。只有在沒有任何工具或文章能解決訊息時,備援回覆才是正確的答案。
1"""Replay all 20 dev-day messages and add up each model step over the day: its calls, its recorded time, its tokens, and its2share of the day's model time and tokens. Tool time is not in the recording (the tools are modelled), so it is counted3and left out of the shares; retrieve and fallback take no time. The route-to-answer gap is the recorder's, not the replay's."""4from collections import Counter5from lib.dayrun import recorded_gap_ns, run_dev_day6from lib.report import fmt_int, fmt_ms, fmt_share78MODEL_STEPS = ("route", "answer")9runs = run_dev_day() # all 20 messages, in arrival order10calls, time_ns, tokens = Counter(), Counter(), Counter()11cached, overlapping, fallbacks = Counter(), 0, 012for run in runs:13 ordered = sorted(run.outcome.steps, key=lambda s: s.start_ns)14 overlapping += any(later.start_ns < earlier.end_ns for earlier, later in zip(ordered, ordered[1:]))15 fallbacks += run.outcome.source == "fallback"16 for step in run.outcome.steps:17 calls[step.step] += 118 if step.step in MODEL_STEPS: # the recording's times and tokens; input counts cached tokens too19 time_ns[step.step] += step.end_ns - step.start_ns20 tokens[step.step] += step.prompt_tokens + step.completion_tokens21 cached[step.step] += step.cached_tokens22 tokens[f"{step.step} input"] += step.prompt_tokens2324slowest = max(runs, key=lambda run: run.replied_ns - run.arrived_ns) # the first of the slowest, if two tie25total_time, total_tokens = sum(time_ns[s] for s in MODEL_STEPS), sum(tokens[s] for s in MODEL_STEPS)26input_total = sum(tokens[f"{s} input"] for s in MODEL_STEPS)27print("messages in the dev day:", fmt_int(len(runs)))28print("messages whose steps overlap in time:", f"{overlapping} of {len(runs)}")29print("messages answered by the fallback reply:", f"{fallbacks} of {len(runs)}")30print("slowest message:", slowest.message.message_id)31print("slowest message time:", fmt_ms(slowest.replied_ns - slowest.arrived_ns))32print("slowest message route:", slowest.outcome.route)33for step in MODEL_STEPS:34 print(f"{step} calls:", fmt_int(calls[step]))35 print(f"{step}, recorded time:", fmt_ms(time_ns[step]))36 print(f"{step}, share of model time:", fmt_share(time_ns[step], total_time))37 print(f"{step}, share of tokens (input plus output):", fmt_share(tokens[step], total_tokens))38print("tool calls:", fmt_int(calls["tool"]))39print("retrieve calls:", fmt_int(calls["retrieve"]))40print("route to answer gap, message 809:", fmt_ms(recorded_gap_ns("809", "route", "answer")))41print("input tokens, total:", fmt_int(input_total))42print("cached input tokens, total:", fmt_int(sum(cached[s] for s in MODEL_STEPS)))43print("output tokens, total:", fmt_int(total_tokens - input_total))44assert calls["route"] == len(runs) # every message is routed once45assert overlapping == 0 # the steps never overlap in the replay
python sum-dev-day-steps.pymessages 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
計算每個模型步驟的輸入與輸出 token
+10 則證明來自 二十則訊息的時間花在哪裡,第 1 章再讀一次
新版次已改變本練習所涵蓋的內容。版次 2026.11.2 的變更內容
第 20 行只加總了每次模型呼叫所寫出的內容,因此 token 占比漏掉了當天的輸入。請修正第 20 行,讓每個模型步驟的 token 等於其輸入加上其輸出。
為何有效
這個指令碼依序重播全部二十則訊息,並加總一天中每個模型步驟。當天的工具呼叫都送往行程內(in-process)工具,也就是行事曆、鬧鐘與清單工具;它們的耗時是依本書設定中的一張表建模而來,並非實際記錄,因此各項占比不含這些工具,只把它們算作呼叫次數。檢索(Retrieve)同樣沒有記錄時間。指令碼也會計算步驟在時間上重疊的訊息數,結果是 0 of 20。因此,一天的總和是各步驟時間的總和,並不是把每則訊息的根時間(root time)拆開的結果。
回答(answer)步驟占了一天模型時間的大部分,為 83.3%;而路由(route)步驟占 token 的 21.2%,占時間的 16.7%。回答呼叫的次數多於模型有回答的訊息數,因為每則呼叫過工具的訊息,在工具回傳後還需要再一次回答呼叫,所以回答步驟共執行了 17 次。各項占比是相對於一天的模型時間及其 token(輸入加輸出)而言,輸出會印出這兩個總量。
圖 1.2畫出每個模型步驟的這兩種占比。如圖所示,時間與 token 的分布形狀並不相同。
1"""Draw each model step's share of the dev day's model time, beside its share of the tokens (input plus output), over all220 messages. Each bar is labelled with the share the example prints, so the figure and the printed lines are one set of3numbers. Tool time is not in the recording, so the tool step is not drawn."""4from collections import Counter5from lib.dayrun import run_dev_day6from lib.figures import ACCENT, INK, new_figure, save7from lib.report import fmt_int, fmt_ms, fmt_share89MODEL_STEPS = ("route", "answer")10runs = run_dev_day()11calls, time_ns, tokens = Counter(), Counter(), Counter()12for run in runs:13 for step in (s for s in run.outcome.steps if s.step in MODEL_STEPS):14 calls[step.step] += 115 time_ns[step.step] += step.end_ns - step.start_ns16 tokens[step.step] += step.prompt_tokens + step.completion_tokens # input plus output1718total_time, total_tokens = sum(time_ns.values()), sum(tokens.values())19time_labels = [fmt_share(time_ns[s], total_time) for s in MODEL_STEPS]20token_labels = [fmt_share(tokens[s], total_tokens) for s in MODEL_STEPS]21fig, ax = new_figure(height=2.6)22positions = list(range(len(MODEL_STEPS)))23time_bars = ax.bar([p - 0.2 for p in positions], [100 * time_ns[s] / total_time for s in MODEL_STEPS], width=0.4,24 color=ACCENT, label="share of model time")25token_bars = ax.bar([p + 0.2 for p in positions], [100 * tokens[s] / total_tokens for s in MODEL_STEPS], width=0.4,26 color=INK, label="share of tokens")27ax.bar_label(time_bars, labels=time_labels, padding=2)28ax.bar_label(token_bars, labels=token_labels, padding=2)29ax.set_xticks(positions, list(MODEL_STEPS))30ax.set_ylim(0, 100)31ax.set_ylabel("percent of the dev day")32ax.legend(loc="upper left") # the route bars reach only about 21 percent, so the top left is clear of labels33save(fig, "dev-day-step-shares")3435print("messages in the dev day:", fmt_int(len(runs)))36for step, time_label, token_label in zip(MODEL_STEPS, time_labels, token_labels):37 print(f"{step} calls:", fmt_int(calls[step]))38 print(f"{step}, recorded time:", fmt_ms(time_ns[step]))39 print(f"{step}, share of model time:", time_label)40 print(f"{step}, tokens, input plus output:", fmt_int(tokens[step]))41 print(f"{step}, share of tokens:", token_label)42print("model time, total:", fmt_ms(total_time))43print("tokens, input plus output, total:", fmt_int(total_tokens))44assert sum(calls.values()) == 37 # 20 route calls and 17 answer calls, as the recording holds
python figure-dev-day-step-shares.pyfigure: 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
步驟的時間占比說明一天的等待花在哪裡,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。