2023-03-15 17:02:20 -03:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module DiscourseAi
|
|
|
|
module AiHelper
|
|
|
|
class OpenAiPrompt
|
|
|
|
TRANSLATE = "translate"
|
|
|
|
GENERATE_TITLES = "generate_titles"
|
|
|
|
PROOFREAD = "proofread"
|
|
|
|
VALID_TYPES = [TRANSLATE, GENERATE_TITLES, PROOFREAD]
|
|
|
|
|
2023-03-17 15:14:19 -03:00
|
|
|
def available_prompts
|
|
|
|
CompletionPrompt
|
|
|
|
.where(enabled: true)
|
|
|
|
.map do |prompt|
|
|
|
|
translation =
|
|
|
|
I18n.t("discourse_ai.ai_helper.prompts.#{prompt.name}", default: nil) ||
|
|
|
|
prompt.translated_name
|
|
|
|
|
|
|
|
{ name: prompt.name, translated_name: translation, prompt_type: prompt.prompt_type }
|
|
|
|
end
|
2023-03-15 17:02:20 -03:00
|
|
|
end
|
|
|
|
|
2023-03-17 15:14:19 -03:00
|
|
|
def generate_and_send_prompt(prompt, text)
|
|
|
|
result = { type: prompt.prompt_type }
|
2023-03-15 17:02:20 -03:00
|
|
|
|
2023-03-17 15:14:19 -03:00
|
|
|
ai_messages = [{ role: "system", content: prompt.value }, { role: "user", content: text }]
|
2023-03-15 17:02:20 -03:00
|
|
|
|
|
|
|
result[:suggestions] = DiscourseAi::Inference::OpenAiCompletions
|
2023-03-17 15:14:19 -03:00
|
|
|
.perform!(ai_messages)
|
2023-03-15 17:02:20 -03:00
|
|
|
.dig(:choices)
|
|
|
|
.to_a
|
2023-03-17 15:14:19 -03:00
|
|
|
.flat_map { |choice| parse_content(prompt, choice.dig(:message, :content).to_s) }
|
2023-03-15 17:02:20 -03:00
|
|
|
.compact_blank
|
|
|
|
|
2023-03-17 15:14:19 -03:00
|
|
|
result[:diff] = generate_diff(text, result[:suggestions].first) if prompt.diff?
|
2023-03-15 17:02:20 -03:00
|
|
|
|
|
|
|
result
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def generate_diff(text, suggestion)
|
|
|
|
cooked_text = PrettyText.cook(text)
|
|
|
|
cooked_suggestion = PrettyText.cook(suggestion)
|
|
|
|
|
2023-03-16 11:09:28 -03:00
|
|
|
DiscourseDiff.new(cooked_text, cooked_suggestion).inline_html
|
2023-03-15 17:02:20 -03:00
|
|
|
end
|
|
|
|
|
2023-03-17 15:14:19 -03:00
|
|
|
def parse_content(prompt, content)
|
2023-03-15 17:02:20 -03:00
|
|
|
return "" if content.blank?
|
2023-03-17 15:14:19 -03:00
|
|
|
return content.strip if !prompt.list?
|
2023-03-15 17:02:20 -03:00
|
|
|
|
|
|
|
content.gsub("\"", "").gsub(/\d./, "").split("\n").map(&:strip)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|