Class: Phronomy::Tracing::LangfuseTracer

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

Overview

Langfuse tracer adapter.

Sends spans to Langfuse via the batch ingestion REST API (+POST /api/public/ingestion+). No external gem is required — only Ruby standard-library network primitives are used.

Ingestion errors are silently swallowed so that a Langfuse outage never breaks the application.

Examples:

Configure globally

Phronomy.configure do |c|
  c.tracer = Phronomy::Tracing::LangfuseTracer.new(
    public_key: ENV.fetch("LANGFUSE_PUBLIC_KEY"),
    secret_key: ENV.fetch("LANGFUSE_SECRET_KEY"),
    host:       ENV.fetch("LANGFUSE_HOST", "https://cloud.langfuse.com")
  )
end

Constant Summary collapse

DEFAULT_HOST =

Default Langfuse cloud host.

"https://cloud.langfuse.com"

Instance Method Summary collapse

Methods inherited from Base

#trace

Constructor Details

#initialize(public_key:, secret_key:, host: DEFAULT_HOST) ⇒ LangfuseTracer

Returns a new instance of LangfuseTracer.

Parameters:

  • public_key (String)

    Langfuse project public key

  • secret_key (String)

    Langfuse project secret key

  • host (String) (defaults to: DEFAULT_HOST)

    Langfuse host URL (override for self-hosted instances)



34
35
36
37
38
# File 'lib/phronomy/tracing/langfuse_tracer.rb', line 34

def initialize(public_key:, secret_key:, host: DEFAULT_HOST)
  @public_key = public_key
  @secret_key = secret_key
  @host = host.chomp("/")
end

Instance Method Details

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

Serialises the span and fires it to Langfuse via the ingestion API.



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/phronomy/tracing/langfuse_tracer.rb', line 55

def finish_span(span, output: nil, usage: nil, error: nil)
  body = {
    id: span[:id],
    traceId: span[:trace_id],
    name: span[:name],
    startTime: span[:start_time].utc.iso8601(3),
    endTime: Time.now.utc.iso8601(3),
    input: span[:input],
    output: error ? nil : output,
    metadata: span[:meta]
  }
  body[:level] = "ERROR" if error
  body[:statusMessage] = error.message if error
  if usage
    body[:usage] = {
      input: usage.input,
      output: usage.output,
      total: (usage.input || 0) + (usage.output || 0)
    }
  end
  ingest([{type: "span-create", body: body}])
end

#start_span(name, input: nil, **meta) ⇒ Hash

Returns a plain Hash that records the span start state.

Returns:



43
44
45
46
47
48
49
50
51
52
# File 'lib/phronomy/tracing/langfuse_tracer.rb', line 43

def start_span(name, input: nil, **meta)
  {
    id: SecureRandom.uuid,
    trace_id: SecureRandom.uuid,
    name: name,
    input: input,
    start_time: Time.now,
    meta: meta
  }
end