Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Truera Trulens Instrument Decorator

From Leeroopedia
Knowledge Sources
Domains Observability, Tracing
Last Updated 2026-02-14 08:00 GMT

Overview

Concrete tool for decorating Python methods with OpenTelemetry span creation for tracing and evaluation, provided by the trulens-core library.

Description

The instrument class is a Python decorator that wraps functions to create OTEL spans when called within a recording context. It supports synchronous functions, async coroutines, sync generators, and async generators via the wrapt library. The decorator captures function arguments, return values, and custom attributes as span data.

The companion function instrument_method provides programmatic instrumentation for methods that cannot be decorated at definition time.

Usage

Import and apply @instrument() to methods of custom application classes that you want to trace. Set the span_type parameter to categorize the operation type. Use with TruApp wrapper for recording.

Code Reference

Source Location

  • Repository: trulens
  • File: src/core/trulens/core/otel/instrument.py
  • Lines: L198-451

Signature

class instrument:
    enabled: bool = True

    def __init__(
        self,
        *,
        name: Optional[str] = None,
        span_type: SpanAttributes.SpanType = SpanAttributes.SpanType.UNKNOWN,
        attributes: Attributes = None,
        **kwargs,
    ) -> None:
        """
        Decorator for marking functions to be instrumented with OTEL tracing.

        Args:
            name: Optional custom span name. If not provided, derives from
                function's __module__.__qualname__.
            span_type: Span type for the span (UNKNOWN, RETRIEVAL, GENERATION,
                TOOL, AGENT). Cannot be set to RECORD_ROOT explicitly.
            attributes: Dict or callable returning dict of custom span attributes.
        """

    def __call__(self, func: Callable) -> Callable:
        """Wrap the function with tracing logic."""

# Companion function:
def instrument_method(
    cls: type,
    method_name: str,
    span_type: SpanAttributes.SpanType = SpanAttributes.SpanType.UNKNOWN,
    attributes: Attributes = None,
    must_be_first_wrapper: bool = False,
) -> None:
    """Programmatically instrument a method on a class."""

Import

from trulens.core.otel.instrument import instrument, instrument_method
# Or via convenience import:
from trulens.core import instrument

I/O Contract

Inputs

Name Type Required Description
name str No Custom span name (defaults to module.qualname)
span_type SpanAttributes.SpanType No Span type: UNKNOWN, RETRIEVAL, GENERATION, TOOL, AGENT (default: UNKNOWN)
attributes Dict or Callable No Custom attributes to set on the span

Outputs

Name Type Description
return Callable Wrapped function that creates OTEL spans when called within recording context

Usage Examples

Basic Instrumentation

from trulens.core.otel.instrument import instrument
from trulens.otel.semconv.trace import SpanAttributes

class MyRAG:
    @instrument(span_type=SpanAttributes.SpanType.RETRIEVAL)
    def retrieve(self, query: str) -> list:
        return self.vector_store.query(query)

    @instrument(span_type=SpanAttributes.SpanType.GENERATION)
    def generate(self, context: str, query: str) -> str:
        return self.llm.invoke(f"Context: {context}\nQuestion: {query}")

    @instrument()
    def respond(self, query: str) -> str:
        contexts = self.retrieve(query)
        return self.generate("\n".join(contexts), query)

Custom Attributes

@instrument(
    span_type=SpanAttributes.SpanType.RETRIEVAL,
    attributes={"retrieval.source": "pinecone", "retrieval.top_k": 5}
)
def retrieve(self, query: str) -> list:
    return self.index.query(query, top_k=5)

Programmatic Instrumentation

from trulens.core.otel.instrument import instrument_method
from trulens.otel.semconv.trace import SpanAttributes

# Instrument an existing class method without decorators
instrument_method(
    MyApp,
    "retrieve_chunks",
    span_type=SpanAttributes.SpanType.RETRIEVAL
)

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment