2023-12-28 08:28:01 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module ::DiscourseAi
|
|
|
|
module Inference
|
|
|
|
class GeminiEmbeddings
|
2024-12-10 13:42:31 -05:00
|
|
|
def self.instance
|
|
|
|
new(SiteSetting.ai_gemini_api_key)
|
|
|
|
end
|
|
|
|
|
2024-11-25 11:12:43 -05:00
|
|
|
def initialize(api_key, referer = Discourse.base_url)
|
|
|
|
@api_key = api_key
|
|
|
|
@referer = referer
|
|
|
|
end
|
2023-12-28 08:28:01 -05:00
|
|
|
|
2024-11-25 11:12:43 -05:00
|
|
|
attr_reader :api_key, :referer
|
2023-12-28 08:28:01 -05:00
|
|
|
|
2024-11-25 11:12:43 -05:00
|
|
|
def perform!(content)
|
|
|
|
headers = { "Referer" => referer, "Content-Type" => "application/json" }
|
|
|
|
url =
|
|
|
|
"https://generativelanguage.googleapis.com/v1beta/models/embedding-001:embedContent\?key\=#{api_key}"
|
2023-12-28 08:28:01 -05:00
|
|
|
body = { content: { parts: [{ text: content }] } }
|
|
|
|
|
2024-02-21 15:14:50 -05:00
|
|
|
conn = Faraday.new { |f| f.adapter FinalDestination::FaradayAdapter }
|
|
|
|
response = conn.post(url, body.to_json, headers)
|
2023-12-28 08:28:01 -05:00
|
|
|
|
2024-08-01 16:25:24 -04:00
|
|
|
case response.status
|
|
|
|
when 200
|
2024-12-10 13:42:31 -05:00
|
|
|
JSON.parse(response.body, symbolize_names: true).dig(:embedding, :values)
|
2024-08-01 16:25:24 -04:00
|
|
|
when 429
|
|
|
|
# TODO add a AdminDashboard Problem?
|
|
|
|
else
|
|
|
|
Rails.logger.warn(
|
|
|
|
"Google Gemini Embeddings failed with status: #{response.status} body: #{response.body}",
|
|
|
|
)
|
|
|
|
raise Net::HTTPBadResponse
|
|
|
|
end
|
2023-12-28 08:28:01 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|