Class: Phronomy::Tracing::OpenTelemetryTracer

Inherits:
Base
  • Object
show all
Defined in:
lib/phronomy/tracing/open_telemetry_tracer.rb

Overview

OpenTelemetry tracer adapter.

Requires the +opentelemetry-api+ gem (or +opentelemetry-sdk+ for testing). The caller is responsible for configuring the OpenTelemetry SDK before using this tracer — phronomy does not configure an exporter or propagator.

Examples:

Configure globally

require "opentelemetry-sdk"
OpenTelemetry::SDK.configure { |c| c.use_all }

Phronomy.configure do |c|
  c.tracer = Phronomy::Tracing::OpenTelemetryTracer.new
end

Instance Method Summary collapse

Methods inherited from Base

#trace

Constructor Details

#initialize(tracer_name: "phronomy") ⇒ OpenTelemetryTracer

Returns a new instance of OpenTelemetryTracer.

Parameters:

  • tracer_name (String) (defaults to: "phronomy")

    name passed to the OTel TracerProvider



20
21
22
23
# File 'lib/phronomy/tracing/open_telemetry_tracer.rb', line 20

def initialize(tracer_name: "phronomy")
  require "opentelemetry"
  @otel_tracer = OpenTelemetry.tracer_provider.tracer(tracer_name, Phronomy::VERSION)
end

Instance Method Details

#finish_span(span, output: nil, usage: nil, error: nil) ⇒ Object

Finishes the OTel span, recording output, token usage, or error.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/phronomy/tracing/open_telemetry_tracer.rb', line 38

def finish_span(span, output: nil, usage: nil, error: nil)
  if error
    span.record_exception(error)
    span.status = OpenTelemetry::Trace::Status.error(error.message)
  else
    span.set_attribute("phronomy.output", output.to_s) if output
    if usage
      span.set_attribute("llm.usage.input_tokens", usage.input)
      span.set_attribute("llm.usage.output_tokens", usage.output)
      total = (usage.input || 0) + (usage.output || 0)
      span.set_attribute("llm.usage.total_tokens", total)
    end
  end
  span.finish
end

#start_span(name, input: nil, **attributes) ⇒ OpenTelemetry::Trace::Span

Starts an OTel span. Input and extra metadata are stored as span attributes prefixed with +phronomy.+.

Returns:

  • (OpenTelemetry::Trace::Span)


30
31
32
33
34
35
# File 'lib/phronomy/tracing/open_telemetry_tracer.rb', line 30

def start_span(name, input: nil, **attributes)
  attrs = {}
  attrs["phronomy.input"] = input.to_s if input
  attributes.each { |k, v| attrs["phronomy.#{k}"] = v.to_s }
  @otel_tracer.start_span(name, attributes: attrs)
end