Repository navigation
feat(metrics): cross-request TTFT and gap latency after tool calls #3173
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| /** | ||
| * Tracks per-provider tool call latency metrics. | ||
| * Resets on server restart. | ||
| */ | ||
|
|
||
| interface ToolLatencyEntry { | ||
| totalRequests: number; | ||
| ttftAfterToolSum: number; | ||
| gapAfterToolSum: number; | ||
| ttftCount: number; | ||
| gapCount: number; | ||
| } | ||
|
|
||
| const metrics = new Map<string, ToolLatencyEntry>(); | ||
|
|
||
| export function recordToolLatency( | ||
| provider: string, | ||
| ttftAfterToolMs: number | null, | ||
| gapAfterToolMs: number | null | ||
| ): void { | ||
| if (!provider) return; | ||
|
|
||
| if (!metrics.has(provider)) { | ||
| metrics.set(provider, { | ||
| totalRequests: 0, | ||
| ttftAfterToolSum: 0, | ||
| gapAfterToolSum: 0, | ||
| ttftCount: 0, | ||
| gapCount: 0, | ||
| }); | ||
| } | ||
|
|
||
| const entry = metrics.get(provider)!; | ||
| entry.totalRequests++; | ||
|
|
||
| if (ttftAfterToolMs != null && ttftAfterToolMs >= 0) { | ||
| entry.ttftAfterToolSum += ttftAfterToolMs; | ||
| entry.ttftCount++; | ||
| } | ||
|
|
||
| if (gapAfterToolMs != null && gapAfterToolMs >= 0) { | ||
| entry.gapAfterToolSum += gapAfterToolMs; | ||
| entry.gapCount++; | ||
| } | ||
| } | ||
|
|
||
| export function getToolLatencyByProvider(): Record< | ||
| string, | ||
| { | ||
| avgTtftAfterToolMs: number; | ||
| avgGapAfterToolMs: number; | ||
| measurementCount: number; | ||
| } | ||
| > { | ||
| const result: Record<string, any> = {}; | ||
| for (const [provider, entry] of metrics) { | ||
| result[provider] = { | ||
| avgTtftAfterToolMs: | ||
| entry.ttftCount > 0 ? Math.round(entry.ttftAfterToolSum / entry.ttftCount) : 0, | ||
| avgGapAfterToolMs: | ||
| entry.gapCount > 0 ? Math.round(entry.gapAfterToolSum / entry.gapCount) : 0, | ||
| measurementCount: entry.totalRequests, | ||
| }; | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| export function recordToolTtft(provider: string, ttftMs: number): void { | ||
| if (!provider || ttftMs < 0) return; | ||
|
|
||
| if (!metrics.has(provider)) { | ||
| metrics.set(provider, { | ||
| totalRequests: 0, | ||
| ttftAfterToolSum: 0, | ||
| gapAfterToolSum: 0, | ||
| ttftCount: 0, | ||
| gapCount: 0, | ||
| }); | ||
| } | ||
|
|
||
| const entry = metrics.get(provider)!; | ||
| entry.ttftAfterToolSum += ttftMs; | ||
| entry.ttftCount++; | ||
| } | ||
|
|
||
| export function resetToolLatency(): void { | ||
| metrics.clear(); | ||
| } | ||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -29,6 +29,12 @@ import { | |||||||||||||||||
| extractThinkingFromContent, | ||||||||||||||||||
| } from "../handlers/responseSanitizer.ts"; | ||||||||||||||||||
| import { buildErrorBody } from "./error.ts"; | ||||||||||||||||||
| import { recordToolLatency } from "../services/toolLatencyTracker.ts"; | ||||||||||||||||||
| import { | ||||||||||||||||||
| generateSessionId, | ||||||||||||||||||
| markToolFinish, | ||||||||||||||||||
| consumeToolFinishTime, | ||||||||||||||||||
| } from "../services/sessionManager.ts"; | ||||||||||||||||||
|
|
||||||||||||||||||
| /** | ||||||||||||||||||
| * Race a response body read against a timeout. | ||||||||||||||||||
|
|
@@ -602,6 +608,21 @@ export function createSSEStream(options: StreamOptions = {}) { | |||||||||||||||||
| const passthroughResponsesReasoningSummarySeen = new Set<string>(); | ||||||||||||||||||
| const streamStartedAt = Date.now(); | ||||||||||||||||||
|
|
||||||||||||||||||
| let lastToolCallChunkTime: number | null = null; | ||||||||||||||||||
| let toolFinishTime: number | null = null; | ||||||||||||||||||
| let contentAfterToolSeen = false; | ||||||||||||||||||
|
|
||||||||||||||||||
| // Cross-request tool latency: fingerprint the session from the request body | ||||||||||||||||||
| // so Request 2 can pick up the tool-finish timestamp left by Request 1. | ||||||||||||||||||
| const sessionId = generateSessionId(body as Parameters<typeof generateSessionId>[0], { | ||||||||||||||||||
| provider: provider ?? undefined, | ||||||||||||||||||
| connectionId: connectionId ?? undefined, | ||||||||||||||||||
| }); | ||||||||||||||||||
| let pendingToolFinishTime: number | null = null; | ||||||||||||||||||
| try { | ||||||||||||||||||
| pendingToolFinishTime = consumeToolFinishTime(sessionId); | ||||||||||||||||||
| } catch {} | ||||||||||||||||||
|
|
||||||||||||||||||
| // Guard against duplicate [DONE] events — ensures exactly one per stream | ||||||||||||||||||
| let doneSent = false; | ||||||||||||||||||
| const providerPayloadCollector = createStructuredSSECollector({ | ||||||||||||||||||
|
|
@@ -1252,6 +1273,7 @@ export function createSSEStream(options: StreamOptions = {}) { | |||||||||||||||||
| // T18: Track if we saw tool calls & accumulate for call log | ||||||||||||||||||
| if (delta?.tool_calls && delta.tool_calls.length > 0) { | ||||||||||||||||||
| passthroughHasToolCalls = true; | ||||||||||||||||||
| lastToolCallChunkTime = Date.now(); | ||||||||||||||||||
| for (const tc of delta.tool_calls) { | ||||||||||||||||||
| // Key by index first — id only appears on the first delta in OpenAI streaming | ||||||||||||||||||
| let key: string; | ||||||||||||||||||
|
|
@@ -1287,6 +1309,23 @@ export function createSSEStream(options: StreamOptions = {}) { | |||||||||||||||||
| const content = delta?.content || delta?.reasoning_content; | ||||||||||||||||||
| if (content && typeof content === "string") { | ||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The current check We should explicitly check if
Suggested change
|
||||||||||||||||||
| totalContentLength += content.length; | ||||||||||||||||||
|
|
||||||||||||||||||
| if (!contentAfterToolSeen) { | ||||||||||||||||||
| const toolTs = toolFinishTime || pendingToolFinishTime; | ||||||||||||||||||
| const lastChunkTs = lastToolCallChunkTime; | ||||||||||||||||||
| if (toolTs || lastChunkTs) { | ||||||||||||||||||
| contentAfterToolSeen = true; | ||||||||||||||||||
| const now = Date.now(); | ||||||||||||||||||
| try { | ||||||||||||||||||
| recordToolLatency( | ||||||||||||||||||
| provider || "unknown", | ||||||||||||||||||
| toolTs ? now - toolTs : null, | ||||||||||||||||||
| lastChunkTs ? now - lastChunkTs : null | ||||||||||||||||||
| ); | ||||||||||||||||||
| } catch {} | ||||||||||||||||||
| pendingToolFinishTime = null; | ||||||||||||||||||
| } | ||||||||||||||||||
| } | ||||||||||||||||||
| } | ||||||||||||||||||
| if (typeof delta?.content === "string") | ||||||||||||||||||
| passthroughAccumulatedContent = appendBoundedText( | ||||||||||||||||||
|
|
@@ -1306,6 +1345,13 @@ export function createSSEStream(options: StreamOptions = {}) { | |||||||||||||||||
|
|
||||||||||||||||||
| const isFinishChunk = parsed.choices?.[0]?.finish_reason; | ||||||||||||||||||
|
|
||||||||||||||||||
| if (isFinishChunk && passthroughHasToolCalls) { | ||||||||||||||||||
| toolFinishTime = Date.now(); | ||||||||||||||||||
| try { | ||||||||||||||||||
| markToolFinish(sessionId); | ||||||||||||||||||
| } catch {} | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| // T18: Normalize finish_reason to 'tool_calls' if tool calls were used | ||||||||||||||||||
| if ( | ||||||||||||||||||
| isFinishChunk && | ||||||||||||||||||
|
|
@@ -1395,6 +1441,16 @@ export function createSSEStream(options: StreamOptions = {}) { | |||||||||||||||||
| continue; | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| if (parsed.choices?.[0]?.delta?.tool_calls) { | ||||||||||||||||||
| lastToolCallChunkTime = Date.now(); | ||||||||||||||||||
| } | ||||||||||||||||||
| if (parsed.choices?.[0]?.finish_reason === "tool_calls") { | ||||||||||||||||||
| toolFinishTime = Date.now(); | ||||||||||||||||||
| try { | ||||||||||||||||||
| markToolFinish(sessionId); | ||||||||||||||||||
| } catch {} | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| // Track content length and accumulate for call log (from raw provider chunk, so content is never missed) | ||||||||||||||||||
| // Do this before translation so we capture content regardless of translator output shape | ||||||||||||||||||
|
|
||||||||||||||||||
|
|
@@ -1492,6 +1548,27 @@ export function createSSEStream(options: StreamOptions = {}) { | |||||||||||||||||
| } | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| const translateHasContent = | ||||||||||||||||||
| parsed.delta?.text || | ||||||||||||||||||
| parsed.choices?.[0]?.delta?.content || | ||||||||||||||||||
| parsed.choices?.[0]?.delta?.reasoning_content; | ||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In translate mode, the check We should check if any of the content fields are of type
Suggested change
|
||||||||||||||||||
| if (translateHasContent && !contentAfterToolSeen) { | ||||||||||||||||||
| const toolTs = toolFinishTime || pendingToolFinishTime; | ||||||||||||||||||
| const lastChunkTs = lastToolCallChunkTime; | ||||||||||||||||||
| if (toolTs || lastChunkTs) { | ||||||||||||||||||
| contentAfterToolSeen = true; | ||||||||||||||||||
| const now = Date.now(); | ||||||||||||||||||
| try { | ||||||||||||||||||
| recordToolLatency( | ||||||||||||||||||
| provider || "unknown", | ||||||||||||||||||
| toolTs ? now - toolTs : null, | ||||||||||||||||||
| lastChunkTs ? now - lastChunkTs : null | ||||||||||||||||||
| ); | ||||||||||||||||||
| } catch {} | ||||||||||||||||||
| pendingToolFinishTime = null; | ||||||||||||||||||
| } | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| // Extract usage | ||||||||||||||||||
| const extracted = extractUsage(parsed); | ||||||||||||||||||
| if (extracted) state.usage = extracted; // Keep original usage for logging | ||||||||||||||||||
|
|
||||||||||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In
recordToolTtft,entry.totalRequestsis not incremented when recording the TTFT latency. SincegetToolLatencyByProviderusesentry.totalRequestsas themeasurementCount, any requests that only record TTFT viarecordToolTtftwill not be counted in the total measurement count, leading to inaccurate metrics reporting.We should increment
entry.totalRequestsinrecordToolTtftjust like we do inrecordToolLatency.