Class: Langfuse::ApiClient

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ ApiClient

Returns a new instance of ApiClient.



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

def initialize(config)
  @config = config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



8
9
10
# File 'lib/langfuse/api_client.rb', line 8

def config
  @config
end

Instance Method Details

#ingest(events) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
65
66
67
68
69
# File 'lib/langfuse/api_client.rb', line 14

def ingest(events)
  uri = URI.parse("#{@config.host}/api/public/ingestion")

  # Build the request
  request = Net::HTTP::Post.new(uri.path)
  request.content_type = 'application/json'

  # Set authorization header using base64 encoded credentials
  auth = Base64.strict_encode64("#{@config.public_key}:#{@config.secret_key}")
  # Log the encoded auth header for debugging
  if @config.debug
    log("Using auth header: Basic #{auth} (public_key: #{@config.public_key}, secret_key: #{@config.secret_key})")
  end
  request['Authorization'] = "Basic #{auth}"

  # Set the payload
  request.body = {
    batch: events
  }.to_json

  # Send the request
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == 'https'
  http.read_timeout = 10 # 10 seconds

  if @config.debug
    log("Sending #{events.size} events to Langfuse API at #{@config.host}")
    log("Events: #{events.inspect}")
    # log("Using auth header: Basic #{auth.gsub(/.(?=.{4})/, '*')}") # Mask most of the auth token
    log("Using auth header: Basic #{auth}") # Mask most of the auth token
    log("Request url: #{uri}")
  end

  response = http.request(request)

  if response.code.to_i == 207 # Partial success
    log('Received 207 partial success response') if @config.debug
    JSON.parse(response.body)
  elsif response.code.to_i >= 200 && response.code.to_i < 300
    log("Received successful response: #{response.code}") if @config.debug
    JSON.parse(response.body)
  else
    error_msg = "API error: #{response.code} #{response.message}"
    if @config.debug
      log("Response body: #{response.body}", :error)
      log("Request URL: #{uri}", :error)
    end
    log(error_msg, :error)
    raise error_msg
  end

  log('---')
rescue StandardError => e
  log("Error during API request: #{e.message}", :error)
  raise
end