11import { captureException } from '../../exports' ;
22import { SPAN_STATUS_ERROR } from '../../tracing' ;
33import type { Span } from '../../types-hoist/span' ;
4+ import { updateSpanName } from '../../utils/spanUtils' ;
45import {
6+ GEN_AI_REQUEST_MODEL_ATTRIBUTE ,
57 GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE ,
68 GEN_AI_RESPONSE_STREAMING_ATTRIBUTE ,
79 GEN_AI_RESPONSE_TEXT_ATTRIBUTE ,
810 GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE ,
11+ OPENAI_OPERATIONS ,
912} from '../ai/gen-ai-attributes' ;
1013import { RESPONSE_EVENT_TYPES } from './constants' ;
1114import type {
@@ -26,6 +29,8 @@ import {
2629 * State object used to accumulate information from a stream of OpenAI events/chunks.
2730 */
2831interface StreamingState {
32+ /** Whether this stream contained Responses API events. */
33+ sawResponsesApiEvent : boolean ;
2934 /** Types of events encountered in the stream. */
3035 eventTypes : string [ ] ;
3136 /** Collected response text fragments (for output recording). */
@@ -222,6 +227,7 @@ export async function* instrumentStream<T>(
222227 recordOutputs : boolean ,
223228) : AsyncGenerator < T , void , unknown > {
224229 const state : StreamingState = {
230+ sawResponsesApiEvent : false ,
225231 eventTypes : [ ] ,
226232 responseTexts : [ ] ,
227233 finishReasons : [ ] ,
@@ -240,12 +246,19 @@ export async function* instrumentStream<T>(
240246 if ( isChatCompletionChunk ( event ) ) {
241247 processChatCompletionChunk ( event as ChatCompletionChunk , state , recordOutputs ) ;
242248 } else if ( isResponsesApiStreamEvent ( event ) ) {
249+ state . sawResponsesApiEvent = true ;
243250 processResponsesApiEvent ( event as ResponseStreamingEvent , state , recordOutputs , span ) ;
244251 }
245252 yield event ;
246253 }
247254 } finally {
248255 setCommonResponseAttributes ( span , state . responseId , state . responseModel , state . responseTimestamp ) ;
256+ if ( state . sawResponsesApiEvent && state . responseModel ) {
257+ span . setAttributes ( {
258+ [ GEN_AI_REQUEST_MODEL_ATTRIBUTE ] : state . responseModel ,
259+ } ) ;
260+ updateSpanName ( span , `${ OPENAI_OPERATIONS . CHAT } ${ state . responseModel } ` ) ;
261+ }
249262 setTokenUsageAttributes ( span , state . promptTokens , state . completionTokens , state . totalTokens ) ;
250263
251264 span . setAttributes ( {
0 commit comments