2025-05-29 17:28:06 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module DiscourseAi
|
|
|
|
module Translation
|
|
|
|
class BaseTranslator
|
2025-06-06 23:24:24 +08:00
|
|
|
def initialize(text:, target_locale:, topic_id: nil, post_id: nil)
|
2025-05-29 17:28:06 +08:00
|
|
|
@text = text
|
2025-06-06 23:24:24 +08:00
|
|
|
@target_locale = target_locale
|
|
|
|
@topic_id = topic_id
|
|
|
|
@post_id = post_id
|
2025-05-29 17:28:06 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def translate
|
|
|
|
prompt =
|
|
|
|
DiscourseAi::Completions::Prompt.new(
|
|
|
|
prompt_template,
|
|
|
|
messages: [{ type: :user, content: formatted_content, id: "user" }],
|
2025-06-06 23:24:24 +08:00
|
|
|
topic_id: @topic_id,
|
|
|
|
post_id: @post_id,
|
2025-05-29 17:28:06 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
structured_output =
|
|
|
|
DiscourseAi::Completions::Llm.proxy(SiteSetting.ai_translation_model).generate(
|
|
|
|
prompt,
|
|
|
|
user: Discourse.system_user,
|
|
|
|
feature_name: "translation",
|
|
|
|
response_format: response_format,
|
|
|
|
)
|
|
|
|
|
|
|
|
structured_output&.read_buffered_property(:translation)
|
|
|
|
end
|
|
|
|
|
|
|
|
def formatted_content
|
2025-06-06 23:24:24 +08:00
|
|
|
{ content: @text, target_locale: @target_locale }.to_json
|
2025-05-29 17:28:06 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def response_format
|
|
|
|
{
|
|
|
|
type: "json_schema",
|
|
|
|
json_schema: {
|
|
|
|
name: "reply",
|
|
|
|
schema: {
|
|
|
|
type: "object",
|
|
|
|
properties: {
|
|
|
|
translation: {
|
|
|
|
type: "string",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
required: ["translation"],
|
|
|
|
additionalProperties: false,
|
|
|
|
},
|
|
|
|
strict: true,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def prompt_template
|
|
|
|
raise NotImplementedError
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|