Skip to content

Commit

Permalink
Add MiddlewareErrors to own file
Browse files Browse the repository at this point in the history
  • Loading branch information
madwork committed Aug 7, 2024
1 parent 6cfabd6 commit 475b25e
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 19 deletions.
2 changes: 1 addition & 1 deletion lib/middleware/beta.rb
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
19 changes: 19 additions & 0 deletions lib/middleware/errors.rb
Original file line number Diff line number Diff line change
@@ -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
19 changes: 2 additions & 17 deletions lib/openai.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -90,5 +77,3 @@ def self.rough_token_count(content = "")
[1, estimate].max
end
end

require_relative "middleware/beta"
2 changes: 1 addition & 1 deletion lib/openai/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 475b25e

Please sign in to comment.