lib/quick_openai.rb in quick_openai-0.1.0 vs lib/quick_openai.rb in quick_openai-0.1.1

- old
+ new

@@ -6,25 +6,41 @@ require_relative "quick_openai/extensions/string" module QuickOpenAI class Error < StandardError; end - def self.client - OpenAI::Client.new - end + class << self + def client + OpenAI::Client.new + end - def self.fetch_response_from_client - begin - response = yield client - rescue StandardError - raise QuickOpenAI::Error, "Unable to fetch response." + def fetch_response_from_client + ensure_access_token! + + begin + response = yield client + rescue StandardError + raise QuickOpenAI::Error, "Unable to fetch response." + end + + ensure_no_error!(response) + + response end - if (error = response.dig("error", "message")) - raise QuickOpenAI::Error, "Unable to fetch response: #{error}" + private + + def ensure_access_token! + return if ENV.key?("OPENAI_ACCESS_TOKEN") + + raise QuickOpenAI::Error, "Make sure OPENAI_ACCESS_TOKEN is present in ENV." end - response + def ensure_no_error!(response) + return unless (error = response.dig("error", "message")) + + raise QuickOpenAI::Error, "Unable to fetch response: #{error}" + end end end require "down" require "ruby/openai"