55
66import logging
77import time
8- import uuid
98from dataclasses import dataclass
109from typing import (
1110 Any ,
@@ -402,9 +401,17 @@ def _pop_run_metadata(self, run_id: UUID) -> Optional[RunMetadataUnion]:
402401 def _get_trace_id (self , run_id : UUID ):
403402 trace_id = self ._trace_id or self ._find_root_run (run_id )
404403 if not trace_id :
405- trace_id = uuid . uuid4 ()
404+ return run_id
406405 return trace_id
407406
407+ def _get_parent_run_id (self , trace_id : Any , run_id : UUID , parent_run_id : Optional [UUID ]):
408+ """
409+ Replace the parent run ID with the trace ID for second level runs when a custom trace ID is set.
410+ """
411+ if parent_run_id is not None and parent_run_id not in self ._parent_tree :
412+ return trace_id
413+ return parent_run_id
414+
408415 def _pop_run_and_capture_trace_or_span (self , run_id : UUID , parent_run_id : Optional [UUID ], outputs : Any ):
409416 trace_id = self ._get_trace_id (run_id )
410417 self ._pop_parent_of_run (run_id )
@@ -414,7 +421,9 @@ def _pop_run_and_capture_trace_or_span(self, run_id: UUID, parent_run_id: Option
414421 if isinstance (run , GenerationMetadata ):
415422 log .warning (f"Run { run_id } is not a generation but attempted to be captured as a trace or span." )
416423 return
417- self ._capture_trace_or_span (trace_id , run_id , run , outputs , parent_run_id )
424+ self ._capture_trace_or_span (
425+ trace_id , run_id , run , outputs , self ._get_parent_run_id (trace_id , run_id , parent_run_id )
426+ )
418427
419428 def _capture_trace_or_span (
420429 self ,
@@ -462,7 +471,9 @@ def _pop_run_and_capture_generation(
462471 if not isinstance (run , GenerationMetadata ):
463472 log .warning (f"Run { run_id } is not a generation but attempted to be captured as a generation." )
464473 return
465- self ._capture_generation (trace_id , run_id , run , response , parent_run_id )
474+ self ._capture_generation (
475+ trace_id , run_id , run , response , self ._get_parent_run_id (trace_id , run_id , parent_run_id )
476+ )
466477
467478 def _capture_generation (
468479 self ,
0 commit comments