diff --git a/lib/middleware/beta.rb b/lib/middleware/beta.rb index 1c22fb34..ba58bc66 100644 --- a/lib/middleware/beta.rb +++ b/lib/middleware/beta.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true module OpenAI - class BetaMiddleware < Faraday::Middleware + class MiddlewareBeta < Faraday::Middleware BETA_REGEX = %r{ \A/#{OpenAI.configuration.api_version} /(assistants|batches|threads|vector_stores) diff --git a/lib/middleware/errors.rb b/lib/middleware/errors.rb new file mode 100644 index 00000000..d58e436c --- /dev/null +++ b/lib/middleware/errors.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +module OpenAI + class MiddlewareErrors < Faraday::Middleware + def call(env) + @app.call(env) + rescue Faraday::Error => e + raise e unless e.response.is_a?(Hash) + + logger = Logger.new($stdout) + logger.formatter = proc do |_severity, _datetime, _progname, msg| + "\033[31mOpenAI HTTP Error (spotted in ruby-openai #{VERSION}): #{msg}\n\033[0m" + end + logger.error(e.response[:body]) + + raise e + end + end +end diff --git a/lib/openai.rb b/lib/openai.rb index 25638ac8..5a584072 100644 --- a/lib/openai.rb +++ b/lib/openai.rb @@ -23,21 +23,8 @@ module OpenAI class Error < StandardError; end class ConfigurationError < Error; end - class MiddlewareErrors < Faraday::Middleware - def call(env) - @app.call(env) - rescue Faraday::Error => e - raise e unless e.response.is_a?(Hash) - - logger = Logger.new($stdout) - logger.formatter = proc do |_severity, _datetime, _progname, msg| - "\033[31mOpenAI HTTP Error (spotted in ruby-openai #{VERSION}): #{msg}\n\033[0m" - end - logger.error(e.response[:body]) - - raise e - end - end + autoload :MiddlewareErrors, "middleware/errors" + autoload :MiddlewareBeta, "middleware/beta" class Configuration attr_accessor :access_token, @@ -90,5 +77,3 @@ def self.rough_token_count(content = "") [1, estimate].max end end - -require_relative "middleware/beta" diff --git a/lib/openai/client.rb b/lib/openai/client.rb index 2b84b562..fa5cd304 100644 --- a/lib/openai/client.rb +++ b/lib/openai/client.rb @@ -116,7 +116,7 @@ def build_connection(multipart: false) faraday.options[:timeout] = @request_timeout faraday.request(:multipart) if multipart faraday.use MiddlewareErrors if @log_errors - faraday.use BetaMiddleware + faraday.use MiddlewareBeta faraday.response :raise_error faraday.response :json end