2025-05-29 17:28:06 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module DiscourseAi
|
|
|
|
module Translation
|
|
|
|
class BaseTranslator
|
2025-06-13 10:17:27 +08:00
|
|
|
def initialize(text:, target_locale:, topic: nil, post: nil)
|
2025-05-29 17:28:06 +08:00
|
|
|
@text = text
|
2025-06-06 23:24:24 +08:00
|
|
|
@target_locale = target_locale
|
2025-06-13 10:17:27 +08:00
|
|
|
@topic = topic
|
|
|
|
@post = post
|
2025-05-29 17:28:06 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def translate
|
2025-06-13 10:17:27 +08:00
|
|
|
return nil if !SiteSetting.ai_translation_enabled
|
|
|
|
if (ai_persona = AiPersona.find_by(id: persona_setting)).blank?
|
|
|
|
return nil
|
|
|
|
end
|
2025-06-23 21:11:20 +08:00
|
|
|
translation_user = ai_persona.user || Discourse.system_user
|
2025-06-13 10:17:27 +08:00
|
|
|
persona_klass = ai_persona.class_instance
|
|
|
|
persona = persona_klass.new
|
|
|
|
|
2025-06-23 21:11:20 +08:00
|
|
|
model = LlmModel.find_by(id: preferred_llm_model(persona_klass))
|
|
|
|
return nil if model.blank?
|
2025-06-13 10:17:27 +08:00
|
|
|
|
2025-06-23 21:11:20 +08:00
|
|
|
bot = DiscourseAi::Personas::Bot.as(translation_user, persona:, model:)
|
|
|
|
|
|
|
|
ContentSplitter
|
|
|
|
.split(content: @text, chunk_size: model.max_output_tokens)
|
|
|
|
.map { |text| get_translation(text:, bot:, translation_user:) }
|
|
|
|
.join("")
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
2025-05-29 17:28:06 +08:00
|
|
|
|
2025-06-23 21:11:20 +08:00
|
|
|
def formatted_content(content)
|
|
|
|
{ content:, target_locale: @target_locale }.to_json
|
|
|
|
end
|
|
|
|
|
|
|
|
def get_translation(text:, bot:, translation_user:)
|
2025-06-13 10:17:27 +08:00
|
|
|
context =
|
|
|
|
DiscourseAi::Personas::BotContext.new(
|
2025-06-23 21:11:20 +08:00
|
|
|
user: translation_user,
|
2025-06-13 10:17:27 +08:00
|
|
|
skip_tool_details: true,
|
2025-05-29 17:28:06 +08:00
|
|
|
feature_name: "translation",
|
2025-06-23 21:11:20 +08:00
|
|
|
messages: [{ type: :user, content: formatted_content(text) }],
|
2025-06-13 10:17:27 +08:00
|
|
|
topic: @topic,
|
|
|
|
post: @post,
|
2025-05-29 17:28:06 +08:00
|
|
|
)
|
|
|
|
|
2025-06-13 10:17:27 +08:00
|
|
|
structured_output = nil
|
|
|
|
bot.reply(context) do |partial, _, type|
|
|
|
|
structured_output = partial if type == :structured_output
|
|
|
|
end
|
|
|
|
|
2025-05-29 17:28:06 +08:00
|
|
|
structured_output&.read_buffered_property(:translation)
|
|
|
|
end
|
|
|
|
|
2025-06-13 10:17:27 +08:00
|
|
|
def persona_setting
|
2025-05-29 17:28:06 +08:00
|
|
|
raise NotImplementedError
|
|
|
|
end
|
2025-06-13 10:17:27 +08:00
|
|
|
|
|
|
|
def preferred_llm_model(persona_klass)
|
|
|
|
persona_klass.default_llm_id || SiteSetting.ai_translation_model&.split(":")&.last
|
|
|
|
end
|
2025-05-29 17:28:06 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|