discourse-ai/lib/inference/open_ai_image_generator.rb
Sam 6ddc17fd61
DEV: port directory structure to Zeitwerk (#319)
Previous to this change we relied on explicit loading for a files in Discourse AI.

This had a few downsides:

- Busywork whenever you add a file (an extra require relative)
- We were not keeping to conventions internally ... some places were OpenAI others are OpenAi
- Autoloader did not work which lead to lots of full application broken reloads when developing.

This moves all of DiscourseAI into a Zeitwerk compatible structure.

It also leaves some minimal amount of manual loading (automation - which is loading into an existing namespace that may or may not be there)

To avoid needing /lib/discourse_ai/... we mount a namespace thus we are able to keep /lib pointed at ::DiscourseAi

Various files were renamed to get around zeitwerk rules and minimize usage of custom inflections

Though we can get custom inflections to work it is not worth it, will require a Discourse core patch which means we create a hard dependency.
2023-11-29 15:17:46 +11:00

56 lines
1.4 KiB
Ruby

# frozen_string_literal: true
module ::DiscourseAi
module Inference
class OpenAiImageGenerator
TIMEOUT = 60
def self.perform!(prompt, model: "dall-e-3", size: "1024x1024", api_key: nil, api_url: nil)
api_key ||= SiteSetting.ai_openai_api_key
api_url ||= SiteSetting.ai_openai_dall_e_3_url
uri = URI(api_url)
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",
}
Net::HTTP.start(
uri.host,
uri.port,
use_ssl: uri.scheme == "https",
read_timeout: TIMEOUT,
open_timeout: TIMEOUT,
write_timeout: TIMEOUT,
) do |http|
request = Net::HTTP::Post.new(uri, headers)
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