2023-11-23 10:58:54 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module DiscourseAi
|
|
|
|
module Completions
|
|
|
|
module Endpoints
|
|
|
|
class Base
|
|
|
|
CompletionFailed = Class.new(StandardError)
|
|
|
|
TIMEOUT = 60
|
|
|
|
|
2024-01-29 14:04:25 -05:00
|
|
|
class << self
|
|
|
|
def endpoint_for(provider_name, model_name)
|
|
|
|
endpoints = [
|
|
|
|
DiscourseAi::Completions::Endpoints::AwsBedrock,
|
|
|
|
DiscourseAi::Completions::Endpoints::OpenAi,
|
|
|
|
DiscourseAi::Completions::Endpoints::HuggingFace,
|
|
|
|
DiscourseAi::Completions::Endpoints::Gemini,
|
|
|
|
DiscourseAi::Completions::Endpoints::Vllm,
|
2024-03-18 15:48:46 -04:00
|
|
|
DiscourseAi::Completions::Endpoints::Anthropic,
|
2024-04-10 17:24:17 -04:00
|
|
|
DiscourseAi::Completions::Endpoints::Cohere,
|
2024-01-29 14:04:25 -05:00
|
|
|
]
|
|
|
|
|
2024-05-07 09:02:16 -04:00
|
|
|
endpoints << DiscourseAi::Completions::Endpoints::Ollama if Rails.env.development?
|
|
|
|
|
2024-01-29 14:04:25 -05:00
|
|
|
if Rails.env.test? || Rails.env.development?
|
|
|
|
endpoints << DiscourseAi::Completions::Endpoints::Fake
|
|
|
|
end
|
|
|
|
|
|
|
|
endpoints.detect(-> { raise DiscourseAi::Completions::Llm::UNKNOWN_MODEL }) do |ek|
|
|
|
|
ek.can_contact?(provider_name, model_name)
|
|
|
|
end
|
2024-01-10 23:56:40 -05:00
|
|
|
end
|
|
|
|
|
2024-01-29 14:04:25 -05:00
|
|
|
def configuration_hint
|
|
|
|
settings = dependant_setting_names
|
|
|
|
I18n.t(
|
|
|
|
"discourse_ai.llm.endpoints.configuration_hint",
|
|
|
|
settings: settings.join(", "),
|
|
|
|
count: settings.length,
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
def display_name(model_name)
|
|
|
|
to_display = endpoint_name(model_name)
|
|
|
|
|
|
|
|
return to_display if correctly_configured?(model_name)
|
|
|
|
|
|
|
|
I18n.t("discourse_ai.llm.endpoints.not_configured", display_name: to_display)
|
|
|
|
end
|
|
|
|
|
|
|
|
def dependant_setting_names
|
|
|
|
raise NotImplementedError
|
2023-11-23 10:58:54 -05:00
|
|
|
end
|
|
|
|
|
2024-01-29 14:04:25 -05:00
|
|
|
def endpoint_name(_model_name)
|
|
|
|
raise NotImplementedError
|
|
|
|
end
|
|
|
|
|
|
|
|
def can_contact?(_endpoint_name, _model_name)
|
|
|
|
raise NotImplementedError
|
|
|
|
end
|
2023-11-23 10:58:54 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def initialize(model_name, tokenizer)
|
|
|
|
@model = model_name
|
|
|
|
@tokenizer = tokenizer
|
|
|
|
end
|
|
|
|
|
2024-04-18 16:54:54 -04:00
|
|
|
def native_tool_support?
|
|
|
|
false
|
|
|
|
end
|
|
|
|
|
2024-05-07 09:02:16 -04:00
|
|
|
def use_ssl?
|
|
|
|
true
|
|
|
|
end
|
|
|
|
|
2024-04-18 16:54:54 -04:00
|
|
|
def perform_completion!(dialect, user, model_params = {}, &blk)
|
2024-03-07 14:37:23 -05:00
|
|
|
allow_tools = dialect.prompt.has_tools?
|
2024-01-04 07:53:47 -05:00
|
|
|
model_params = normalize_model_params(model_params)
|
|
|
|
|
2023-11-23 10:58:54 -05:00
|
|
|
@streaming_mode = block_given?
|
|
|
|
|
2023-12-18 16:06:01 -05:00
|
|
|
prompt = dialect.translate
|
|
|
|
|
2024-02-21 15:14:50 -05:00
|
|
|
FinalDestination::HTTP.start(
|
2023-11-23 10:58:54 -05:00
|
|
|
model_uri.host,
|
|
|
|
model_uri.port,
|
2024-05-07 09:02:16 -04:00
|
|
|
use_ssl: use_ssl?,
|
2023-11-23 10:58:54 -05:00
|
|
|
read_timeout: TIMEOUT,
|
|
|
|
open_timeout: TIMEOUT,
|
|
|
|
write_timeout: TIMEOUT,
|
|
|
|
) do |http|
|
|
|
|
response_data = +""
|
|
|
|
response_raw = +""
|
2023-12-18 16:06:01 -05:00
|
|
|
|
|
|
|
# Needed to response token calculations. Cannot rely on response_data due to function buffering.
|
|
|
|
partials_raw = +""
|
|
|
|
request_body = prepare_payload(prompt, model_params, dialect).to_json
|
2023-11-23 10:58:54 -05:00
|
|
|
|
|
|
|
request = prepare_request(request_body)
|
|
|
|
|
|
|
|
http.request(request) do |response|
|
|
|
|
if response.code.to_i != 200
|
|
|
|
Rails.logger.error(
|
|
|
|
"#{self.class.name}: status: #{response.code.to_i} - body: #{response.body}",
|
|
|
|
)
|
|
|
|
raise CompletionFailed
|
|
|
|
end
|
|
|
|
|
|
|
|
log =
|
|
|
|
AiApiAuditLog.new(
|
|
|
|
provider_id: provider_id,
|
2023-11-28 10:52:22 -05:00
|
|
|
user_id: user&.id,
|
2023-11-23 10:58:54 -05:00
|
|
|
raw_request_payload: request_body,
|
|
|
|
request_tokens: prompt_size(prompt),
|
2024-03-01 15:53:21 -05:00
|
|
|
topic_id: dialect.prompt.topic_id,
|
|
|
|
post_id: dialect.prompt.post_id,
|
2023-11-23 10:58:54 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
if !@streaming_mode
|
|
|
|
response_raw = response.read_body
|
|
|
|
response_data = extract_completion_from(response_raw)
|
2023-12-18 16:06:01 -05:00
|
|
|
partials_raw = response_data.to_s
|
|
|
|
|
2024-04-18 16:54:54 -04:00
|
|
|
if native_tool_support?
|
|
|
|
if allow_tools && has_tool?(response_data)
|
|
|
|
function_buffer = build_buffer # Nokogiri document
|
|
|
|
function_buffer =
|
|
|
|
add_to_function_buffer(function_buffer, payload: response_data)
|
|
|
|
FunctionCallNormalizer.normalize_function_ids!(function_buffer)
|
2023-12-18 16:06:01 -05:00
|
|
|
|
2024-04-18 16:54:54 -04:00
|
|
|
response_data = +function_buffer.at("function_calls").to_s
|
|
|
|
response_data << "\n"
|
|
|
|
end
|
|
|
|
else
|
|
|
|
if allow_tools
|
|
|
|
response_data, function_calls = FunctionCallNormalizer.normalize(response_data)
|
|
|
|
response_data = function_calls if function_calls.present?
|
|
|
|
end
|
2023-12-18 16:06:01 -05:00
|
|
|
end
|
2023-11-23 10:58:54 -05:00
|
|
|
|
|
|
|
return response_data
|
|
|
|
end
|
|
|
|
|
2024-01-04 08:44:07 -05:00
|
|
|
has_tool = false
|
|
|
|
|
2023-11-23 10:58:54 -05:00
|
|
|
begin
|
|
|
|
cancelled = false
|
2024-04-18 16:54:54 -04:00
|
|
|
cancel = -> { cancelled = true }
|
|
|
|
|
|
|
|
wrapped_blk = ->(partial, inner_cancel) do
|
|
|
|
response_data << partial
|
|
|
|
blk.call(partial, inner_cancel)
|
|
|
|
end
|
|
|
|
|
|
|
|
normalizer = FunctionCallNormalizer.new(wrapped_blk, cancel)
|
2023-11-23 10:58:54 -05:00
|
|
|
|
|
|
|
leftover = ""
|
2023-12-18 16:06:01 -05:00
|
|
|
function_buffer = build_buffer # Nokogiri document
|
2023-12-20 12:28:05 -05:00
|
|
|
prev_processed_partials = 0
|
2023-11-23 10:58:54 -05:00
|
|
|
|
|
|
|
response.read_body do |chunk|
|
|
|
|
if cancelled
|
|
|
|
http.finish
|
2023-12-20 12:28:05 -05:00
|
|
|
break
|
2023-11-23 10:58:54 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
decoded_chunk = decode(chunk)
|
2024-02-01 06:01:07 -05:00
|
|
|
if decoded_chunk.nil?
|
|
|
|
raise CompletionFailed, "#{self.class.name}: Failed to decode LLM completion"
|
|
|
|
end
|
2023-11-23 10:58:54 -05:00
|
|
|
response_raw << decoded_chunk
|
|
|
|
|
2023-12-20 12:28:05 -05:00
|
|
|
redo_chunk = leftover + decoded_chunk
|
|
|
|
|
|
|
|
raw_partials = partials_from(redo_chunk)
|
|
|
|
|
|
|
|
raw_partials =
|
|
|
|
raw_partials[prev_processed_partials..-1] if prev_processed_partials > 0
|
|
|
|
|
|
|
|
if raw_partials.blank? || (raw_partials.size == 1 && raw_partials.first.blank?)
|
|
|
|
leftover = redo_chunk
|
2023-12-18 16:06:01 -05:00
|
|
|
next
|
|
|
|
end
|
|
|
|
|
2023-12-20 12:28:05 -05:00
|
|
|
json_error = false
|
|
|
|
|
|
|
|
raw_partials.each do |raw_partial|
|
|
|
|
json_error = false
|
|
|
|
prev_processed_partials += 1
|
|
|
|
|
2023-11-23 10:58:54 -05:00
|
|
|
next if cancelled
|
|
|
|
next if raw_partial.blank?
|
|
|
|
|
|
|
|
begin
|
|
|
|
partial = extract_completion_from(raw_partial)
|
2023-12-06 09:22:42 -05:00
|
|
|
next if partial.nil?
|
2024-03-05 14:04:37 -05:00
|
|
|
# empty vs blank... we still accept " "
|
|
|
|
next if response_data.empty? && partial.empty?
|
2024-01-04 08:44:07 -05:00
|
|
|
partials_raw << partial.to_s
|
|
|
|
|
2024-04-18 16:54:54 -04:00
|
|
|
if native_tool_support?
|
|
|
|
# Stop streaming the response as soon as you find a tool.
|
|
|
|
# We'll buffer and yield it later.
|
|
|
|
has_tool = true if allow_tools && has_tool?(partials_raw)
|
2023-11-23 10:58:54 -05:00
|
|
|
|
2024-04-18 16:54:54 -04:00
|
|
|
if has_tool
|
|
|
|
function_buffer =
|
|
|
|
add_to_function_buffer(function_buffer, partial: partial)
|
|
|
|
else
|
|
|
|
response_data << partial
|
|
|
|
blk.call(partial, cancel) if partial
|
2024-03-07 14:37:23 -05:00
|
|
|
end
|
2023-12-18 16:06:01 -05:00
|
|
|
else
|
2024-04-18 16:54:54 -04:00
|
|
|
if allow_tools
|
|
|
|
normalizer << partial
|
2024-03-07 14:37:23 -05:00
|
|
|
else
|
|
|
|
response_data << partial
|
2024-04-18 16:54:54 -04:00
|
|
|
blk.call(partial, cancel) if partial
|
2024-03-07 14:37:23 -05:00
|
|
|
end
|
2023-12-18 16:06:01 -05:00
|
|
|
end
|
2023-11-23 10:58:54 -05:00
|
|
|
rescue JSON::ParserError
|
2023-12-20 12:28:05 -05:00
|
|
|
leftover = redo_chunk
|
|
|
|
json_error = true
|
2023-11-23 10:58:54 -05:00
|
|
|
end
|
|
|
|
end
|
2023-12-20 12:28:05 -05:00
|
|
|
|
|
|
|
if json_error
|
|
|
|
prev_processed_partials -= 1
|
|
|
|
else
|
|
|
|
leftover = ""
|
|
|
|
end
|
|
|
|
prev_processed_partials = 0 if leftover.blank?
|
2023-11-23 10:58:54 -05:00
|
|
|
end
|
|
|
|
rescue IOError, StandardError
|
|
|
|
raise if !cancelled
|
|
|
|
end
|
|
|
|
|
2024-01-02 09:21:13 -05:00
|
|
|
# Once we have the full response, try to return the tool as a XML doc.
|
2024-04-18 16:54:54 -04:00
|
|
|
if has_tool && native_tool_support?
|
2024-03-07 14:37:23 -05:00
|
|
|
function_buffer = add_to_function_buffer(function_buffer, payload: partials_raw)
|
|
|
|
|
2024-01-02 09:21:13 -05:00
|
|
|
if function_buffer.at("tool_name").text.present?
|
2024-04-18 16:54:54 -04:00
|
|
|
FunctionCallNormalizer.normalize_function_ids!(function_buffer)
|
2024-03-07 14:37:23 -05:00
|
|
|
|
2024-01-02 09:21:13 -05:00
|
|
|
invocation = +function_buffer.at("function_calls").to_s
|
|
|
|
invocation << "\n"
|
|
|
|
|
|
|
|
response_data << invocation
|
2024-04-18 16:54:54 -04:00
|
|
|
blk.call(invocation, cancel)
|
2024-01-02 09:21:13 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2024-04-18 16:54:54 -04:00
|
|
|
if !native_tool_support? && function_calls = normalizer.function_calls
|
|
|
|
response_data << function_calls
|
|
|
|
blk.call(function_calls, cancel)
|
|
|
|
end
|
|
|
|
|
2023-11-23 10:58:54 -05:00
|
|
|
return response_data
|
|
|
|
ensure
|
2023-11-28 09:15:12 -05:00
|
|
|
if log
|
|
|
|
log.raw_response_payload = response_raw
|
2023-12-18 16:06:01 -05:00
|
|
|
log.response_tokens = tokenizer.size(partials_raw)
|
2024-03-05 14:04:37 -05:00
|
|
|
final_log_update(log)
|
2023-11-28 09:15:12 -05:00
|
|
|
log.save!
|
2023-11-23 10:58:54 -05:00
|
|
|
|
2023-11-28 09:15:12 -05:00
|
|
|
if Rails.env.development?
|
|
|
|
puts "#{self.class.name}: request_tokens #{log.request_tokens} response_tokens #{log.response_tokens}"
|
|
|
|
end
|
2023-11-23 10:58:54 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2024-03-05 14:04:37 -05:00
|
|
|
def final_log_update(log)
|
|
|
|
# for people that need to override
|
|
|
|
end
|
|
|
|
|
2023-11-23 10:58:54 -05:00
|
|
|
def default_options
|
|
|
|
raise NotImplementedError
|
|
|
|
end
|
|
|
|
|
|
|
|
def provider_id
|
|
|
|
raise NotImplementedError
|
|
|
|
end
|
|
|
|
|
|
|
|
def prompt_size(prompt)
|
|
|
|
tokenizer.size(extract_prompt_for_tokenizer(prompt))
|
|
|
|
end
|
|
|
|
|
2024-01-17 13:08:49 -05:00
|
|
|
attr_reader :tokenizer, :model
|
2023-11-23 10:58:54 -05:00
|
|
|
|
|
|
|
protected
|
|
|
|
|
2024-01-04 07:53:47 -05:00
|
|
|
# should normalize temperature, max_tokens, stop_words to endpoint specific values
|
|
|
|
def normalize_model_params(model_params)
|
|
|
|
raise NotImplementedError
|
|
|
|
end
|
|
|
|
|
2023-11-23 10:58:54 -05:00
|
|
|
def model_uri
|
|
|
|
raise NotImplementedError
|
|
|
|
end
|
|
|
|
|
|
|
|
def prepare_payload(_prompt, _model_params)
|
|
|
|
raise NotImplementedError
|
|
|
|
end
|
|
|
|
|
|
|
|
def prepare_request(_payload)
|
|
|
|
raise NotImplementedError
|
|
|
|
end
|
|
|
|
|
|
|
|
def extract_completion_from(_response_raw)
|
|
|
|
raise NotImplementedError
|
|
|
|
end
|
|
|
|
|
|
|
|
def decode(chunk)
|
|
|
|
chunk
|
|
|
|
end
|
|
|
|
|
|
|
|
def partials_from(_decoded_chunk)
|
|
|
|
raise NotImplementedError
|
|
|
|
end
|
|
|
|
|
|
|
|
def extract_prompt_for_tokenizer(prompt)
|
2024-05-07 09:02:16 -04:00
|
|
|
prompt.map { |message| message[:content] || message["content"] || "" }.join("\n")
|
2023-11-23 10:58:54 -05:00
|
|
|
end
|
2023-12-18 16:06:01 -05:00
|
|
|
|
|
|
|
def build_buffer
|
|
|
|
Nokogiri::HTML5.fragment(<<~TEXT)
|
|
|
|
<function_calls>
|
2024-03-01 15:53:21 -05:00
|
|
|
#{noop_function_call_text}
|
2023-12-18 16:06:01 -05:00
|
|
|
</function_calls>
|
|
|
|
TEXT
|
|
|
|
end
|
|
|
|
|
2024-03-01 15:53:21 -05:00
|
|
|
def noop_function_call_text
|
|
|
|
(<<~TEXT).strip
|
|
|
|
<invoke>
|
|
|
|
<tool_name></tool_name>
|
|
|
|
<parameters>
|
|
|
|
</parameters>
|
2024-03-07 14:37:23 -05:00
|
|
|
<tool_id></tool_id>
|
2024-03-01 15:53:21 -05:00
|
|
|
</invoke>
|
|
|
|
TEXT
|
|
|
|
end
|
|
|
|
|
2024-01-02 09:21:13 -05:00
|
|
|
def has_tool?(response)
|
2024-03-07 14:37:23 -05:00
|
|
|
response.include?("<function_calls>")
|
2023-12-18 16:06:01 -05:00
|
|
|
end
|
|
|
|
|
2024-03-07 14:37:23 -05:00
|
|
|
def add_to_function_buffer(function_buffer, partial: nil, payload: nil)
|
|
|
|
if payload&.include?("</invoke>")
|
|
|
|
matches = payload.match(%r{<function_calls>.*</invoke>}m)
|
|
|
|
function_buffer =
|
|
|
|
Nokogiri::HTML5.fragment(matches[0] + "\n</function_calls>") if matches
|
|
|
|
end
|
2023-12-26 12:49:55 -05:00
|
|
|
|
|
|
|
function_buffer
|
2023-12-18 16:06:01 -05:00
|
|
|
end
|
2023-11-23 10:58:54 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|