|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "rails_helper" |
| 4 | + |
| 5 | +describe DiscourseAi::Translator do |
| 6 | + before do |
| 7 | + Fabricate(:fake_model).tap do |fake_llm| |
| 8 | + SiteSetting.public_send("ai_helper_model=", "custom:#{fake_llm.id}") |
| 9 | + end |
| 10 | + SiteSetting.ai_helper_enabled = true |
| 11 | + end |
| 12 | + |
| 13 | + describe ".translate" do |
| 14 | + let(:text_to_translate) { "cats are great" } |
| 15 | + let(:target_language) { "de" } |
| 16 | + |
| 17 | + it "creates the correct prompt" do |
| 18 | + allow(DiscourseAi::Completions::Prompt).to receive(:new).with( |
| 19 | + <<~TEXT, |
| 20 | + You are a highly skilled translator with expertise in many languages. |
| 21 | + Your task is to identify the language of the text I provide and accurately translate it into this language locale "de" while preserving the meaning, tone, and nuance of the original text. |
| 22 | + The text may also contain html tags, which should be preserved in the translation. |
| 23 | + Please maintain proper grammar, spelling, and punctuation in the translated version. |
| 24 | + Wrap the translated text in a <translation> tag. |
| 25 | + TEXT |
| 26 | + messages: [{ type: :user, content: text_to_translate, id: "user" }], |
| 27 | + ).and_call_original |
| 28 | + |
| 29 | + described_class.new(text_to_translate, target_language).translate |
| 30 | + end |
| 31 | + |
| 32 | + it "sends the translation prompt to the selected ai helper model" do |
| 33 | + mock_prompt = instance_double(DiscourseAi::Completions::Prompt) |
| 34 | + mock_llm = instance_double(DiscourseAi::Completions::Llm) |
| 35 | + |
| 36 | + allow(DiscourseAi::Completions::Prompt).to receive(:new).and_return(mock_prompt) |
| 37 | + allow(DiscourseAi::Completions::Llm).to receive(:proxy).with( |
| 38 | + SiteSetting.ai_helper_model, |
| 39 | + ).and_return(mock_llm) |
| 40 | + allow(mock_llm).to receive(:generate).with( |
| 41 | + mock_prompt, |
| 42 | + user: Discourse.system_user, |
| 43 | + feature_name: "translator-translate", |
| 44 | + ) |
| 45 | + |
| 46 | + described_class.new(text_to_translate, target_language).translate |
| 47 | + end |
| 48 | + |
| 49 | + it "returns the translation from the llm's response in the translation tag" do |
| 50 | + DiscourseAi::Completions::Llm.with_prepared_responses( |
| 51 | + ["<translation>hur dur hur dur!</translation>"], |
| 52 | + ) do |
| 53 | + expect( |
| 54 | + described_class.new(text_to_translate, target_language).translate, |
| 55 | + ).to eq "hur dur hur dur!" |
| 56 | + end |
| 57 | + end |
| 58 | + |
| 59 | + it "returns the raw response if the translation tag is not present" do |
| 60 | + DiscourseAi::Completions::Llm.with_prepared_responses(["raw response."]) do |
| 61 | + expect( |
| 62 | + described_class.new(text_to_translate, target_language).translate, |
| 63 | + ).to eq "raw response." |
| 64 | + end |
| 65 | + end |
| 66 | + end |
| 67 | +end |
0 commit comments