2023-03-07 14:14:39 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2023-03-14 15:03:50 -04:00
|
|
|
module ::DiscourseAi
|
2023-03-07 14:14:39 -05:00
|
|
|
module Inference
|
2023-03-15 16:02:20 -04:00
|
|
|
class OpenAiEmbeddings
|
2024-01-29 11:24:30 -05:00
|
|
|
def self.perform!(content, model:, dimensions: nil)
|
2023-06-20 20:39:51 -04:00
|
|
|
headers = { "Content-Type" => "application/json" }
|
|
|
|
|
2024-01-12 18:28:06 -05:00
|
|
|
if SiteSetting.ai_openai_embeddings_url.include?("azure")
|
2023-06-20 20:39:51 -04:00
|
|
|
headers["api-key"] = SiteSetting.ai_openai_api_key
|
|
|
|
else
|
|
|
|
headers["Authorization"] = "Bearer #{SiteSetting.ai_openai_api_key}"
|
|
|
|
end
|
2023-03-07 14:14:39 -05:00
|
|
|
|
2024-01-29 11:24:30 -05:00
|
|
|
payload = { model: model, input: content }
|
|
|
|
payload[:dimensions] = dimensions if dimensions.present?
|
2023-03-07 14:14:39 -05:00
|
|
|
|
2024-01-29 11:24:30 -05:00
|
|
|
response = Faraday.post(SiteSetting.ai_openai_embeddings_url, payload.to_json, headers)
|
2024-01-24 13:57:18 -05:00
|
|
|
|
|
|
|
case response.status
|
|
|
|
when 200
|
|
|
|
JSON.parse(response.body, symbolize_names: true)
|
|
|
|
when 429
|
|
|
|
# TODO add a AdminDashboard Problem?
|
|
|
|
else
|
2023-06-20 20:39:51 -04:00
|
|
|
Rails.logger.warn(
|
|
|
|
"OpenAI Embeddings failed with status: #{response.status} body: #{response.body}",
|
|
|
|
)
|
|
|
|
raise Net::HTTPBadResponse
|
|
|
|
end
|
2023-03-07 14:14:39 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|