Ends a trace (its root span) and finalizes it. If no trace_context is provided, ends all active session spans. Args: trace_context: The TraceContext object returned by start_trace. If None, ends all active traces. end_state: The final state of the tr
(
self, trace_context: Optional[TraceContext] = None, end_state: Union[Any, StatusCode, str] = None
)
| 428 | return trace_context |
| 429 | |
| 430 | def end_trace( |
| 431 | self, trace_context: Optional[TraceContext] = None, end_state: Union[Any, StatusCode, str] = None |
| 432 | ) -> None: |
| 433 | """ |
| 434 | Ends a trace (its root span) and finalizes it. |
| 435 | If no trace_context is provided, ends all active session spans. |
| 436 | |
| 437 | Args: |
| 438 | trace_context: The TraceContext object returned by start_trace. If None, ends all active traces. |
| 439 | end_state: The final state of the trace (e.g., "Success", "Indeterminate", "Error"). |
| 440 | """ |
| 441 | if not self.initialized: |
| 442 | logger.warning("Global tracer not initialized. Cannot end trace.") |
| 443 | return |
| 444 | |
| 445 | # Set default if not provided |
| 446 | if end_state is None: |
| 447 | from agentops.enums import TraceState |
| 448 | |
| 449 | end_state = TraceState.SUCCESS |
| 450 | |
| 451 | # If no specific trace_context provided, end all active traces |
| 452 | if trace_context is None: |
| 453 | with self._traces_lock: |
| 454 | active_traces = list(self._active_traces.values()) |
| 455 | logger.debug(f"Ending all {len(active_traces)} active traces with state: {end_state}") |
| 456 | |
| 457 | for active_trace in active_traces: |
| 458 | self._end_single_trace(active_trace, end_state) |
| 459 | return |
| 460 | |
| 461 | # End specific trace |
| 462 | self._end_single_trace(trace_context, end_state) |
| 463 | |
| 464 | def _end_single_trace(self, trace_context: TraceContext, end_state: Union[Any, StatusCode, str]) -> None: |
| 465 | """ |