Class: Langfuse::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/langfuse/client.rb

Defined Under Namespace

Classes: StdoutLogDevice

Constant Summary collapse

MAX_BATCH_SIZE_BYTES =

The ingestion API limits batch payloads to 3.5 MB in total

3_500_000
ENVIRONMENT_PATTERN =

Allowed format for the tracing environment field

/\A(?!langfuse)[a-z0-9\-_]{1,40}\z/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(public_key: nil, secret_key: nil, host: nil, debug: false, timeout: 30, retries: 3, flush_interval: nil, auto_flush: nil, ingestion_mode: nil, environment: nil, sample_rate: nil, mask: nil, flush_at: nil, logger: nil, shutdown_on_exit: nil) ⇒ Client

Returns a new instance of Client.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/langfuse/client.rb', line 33

def initialize(public_key: nil, secret_key: nil, host: nil, debug: false, timeout: 30, retries: 3,
               flush_interval: nil, auto_flush: nil, ingestion_mode: nil, environment: nil,
               sample_rate: nil, mask: nil, flush_at: nil, logger: nil, shutdown_on_exit: nil)
  @public_key = config_value(public_key, 'LANGFUSE_PUBLIC_KEY', :public_key)
  @secret_key = config_value(secret_key, 'LANGFUSE_SECRET_KEY', :secret_key)
  @host = host || ENV['LANGFUSE_HOST'] || ENV['LANGFUSE_BASE_URL'] || Langfuse.configuration.host
  @debug = debug || ENV['LANGFUSE_DEBUG'] == 'true' || Langfuse.configuration.debug
  @timeout = config_value(timeout, nil, :timeout) { 30 }
  @retries = config_value(retries, nil, :retries) { 3 }
  @flush_interval = config_value(flush_interval, 'LANGFUSE_FLUSH_INTERVAL', :flush_interval) { 5 }
  @flush_at = config_value(flush_at, 'LANGFUSE_FLUSH_AT', :flush_at) { 15 }
  @auto_flush = resolve_auto_flush(auto_flush)
  @ingestion_mode = resolve_ingestion_mode(ingestion_mode)
  @logger = logger || Langfuse.configuration.logger || build_default_logger
  @environment = resolve_environment(environment)
  @sample_rate = resolve_sample_rate(sample_rate)
  @mask = resolve_mask(mask)
  @shutdown_on_exit = shutdown_on_exit.nil? ? Langfuse.configuration.shutdown_on_exit : shutdown_on_exit
  @shutdown = false

  raise AuthenticationError, 'Public key is required' unless @public_key
  raise AuthenticationError, 'Secret key is required' unless @secret_key

  @connection = build_connection
  @otel_connection = build_otel_connection if @ingestion_mode == :otel
  @otel_exporter = OtelExporter.new(connection: @otel_connection, debug: @debug, logger: @logger) if @ingestion_mode == :otel
  @event_queue = Concurrent::Array.new
  @flush_mutex = Mutex.new
  @flush_condition = ConditionVariable.new
  @flush_thread = start_flush_thread if @auto_flush
  register_shutdown_hook if @shutdown_on_exit
end

Instance Attribute Details

#auto_flushObject (readonly)

Returns the value of attribute auto_flush.



30
31
32
# File 'lib/langfuse/client.rb', line 30

def auto_flush
  @auto_flush
end

#debugObject (readonly)

Returns the value of attribute debug.



30
31
32
# File 'lib/langfuse/client.rb', line 30

def debug
  @debug
end

#environmentObject (readonly)

Returns the value of attribute environment.



30
31
32
# File 'lib/langfuse/client.rb', line 30

def environment
  @environment
end

#flush_atObject (readonly)

Returns the value of attribute flush_at.



30
31
32
# File 'lib/langfuse/client.rb', line 30

def flush_at
  @flush_at
end

#flush_intervalObject (readonly)

Returns the value of attribute flush_interval.



30
31
32
# File 'lib/langfuse/client.rb', line 30

def flush_interval
  @flush_interval
end

#hostObject (readonly)

Returns the value of attribute host.



30
31
32
# File 'lib/langfuse/client.rb', line 30

def host
  @host
end

#ingestion_modeObject (readonly)

Returns the value of attribute ingestion_mode.



30
31
32
# File 'lib/langfuse/client.rb', line 30

def ingestion_mode
  @ingestion_mode
end

#loggerObject (readonly)

Returns the value of attribute logger.



30
31
32
# File 'lib/langfuse/client.rb', line 30

def logger
  @logger
end

#maskObject (readonly)

Returns the value of attribute mask.



30
31
32
# File 'lib/langfuse/client.rb', line 30

def mask
  @mask
end

#public_keyObject (readonly)

Returns the value of attribute public_key.



30
31
32
# File 'lib/langfuse/client.rb', line 30

def public_key
  @public_key
end

#retriesObject (readonly)

Returns the value of attribute retries.



30
31
32
# File 'lib/langfuse/client.rb', line 30

def retries
  @retries
end

#sample_rateObject (readonly)

Returns the value of attribute sample_rate.



30
31
32
# File 'lib/langfuse/client.rb', line 30

def sample_rate
  @sample_rate
end

#secret_keyObject (readonly)

Returns the value of attribute secret_key.



30
31
32
# File 'lib/langfuse/client.rb', line 30

def secret_key
  @secret_key
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



30
31
32
# File 'lib/langfuse/client.rb', line 30

def timeout
  @timeout
end

Instance Method Details

#agent(trace_id:, name: nil, start_time: nil, end_time: nil, input: nil, output: nil, metadata: nil, level: nil, status_message: nil, parent_observation_id: nil, version: nil, **kwargs) ⇒ Object

Create an agent observation (wrapper around span with as_type: 'agent')



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/langfuse/client.rb', line 124

def agent(trace_id:, name: nil, start_time: nil, end_time: nil, input: nil, output: nil,
          metadata: nil, level: nil, status_message: nil, parent_observation_id: nil,
          version: nil, **kwargs)
  span(
    trace_id: trace_id,
    name: name,
    start_time: start_time,
    end_time: end_time,
    input: input,
    output: output,
    metadata: ,
    level: level,
    status_message: status_message,
    parent_observation_id: parent_observation_id,
    version: version,
    as_type: ObservationType::AGENT,
    **kwargs
  )
end

#chain(trace_id:, name: nil, start_time: nil, end_time: nil, input: nil, output: nil, metadata: nil, level: nil, status_message: nil, parent_observation_id: nil, version: nil, **kwargs) ⇒ Object

Create a chain observation (wrapper around span with as_type: 'chain')



166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/langfuse/client.rb', line 166

def chain(trace_id:, name: nil, start_time: nil, end_time: nil, input: nil, output: nil,
          metadata: nil, level: nil, status_message: nil, parent_observation_id: nil,
          version: nil, **kwargs)
  span(
    trace_id: trace_id,
    name: name,
    start_time: start_time,
    end_time: end_time,
    input: input,
    output: output,
    metadata: ,
    level: level,
    status_message: status_message,
    parent_observation_id: parent_observation_id,
    version: version,
    as_type: ObservationType::CHAIN,
    **kwargs
  )
end

#create_prompt(name:, prompt:, labels: [], config: {}, **kwargs) ⇒ Object



363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/langfuse/client.rb', line 363

def create_prompt(name:, prompt:, labels: [], config: {}, **kwargs)
  data = {
    name: name,
    prompt: prompt,
    labels: labels,
    config: config,
    **kwargs
  }

  response = post('/api/public/v2/prompts', data)
  Prompt.new(response.body)
end

#embedding(trace_id:, name: nil, start_time: nil, end_time: nil, input: nil, output: nil, model: nil, usage: nil, metadata: nil, level: nil, status_message: nil, parent_observation_id: nil, version: nil, **kwargs) ⇒ Object

Create an embedding observation (wrapper around span with as_type: 'embedding')



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/langfuse/client.rb', line 208

def embedding(trace_id:, name: nil, start_time: nil, end_time: nil, input: nil, output: nil,
              model: nil, usage: nil, metadata: nil, level: nil, status_message: nil,
              parent_observation_id: nil, version: nil, **kwargs)
   = ( || {}).merge(
    { model: model, usage: usage }.compact
  )
  span(
    trace_id: trace_id,
    name: name,
    start_time: start_time,
    end_time: end_time,
    input: input,
    output: output,
    metadata: .empty? ? nil : ,
    level: level,
    status_message: status_message,
    parent_observation_id: parent_observation_id,
    version: version,
    as_type: ObservationType::EMBEDDING,
    **kwargs
  )
end

#enqueue_event(type, body) ⇒ Object

Event queue management



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
# File 'lib/langfuse/client.rb', line 408

def enqueue_event(type, body)
  # 验证事件类型是否有效
  valid_types = %w[
    trace-create trace-update
    generation-create generation-update
    span-create span-update
    event-create
    score-create
  ]

  unless valid_types.include?(type)
    @logger.debug("Warning: Invalid event type '#{type}'. Skipping event.")
    return
  end

  prepared_body = Utils.prepare_event_body(body)
  inject_default_environment(prepared_body)
  apply_mask(prepared_body)

  return unless sampled_event?(type, prepared_body)

  event = {
    id: Utils.generate_id,
    type: type,
    timestamp: Utils.current_timestamp,
    body: prepared_body
  }

  if type == 'trace-update'
    # 查找对应的 trace-create 事件并更新
    trace_id = body['id'] || body[:id]
    if trace_id
      existing_event_index = @event_queue.find_index do |existing_event|
        existing_event[:type] == 'trace-create' &&
          (existing_event[:body]['id'] == trace_id || existing_event[:body][:id] == trace_id)
      end

      if existing_event_index
        # 更新现有的 trace-create 事件
        @event_queue[existing_event_index][:body].merge!(event[:body])
        @event_queue[existing_event_index][:timestamp] = event[:timestamp]
        @logger.debug("Updated existing trace-create event for trace_id: #{trace_id}")
      else
        # 如果没找到对应的 trace-create 事件,将 trace-update 转换为 trace-create
        event[:type] = 'trace-create'
        @event_queue << event
        @logger.debug("Converted trace-update to trace-create for trace_id: #{trace_id}")
      end
    else
      @logger.debug('Warning: trace-update event missing trace_id, skipping')
    end
  else
    @event_queue << event
  end
  @logger.debug("Enqueued event: #{type}")

  request_flush if @auto_flush && @event_queue.length >= @flush_at
end

#evaluator_obs(trace_id:, name: nil, start_time: nil, end_time: nil, input: nil, output: nil, metadata: nil, level: nil, status_message: nil, parent_observation_id: nil, version: nil, **kwargs) ⇒ Object

Create an evaluator observation (wrapper around span with as_type: 'evaluator')



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/langfuse/client.rb', line 232

def evaluator_obs(trace_id:, name: nil, start_time: nil, end_time: nil, input: nil, output: nil,
                  metadata: nil, level: nil, status_message: nil, parent_observation_id: nil,
                  version: nil, **kwargs)
  span(
    trace_id: trace_id,
    name: name,
    start_time: start_time,
    end_time: end_time,
    input: input,
    output: output,
    metadata: ,
    level: level,
    status_message: status_message,
    parent_observation_id: parent_observation_id,
    version: version,
    as_type: ObservationType::EVALUATOR,
    **kwargs
  )
end

#event(trace_id:, name:, id: nil, start_time: nil, input: nil, output: nil, metadata: nil, level: nil, status_message: nil, parent_observation_id: nil, version: nil, **kwargs) ⇒ Object

Event operations



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/langfuse/client.rb', line 305

def event(trace_id:, name:, id: nil, start_time: nil, input: nil, output: nil, metadata: nil,
          level: nil, status_message: nil, parent_observation_id: nil, version: nil, **kwargs)
  Event.new(
    client: self,
    trace_id: trace_id,
    id: id || generate_observation_id,
    name: name,
    start_time: start_time,
    input: input,
    output: output,
    metadata: ,
    level: level,
    status_message: status_message,
    parent_observation_id: parent_observation_id,
    version: version,
    **kwargs
  )
end

#flushObject



467
468
469
470
471
472
473
474
# File 'lib/langfuse/client.rb', line 467

def flush
  return if @event_queue.empty?

  events = @event_queue.shift(@event_queue.length)
  return if events.empty?

  send_batch(events)
end

#generate_observation_idObject

Generate an observation ID matching the active ingestion mode (W3C 16-char hex for :otel, UUID for :legacy)



74
75
76
# File 'lib/langfuse/client.rb', line 74

def generate_observation_id
  @ingestion_mode == :otel ? Utils.generate_hex_span_id : Utils.generate_id
end

#generate_trace_idObject

Generate a trace ID matching the active ingestion mode (W3C 32-char hex for :otel, UUID for :legacy)



68
69
70
# File 'lib/langfuse/client.rb', line 68

def generate_trace_id
  @ingestion_mode == :otel ? Utils.generate_hex_trace_id : Utils.generate_id
end

#generation(trace_id:, id: nil, name: nil, start_time: nil, end_time: nil, completion_start_time: nil, model: nil, model_parameters: nil, input: nil, output: nil, usage: nil, usage_details: nil, cost_details: nil, prompt: nil, metadata: nil, level: nil, status_message: nil, parent_observation_id: nil, version: nil, **kwargs) ⇒ Object

Generation operations



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
# File 'lib/langfuse/client.rb', line 274

def generation(trace_id:, id: nil, name: nil, start_time: nil, end_time: nil, completion_start_time: nil,
               model: nil, model_parameters: nil, input: nil, output: nil, usage: nil,
               usage_details: nil, cost_details: nil, prompt: nil,
               metadata: nil, level: nil, status_message: nil, parent_observation_id: nil,
               version: nil, **kwargs)
  Generation.new(
    client: self,
    trace_id: trace_id,
    id: id || generate_observation_id,
    name: name,
    start_time: start_time || Utils.current_timestamp,
    end_time: end_time,
    completion_start_time: completion_start_time,
    model: model,
    model_parameters: model_parameters,
    input: input,
    output: output,
    usage: usage,
    usage_details: usage_details,
    cost_details: cost_details,
    prompt: prompt,
    metadata: ,
    level: level,
    status_message: status_message,
    parent_observation_id: parent_observation_id,
    version: version,
    **kwargs
  )
end

#get_prompt(name, version: nil, label: nil, cache_ttl_seconds: 60) ⇒ Object

Prompt operations



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
# File 'lib/langfuse/client.rb', line 325

def get_prompt(name, version: nil, label: nil, cache_ttl_seconds: 60)
  cache_key = "prompt:#{name}:#{version}:#{label}"

  if (cached_prompt = @prompt_cache&.dig(cache_key)) && (Time.now - cached_prompt[:cached_at] < cache_ttl_seconds)
    return cached_prompt[:prompt]
  end

  encoded_name = Utils.url_encode(name)
  path = "/api/public/v2/prompts/#{encoded_name}"
  params = {}
  params[:version] = version if version
  params[:label] = label if label

  @logger.debug("Making request to: #{@host}#{path} with params: #{params}")

  response = get(path, params)

  @logger.debug("Response status: #{response.status}")
  @logger.debug("Response headers: #{response.headers}")
  @logger.debug("Response body type: #{response.body.class}")

  # Check if response body is a string (HTML) instead of parsed JSON
  if response.body.is_a?(String) && response.body.include?('<!DOCTYPE html>')
    @logger.debug('Received HTML response instead of JSON:')
    @logger.debug(response.body[0..200])
    raise APIError,
          'Received HTML response instead of JSON. This usually indicates a 404 error or incorrect API endpoint.'
  end

  prompt = Prompt.new(response.body)

  # Cache the prompt
  @prompt_cache ||= {}
  @prompt_cache[cache_key] = { prompt: prompt, cached_at: Time.now }

  prompt
end

#guardrail(trace_id:, name: nil, start_time: nil, end_time: nil, input: nil, output: nil, metadata: nil, level: nil, status_message: nil, parent_observation_id: nil, version: nil, **kwargs) ⇒ Object

Create a guardrail observation (wrapper around span with as_type: 'guardrail')



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/langfuse/client.rb', line 253

def guardrail(trace_id:, name: nil, start_time: nil, end_time: nil, input: nil, output: nil,
              metadata: nil, level: nil, status_message: nil, parent_observation_id: nil,
              version: nil, **kwargs)
  span(
    trace_id: trace_id,
    name: name,
    start_time: start_time,
    end_time: end_time,
    input: input,
    output: output,
    metadata: ,
    level: level,
    status_message: status_message,
    parent_observation_id: parent_observation_id,
    version: version,
    as_type: ObservationType::GUARDRAIL,
    **kwargs
  )
end

#retriever(trace_id:, name: nil, start_time: nil, end_time: nil, input: nil, output: nil, metadata: nil, level: nil, status_message: nil, parent_observation_id: nil, version: nil, **kwargs) ⇒ Object

Create a retriever observation (wrapper around span with as_type: 'retriever')



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/langfuse/client.rb', line 187

def retriever(trace_id:, name: nil, start_time: nil, end_time: nil, input: nil, output: nil,
              metadata: nil, level: nil, status_message: nil, parent_observation_id: nil,
              version: nil, **kwargs)
  span(
    trace_id: trace_id,
    name: name,
    start_time: start_time,
    end_time: end_time,
    input: input,
    output: output,
    metadata: ,
    level: level,
    status_message: status_message,
    parent_observation_id: parent_observation_id,
    version: version,
    as_type: ObservationType::RETRIEVER,
    **kwargs
  )
end

#score(name:, value:, trace_id: nil, observation_id: nil, session_id: nil, dataset_run_id: nil, id: nil, data_type: nil, comment: nil, metadata: nil, config_id: nil, queue_id: nil, environment: nil, **kwargs) ⇒ Object Also known as: create_score

Score/Evaluation operations Scores can target a trace, an observation (trace_id + observation_id), a session (session_id) or a dataset run (dataset_run_id).



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
# File 'lib/langfuse/client.rb', line 379

def score(name:, value:, trace_id: nil, observation_id: nil, session_id: nil, dataset_run_id: nil,
          id: nil, data_type: nil, comment: nil, metadata: nil, config_id: nil, queue_id: nil,
          environment: nil, **kwargs)
  data = {
    id: id,
    trace_id: trace_id,
    observation_id: observation_id,
    session_id: session_id,
    dataset_run_id: dataset_run_id,
    name: name,
    value: value,
    data_type: data_type,
    comment: comment,
    metadata: ,
    config_id: config_id,
    queue_id: queue_id,
    environment: environment,
    **kwargs
  }.compact

  if trace_id.nil? && observation_id.nil? && session_id.nil? && dataset_run_id.nil?
    @logger.warn('Langfuse score should reference a trace_id, observation_id, session_id or dataset_run_id')
  end

  enqueue_event('score-create', data)
end

#shutdownObject



476
477
478
479
480
481
482
# File 'lib/langfuse/client.rb', line 476

def shutdown
  return if @shutdown

  @shutdown = true
  @flush_thread&.kill if @auto_flush
  flush unless @event_queue.empty?
end

#span(trace_id:, id: nil, name: nil, start_time: nil, end_time: nil, input: nil, output: nil, metadata: nil, level: nil, status_message: nil, parent_observation_id: nil, version: nil, as_type: nil, **kwargs) ⇒ Object

Span operations



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/langfuse/client.rb', line 99

def span(trace_id:, id: nil, name: nil, start_time: nil, end_time: nil, input: nil, output: nil,
         metadata: nil, level: nil, status_message: nil, parent_observation_id: nil,
         version: nil, as_type: nil, **kwargs)
  Span.new(
    client: self,
    trace_id: trace_id,
    id: id || generate_observation_id,
    name: name,
    start_time: start_time || Utils.current_timestamp,
    end_time: end_time,
    input: input,
    output: output,
    metadata: ,
    level: level,
    status_message: status_message,
    parent_observation_id: parent_observation_id,
    version: version,
    as_type: as_type,
    **kwargs
  )
end

#tool(trace_id:, name: nil, start_time: nil, end_time: nil, input: nil, output: nil, metadata: nil, level: nil, status_message: nil, parent_observation_id: nil, version: nil, **kwargs) ⇒ Object

Create a tool observation (wrapper around span with as_type: 'tool')



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/langfuse/client.rb', line 145

def tool(trace_id:, name: nil, start_time: nil, end_time: nil, input: nil, output: nil,
         metadata: nil, level: nil, status_message: nil, parent_observation_id: nil,
         version: nil, **kwargs)
  span(
    trace_id: trace_id,
    name: name,
    start_time: start_time,
    end_time: end_time,
    input: input,
    output: output,
    metadata: ,
    level: level,
    status_message: status_message,
    parent_observation_id: parent_observation_id,
    version: version,
    as_type: ObservationType::TOOL,
    **kwargs
  )
end

#trace(id: nil, name: nil, user_id: nil, session_id: nil, version: nil, release: nil, input: nil, output: nil, metadata: nil, tags: nil, timestamp: nil, **kwargs) ⇒ Object

Trace operations



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/langfuse/client.rb', line 79

def trace(id: nil, name: nil, user_id: nil, session_id: nil, version: nil, release: nil,
          input: nil, output: nil, metadata: nil, tags: nil, timestamp: nil, **kwargs)
  Trace.new(
    client: self,
    id: id || generate_trace_id,
    name: name,
    user_id: user_id,
    session_id: session_id,
    version: version,
    release: release,
    input: input,
    output: output,
    metadata: ,
    tags: tags,
    timestamp: timestamp || Utils.current_timestamp,
    **kwargs
  )
end