Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions open-sse/services/sessionManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ interface SessionEntry {
lastActive: number;
requestCount: number;
connectionId: string | null;
/** Timestamp when the last tool_calls finish_reason was emitted (cross-request TTFT tracking) */
lastToolFinishAt?: number;
}

interface SessionFingerprintOptions {
Expand Down Expand Up @@ -131,6 +133,29 @@ export function touchSession(sessionId: string | null, connectionId: string | nu
}
}

/**
* Persist the tool-finish timestamp so Request 2 (the follow-up after tool execution)
* can measure cross-request TTFT.
*/
export function markToolFinish(sessionId: string | null): void {
if (!sessionId) return;
const session = sessions.get(sessionId);
if (session) session.lastToolFinishAt = Date.now();
}

/**
* Consume the previously persisted tool-finish timestamp (one-shot: clears after read).
* Returns null if no pending timestamp or session not found.
*/
export function consumeToolFinishTime(sessionId: string | null): number | null {
if (!sessionId) return null;
const session = sessions.get(sessionId);
if (!session?.lastToolFinishAt) return null;
const ts = session.lastToolFinishAt;
session.lastToolFinishAt = undefined;
return ts;
}

/**
* Get session info (for sticky routing decisions)
*/
Expand Down
88 changes: 88 additions & 0 deletions open-sse/services/toolLatencyTracker.ts
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++;
Comment on lines +81 to +84

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In recordToolTtft, entry.totalRequests is not incremented when recording the TTFT latency. Since getToolLatencyByProvider uses entry.totalRequests as the measurementCount, any requests that only record TTFT via recordToolTtft will not be counted in the total measurement count, leading to inaccurate metrics reporting.

We should increment entry.totalRequests in recordToolTtft just like we do in recordToolLatency.

  const entry = metrics.get(provider)!;
  entry.totalRequests++;
  entry.ttftAfterToolSum += ttftMs;
  entry.ttftCount++;

}

export function resetToolLatency(): void {
metrics.clear();
}
77 changes: 77 additions & 0 deletions open-sse/utils/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -1287,6 +1309,23 @@ export function createSSEStream(options: StreamOptions = {}) {
const content = delta?.content || delta?.reasoning_content;
if (content && typeof content === "string") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current check content && typeof content === "string" will evaluate to falsy if the first content chunk contains an empty string (""). In streaming responses, the first chunk often contains an empty string to signal the start of the content stream. By ignoring empty strings, the latency tracking (TTFT and gap latency) is delayed until the first non-empty chunk, which can lead to inaccurate metrics.

We should explicitly check if content is a string, even if it is empty, to accurately capture the true start of the content.

Suggested change
const content = delta?.content || delta?.reasoning_content;
if (content && typeof content === "string") {
const content = delta?.content !== undefined ? delta.content : delta?.reasoning_content;
if (typeof content === "string") {

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(
Expand All @@ -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 &&
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

In translate mode, the check translateHasContent uses logical OR on the string values. If the first content chunk contains an empty string (""), translateHasContent will be falsy, delaying the latency tracking until the first non-empty chunk.

We should check if any of the content fields are of type "string" to ensure empty strings are correctly recognized as the start of content.

Suggested change
const translateHasContent =
parsed.delta?.text ||
parsed.choices?.[0]?.delta?.content ||
parsed.choices?.[0]?.delta?.reasoning_content;
const translateHasContent =
typeof parsed.delta?.text === "string" ||
typeof parsed.choices?.[0]?.delta?.content === "string" ||
typeof parsed.choices?.[0]?.delta?.reasoning_content === "string";

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
Expand Down
2 changes: 1 addition & 1 deletion src/sse/handlers/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -902,7 +902,7 @@ async function handleSingleModelChat(
refreshedCredentials
);
}
const proxyInfo = await safeResolveProxy(credentials.connectionId);
const proxyInfo = await safeResolveProxy(credentials.connectionId, apiKeyInfo?.id);
const proxyStartTime = Date.now();

// 4. Execute chat via core after breaker gate checks (with optional TLS tracking)
Expand Down
7 changes: 4 additions & 3 deletions src/sse/handlers/chatHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,8 @@ export async function resolveModelOrError(
const { getCombos } = await import("@/lib/localDb");
const all = await getCombos();
for (const c of all) {
if (c.name?.startsWith("auto/")) available.push(c.name);
const name = typeof c === "object" && c !== null ? (c as Record<string, unknown>).name : undefined;
if (typeof name === "string" && name.startsWith("auto/")) available.push(name);
}
} catch {
/* DB unavailable */
Expand Down Expand Up @@ -507,9 +508,9 @@ export function handleNoCredentials(
);
}

export async function safeResolveProxy(connectionId: string) {
export async function safeResolveProxy(connectionId: string, apiKeyId?: string) {
try {
return await resolveProxyForConnection(connectionId);
return await resolveProxyForConnection(connectionId, apiKeyId);
} catch (proxyErr: any) {
log.debug("PROXY", `Failed to resolve proxy: ${proxyErr.message}`);
return null;
Expand Down