콘텐츠로 이동

spakky-opentelemetry

spakky-opentelemetry는 Spakky TraceContext propagation과 privacy-safe Agent telemetry를 OpenTelemetry SDK에 연결합니다.

플러그인 initialize 단계에서 OpenTelemetryAgentTelemetry를 Pod로 등록하고 IAgentTelemetry에 bind합니다. Injected AgentRunnerFactory가 이 binding을 사용하며, export 여부와 endpoint/sample rate는 기존 OpenTelemetryConfig가 소유합니다.

Agent bridge는 core AgentSpanRecord의 exact nanosecond interval, scalar attributes, OK/ERROR status를 OTel span으로 옮깁니다. Ambient Spakky TraceContext가 있으면 그 trace/span을 parent로 보존합니다. Prompt/context/system instructions/completion, retrieval query/content, tool arguments/results key는 exporter 전에 제거하고 gen_ai.operation.name과 optional error.type은 adapter가 결정합니다.

사용 흐름은 OpenTelemetry 통합, core pricing/telemetry와의 결합은 Agent Memory, Evaluation, Cost와 Telemetry를 확인하세요.

브릿지

LogContextBridge — optional trace-to-logging context synchronization.

LogContextBridge(binder=None)

Synchronizes TraceContext fields into LogContext.

When an ILogContextBinder is available (i.e., spakky-logging is installed and registered), sync() binds the current trace_id and span_id into the structured logging context. When no binder is available, all operations are no-ops.

Source code in plugins/spakky-opentelemetry/src/spakky/plugins/opentelemetry/bridge.py
def __init__(self, binder: ILogContextBinder | None = None) -> None:
    self.__binder = binder

sync()

Bind current TraceContext's trace_id/span_id into LogContext.

If no ILogContextBinder was injected, this is a no-op. If no TraceContext is active, unbinds trace fields.

Source code in plugins/spakky-opentelemetry/src/spakky/plugins/opentelemetry/bridge.py
def sync(self) -> None:
    """Bind current TraceContext's trace_id/span_id into LogContext.

    If no ``ILogContextBinder`` was injected, this is a no-op.
    If no TraceContext is active, unbinds trace fields.
    """
    if self.__binder is None:
        return
    ctx = TraceContext.get()
    if ctx is not None:
        self.__binder.bind(trace_id=ctx.trace_id, span_id=ctx.span_id)
    else:
        self.__binder.unbind("trace_id", "span_id")

Propagator

OTelTracePropagator — OpenTelemetry SDK bridge for ITracePropagator.

OTelContextConverter

Convert Spakky trace state into an explicit OpenTelemetry parent context.

to_otel_context(trace_context) classmethod

Build an OTel context containing a non-recording parent span.

Source code in plugins/spakky-opentelemetry/src/spakky/plugins/opentelemetry/propagator.py
@classmethod
def to_otel_context(cls, trace_context: TraceContext) -> context.Context:
    """Build an OTel context containing a non-recording parent span."""
    span_context = SpanContext(
        trace_id=int(trace_context.trace_id, cls._HEX_BASE),
        span_id=int(trace_context.span_id, cls._HEX_BASE),
        is_remote=False,
        trace_flags=TraceFlags(trace_context.trace_flags),
        trace_state=TraceState(),
    )
    return trace.set_span_in_context(NonRecordingSpan(span_context))

OTelTracePropagator()

Bases: ITracePropagator

Bridges Spakky's TraceContext with OpenTelemetry's context propagation.

Converts between Spakky's contextvars-based TraceContext and OTel's Context system using NonRecordingSpan for lightweight propagation.

Source code in plugins/spakky-opentelemetry/src/spakky/plugins/opentelemetry/propagator.py
def __init__(self) -> None:
    self._propagator = TraceContextTextMapPropagator()

inject(carrier)

Read the ambient TraceContext and write it into the carrier.

Converts Spakky's TraceContext to an OTel Context, then delegates to the W3C TraceContext propagator for header serialization.

Parameters:

Name Type Description Default
carrier dict[str, str]

Mutable header dictionary.

required
Source code in plugins/spakky-opentelemetry/src/spakky/plugins/opentelemetry/propagator.py
@override
def inject(self, carrier: dict[str, str]) -> None:
    """Read the ambient TraceContext and write it into the carrier.

    Converts Spakky's TraceContext to an OTel Context, then delegates
    to the W3C TraceContext propagator for header serialization.

    Args:
        carrier: Mutable header dictionary.
    """
    ctx = TraceContext.get()
    if ctx is None:
        return
    otel_ctx = OTelContextConverter.to_otel_context(ctx)
    self._propagator.inject(carrier, context=otel_ctx)

extract(carrier)

Reconstruct a TraceContext from the carrier.

Delegates to the OTel propagator for header parsing, then converts the resulting OTel SpanContext back to Spakky's TraceContext.

Parameters:

Name Type Description Default
carrier dict[str, str]

Read-only header dictionary.

required

Returns:

Type Description
TraceContext | None

The restored TraceContext, or None if headers are missing/invalid.

Source code in plugins/spakky-opentelemetry/src/spakky/plugins/opentelemetry/propagator.py
@override
def extract(self, carrier: dict[str, str]) -> TraceContext | None:
    """Reconstruct a TraceContext from the carrier.

    Delegates to the OTel propagator for header parsing, then converts
    the resulting OTel SpanContext back to Spakky's TraceContext.

    Args:
        carrier: Read-only header dictionary.

    Returns:
        The restored TraceContext, or None if headers are missing/invalid.
    """
    otel_ctx = self._propagator.extract(carrier)
    span = trace.get_current_span(otel_ctx)
    span_context = span.get_span_context()
    if not span_context.is_valid:
        return None
    return TraceContext(
        trace_id=format(span_context.trace_id, "032x"),
        span_id=format(span_context.span_id, "016x"),
        trace_flags=span_context.trace_flags,
    )

fields()

Return the header field names used by this propagator.

Returns:

Type Description
list[str]

List of header names (traceparent, tracestate).

Source code in plugins/spakky-opentelemetry/src/spakky/plugins/opentelemetry/propagator.py
@override
def fields(self) -> list[str]:
    """Return the header field names used by this propagator.

    Returns:
        List of header names (traceparent, tracestate).
    """
    return list(self._propagator.fields)

Agent telemetry

OpenTelemetry sink for completed Agent telemetry records.

OpenTelemetryAgentTelemetry(tracer=None)

Bases: IAgentTelemetry

Record privacy-safe completed Agent operations as OpenTelemetry spans.

Source code in plugins/spakky-opentelemetry/src/spakky/plugins/opentelemetry/telemetry.py
def __init__(self, tracer: Tracer | None = None) -> None:
    self.__tracer = (
        tracer if tracer is not None else trace.get_tracer(self._TRACER_NAME)
    )

record(span)

Create and end one OTel span using the record's exact timestamps.

Source code in plugins/spakky-opentelemetry/src/spakky/plugins/opentelemetry/telemetry.py
@override
def record(self, span: AgentSpanRecord) -> None:
    """Create and end one OTel span using the record's exact timestamps."""
    operation_name, span_kind = self._operation(span.kind)
    attributes = self._attributes(span, operation_name)
    status = self._status(span)
    parent_context = self._parent_context()
    otel_span = self.__tracer.start_span(
        span.name,
        context=parent_context,
        kind=span_kind,
        attributes=attributes,
        start_time=span.started_at_ns,
    )
    try:
        otel_span.set_status(status)
    finally:
        otel_span.end(end_time=span.ended_at_ns)

후처리기

Post-processor that configures OpenTelemetry SDK and replaces W3CTracePropagator.

OTelSetupPostProcessor()

Bases: IPostProcessor, IContainerAware

Initializes OTel TracerProvider and replaces W3CTracePropagator.

On first post_process call, configures the global TracerProvider with the user's chosen exporter. For every pod that is an instance of W3CTracePropagator, returns an OTelTracePropagator instead.

Source code in plugins/spakky-opentelemetry/src/spakky/plugins/opentelemetry/post_processor.py
def __init__(self) -> None:
    super().__init__()
    self.__configured = False

post_process(pod)

Configure TracerProvider on first call; replace W3CTracePropagator.

Parameters:

Name Type Description Default
pod object

The Pod instance being processed.

required

Returns:

Type Description
object

OTelTracePropagator if pod is W3CTracePropagator, else pod unchanged.

Source code in plugins/spakky-opentelemetry/src/spakky/plugins/opentelemetry/post_processor.py
@override
def post_process(self, pod: object) -> object:
    """Configure TracerProvider on first call; replace W3CTracePropagator.

    Args:
        pod: The Pod instance being processed.

    Returns:
        OTelTracePropagator if pod is W3CTracePropagator, else pod unchanged.
    """
    if not self.__configured:
        self.__configured = True
        self._configure_tracer_provider()
    if isinstance(pod, W3CTracePropagator):
        return OTelTracePropagator()
    return pod

설정

OpenTelemetry plugin configuration.

ExporterType

Bases: StrEnum

Supported span exporter types.

OpenTelemetryConfig()

Bases: BaseSettings

Configuration for the OpenTelemetry SDK bridge.

Attributes:

Name Type Description
service_name str

OTel service name for resource identification.

exporter_type ExporterType

Span exporter backend (otlp, console, none).

exporter_endpoint str

OTLP collector endpoint URL.

sample_rate Annotated[float, Field(ge=0.0, le=1.0)]

Trace sampling rate (0.0 to 1.0).

Source code in plugins/spakky-opentelemetry/src/spakky/plugins/opentelemetry/config.py
def __init__(self) -> None:
    super().__init__()

에러

Error classes for the spakky-opentelemetry package.

AbstractSpakkyOpenTelemetryError

Bases: AbstractSpakkyFrameworkError, ABC

Base class for all OpenTelemetry plugin errors.

UnsupportedExporterTypeError

Bases: AbstractSpakkyOpenTelemetryError

Raised when the configured exporter type is not supported.

추가 모듈

Plugin initialization entry point for spakky-opentelemetry.

initialize(app)

Initialize the spakky-opentelemetry plugin.

Registers the OpenTelemetry configuration, the post-processor that sets up TracerProvider and replaces W3CTracePropagator, the LogContextBridge for optional trace-to-logging sync, and the Agent telemetry bridge without replacing either existing integration.

Parameters:

Name Type Description Default
app SpakkyApplication

The SpakkyApplication instance.

required
Source code in plugins/spakky-opentelemetry/src/spakky/plugins/opentelemetry/main.py
def initialize(app: SpakkyApplication) -> None:
    """Initialize the spakky-opentelemetry plugin.

    Registers the OpenTelemetry configuration, the post-processor
    that sets up TracerProvider and replaces W3CTracePropagator,
    the LogContextBridge for optional trace-to-logging sync, and the
    Agent telemetry bridge without replacing either existing integration.

    Args:
        app: The SpakkyApplication instance.
    """
    app.add(OpenTelemetryConfig)
    app.add(OTelSetupPostProcessor)
    app.add(LogContextBridge)
    app.add(OpenTelemetryAgentTelemetry)
    app.container.bind_to_type(IAgentTelemetry, OpenTelemetryAgentTelemetry)