discourse/plugins/discourse-ai/spec/lib/translation/base_translator_spec.rb

77 lines
2.6 KiB
Ruby
Vendored

# frozen_string_literal: true
describe DiscourseAi::Translation::BaseTranslator do
let!(:agent) do
AiAgent.find(DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::PostRawTranslator])
end
before do
enable_current_plugin
assign_fake_provider_to(:ai_default_llm_model)
SiteSetting.ai_translation_enabled = true
end
describe ".translate" do
let(:text) { "cats are great" }
let(:target_locale) { "de" }
let(:llm_response) { "hur dur hur dur!" }
fab!(:post)
fab!(:topic) { post.topic }
it "creates the correct prompt" do
post_translator =
DiscourseAi::Translation::PostRawTranslator.new(text:, target_locale:, post:)
allow(DiscourseAi::Completions::Prompt).to receive(:new).with(
agent.system_prompt,
messages: array_including({ type: :user, content: a_string_including(text) }),
post_id: post.id,
topic_id: post.topic_id,
).and_call_original
DiscourseAi::Completions::Llm.with_prepared_responses([llm_response]) do
post_translator.translate
end
end
it "creates BotContext with the correct parameters and calls bot.reply with model max_output_tokens" do
post_translator =
DiscourseAi::Translation::PostRawTranslator.new(text:, target_locale:, post:, topic:)
expected_content = { content: text, target_locale: target_locale }.to_json
bot_context = instance_double(DiscourseAi::Agents::BotContext)
allow(DiscourseAi::Agents::BotContext).to receive(:new).and_return(bot_context)
mock_bot = instance_double(DiscourseAi::Agents::Bot)
allow(DiscourseAi::Agents::Bot).to receive(:as).and_return(mock_bot)
allow(mock_bot).to receive(:reply).and_yield(llm_response, nil, nil)
post_translator.translate
expect(DiscourseAi::Agents::BotContext).to have_received(:new).with(
user: an_instance_of(User),
skip_show_thinking: true,
feature_name: "translation",
messages: [{ type: :user, content: expected_content }],
topic: topic,
post: post,
)
expect(DiscourseAi::Agents::Bot).to have_received(:as)
expect(mock_bot).to have_received(:reply).with(
bot_context,
llm_args: {
max_tokens: LlmModel.last.max_output_tokens,
},
)
end
it "returns the translation from the llm's response" do
DiscourseAi::Completions::Llm.with_prepared_responses([llm_response]) do
expect(
DiscourseAi::Translation::PostRawTranslator.new(text:, target_locale:).translate,
).to eq "hur dur hur dur!"
end
end
end
end