2023-11-24 02:08:08 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module ::DiscourseAi
|
|
|
|
module Inference
|
|
|
|
class OpenAiImageGenerator
|
|
|
|
TIMEOUT = 60
|
|
|
|
|
2023-11-26 21:01:05 -05:00
|
|
|
def self.perform!(prompt, model: "dall-e-3", size: "1024x1024", api_key: nil, api_url: nil)
|
2023-11-24 02:08:08 -05:00
|
|
|
api_key ||= SiteSetting.ai_openai_api_key
|
2023-11-26 21:01:05 -05:00
|
|
|
api_url ||= SiteSetting.ai_openai_dall_e_3_url
|
2023-11-24 02:08:08 -05:00
|
|
|
|
2023-11-26 21:01:05 -05:00
|
|
|
uri = URI(api_url)
|
2023-11-24 02:08:08 -05:00
|
|
|
|
2023-11-26 21:01:05 -05:00
|
|
|
headers = { "Content-Type" => "application/json" }
|
|
|
|
|
|
|
|
if uri.host.include?("azure")
|
|
|
|
headers["api-key"] = api_key
|
|
|
|
else
|
|
|
|
headers["Authorization"] = "Bearer #{api_key}"
|
|
|
|
end
|
|
|
|
|
|
|
|
payload = {
|
|
|
|
quality: "hd",
|
|
|
|
model: model,
|
|
|
|
prompt: prompt,
|
|
|
|
n: 1,
|
|
|
|
size: size,
|
|
|
|
response_format: "b64_json",
|
|
|
|
}
|
2023-11-24 02:08:08 -05:00
|
|
|
|
|
|
|
Net::HTTP.start(
|
2023-11-26 21:01:05 -05:00
|
|
|
uri.host,
|
|
|
|
uri.port,
|
|
|
|
use_ssl: uri.scheme == "https",
|
2023-11-24 02:08:08 -05:00
|
|
|
read_timeout: TIMEOUT,
|
|
|
|
open_timeout: TIMEOUT,
|
|
|
|
write_timeout: TIMEOUT,
|
|
|
|
) do |http|
|
2023-11-26 21:01:05 -05:00
|
|
|
request = Net::HTTP::Post.new(uri, headers)
|
2023-11-24 02:08:08 -05:00
|
|
|
request.body = payload.to_json
|
|
|
|
|
|
|
|
json = nil
|
|
|
|
http.request(request) do |response|
|
|
|
|
if response.code.to_i != 200
|
|
|
|
raise "OpenAI API returned #{response.code} #{response.body}"
|
|
|
|
else
|
|
|
|
json = JSON.parse(response.body, symbolize_names: true)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
json
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|