Sha256: 4fa69c7e209b4b64c23e81893829d4fa08e988042ebefbcba3c996b41759bca8

Contents?: true

Size: 1.21 KB

Versions: 10

Compression:

Stored size: 1.21 KB

Contents

# frozen_string_literal: true

require 'faraday'
require 'faraday/multipart'

module GenAI
  module Api
    class Client
      def initialize(url:, token:)
        @url = url
        @token = token
      end

      def post(path, body, options = {})
        multipart = options.delete(:multipart) || false
        payload = multipart ? body : JSON.generate(body)

        handle_response do
          connection(multipart: multipart).post(path, payload)
        end
      end

      def get(path, options)
        handle_response do
          connection.get(path, options)
        end
      end

      private

      attr_reader :url, :token

      def connection(multipart: false)
        Faraday.new(url: url, headers: {
          'Accept' => 'application/json',
          'Content-Type' => multipart ? 'multipart/form-data' : 'application/json',
          'Authorization' => "Bearer #{token}"
        }) do |conn|
          conn.request :multipart if multipart
          conn.request :url_encoded
        end
      end

      def handle_response
        response = yield

        raise GenAI::ApiError, "API error: #{JSON.parse(response.body)}" unless response.success?

        JSON.parse(response.body)
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
gen-ai-0.4.0.alpha.3 lib/gen_ai/api/client.rb
gen-ai-0.4.0.alpha.2 lib/gen_ai/api/client.rb
gen-ai-0.4.0.alpha.1 lib/gen_ai/api/client.rb
gen-ai-0.3.2 lib/gen_ai/api/client.rb
gen-ai-0.3.1 lib/gen_ai/api/client.rb
gen-ai-0.3.0 lib/gen_ai/api/client.rb
gen-ai-0.2.3 lib/gen_ai/api/client.rb
gen-ai-0.2.2 lib/gen_ai/api/client.rb
gen-ai-0.2.1 lib/gen_ai/api/client.rb
gen-ai-0.2.0 lib/gen_ai/api/client.rb