追踪一次请求,再追问时间花在了哪里
阅读约 33分钟,7节中含6个示例。
实验室
通过动手实践学习本章
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。约 30 秒后打开。
完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。Labs 为你运行:每月 40小时。
在你自己的机器上,免费: 下载本书的笔记本,附其代码和数据,来源为 GitHub。
在本书所用版本上运行你的代码
读完本章,你可以手工构建一条消息的追踪,将其打印为树,并说明它的时间和词元花在了哪里。随后,你可以对一天的消息做同样的汇总,并指出哪一步耗时最多。
Ambrewick 是为本书编写的一款个人助手应用的后端。用户发送一条消息,助手会根据知识库、某个工具或固定回复来作答。它的日志为每条消息记一行,为每条回复也记一行,两者之间什么都没有。在开发日,也就是本章回放的 2026-12-07 这一天的二十条消息中,最慢的一条是消息 3271。从到达到回复,它用了 36,230.7 ms。消息 809 是本章追踪的第一条。它的内容是“brew coffee at noon”,从到达到回复的时间是 11,520.7 ms。日志无法说明这段时间在选择路由、搜索知识库和撰写答案之间是如何分配的。追踪记录的正是这种分配,逐个记录带计时的步骤。
一条消息,一条追踪
追踪按消息保存,因为关于用户体验的问题正是以消息为单位提出的。有人问消息 809 为什么慢,就需要把它的各个步骤放在一起看;有人问这一天的时间都花在哪里,就需要把全部二十条消息的追踪并排比较。如果没有键,按事件逐行记录的日志就无法这样分组,而追踪 ID正是这个键。同一条消息的每个 span 都带有它,所以这两个问题各用一次查询就能回答,不必在文本中搜索。
追踪是一条用户消息所做工作的记录:为这条消息创建的每个 span 共用同一个追踪 ID。它们的父级链接把它们连成一棵树,父 span 缺失的 span 仍然属于该追踪。span 是一个有名称、有计时的操作,带有属性和一个父级,只有根 span 没有父级。根 span 覆盖整条消息,助手执行的每个步骤都是它之下的一个 span,各有自己的开始和结束时间。
《Agent Harnesses》一书同样为每个步骤保存记录,并把这种记录称为追踪。在那里,追踪是一个文件,每行一个 JSON 对象,是智能体一次运行的记录,如每个事件一行所述。在这里,追踪是 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。覆盖多条消息的一次运行、或只覆盖部分步骤的追踪,无法回答关于某一条消息的问题;缺少追踪 ID 的日志行也无法与其他日志行关联起来。
回放与虚拟时钟
消息 809 的轨迹需要每个步骤的时间,而这里的时间来自一份录制记录,不来自时钟。回放会给每次模型调用提供记录中保存的回复,同时给出该次调用的记录时间和它的 token 计数。这里没有任何东西在等待模型,也没有任何东西被测量。OpenTelemetry Specification, Trace API(v1.52.0)要求 span 的时间戳反映操作实际经过的真实时间,所以本书中的时间是录制记录的时间,经回放得到,这是有意的选择。回放按每次调用的记录时间推进一个虚拟时钟。该时钟是自 Unix 纪元起、以 UTC 计的纳秒整数,从消息到达时开始计时。回放运行完毕后,时钟就表明这条消息用了多长时间。同一份录制记录在每次运行中都会让时钟前进相同的量。
开发日是包含二十条消息的一天,也是本章唯一使用的一天。其中每次模型调用都在录制机器上录制过一次,这台机器是 4 个 vCPU、主频 2.10 GHz 的 Intel Xeon,运行的是 Q4_K_M GGUF 文件形式的 Qwen3-4B-Instruct-2507。这些示例回放的就是这份录制记录:每次模型调用得到该次运行给出的回复,以及其记录时间和 token 计数,没有任何示例会运行模型。托管模型的响应时间会有所不同。下面的方法可以沿用到托管模型上,但这些数字不能。
一次调用的 token 计数不是时间,因此它们不会推进时钟。它们是录制记录为每次调用保存的属性,由 span 携带。缓存输入 token 是推算得出的,不是上报的:它等于提示词 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 项证明建立在 message 的基础上,参见第1章,“一条消息,一条追踪”
建立在 trace 的基础上,参见第1章,“一条消息,一条追踪”
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
在本书的数据上,第 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,这就是该消息在模型调用上花费的时间。回放不给检索步骤任何时间,因为录制记录中没有保存搜索的时间。录制的那次运行在路由调用结束与回答调用开始之间花了 7.3 ms,而回放丢掉了这段间隔。对时钟的断言只检查回放的代码:时钟仅按步骤时间前进,所以它发现不了录制记录所丢掉的间隔。
工作准则: 让录制记录推动时钟,绝不要手工累加某个步骤的时间。在时钟旁放一个断言,对照各步骤检查时钟的推进量,这样丢掉时间的步骤会使这次运行失败,而不会以偏短的总数呈现给读者。
手工构造 span
有了回放中的各个步骤和时间(回放与虚拟时钟),SDK 就可以生成 span 了。本章的代码使用 Python 版 OpenTelemetry SDK,版本为 1.45.2。由 SDK 的 tracer 生成 span,而 span 的去向由配置给它的两个部分决定。span processor 在每个 span 开始和结束时被调用,结束时它把 span 交给 exporter,由 exporter 把 span 发送到某处:内存、文件或 OTLP 端点。这里的代码使用 SimpleSpanProcessor,它在每个 span 结束的那一刻就将其导出。相比之下,批处理 processor 会在之后按定时器分批导出,因此在刷新之前打印的代码可能一个 span 也找不到,而且队列写满后还会丢弃 span(OpenTelemetry Specification, Trace SDK,v1.52.0)。我们使用简单 processor,是为了让每个 span 在打印时都已导出。在生产环境中,我们建议使用批处理 processor,因为简单 processor 会在结束 span 的线程上调用 exporter,所以较慢的 exporter 会拖慢请求。SDK 中 SimpleSpanProcessor.on_end 的源码(位于 1.45.2)就是直接进行这一调用的。这里的 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 上下文主要由 trace ID、span ID 和 trace flags 组成,其他代码和其他进程凭它来指称该 span。辅助函数接收一个父 span 并将其放入上下文,这样子 span 就能指明它的父 span。
resource 描述产生遥测数据的对象,同一个 tracer provider 生成的每个 span 上都相同:service.name、service.version、service.instance.id。在本书中,服务是 ambrewick-assistant,版本为录制时所用的版本,其实例 ID 是手工设定的固定字符串,因为 SDK 的默认值是每次运行都新生成的随机 UUID。
属性是记录在 span 或 resource 上的键和值,例如 gen_ai.request.model。本章的属性是本书自定义的。每个步骤的 span 都带有 ambrewick.step,它指明该 span 来自哪个步骤。根 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 只有在结束时才会被导出,因为正如规范的 SDK 页面所说,简单 processor 在 span 一结束就把它交给 exporter,所以其工作从未走到 end() 调用的 span 根本不会被导出。在实际运行的代码中,根 span 覆盖整条消息,因此它最后结束;若进程在处理消息的中途崩溃,根 span 和当时正在运行的步骤就会丢失。这样,trace 到达时就只有已完成的步骤,而它们的父 span 始终没有到达;若使用批处理 processor,仍在其队列中的 span 也会丢失。示例中先结束根 span,只是因为它们是在回放之后才构造 span,而实际运行的代码绝不会这样做。找出唯一一个没有父 span 的 span 的检查,正是用来发现这类 trace 的。
工作准则: 在回放中,用回放时钟给出的明确结束时间来结束每个 span。在实际运行的代码中,让 SDK 从机器时钟获取开始和结束两个时间。无论哪种情况,都要检查每条 trace 是否有根 span,即恰好一个没有父 span 的 span,因为没有根 span 的 trace 正是崩溃留下的结果,它看上去只是几个很短的步骤,而不像一次故障。
一条追踪的树
手工构造跨度为消息 809 生成的四个跨度,通过父链接构成一棵树,随后脚本检查它们的时间如何相加。这棵树列出了根跨度及其三个步骤,后面的几行给出它们的时间和检查结果:
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 的三个步骤位于根跨度之下一层。OpenTelemetry 规范把一条追踪称为由跨度组成的有向无环图,而父链接使这张图成为一棵树,每个跨度只有一个父跨度。树本身不给出时间,时间由接下来的几行给出。
子跨度可以在其父跨度之后结束。规范的概述中画出了这样的情形,并且没有任何规则禁止这样做(OpenTelemetry 规范,概述:Traces、Spans、SpanContext,标签 v1.52.0)。因此,当子跨度相互重叠时,父跨度的持续时间不等于各子跨度之和;当子跨度之间留有空隙时,两者也可能不同。在这次重放中,消息 809 的各步骤既不重叠也没有空隙:路由结束时,回答随即开始。脚本对此做了检验,输出中消息的时间为 11,520.7 ms,各步骤的时间为 11,520.7 ms,两者是同一个数。
读者容易把父跨度的条形当作其子跨度所做的工作。条形只表示父跨度从何时开始、到何时结束,而空隙是没有任何子跨度记录的工作。这两种情形都没有出现在这次重放中。
图 1.1把同一条追踪画成了瀑布图。瀑布图在时间轴上为每个跨度画一条条形,是追踪工具通常绘制的视图,规范的概述对它有示意;规范并未将它定义为一种格式,这幅图是本书自己的画法。图中每个跨度对应一条条形,从跨度的开始到结束,单位为消息到达之后的秒数。最上方是整条消息的条形,然后是从到达时刻开始的路由条形,检索步骤在路由结束处是一条刻度线,接着是从该处延伸到消息结束的较长的回答条形。
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
回答跨度在到达后 3,336.3 ms 开始,也就是路由结束的时刻。图中的顺序就是各步骤运行的顺序,其长度就是时钟记录的时间。
工作准则: 将追踪打印为父链接构成的树,在把子跨度的时间相加之前,先检查它们是否既不重叠也没有空隙。若有重叠或空隙,应分别报告父跨度的时间和各子跨度的时间。
二十条消息的时间去向
消息 809 只是一条追踪,而开发日共有二十条。一条消息,一条追踪把每条消息的各个步骤放在一起,因此可以把全天的步骤加总。回退回复是路由器选择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
统计每个模型步骤的输入和输出词元
+10 项证明来自二十条消息的时间去向,第 1 章再读一遍
新版次改变了本节所练习的内容。版次 2026.11.2 的变更内容
第 20 行只累加了每次模型调用写出的内容,因此词元占比漏掉了当天的输入。请修改第 20 行,使每个模型步骤的词元数等于它的输入加上输出。
原理何在
脚本依次重放全部二十条消息,并把全天每个模型步骤的数据加总。全天的工具调用都交给了进程内工具,即日历、闹钟和列表工具,它们的耗时由本书配置中的一张表建模得出,并非实际记录,所以占比中不含这些工具,只把它们计为调用次数。检索(Retrieve)同样没有记录耗时。脚本还统计了各步骤在时间上有重叠的消息,数量为0 of 20。因此,全天的合计是各步骤耗时之和,而不是对每条消息根耗时的拆分。
回答步骤占去全天模型时间的大部分,为83.3%;路由步骤占 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客户端库的官方插桩在同类调用上会输出什么。 - 第二个进程。 这条追踪只是一个进程的记录。第 4 章把联系人团队服务器的 span 接入这条追踪,该服务器作为独立的进程运行。
- 存储。 span 保存在内存中,进程结束时就会消失。第 5 章把它们发送到负责存储的后端。
- 尾部。 二十条消息无法给出可信度较高的尾部百分位数。第 7 章给出附带样本数和区间的百分位数。
- 采样。 每条追踪都被保留。第 11 章决定保留哪些追踪,以及为什么这样选。
- 提示词。 span 中不含提示词文本,这是有意为之。第 3 章会指出可以记录提示词的开关,第 12 章讲述该开关会泄露什么。
- 错误的路由。 有 6 of 20 条 dev-day 消息得到了兜底回复,而本章不检查每条路由是否正确。第 8 章会检查。
本章做出的决定
这些决定会影响本书的其余部分:
- 目前,各个 span 按步骤命名。从第 2 章起,本书使用标准的命名。
- 每个时长都是记录下来的值,而不是实时测量的结果,因此每一个打印出的时间都可以重新运行并得到相同的结果。
- span 在结束的那一刻由同步处理器导出,因此在打印时,每个 span 都已经导出。
- 占比与其分母一同打印;对于时间没有记录的步骤,不做估算,而是将其排除在占比之外。
- 每条追踪(trace)只属于一条消息,按天的汇总是按记录中的原样把各条消息的步骤相加,不使用由 span 另行构造的其他度量。
工作准则: 要回答关于某一条消息的问题,只依据该消息自己的追踪。该消息的每个 span 都带有相同的追踪 ID,根 span 覆盖了它的全部时间,因此这条追踪包含这条消息的各个步骤,而不包含其他消息的步骤。没有该 ID 的 span 或日志行无法归入答案,应当将其排除并加以说明,而不要猜测它属于哪一条消息。猜测会把一条消息的时间算进另一条消息的总数。
本章,在本版次中
版次 2026.11.2示例于 2026年11月23日 通过6 of 6个示例 in this chapter pass
译自英文版图书,版次 2026.11.2。