@@ -1045,6 +1045,10 @@ def __init__(
10451045 self ._ignore_agent = ignore_agent
10461046 # For async: manage our own trace mapping since context vars are unreliable
10471047 self ._traces_by_root : Dict [UUID , traces .Trace ] = {}
1048+ # Detect if an external trace context exists at initialization time
1049+ # If true, we'll create standalone traces for external system integration
1050+ # instead of uploading them independently
1051+ self ._has_external_trace : bool = tracer .get_current_trace () is not None
10481052
10491053 @property
10501054 def ignore_llm (self ) -> bool :
@@ -1108,9 +1112,17 @@ def _start_step(
11081112 # We're inside an existing step context - add as nested
11091113 current_step .add_nested_step (step )
11101114 elif current_trace is not None :
1111- # Existing trace but no current step - add to trace
1112- current_trace .add_step (step )
1113- # Don't track in _traces_by_root since we're using external trace
1115+ # Have trace but no current step
1116+ # If it's an external trace, we should NOT add at root - external system will integrate
1117+ # If it's a ContextVar trace with no current step, add to trace
1118+ if not self ._has_external_trace :
1119+ # ContextVar-detected trace - add directly
1120+ current_trace .add_step (step )
1121+ else :
1122+ # External trace without current step - create temp standalone for later integration
1123+ trace = traces .Trace ()
1124+ trace .add_step (step )
1125+ self ._traces_by_root [run_id ] = trace
11141126 else :
11151127 # No existing context - create standalone trace
11161128 trace = traces .Trace ()
@@ -1163,8 +1175,10 @@ def _end_step(
11631175 setattr (step , key , value )
11641176
11651177 # Only upload if this is a standalone trace (not integrated with external trace)
1166- # If current_step is set, we're part of a larger trace and shouldn't upload
1167- if is_root_step and run_id in self ._traces_by_root and tracer .get_current_step () is None :
1178+ has_standalone_trace = run_id in self ._traces_by_root
1179+
1180+ # Only upload if: root step + has standalone trace + not part of external trace
1181+ if is_root_step and has_standalone_trace and not self ._has_external_trace :
11681182 trace = self ._traces_by_root .pop (run_id )
11691183 self ._process_and_upload_async_trace (trace )
11701184
0 commit comments