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
|
|
|
|
class DiscourseClassifier
|
2024-11-25 11:12:43 -05:00
|
|
|
def initialize(endpoint, api_key, model, referer = Discourse.base_url)
|
|
|
|
@endpoint = endpoint
|
|
|
|
@api_key = api_key
|
|
|
|
@model = model
|
|
|
|
@referer = referer
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.instance(model)
|
|
|
|
endpoint =
|
|
|
|
if SiteSetting.ai_embeddings_discourse_service_api_endpoint_srv.present?
|
|
|
|
service =
|
|
|
|
DiscourseAi::Utils::DnsSrv.lookup(
|
|
|
|
SiteSetting.ai_embeddings_discourse_service_api_endpoint_srv,
|
|
|
|
)
|
|
|
|
"https://#{service.target}:#{service.port}"
|
|
|
|
else
|
|
|
|
SiteSetting.ai_embeddings_discourse_service_api_endpoint
|
|
|
|
end
|
|
|
|
|
|
|
|
new(
|
|
|
|
"#{endpoint}/api/v1/classify",
|
|
|
|
SiteSetting.ai_embeddings_discourse_service_api_key,
|
|
|
|
model,
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
attr_reader :endpoint, :api_key, :model, :referer
|
2023-03-07 14:14:39 -05:00
|
|
|
|
2024-11-25 11:12:43 -05:00
|
|
|
def perform!(content)
|
|
|
|
headers = { "Referer" => referer, "Content-Type" => "application/json" }
|
2023-03-07 14:14:39 -05:00
|
|
|
headers["X-API-KEY"] = api_key if api_key.present?
|
|
|
|
|
2024-02-21 15:14:50 -05:00
|
|
|
conn = Faraday.new { |f| f.adapter FinalDestination::FaradayAdapter }
|
|
|
|
response = conn.post(endpoint, { model: model, content: content }.to_json, headers)
|
2023-03-07 14:14:39 -05:00
|
|
|
|
2023-05-11 14:35:39 -04:00
|
|
|
raise Net::HTTPBadResponse if ![200, 415].include?(response.status)
|
2023-03-07 14:14:39 -05:00
|
|
|
|
|
|
|
JSON.parse(response.body, symbolize_names: true)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|