2023-03-17 14:14:19 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class CompletionPrompt < ActiveRecord::Base
|
2023-03-21 11:04:59 -04:00
|
|
|
# TODO(roman): Remove sept 2023.
|
|
|
|
self.ignored_columns = ["value"]
|
|
|
|
|
2023-03-17 14:14:19 -04:00
|
|
|
enum :prompt_type, { text: 0, list: 1, diff: 2 }
|
2023-03-21 11:04:59 -04:00
|
|
|
|
|
|
|
validates :messages, length: { maximum: 20 }
|
|
|
|
validate :each_message_length
|
|
|
|
|
|
|
|
def messages_with_user_input(user_input)
|
2023-10-23 10:41:36 -04:00
|
|
|
return messages unless user_input.present?
|
|
|
|
|
2023-09-25 14:12:54 -04:00
|
|
|
if user_input[:custom_prompt].present?
|
|
|
|
case ::DiscourseAi::AiHelper::LlmPrompt.new.enabled_provider
|
|
|
|
when "huggingface"
|
|
|
|
self.messages.each { |msg| msg.sub!("{{custom_prompt}}", user_input[:custom_prompt]) }
|
|
|
|
else
|
|
|
|
self.messages.each do |msg|
|
|
|
|
msg["content"].sub!("{{custom_prompt}}", user_input[:custom_prompt])
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2023-08-25 14:54:51 -04:00
|
|
|
case ::DiscourseAi::AiHelper::LlmPrompt.new.enabled_provider
|
|
|
|
when "openai"
|
2023-09-25 14:12:54 -04:00
|
|
|
self.messages << { role: "user", content: user_input[:text] }
|
2023-08-25 14:54:51 -04:00
|
|
|
when "anthropic"
|
2023-09-25 14:12:54 -04:00
|
|
|
self.messages << { "role" => "Input", "content" => "<input>#{user_input[:text]}</input>" }
|
2023-08-25 14:54:51 -04:00
|
|
|
when "huggingface"
|
2023-09-25 14:12:54 -04:00
|
|
|
self.messages.first.sub("{{user_input}}", user_input[:text])
|
2023-04-10 10:04:42 -04:00
|
|
|
end
|
2023-03-21 11:04:59 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def each_message_length
|
|
|
|
messages.each_with_index do |msg, idx|
|
|
|
|
next if msg["content"].length <= 1000
|
|
|
|
|
|
|
|
errors.add(:messages, I18n.t("errors.prompt_message_length", idx: idx + 1))
|
|
|
|
end
|
|
|
|
end
|
2023-03-17 14:14:19 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: completion_prompts
|
|
|
|
#
|
|
|
|
# id :bigint not null, primary key
|
|
|
|
# name :string not null
|
|
|
|
# translated_name :string
|
|
|
|
# prompt_type :integer default("text"), not null
|
|
|
|
# enabled :boolean default(TRUE), not null
|
|
|
|
# created_at :datetime not null
|
|
|
|
# updated_at :datetime not null
|
2023-04-10 10:04:42 -04:00
|
|
|
# messages :jsonb
|
|
|
|
# provider :text
|
2023-03-17 14:14:19 -04:00
|
|
|
#
|
|
|
|
# Indexes
|
|
|
|
#
|
2023-04-10 10:04:42 -04:00
|
|
|
# index_completion_prompts_on_name (name)
|
2023-03-17 14:14:19 -04:00
|
|
|
#
|