Class: Maglev::Adapters::FaradayClient

Inherits:
Object
  • Object
show all
Defined in:
lib/maglev/adapters/faraday_client.rb

Overview

Shared HTTP client for OpenAI-compatible APIs

Constant Summary collapse

RETRYABLE_STATUSES =
[408, 409, 425, 429].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config, connection: nil) ⇒ FaradayClient

Returns a new instance of FaradayClient.



17
18
19
20
# File 'lib/maglev/adapters/faraday_client.rb', line 17

def initialize(config, connection: nil)
  @config = config
  @connection = connection
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



15
16
17
# File 'lib/maglev/adapters/faraday_client.rb', line 15

def config
  @config
end

Instance Method Details

#post(path, payload) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/maglev/adapters/faraday_client.rb', line 22

def post(path, payload)
  response = connection.post(endpoint(path)) do |req|
    req.headers["Content-Type"] = "application/json"
    req.headers["Authorization"] = "Bearer #{@config.api_key}" if @config.api_key
    req.body = payload
  end

  handle_response(response)
rescue Faraday::TimeoutError, Faraday::ConnectionFailed => error
  raise Maglev::RetryableProviderError, error.message
rescue Faraday::ParsingError => error
  status = error.response_status
  error_class = (status && retryable_status?(status)) ? Maglev::RetryableProviderError : Maglev::PermanentProviderError
  prefix = status ? "HTTP #{status}: " : ""
  raise error_class, "#{prefix}Provider returned invalid JSON: #{error.message}"
end