Class: GenerateImage::Client
- Inherits:
-
Object
- Object
- GenerateImage::Client
- Defined in:
- lib/generate_image.rb
Constant Summary collapse
- API_ENDPOINT =
'https://api.openai.com/v1/images/generations'
- IMAGE_MODEL_NAME =
'image-alpha-001'
- TEXT_MODEL_NAME =
'text-davinci-002'
Instance Attribute Summary collapse
-
#api_key ⇒ Object
Returns the value of attribute api_key.
Instance Method Summary collapse
- #generate_image(text, options = {}) ⇒ Object
-
#initialize(api_key = nil) ⇒ Client
constructor
A new instance of Client.
Constructor Details
#initialize(api_key = nil) ⇒ Client
Returns a new instance of Client.
14 15 16 17 |
# File 'lib/generate_image.rb', line 14 def initialize(api_key = nil) @api_key = api_key || ENV['DALL_E_API_KEY'] raise StandardError, "API Key not set" unless @api_key end |
Instance Attribute Details
#api_key ⇒ Object
Returns the value of attribute api_key.
12 13 14 |
# File 'lib/generate_image.rb', line 12 def api_key @api_key end |
Instance Method Details
#generate_image(text, options = {}) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/generate_image.rb', line 19 def generate_image(text, = {}) unless API_KEY raise StandardError, "API Key not set" end uri = URI(API_ENDPOINT) request = Net::HTTP::Post.new(uri) request['Content-Type'] = 'application/json' request['Authorization'] = "Bearer #{API_KEY}" request.body = { prompt: text, n: [:num_images] || 1, size: [:size] || '512x512', response_format: [:response_format] || 'url', }.to_json response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(request) end if response.code == '200' if [:response_format] == 'base64' image_base64 = JSON.parse(response.body)['data'][0]['base64'] return { image_base64: image_base64 } else image_url = JSON.parse(response.body)['data'][0]['url'] return { image_url: image_url } end else raise RequestFailed, "Failed to generate image. Response code: #{response.code}. Response body: #{response.body}" end end |