DeepVCode icon indicating copy to clipboard operation
DeepVCode copied to clipboard

perf: 遥测关闭时跳过完整响应/请求的 JSON 序列化 (#31)

Open appergb opened this issue 6 months ago • 0 comments

关联 issue

Closes #31

问题

GeminiChat 在每轮响应结束后,都会对完整响应(非流式)/ 全部累积 chunk(流式)以及完整 curated 请求历史执行 JSON.stringify,仅仅为了传给 logApiRequest / logApiResponse。

但这些文本只在 OpenTelemetry SDK 初始化后才会作为日志属性使用(telemetry/loggers.ts 中 if (!isTelemetrySdkInitialized()) return; 之后才 attributes.response_text = ...);ClearcutLogger.logApiRequestEvent/logApiResponseEvent 完全不读取 request_text / response_text(仅用 model / token 数 / 状态码 / auth_type 等)。

因此在**默认路径(遥测关闭)**下,这是发生在「响应结束 → 记录历史」热路径上的纯 O(响应大小) 开销;流式大响应(上百个 chunk)尤其明显。

改动

  • 新增私有助手 _serializeForTelemetry(value):仅当 isTelemetrySdkInitialized() 为真时才 JSON.stringify,否则返回 undefined。
  • _getRequestTextFromContents 与两处 _logApiResponse 调用(非流式 geminiChat.ts:~380 / 流式 :~991)改用该助手。
  • 遥测开启时行为完全不变(仍记录同样的文本),仅消除遥测关闭时的无谓序列化。

测试

  • 新增 3 个单测(geminiChat.test.ts):
    • 非流式 + SDK 未初始化 → request_text / response_text 均为 undefined;
    • 非流式 + SDK 已初始化 → 两者均为字符串(行为保持);
    • 流式 + SDK 未初始化 → 不序列化整个 chunk 数组(response_text 为 undefined)。
  • npx vitest run packages/core/src/core/geminiChat.test.ts → 25 passed。
  • npm run typecheck --workspace=packages/core → 通过。
  • 仅改动 geminiChat.ts / geminiChat.test.ts;新增行均符合 Prettier,未触碰文件中既有的历史 lint 负债。

appergb avatar May 31 '26 09:05 appergb