Class: Langfuse::Client

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

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) ⇒ Client

Returns a new instance of Client.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/langfuse/client.rb', line 12

def initialize(public_key: nil, secret_key: nil, host: nil, debug: false, timeout: 30, retries: 3,
               flush_interval: nil, auto_flush: nil)
  @public_key = public_key || ENV['LANGFUSE_PUBLIC_KEY'] || Langfuse.configuration.public_key
  @secret_key = secret_key || ENV['LANGFUSE_SECRET_KEY'] || Langfuse.configuration.secret_key
  @host = host || ENV['LANGFUSE_HOST'] || Langfuse.configuration.host
  @debug = debug || Langfuse.configuration.debug
  @timeout = timeout || Langfuse.configuration.timeout
  @retries = retries || Langfuse.configuration.retries
  @flush_interval = flush_interval || ENV['LANGFUSE_FLUSH_INTERVAL']&.to_i || Langfuse.configuration.flush_interval
  @auto_flush = if auto_flush.nil?
                  ENV['LANGFUSE_AUTO_FLUSH'] == 'false' ? false : Langfuse.configuration.auto_flush
                else
                  auto_flush
                end

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

  @connection = build_connection
  @event_queue = Concurrent::Array.new
  @flush_thread = start_flush_thread if @auto_flush
end

Instance Attribute Details

#auto_flushObject (readonly)

Returns the value of attribute auto_flush.



10
11
12
# File 'lib/langfuse/client.rb', line 10

def auto_flush
  @auto_flush
end

#debugObject (readonly)

Returns the value of attribute debug.



10
11
12
# File 'lib/langfuse/client.rb', line 10

def debug
  @debug
end

#flush_intervalObject (readonly)

Returns the value of attribute flush_interval.



10
11
12
# File 'lib/langfuse/client.rb', line 10

def flush_interval
  @flush_interval
end

#hostObject (readonly)

Returns the value of attribute host.



10
11
12
# File 'lib/langfuse/client.rb', line 10

def host
  @host
end

#public_keyObject (readonly)

Returns the value of attribute public_key.



10
11
12
# File 'lib/langfuse/client.rb', line 10

def public_key
  @public_key
end

#retriesObject (readonly)

Returns the value of attribute retries.



10
11
12
# File 'lib/langfuse/client.rb', line 10

def retries
  @retries
end

#secret_keyObject (readonly)

Returns the value of attribute secret_key.



10
11
12
# File 'lib/langfuse/client.rb', line 10

def secret_key
  @secret_key
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



10
11
12
# File 'lib/langfuse/client.rb', line 10

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’)



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

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’)



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

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



313
314
315
316
317
318
319
320
321
322
323
324
# File 'lib/langfuse/client.rb', line 313

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’)



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

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



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/langfuse/client.rb', line 343

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)
    puts "Warning: Invalid event type '#{type}'. Skipping event." if @debug
    return
  end

  event = {
    id: Utils.generate_id,
    type: type,
    timestamp: Utils.current_timestamp,
    body: Utils.deep_stringify_keys(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]
        puts "Updated existing trace-create event for trace_id: #{trace_id}" if @debug
      else
        # 如果没找到对应的 trace-create 事件,将 trace-update 转换为 trace-create
        event[:type] = 'trace-create'
        @event_queue << event
        puts "Converted trace-update to trace-create for trace_id: #{trace_id}" if @debug
      end
    elsif @debug
      puts 'Warning: trace-update event missing trace_id, skipping'
    end
  else
    @event_queue << event
  end
  puts "Enqueued event: #{type}" if @debug
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’)



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

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:, start_time: nil, input: nil, output: nil, metadata: nil, level: nil, status_message: nil, parent_observation_id: nil, version: nil, **kwargs) ⇒ Object

Event operations



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

def event(trace_id:, name:, 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,
    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



394
395
396
397
398
399
400
401
# File 'lib/langfuse/client.rb', line 394

def flush
  return if @event_queue.empty?

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

  send_batch(events)
end

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

Generation operations



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

def generation(trace_id:, name: nil, start_time: nil, end_time: nil, completion_start_time: nil,
               model: nil, model_parameters: nil, input: nil, output: nil, usage: nil,
               metadata: nil, level: nil, status_message: nil, parent_observation_id: nil,
               version: nil, **kwargs)
  Generation.new(
    client: self,
    trace_id: trace_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,
    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



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
303
304
305
306
307
308
309
310
311
# File 'lib/langfuse/client.rb', line 275

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

  puts "Making request to: #{@host}#{path} with params: #{params}" if @debug

  response = get(path, params)

  puts "Response status: #{response.status}" if @debug
  puts "Response headers: #{response.headers}" if @debug
  puts "Response body type: #{response.body.class}" if @debug

  # Check if response body is a string (HTML) instead of parsed JSON
  if response.body.is_a?(String) && response.body.include?('<!DOCTYPE html>')
    puts 'Received HTML response instead of JSON:' if @debug
    puts response.body[0..200] if @debug
    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’)



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

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’)



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

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, data_type: nil, comment: nil, **kwargs) ⇒ Object

Score/Evaluation operations



327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/langfuse/client.rb', line 327

def score(name:, value:, trace_id: nil, observation_id: nil, data_type: nil, comment: nil, **kwargs)
  data = {
    name: name,
    value: value,
    data_type: data_type,
    comment: comment,
    **kwargs
  }

  data[:trace_id] = trace_id if trace_id
  data[:observation_id] = observation_id if observation_id

  enqueue_event('score-create', data)
end

#shutdownObject



403
404
405
406
# File 'lib/langfuse/client.rb', line 403

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

#span(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, as_type: nil, **kwargs) ⇒ Object

Span operations



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

def span(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, as_type: nil, **kwargs)
  Span.new(
    client: self,
    trace_id: trace_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’)



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 101

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



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/langfuse/client.rb', line 36

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 || Utils.generate_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