@@ -238,21 +238,9 @@ def _end_span(self, run_id: UUID):
238238 del self .spans [run_id ]
239239
240240 def start (self , invocation : LLMInvocation ):
241- parent_state = (
242- self .spans .get (invocation .parent_run_id )
243- if invocation .parent_run_id is not None
244- else None
245- )
246- if parent_state is not None :
247- parent_state .children .append (invocation .run_id )
248- span = self ._start_span (
249- name = f"{ GenAI .GenAiOperationNameValues .CHAT .value } { invocation .request_model } " ,
250- kind = SpanKind .CLIENT ,
251- parent_run_id = invocation .parent_run_id ,
252- )
253- # Keep span active but do not end it here; it will be ended in finish()/error()
254- with use_span (span , end_on_exit = False ):
255- self .spans [invocation .run_id ] = _SpanState (span = span )
241+ # Create/register the span; keep it active but do not end it here.
242+ with self ._start_span_for_invocation (invocation ):
243+ pass
256244
257245 @contextmanager
258246 def _start_span_for_invocation (self , invocation : LLMInvocation ):
@@ -261,6 +249,14 @@ def _start_span_for_invocation(self, invocation: LLMInvocation):
261249 The span is not ended automatically on exiting the context; callers
262250 must finalize via _finalize_invocation.
263251 """
252+ # Establish parent/child relationship if a parent span exists.
253+ parent_state = (
254+ self .spans .get (invocation .parent_run_id )
255+ if invocation .parent_run_id is not None
256+ else None
257+ )
258+ if parent_state is not None :
259+ parent_state .children .append (invocation .run_id )
264260 span = self ._start_span (
265261 name = f"{ GenAI .GenAiOperationNameValues .CHAT .value } { invocation .request_model } " ,
266262 kind = SpanKind .CLIENT ,
0 commit comments