import { captureException, SPAN_STATUS_ERROR } from '@sentry/core'; import type { Span } from '@sentry/core'; import type { GenAiSpanResult } from '../core/span-hooks'; import { endStreamSpan, getErrorStatus } from '../core/utils'; import { recordTimeToFirstChunk } from '../core/time-to-first-chunk'; import type { GoogleGenAIResponse } from './types'; import type { MessagePart } from './utils'; import { candidatesToMessageParts, setOutputMessagesAttribute } from './utils'; /** * State object used to accumulate information from a stream of Google GenAI events. */ interface StreamingState { /** Collected response text fragments (for output recording). */ responseTexts: string[]; /** Reasons for finishing the response, as reported by the API. */ finishReasons: string[]; /** The response ID. */ responseId?: string; /** The model name. */ responseModel?: string; /** Number of prompt/input tokens used. Tool-use prompt tokens are added when the stream ends. */ promptTokens?: number; toolUsePromptTokens?: number; /** Number of completion/output tokens used. */ completionTokens?: number; candidateTokens?: number; reasoningOutputTokens?: number; /** Number of total tokens used. */ totalTokens?: number; cacheReadInputTokens?: number; /** Accumulated tool calls (finalized) */ toolCalls: Array>; /** Accumulated output message parts (for output recording). */ outputParts: MessagePart[]; } /** * Checks if a response chunk contains an error * @param chunk - The response chunk to check * @param span - The span to update if error is found * @returns Whether an error occurred */ function isErrorChunk(chunk: GoogleGenAIResponse, span: Span): boolean { const feedback = chunk?.promptFeedback; if (feedback?.blockReason) { const message = feedback.blockReasonMessage ?? feedback.blockReason; span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' }); captureException(`Content blocked: ${message}`, { mechanism: { handled: false, type: 'auto.ai.google_genai' }, }); return true; } return false; } /** * Processes response metadata from a chunk * @param chunk - The response chunk to process * @param state - The state of the streaming process */ function handleResponseMetadata(chunk: GoogleGenAIResponse, state: StreamingState): void { if (typeof chunk.responseId === 'string') state.responseId = chunk.responseId; if (typeof chunk.modelVersion === 'string') state.responseModel = chunk.modelVersion; const usage = chunk.usageMetadata; if (usage) { if (typeof usage.promptTokenCount === 'number') state.promptTokens = usage.promptTokenCount; if (typeof usage.toolUsePromptTokenCount === 'number') state.toolUsePromptTokens = usage.toolUsePromptTokenCount; if (typeof usage.candidatesTokenCount === 'number') state.candidateTokens = usage.candidatesTokenCount; if (typeof usage.thoughtsTokenCount === 'number') state.reasoningOutputTokens = usage.thoughtsTokenCount; if (state.candidateTokens !== undefined || state.reasoningOutputTokens !== undefined) { state.completionTokens = (state.candidateTokens ?? 0) + (state.reasoningOutputTokens ?? 0); } if (typeof usage.totalTokenCount === 'number') state.totalTokens = usage.totalTokenCount; if (typeof usage.cachedContentTokenCount === 'number') state.cacheReadInputTokens = usage.cachedContentTokenCount; } } /** * Processes candidate content from a response chunk * @param chunk - The response chunk to process * @param state - The state of the streaming process * @param recordOutputs - Whether to record outputs */ function handleCandidateContent(chunk: GoogleGenAIResponse, state: StreamingState, recordOutputs: boolean): void { // The SDK getter already extracts function calls from candidate parts. if (Array.isArray(chunk.functionCalls)) { state.toolCalls.push(...chunk.functionCalls); } if (recordOutputs) { state.outputParts.push(...candidatesToMessageParts(chunk.candidates)); } for (const candidate of chunk.candidates ?? []) { if (candidate?.finishReason && !state.finishReasons.includes(candidate.finishReason)) { state.finishReasons.push(candidate.finishReason); } for (const part of candidate?.content?.parts ?? []) { if (recordOutputs && part.text) state.responseTexts.push(part.text); } } } /** * Processes a single chunk from the Google GenAI stream * @param chunk - The chunk to process * @param state - The state of the streaming process * @param recordOutputs - Whether to record outputs * @param span - The span to update */ function processChunk(chunk: GoogleGenAIResponse, state: StreamingState, recordOutputs: boolean, span: Span): void { if (!chunk || isErrorChunk(chunk, span)) return; recordTimeToFirstChunk(span); handleResponseMetadata(chunk, state); handleCandidateContent(chunk, state, recordOutputs); } /** * Instruments an async iterable stream of Google GenAI response chunks, updates the span with * streaming attributes and (optionally) the aggregated output text, and yields * each chunk from the input stream unchanged. */ export async function* instrumentStream( stream: AsyncIterable, span: Span, recordOutputs: boolean, abortSignal?: AbortSignal, beforeSpanEnd?: (result: GenAiSpanResult) => void, ): AsyncGenerator { const state: StreamingState = { responseTexts: [], finishReasons: [], toolCalls: [], outputParts: [], }; const result: GenAiSpanResult = {}; try { for await (const chunk of stream) { processChunk(chunk, state, recordOutputs, span); yield chunk; } } catch (error) { span.setStatus(getErrorStatus(abortSignal)); result.error = error; throw error; } finally { if (recordOutputs) { setOutputMessagesAttribute(span, state.outputParts); } if (typeof state.promptTokens === 'number') state.promptTokens += state.toolUsePromptTokens ?? 0; endStreamSpan(span, state, recordOutputs, () => beforeSpanEnd?.(result)); } }