Skip to content

honeyhive.tracer.instrumentation

Instrumentation framework for HoneyHive tracing.

This module provides user-facing instrumentation capabilities including decorators, enrichment, and tracer initialization. All components use dynamic logic patterns for flexible, configuration-driven instrumentation.

enrich_span module-attribute

enrich_span = UnifiedEnrichSpan()

atrace

atrace(
    event_type: Optional[str] = None,
    event_name: Optional[str] = None,
    **kwargs: Any
) -> Union[
    Callable[[Callable[..., Any]], Callable[..., Any]],
    Callable[..., Any],
]

Legacy async-specific trace decorator (deprecated).

Note

This decorator is maintained for backwards compatibility. Use the unified :func:trace decorator instead, which auto-detects sync/async functions.

Parameters:

Name Type Description Default
event_type Optional[str]

Type of event being traced (e.g., "model", "tool", "chain")

None
event_name Optional[str]

Name of the event (defaults to function name)

None
**kwargs Any

Additional tracing parameters (source, project, session_id, etc.)

{}

Returns:

Type Description
Union[Callable[[Callable[..., Any]], Callable[..., Any]], Callable[..., Any]]

Decorated async function with tracing capabilities

See Also

:func:trace: Unified decorator that handles both sync and async functions

Source code in src/honeyhive/tracer/instrumentation/decorators.py
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
def atrace(
    event_type: Optional[str] = None,
    event_name: Optional[str] = None,
    **kwargs: Any,
) -> Union[Callable[[Callable[..., Any]], Callable[..., Any]], Callable[..., Any]]:
    """Legacy async-specific trace decorator (deprecated).

    Note:
        This decorator is maintained for backwards compatibility.
        Use the unified :func:`trace` decorator instead, which auto-detects
        sync/async functions.

    Args:
        event_type: Type of event being traced (e.g., "model", "tool", "chain")
        event_name: Name of the event (defaults to function name)
        **kwargs: Additional tracing parameters (source, project, session_id, etc.)

    Returns:
        Decorated async function with tracing capabilities

    See Also:
        :func:`trace`: Unified decorator that handles both sync and async functions
    """

    def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
        params = _create_tracing_params(
            event_type=event_type, event_name=event_name, **kwargs
        )
        return _create_wrapper(func, params, is_async=True, **kwargs)

    # Handle both @atrace and @atrace() usage patterns
    if event_type is not None and callable(event_type):
        # Used as @atrace (without parentheses)
        func = event_type
        params = _create_tracing_params(event_type="tool")
        return _create_wrapper(func, params, is_async=True)

    # Used as @atrace(...) (with parentheses)
    return decorator

trace

trace(
    event_type: Optional[str] = None,
    event_name: Optional[str] = None,
    **kwargs: Any
) -> Union[
    Callable[[Callable[..., T]], Callable[..., T]],
    Callable[..., T],
]

Unified trace decorator that auto-detects sync/async functions.

Automatically detects whether the decorated function is synchronous or asynchronous and applies the appropriate wrapper. This decorator can be used on both sync and async functions without needing separate decorators.

Parameters:

Name Type Description Default
event_type Optional[str]

Type of event being traced (e.g., "model", "tool", "chain")

None
event_name Optional[str]

Name of the event (defaults to function name)

None
**kwargs Any

Additional tracing parameters (source, project, session_id, etc.)

{}

Returns:

Type Description
Union[Callable[[Callable[..., T]], Callable[..., T]], Callable[..., T]]

Decorated function with tracing capabilities

Example

@trace(event_type="model", event_name="gpt_call") ... def sync_function(): ... return "result"

@trace(event_type="model", event_name="async_gpt_call") ... async def async_function(): ... return "async result"

Source code in src/honeyhive/tracer/instrumentation/decorators.py
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
def trace(
    event_type: Optional[str] = None,
    event_name: Optional[str] = None,
    **kwargs: Any,
) -> Union[Callable[[Callable[..., T]], Callable[..., T]], Callable[..., T]]:
    """Unified trace decorator that auto-detects sync/async functions.

    Automatically detects whether the decorated function is synchronous or
    asynchronous and applies the appropriate wrapper. This decorator can be
    used on both sync and async functions without needing separate decorators.

    Args:
        event_type: Type of event being traced (e.g., "model", "tool", "chain")
        event_name: Name of the event (defaults to function name)
        **kwargs: Additional tracing parameters (source, project, session_id, etc.)

    Returns:
        Decorated function with tracing capabilities

    Example:
        >>> @trace(event_type="model", event_name="gpt_call")
        ... def sync_function():
        ...     return "result"

        >>> @trace(event_type="model", event_name="async_gpt_call")
        ... async def async_function():
        ...     return "async result"
    """

    def decorator(func: Callable[..., T]) -> Callable[..., T]:
        # Auto-detect if function is async
        is_async = inspect.iscoroutinefunction(func)

        # Filter out tracer argument for _create_tracing_params
        tracing_kwargs = {k: v for k, v in kwargs.items() if k != "tracer"}
        params = _create_tracing_params(
            event_type=event_type, event_name=event_name, **tracing_kwargs
        )
        return _create_wrapper(func, params, is_async=is_async, **kwargs)

    # Handle both @trace and @trace() usage patterns
    if event_type is not None and callable(event_type):
        # Used as @trace (without parentheses)
        func = event_type
        is_async = inspect.iscoroutinefunction(func)
        params = _create_tracing_params(event_type="tool")
        return _create_wrapper(func, params, is_async=is_async)

    # Used as @trace(...) (with parentheses)
    return decorator

trace_class

trace_class(cls: type) -> type

Class decorator to automatically trace all public methods.

Uses dynamic reflection to discover and wrap all public methods of a class. Automatically detects sync/async methods and applies appropriate tracing.

Parameters:

Name Type Description Default
cls type

The class to be decorated

required

Returns:

Type Description
type

The decorated class with all public methods traced

Example

@trace_class ... class MyService: ... def process_data(self, data): ... return data.upper() ... ... async def async_process(self, data): ... return await some_async_operation(data)

Source code in src/honeyhive/tracer/instrumentation/decorators.py
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
def trace_class(cls: type) -> type:
    """Class decorator to automatically trace all public methods.

    Uses dynamic reflection to discover and wrap all public methods of a class.
    Automatically detects sync/async methods and applies appropriate tracing.

    Args:
        cls: The class to be decorated

    Returns:
        The decorated class with all public methods traced

    Example:
        >>> @trace_class
        ... class MyService:
        ...     def process_data(self, data):
        ...         return data.upper()
        ...
        ...     async def async_process(self, data):
        ...         return await some_async_operation(data)
    """
    # Dynamically discover and wrap methods
    for attr_name in dir(cls):
        attr_value = getattr(cls, attr_name)

        # Dynamic method detection
        if (
            callable(attr_value)
            and not attr_name.startswith("_")
            and not isinstance(attr_value, (classmethod, staticmethod))
        ):
            # Determine if method is async
            is_async_method = inspect.iscoroutinefunction(attr_value)

            # Create tracing params for method
            params = _create_tracing_params(
                event_type="tool",
                event_name=f"{cls.__name__}.{attr_name}",
            )

            # Wrap method with appropriate wrapper
            wrapped_method = _create_wrapper(
                attr_value, params, is_async=is_async_method
            )
            setattr(cls, attr_name, wrapped_method)

    return cls

enrich_span_core

enrich_span_core(
    attributes: Optional[Dict[str, Any]] = None,
    metadata: Optional[Dict[str, Any]] = None,
    metrics: Optional[Dict[str, Any]] = None,
    feedback: Optional[Dict[str, Any]] = None,
    inputs: Optional[Dict[str, Any]] = None,
    outputs: Optional[Dict[str, Any]] = None,
    config: Optional[Dict[str, Any]] = None,
    user_properties: Optional[Dict[str, Any]] = None,
    error: Optional[str] = None,
    event_id: Optional[str] = None,
    update_event_id: Optional[str] = None,
    tracer_instance: Optional[Any] = None,
    verbose: bool = False,
    **kwargs: Any
) -> Dict[str, Any]

Core enrichment logic with namespace support and backwards compatibility.

This function implements the unified enrichment architecture that supports multiple invocation patterns while maintaining backwards compatibility with the main branch interface. It routes parameters to proper attribute namespaces and handles arbitrary kwargs.

Backwards Compatibility: Supports the main branch reserved parameter interface (metadata, metrics, feedback, inputs, outputs, config, error, event_id).

New Features: - Simple dict via attributes parameter routes to metadata namespace - Arbitrary kwargs route to metadata namespace for convenience - user_properties routes to honeyhive_user_properties.* namespace

Parameter Precedence: When the same key appears in multiple places, merge/override with this order: 1. Reserved parameters (metadata, metrics, etc.) - Applied first 2. attributes dict - Applied second 3. **kwargs - Applied last (wins conflicts)

:param attributes: Simple dict that routes to metadata namespace :type attributes: Optional[Dict[str, Any]] :param metadata: Metadata namespace (honeyhive_metadata.) :type metadata: Optional[Dict[str, Any]] :param metrics: Metrics namespace (honeyhive_metrics.) :type metrics: Optional[Dict[str, Any]] :param feedback: Feedback namespace (honeyhive_feedback.) :type feedback: Optional[Dict[str, Any]] :param inputs: Inputs namespace (honeyhive_inputs.) :type inputs: Optional[Dict[str, Any]] :param outputs: Outputs namespace (honeyhive_outputs.) :type outputs: Optional[Dict[str, Any]] :param config: Config namespace (honeyhive_config.) :type config: Optional[Dict[str, Any]] :param user_properties: User properties namespace (honeyhive_user_properties.*) :type user_properties: Optional[Dict[str, Any]] :param error: Error string (honeyhive_error, non-namespaced) :type error: Optional[str] :param event_id: If provided, update an existing event with this ID via PUT /events API instead of enriching the current span :type event_id: Optional[str] :param update_event_id: Event ID to override the default event ID on the span (stored as honeyhive_event_id span attribute) :type update_event_id: Optional[str] :param tracer_instance: Optional tracer instance for logging :type tracer_instance: Optional[Any] :param verbose: Whether to log debug information :type verbose: bool :param kwargs: Arbitrary kwargs that route to metadata namespace :type kwargs: Any :return: Enrichment result with success status and span reference :rtype: Dict[str, Any]

Example:

.. code-block:: python

# Main branch backwards compatible usage
result = enrich_span_core(
    metadata={"user_id": "123"},
    metrics={"score": 0.95}
)

# New simplified usage
result = enrich_span_core(
    user_id="123",  # Routes to metadata
    feature="chat"  # Routes to metadata
)

# User properties usage
result = enrich_span_core(
    user_properties={"user_id": "user-123", "plan": "premium"},
    metrics={"score": 0.95}
)

Note:

This function is thread-safe and uses OpenTelemetry's context propagation to access the current span automatically.

Source code in src/honeyhive/tracer/instrumentation/enrichment.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
def enrich_span_core(  # pylint: disable=too-many-locals,too-many-statements
    attributes: Optional[Dict[str, Any]] = None,
    metadata: Optional[Dict[str, Any]] = None,
    metrics: Optional[Dict[str, Any]] = None,
    feedback: Optional[Dict[str, Any]] = None,
    inputs: Optional[Dict[str, Any]] = None,
    outputs: Optional[Dict[str, Any]] = None,
    config: Optional[Dict[str, Any]] = None,
    user_properties: Optional[Dict[str, Any]] = None,
    error: Optional[str] = None,
    event_id: Optional[str] = None,
    update_event_id: Optional[str] = None,
    tracer_instance: Optional[Any] = None,
    verbose: bool = False,
    **kwargs: Any,
) -> Dict[str, Any]:
    """Core enrichment logic with namespace support and backwards compatibility.

    This function implements the unified enrichment architecture that supports
    multiple invocation patterns while maintaining backwards compatibility with
    the main branch interface. It routes parameters to proper attribute
    namespaces and handles arbitrary kwargs.

    **Backwards Compatibility:**
    Supports the main branch reserved parameter interface (metadata, metrics,
    feedback, inputs, outputs, config, error, event_id).

    **New Features:**
    - Simple dict via attributes parameter routes to metadata namespace
    - Arbitrary kwargs route to metadata namespace for convenience
    - user_properties routes to honeyhive_user_properties.* namespace

    **Parameter Precedence:**
    When the same key appears in multiple places, merge/override with this order:
    1. Reserved parameters (metadata, metrics, etc.) - Applied first
    2. attributes dict - Applied second
    3. **kwargs - Applied last (wins conflicts)

    :param attributes: Simple dict that routes to metadata namespace
    :type attributes: Optional[Dict[str, Any]]
    :param metadata: Metadata namespace (honeyhive_metadata.*)
    :type metadata: Optional[Dict[str, Any]]
    :param metrics: Metrics namespace (honeyhive_metrics.*)
    :type metrics: Optional[Dict[str, Any]]
    :param feedback: Feedback namespace (honeyhive_feedback.*)
    :type feedback: Optional[Dict[str, Any]]
    :param inputs: Inputs namespace (honeyhive_inputs.*)
    :type inputs: Optional[Dict[str, Any]]
    :param outputs: Outputs namespace (honeyhive_outputs.*)
    :type outputs: Optional[Dict[str, Any]]
    :param config: Config namespace (honeyhive_config.*)
    :type config: Optional[Dict[str, Any]]
    :param user_properties: User properties namespace (honeyhive_user_properties.*)
    :type user_properties: Optional[Dict[str, Any]]
    :param error: Error string (honeyhive_error, non-namespaced)
    :type error: Optional[str]
    :param event_id: If provided, update an existing event with this ID
        via PUT /events API instead of enriching the current span
    :type event_id: Optional[str]
    :param update_event_id: Event ID to override the default event ID on the span
        (stored as honeyhive_event_id span attribute)
    :type update_event_id: Optional[str]
    :param tracer_instance: Optional tracer instance for logging
    :type tracer_instance: Optional[Any]
    :param verbose: Whether to log debug information
    :type verbose: bool
    :param kwargs: Arbitrary kwargs that route to metadata namespace
    :type kwargs: Any
    :return: Enrichment result with success status and span reference
    :rtype: Dict[str, Any]

    **Example:**

    .. code-block:: python

        # Main branch backwards compatible usage
        result = enrich_span_core(
            metadata={"user_id": "123"},
            metrics={"score": 0.95}
        )

        # New simplified usage
        result = enrich_span_core(
            user_id="123",  # Routes to metadata
            feature="chat"  # Routes to metadata
        )

        # User properties usage
        result = enrich_span_core(
            user_properties={"user_id": "user-123", "plan": "premium"},
            metrics={"score": 0.95}
        )

    **Note:**

    This function is thread-safe and uses OpenTelemetry's context
    propagation to access the current span automatically.
    """
    try:
        # If event_id is provided, update an existing event via PUT /events API
        # This allows users to enrich a specific existing event by ID
        if event_id:
            return _enrich_existing_event_via_api(
                event_id=event_id,
                metadata=metadata,
                metrics=metrics,
                feedback=feedback,
                inputs=inputs,
                outputs=outputs,
                config=config,
                user_properties=user_properties,
                error=error,
                attributes=attributes,
                tracer_instance=tracer_instance,
                **kwargs,
            )

        # Get current span from OpenTelemetry context
        current_span = trace.get_current_span()

        if not current_span or not hasattr(current_span, "set_attribute"):
            safe_log(
                tracer_instance,
                "debug",
                "No active span found or span doesn't support attributes",
            )
            return {"success": False, "span": NoOpSpan(), "error": "No active span"}

        attribute_count: int = 0

        # STEP 1: Apply reserved namespaces first (highest priority)
        # These use _set_span_attributes for recursive dict/list handling
        if metadata:
            _set_span_attributes(current_span, "honeyhive_metadata", metadata)
            attribute_count += len(metadata)

        if metrics:
            _set_span_attributes(current_span, "honeyhive_metrics", metrics)
            attribute_count += len(metrics)

        if feedback:
            _set_span_attributes(current_span, "honeyhive_feedback", feedback)
            attribute_count += len(feedback)

        if inputs:
            safe_log(
                tracer_instance,
                "debug",
                f"Setting inputs on span: {getattr(current_span, 'name', 'unknown')}",
                honeyhive_data={
                    "span_name": getattr(current_span, "name", "unknown"),
                    "inputs": inputs,
                    "span_is_recording": (
                        current_span.is_recording()
                        if hasattr(current_span, "is_recording")
                        else None
                    ),
                },
            )
            _set_span_attributes(current_span, "honeyhive_inputs", inputs)
            attribute_count += len(inputs)
            # Verify attributes were set
            if verbose and hasattr(current_span, "attributes"):
                span_attrs = getattr(current_span, "attributes", {})
                input_attrs = {
                    k: v
                    for k, v in span_attrs.items()
                    if k.startswith("honeyhive_inputs")
                }
                safe_log(
                    tracer_instance,
                    "debug",
                    f"Inputs attributes after setting: {list(input_attrs.keys())}",
                    honeyhive_data={"input_attrs": input_attrs},
                )

        if outputs:
            _set_span_attributes(current_span, "honeyhive_outputs", outputs)
            attribute_count += len(outputs)

        if config:
            _set_span_attributes(current_span, "honeyhive_config", config)
            attribute_count += len(config)

        if user_properties:
            _set_span_attributes(
                current_span, "honeyhive_user_properties", user_properties
            )
            attribute_count += len(user_properties)

        # STEP 2: Apply simple attributes dict → metadata (overwrites conflicts)
        if attributes:
            _set_span_attributes(current_span, "honeyhive_metadata", attributes)
            attribute_count += len(attributes)

        # STEP 3: Apply arbitrary kwargs → metadata (lowest priority, wins conflicts)
        # But exclude reserved parameter names from kwargs
        # Also extract reserved parameters from kwargs if not passed explicitly
        reserved_params = {
            "metadata",
            "metrics",
            "feedback",
            "inputs",
            "outputs",
            "config",
            "user_properties",
            "error",
            "event_id",
            "update_event_id",
            "tracer_instance",
            "verbose",
        }

        # Extract reserved parameters from kwargs if present and not already handled
        # This handles cases where they're passed as kwargs (e.g., from instance method)
        if not metrics and "metrics" in kwargs:
            metrics_from_kwargs = kwargs.pop("metrics")
            if metrics_from_kwargs:
                _set_span_attributes(
                    current_span, "honeyhive_metrics", metrics_from_kwargs
                )
                attribute_count += len(metrics_from_kwargs)

        if not user_properties and "user_properties" in kwargs:
            user_properties_from_kwargs = kwargs.pop("user_properties")
            if user_properties_from_kwargs:
                _set_span_attributes(
                    current_span,
                    "honeyhive_user_properties",
                    user_properties_from_kwargs,
                )
                attribute_count += len(user_properties_from_kwargs)

        if not feedback and "feedback" in kwargs:
            feedback_from_kwargs = kwargs.pop("feedback")
            if feedback_from_kwargs:
                _set_span_attributes(
                    current_span, "honeyhive_feedback", feedback_from_kwargs
                )
                attribute_count += len(feedback_from_kwargs)

        if not inputs and "inputs" in kwargs:
            inputs_from_kwargs = kwargs.pop("inputs")
            if inputs_from_kwargs:
                _set_span_attributes(
                    current_span, "honeyhive_inputs", inputs_from_kwargs
                )
                attribute_count += len(inputs_from_kwargs)

        if not outputs and "outputs" in kwargs:
            outputs_from_kwargs = kwargs.pop("outputs")
            if outputs_from_kwargs:
                _set_span_attributes(
                    current_span, "honeyhive_outputs", outputs_from_kwargs
                )
                attribute_count += len(outputs_from_kwargs)

        if not config and "config" in kwargs:
            config_from_kwargs = kwargs.pop("config")
            if config_from_kwargs:
                _set_span_attributes(
                    current_span, "honeyhive_config", config_from_kwargs
                )
                attribute_count += len(config_from_kwargs)

        kwargs_filtered = {k: v for k, v in kwargs.items() if k not in reserved_params}
        if kwargs_filtered:
            _set_span_attributes(current_span, "honeyhive_metadata", kwargs_filtered)
            attribute_count += len(kwargs_filtered)

        # Handle special non-namespaced attributes
        if error:
            current_span.set_attribute("honeyhive_error", error)
            attribute_count += 1

        # update_event_id allows overriding the default event ID on the span
        if update_event_id:
            current_span.set_attribute("honeyhive_event_id", update_event_id)
            attribute_count += 1

        # Log success if verbose mode is enabled
        if verbose:
            safe_log(
                tracer_instance,
                "debug",
                "Span enriched with attributes",
                honeyhive_data={
                    "attribute_count": attribute_count,
                    "span_name": getattr(current_span, "name", "unknown"),
                },
            )

        return {
            "success": True,
            "span": current_span,
            "attribute_count": attribute_count,
        }

    except Exception as e:
        safe_log(
            tracer_instance,
            "error",
            f"Failed to enrich span: {e}",
            honeyhive_data={"error_type": type(e).__name__, "caller": "enrich_span"},
            exc_info=True,
        )
        return {"success": False, "span": NoOpSpan(), "error": str(e)}

enrich_span_unified

enrich_span_unified(
    attributes: Optional[Dict[str, Any]] = None,
    metadata: Optional[Dict[str, Any]] = None,
    metrics: Optional[Dict[str, Any]] = None,
    feedback: Optional[Dict[str, Any]] = None,
    inputs: Optional[Dict[str, Any]] = None,
    outputs: Optional[Dict[str, Any]] = None,
    config: Optional[Dict[str, Any]] = None,
    error: Optional[str] = None,
    event_id: Optional[str] = None,
    tracer_instance: Optional[Any] = None,
    caller: str = "direct_call",
    **kwargs: Any
) -> Union[bool, _GeneratorContextManager[Any, None, None]]

Unified enrich_span implementation with backwards compatibility.

This function implements the unified enrichment architecture with a simple caller parameter approach. Each caller explicitly identifies itself, making the behavior predictable and following dynamic logic standards.

Backwards Compatibility: Supports all main branch reserved parameters (metadata, metrics, etc.)

Tracer Discovery: If no tracer_instance is provided, automatically discovers tracer using: 1. Baggage-discovered tracer (context-aware) 2. Global default tracer (fallback)

:param attributes: Simple dict that routes to metadata namespace :type attributes: Optional[Dict[str, Any]] :param metadata: Metadata namespace :type metadata: Optional[Dict[str, Any]] :param metrics: Metrics namespace :type metrics: Optional[Dict[str, Any]] :param feedback: Feedback namespace :type feedback: Optional[Dict[str, Any]] :param inputs: Inputs namespace :type inputs: Optional[Dict[str, Any]] :param outputs: Outputs namespace :type outputs: Optional[Dict[str, Any]] :param config: Config namespace :type config: Optional[Dict[str, Any]] :param error: Error string :type error: Optional[str] :param event_id: Event ID :type event_id: Optional[str] :param tracer_instance: Optional tracer instance for context :type tracer_instance: Optional[Any] :param caller: Caller identification ('context_manager' or 'direct_call') :type caller: str :param kwargs: Arbitrary kwargs routing to metadata :type kwargs: Any :return: Context manager (Iterator) or boolean based on caller :rtype: Union[bool, Iterator[Any]]

Usage Patterns:

.. code-block:: python

# Context manager pattern - returns Iterator[Any]
enrich_span_unified(attrs, tracer, caller="context_manager")

# Direct call pattern - returns bool
enrich_span_unified(attrs, tracer, caller="direct_call")
Source code in src/honeyhive/tracer/instrumentation/enrichment.py
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
def enrich_span_unified(
    attributes: Optional[Dict[str, Any]] = None,
    metadata: Optional[Dict[str, Any]] = None,
    metrics: Optional[Dict[str, Any]] = None,
    feedback: Optional[Dict[str, Any]] = None,
    inputs: Optional[Dict[str, Any]] = None,
    outputs: Optional[Dict[str, Any]] = None,
    config: Optional[Dict[str, Any]] = None,
    error: Optional[str] = None,
    event_id: Optional[str] = None,
    tracer_instance: Optional[Any] = None,
    caller: str = "direct_call",
    **kwargs: Any,
) -> Union[bool, _GeneratorContextManager[Any, None, None]]:  # type: ignore[type-arg]
    """Unified enrich_span implementation with backwards compatibility.

    This function implements the unified enrichment architecture with a simple
    caller parameter approach. Each caller explicitly identifies itself, making
    the behavior predictable and following dynamic logic standards.

    **Backwards Compatibility:**
    Supports all main branch reserved parameters (metadata, metrics, etc.)

    **Tracer Discovery:**
    If no tracer_instance is provided, automatically discovers tracer using:
    1. Baggage-discovered tracer (context-aware)
    2. Global default tracer (fallback)

    :param attributes: Simple dict that routes to metadata namespace
    :type attributes: Optional[Dict[str, Any]]
    :param metadata: Metadata namespace
    :type metadata: Optional[Dict[str, Any]]
    :param metrics: Metrics namespace
    :type metrics: Optional[Dict[str, Any]]
    :param feedback: Feedback namespace
    :type feedback: Optional[Dict[str, Any]]
    :param inputs: Inputs namespace
    :type inputs: Optional[Dict[str, Any]]
    :param outputs: Outputs namespace
    :type outputs: Optional[Dict[str, Any]]
    :param config: Config namespace
    :type config: Optional[Dict[str, Any]]
    :param error: Error string
    :type error: Optional[str]
    :param event_id: Event ID
    :type event_id: Optional[str]
    :param tracer_instance: Optional tracer instance for context
    :type tracer_instance: Optional[Any]
    :param caller: Caller identification ('context_manager' or 'direct_call')
    :type caller: str
    :param kwargs: Arbitrary kwargs routing to metadata
    :type kwargs: Any
    :return: Context manager (Iterator) or boolean based on caller
    :rtype: Union[bool, Iterator[Any]]

    **Usage Patterns:**

    .. code-block:: python

        # Context manager pattern - returns Iterator[Any]
        enrich_span_unified(attrs, tracer, caller="context_manager")

        # Direct call pattern - returns bool
        enrich_span_unified(attrs, tracer, caller="direct_call")
    """
    # Discover tracer if not provided (same pattern as trace decorator)
    if tracer_instance is None:
        try:
            current_ctx = context.get_current()
            tracer_instance = discover_tracer(explicit_tracer=None, ctx=current_ctx)
        except Exception as e:
            # Graceful degradation - log but continue
            safe_log(
                None,
                "debug",
                f"Failed to discover tracer: {e}",
                honeyhive_data={"error_type": type(e).__name__},
            )

    safe_log(
        tracer_instance,
        "debug",
        f"Enriching span via {caller}",
        honeyhive_data={"caller": caller, "has_attributes": bool(attributes)},
    )

    if caller == "context_manager":
        # Return context manager for 'with' statement usage
        return _enrich_span_context_manager(
            attributes=attributes,
            metadata=metadata,
            metrics=metrics,
            feedback=feedback,
            inputs=inputs,
            outputs=outputs,
            config=config,
            error=error,
            event_id=event_id,
            tracer_instance=tracer_instance,
            **kwargs,
        )
    # Return boolean for direct call and other patterns
    return _enrich_span_direct_call(
        attributes=attributes,
        metadata=metadata,
        metrics=metrics,
        feedback=feedback,
        inputs=inputs,
        outputs=outputs,
        config=config,
        error=error,
        event_id=event_id,
        tracer_instance=tracer_instance,
        **kwargs,
    )

initialize_tracer_instance

initialize_tracer_instance(
    tracer_instance: HoneyHiveTracerBase,
) -> None

Initialize a HoneyHiveTracer instance with full setup.

This function handles the complete initialization process for a tracer instance, including OpenTelemetry setup, session creation, and provider configuration. It's called by the HoneyHiveTracer.init() class method.

:param tracer_instance: The tracer instance to initialize :type tracer_instance: HoneyHiveTracer :note: Uses graceful degradation - never crashes host application :note: Missing configuration triggers degraded mode with warnings :note: API failures result in no-op mode with local fallback

Example:

.. code-block:: python

tracer = HoneyHiveTracer(api_key="key", project="project")
initialize_tracer_instance(tracer)
# Tracer is now fully initialized and ready to use

Note:

This function modifies the tracer instance in-place and should only be called once per tracer instance during initialization.

Source code in src/honeyhive/tracer/instrumentation/initialization.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def initialize_tracer_instance(tracer_instance: "HoneyHiveTracerBase") -> None:
    """Initialize a HoneyHiveTracer instance with full setup.

    This function handles the complete initialization process for a tracer
    instance, including OpenTelemetry setup, session creation, and provider
    configuration. It's called by the HoneyHiveTracer.init() class method.

    :param tracer_instance: The tracer instance to initialize
    :type tracer_instance: HoneyHiveTracer
    :note: Uses graceful degradation - never crashes host application
    :note: Missing configuration triggers degraded mode with warnings
    :note: API failures result in no-op mode with local fallback

    **Example:**

    .. code-block:: python

        tracer = HoneyHiveTracer(api_key="key", project="project")
        initialize_tracer_instance(tracer)
        # Tracer is now fully initialized and ready to use

    **Note:**

    This function modifies the tracer instance in-place and should only
    be called once per tracer instance during initialization.
    """
    # Multi-instance logging architecture uses safe_log utility
    # No need to attach logger directly to tracer instance

    # Enable debug logging if verbose mode is requested
    if getattr(tracer_instance, "verbose", False):
        # Verbose logging is handled by the tracer's logger.update_verbose_setting()
        # in the tracer initialization - no need for direct logging module calls here
        safe_log(
            tracer_instance,
            "debug",
            "Verbose logging enabled for HoneyHive tracer initialization",
        )

    safe_log(
        tracer_instance,
        "debug",
        "Starting tracer initialization",
        honeyhive_data={
            "project": tracer_instance.project_name,
            "source": tracer_instance.source_environment,
            "test_mode": tracer_instance.test_mode,
        },
    )

    # Configuration already loaded and validated during tracer init

    # Step 2: Initialize OpenTelemetry components
    _initialize_otel_components(tracer_instance)

    # Step 3: Initialize session management
    _initialize_session_management(tracer_instance)

    # Step 4: Register tracer for auto-discovery (assigns _tracer_id)
    _register_tracer_instance(tracer_instance)

    # Step 5: Setup baggage context (after registration so _tracer_id is available)
    _setup_baggage_context(tracer_instance)

    # Mark as initialized
    tracer_instance._initialized = True

    safe_log(
        tracer_instance,
        "info",
        "Tracer initialization completed successfully",
        honeyhive_data={
            "project": tracer_instance.project_name,
            "session_id": tracer_instance.session_id,
            "is_main_provider": tracer_instance.is_main_provider,
        },
    )

    # Clean up the temporary initialization logger
    # The tracer has its own logger (tracer_instance.logger) for runtime use
    if hasattr(tracer_instance, "logger"):
        delattr(tracer_instance, "logger")