2023-11-23 10:58:54 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module DiscourseAi
|
|
|
|
module Completions
|
|
|
|
module Endpoints
|
2023-11-28 23:17:46 -05:00
|
|
|
class HuggingFace < Base
|
2023-11-23 10:58:54 -05:00
|
|
|
def self.can_contact?(model_name)
|
2023-12-06 09:22:42 -05:00
|
|
|
%w[StableBeluga2 Upstage-Llama-2-*-instruct-v2 Llama2-*-chat-hf Llama2-chat-hf].include?(
|
|
|
|
model_name,
|
|
|
|
)
|
2023-11-23 10:58:54 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def default_options
|
|
|
|
{ parameters: { repetition_penalty: 1.1, temperature: 0.7 } }
|
|
|
|
end
|
|
|
|
|
|
|
|
def provider_id
|
|
|
|
AiApiAuditLog::Provider::HuggingFaceTextGeneration
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def model_uri
|
2023-12-06 09:22:42 -05:00
|
|
|
URI(SiteSetting.ai_hugging_face_api_url)
|
2023-11-23 10:58:54 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def prepare_payload(prompt, model_params)
|
|
|
|
default_options
|
|
|
|
.merge(inputs: prompt)
|
|
|
|
.tap do |payload|
|
|
|
|
payload[:parameters].merge!(model_params)
|
|
|
|
|
2023-12-06 09:22:42 -05:00
|
|
|
token_limit = SiteSetting.ai_hugging_face_token_limit || 4_000
|
2023-11-23 10:58:54 -05:00
|
|
|
|
|
|
|
payload[:parameters][:max_new_tokens] = token_limit - prompt_size(prompt)
|
2023-12-06 14:06:26 -05:00
|
|
|
payload[:parameters][:return_full_text] = false
|
2023-12-06 09:22:42 -05:00
|
|
|
|
|
|
|
payload[:stream] = true if @streaming_mode
|
2023-11-23 10:58:54 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def prepare_request(payload)
|
|
|
|
headers =
|
|
|
|
{ "Content-Type" => "application/json" }.tap do |h|
|
|
|
|
if SiteSetting.ai_hugging_face_api_key.present?
|
|
|
|
h["Authorization"] = "Bearer #{SiteSetting.ai_hugging_face_api_key}"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
Net::HTTP::Post.new(model_uri, headers).tap { |r| r.body = payload }
|
|
|
|
end
|
|
|
|
|
|
|
|
def extract_completion_from(response_raw)
|
|
|
|
parsed = JSON.parse(response_raw, symbolize_names: true)
|
|
|
|
|
|
|
|
if @streaming_mode
|
|
|
|
# Last chunk contains full response, which we already yielded.
|
|
|
|
return if parsed.dig(:token, :special)
|
|
|
|
|
|
|
|
parsed.dig(:token, :text).to_s
|
|
|
|
else
|
2023-12-06 09:22:42 -05:00
|
|
|
parsed[0][:generated_text].to_s
|
2023-11-23 10:58:54 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def partials_from(decoded_chunk)
|
|
|
|
decoded_chunk
|
|
|
|
.split("\n")
|
|
|
|
.map do |line|
|
2023-12-06 09:22:42 -05:00
|
|
|
data = line.split("data:", 2)[1]
|
2023-11-23 10:58:54 -05:00
|
|
|
data&.squish == "[DONE]" ? nil : data
|
|
|
|
end
|
|
|
|
.compact
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|