-
Notifications
You must be signed in to change notification settings - Fork 52
FEATURE: Add DiscourseAi translator #181
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
d5a70a7
FEATURE: Add discourse-ai as a translation provider
nattsw f318223
Fix oddities and update spec
nattsw 6440b3a
Define prompts within translator instead of relying on prompts from d…
nattsw 4599c84
Freeze prompt string to avoid realloc
nattsw eaa8eaa
Better errors
nattsw 5aa9492
Improve prompt so that it preserves html tags
nattsw 656ead4
Use html instead of text to keep tags
nattsw 1c7bd0f
Update test for prompt
nattsw File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| { | ||
| "tests": { | ||
| "requiredPlugins": [ | ||
| "https://github.com/discourse/discourse-ai" | ||
| ] | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| module DiscourseAi | ||
| class LanguageDetector | ||
| PROMPT_TEXT = <<~TEXT | ||
| I want you to act as a language expert, determining the locale for a set of text. | ||
| The locale is a language identifier, such as "en" for English, "de" for German, etc, | ||
| and can also include a region identifier, such as "en-GB" for British English, or "zh-Hans" for Simplified Chinese. | ||
| I will provide you with text, and you will determine the locale of the text. | ||
| Include your locale between <language></language> XML tags. | ||
| TEXT | ||
|
|
||
| def initialize(text) | ||
| @text = text | ||
| end | ||
|
|
||
| def detect | ||
| prompt = | ||
| DiscourseAi::Completions::Prompt.new( | ||
| PROMPT_TEXT, | ||
| messages: [{ type: :user, content: @text, id: "user" }], | ||
| ) | ||
|
|
||
| response = | ||
| DiscourseAi::Completions::Llm.proxy(SiteSetting.ai_helper_model).generate( | ||
| prompt, | ||
| user: Discourse.system_user, | ||
| feature_name: "translator-language-detect", | ||
| ) | ||
|
|
||
| (Nokogiri::HTML5.fragment(response).at("language")&.text || response) | ||
| end | ||
| end | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| module DiscourseAi | ||
| class Translator | ||
| PROMPT_TEMPLATE = <<~TEXT.freeze | ||
| You are a highly skilled linguist and web programmer, with expertise in many languages, and very well versed in HTML. | ||
| Your task is to identify the language of the text I provide and accurately translate it into this language locale "%{target_language}" while preserving the meaning, tone, and nuance of the original text. | ||
| The text will contain html tags, which must absolutely be preserved in the translation. | ||
| Maintain proper grammar, spelling, and punctuation in the translated version. | ||
| Wrap the translated text in a <translation> tag. | ||
| TEXT | ||
|
|
||
| def initialize(text, target_language) | ||
| @text = text | ||
pmusaraj marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| @target_language = target_language | ||
| end | ||
|
|
||
| def translate | ||
| prompt = | ||
| DiscourseAi::Completions::Prompt.new( | ||
| build_prompt(@target_language), | ||
| messages: [{ type: :user, content: @text, id: "user" }], | ||
| ) | ||
|
|
||
| llm_translation = | ||
| DiscourseAi::Completions::Llm.proxy(SiteSetting.ai_helper_model).generate( | ||
| prompt, | ||
| user: Discourse.system_user, | ||
| feature_name: "translator-translate", | ||
| ) | ||
|
|
||
| (Nokogiri::HTML5.fragment(llm_translation).at("translation")&.inner_html || llm_translation) | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def build_prompt(target_language) | ||
| PROMPT_TEMPLATE % { target_language: target_language } | ||
| end | ||
| end | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require_relative "base" | ||
| require "json" | ||
|
|
||
| module DiscourseTranslator | ||
| class DiscourseAi < Base | ||
| MAX_DETECT_LOCALE_TEXT_LENGTH = 1000 | ||
| def self.language_supported?(_) | ||
| true | ||
| end | ||
|
|
||
| def self.detect(topic_or_post) | ||
| return unless required_settings_enabled | ||
|
|
||
| topic_or_post.custom_fields[DiscourseTranslator::DETECTED_LANG_CUSTOM_FIELD] ||= begin | ||
| ::DiscourseAi::LanguageDetector.new(text_for_detection(topic_or_post)).detect | ||
| end | ||
| rescue => e | ||
| Rails.logger.warn( | ||
| "#{::DiscourseTranslator::PLUGIN_NAME}: Failed to detect language for #{topic_or_post.class.name} #{topic_or_post.id}: #{e}", | ||
| ) | ||
| end | ||
|
|
||
| def self.translate(topic_or_post) | ||
| return unless required_settings_enabled | ||
|
|
||
| detected_lang = detect(topic_or_post) | ||
| translated_text = | ||
| from_custom_fields(topic_or_post) do | ||
| ::DiscourseAi::Translator.new(text_for_translation(topic_or_post), I18n.locale).translate | ||
| end | ||
|
|
||
| [detected_lang, translated_text] | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def self.required_settings_enabled | ||
| SiteSetting.translator_enabled && SiteSetting.translator == "DiscourseAi" && | ||
| SiteSetting.discourse_ai_enabled && SiteSetting.ai_helper_enabled | ||
| end | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
26 changes: 26 additions & 0 deletions
26
lib/discourse_translator/translator_selection_validator.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| module DiscourseTranslator | ||
| class TranslatorSelectionValidator | ||
| def initialize(opts = {}) | ||
| @opts = opts | ||
| end | ||
|
|
||
| def valid_value?(val) | ||
| return true if val.blank? | ||
|
|
||
| if val == "DiscourseAi" | ||
| return false if !defined?(::DiscourseAi) | ||
| return false if !SiteSetting.ai_helper_enabled | ||
| end | ||
|
|
||
| true | ||
| end | ||
|
|
||
| def error_message | ||
| return I18n.t("translator.discourse_ai.not_installed") if !defined?(::DiscourseAi) | ||
|
|
||
| I18n.t("translator.discourse_ai.ai_helper_required") if !SiteSetting.ai_helper_enabled | ||
| end | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require "rails_helper" | ||
|
|
||
| describe ::DiscourseTranslator::TranslatorSelectionValidator do | ||
| fab!(:llm_model) | ||
|
|
||
| describe "#valid_value?" do | ||
| context "when value is blank" do | ||
| it "returns true" do | ||
| expect(described_class.new.valid_value?(nil)).to eq(true) | ||
| expect(described_class.new.valid_value?("")).to eq(true) | ||
| end | ||
| end | ||
|
|
||
| context "when value is 'DiscourseAi'" do | ||
| context "when DiscourseAi is not defined" do | ||
| it "returns false" do | ||
| hide_const("DiscourseAi") | ||
| expect(described_class.new.valid_value?("DiscourseAi")).to eq(false) | ||
| end | ||
| end | ||
|
|
||
| context "when DiscourseAi is defined but ai_helper_enabled is false" do | ||
| it "returns false" do | ||
| SiteSetting.ai_helper_enabled = false | ||
| expect(described_class.new.valid_value?("DiscourseAi")).to eq(false) | ||
| end | ||
| end | ||
|
|
||
| context "when DiscourseAi is defined and ai_helper_enabled is true" do | ||
| it "returns true" do | ||
| DiscourseAi::Completions::Llm.with_prepared_responses(["OK"]) do | ||
| SiteSetting.ai_helper_model = "custom:#{llm_model.id}" | ||
| SiteSetting.ai_helper_enabled = true | ||
| end | ||
| expect(described_class.new.valid_value?("DiscourseAi")).to eq(true) | ||
| end | ||
| end | ||
| end | ||
|
|
||
| context "when value is not 'DiscourseAi'" do | ||
| it "returns true" do | ||
| expect(described_class.new.valid_value?("googly")).to eq(true) | ||
| expect(described_class.new.valid_value?("poopy")).to eq(true) | ||
| end | ||
| end | ||
| end | ||
|
|
||
| describe "#error_message" do | ||
| context "when DiscourseAi is not defined" do | ||
| it "returns the not_installed error message" do | ||
| hide_const("DiscourseAi") | ||
| expect(described_class.new.error_message).to eq( | ||
| I18n.t("translator.discourse_ai.not_installed"), | ||
| ) | ||
| end | ||
| end | ||
|
|
||
| context "when DiscourseAi is defined but ai_helper_enabled is false" do | ||
| it "returns the ai_helper_required error message" do | ||
| SiteSetting.ai_helper_enabled = false | ||
| expect(described_class.new.error_message).to eq( | ||
| I18n.t("translator.discourse_ai.ai_helper_required"), | ||
| ) | ||
| end | ||
| end | ||
|
|
||
| context "when DiscourseAi is defined and ai_helper_enabled is true" do | ||
| it "returns nil" do | ||
| DiscourseAi::Completions::Llm.with_prepared_responses(["OK"]) do | ||
| SiteSetting.ai_helper_model = "custom:#{llm_model.id}" | ||
| SiteSetting.ai_helper_enabled = true | ||
| end | ||
| expect(described_class.new.error_message).to be_nil | ||
| end | ||
| end | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require "rails_helper" | ||
|
|
||
| describe DiscourseAi::LanguageDetector do | ||
| before do | ||
| Fabricate(:fake_model).tap do |fake_llm| | ||
| SiteSetting.public_send("ai_helper_model=", "custom:#{fake_llm.id}") | ||
| end | ||
| SiteSetting.ai_helper_enabled = true | ||
| end | ||
|
|
||
| describe ".detect" do | ||
| it "creates the correct prompt" do | ||
| allow(DiscourseAi::Completions::Prompt).to receive(:new).with( | ||
| DiscourseAi::LanguageDetector::PROMPT_TEXT, | ||
| messages: [{ type: :user, content: "meow", id: "user" }], | ||
| ).and_call_original | ||
|
|
||
| described_class.new("meow").detect | ||
| end | ||
|
|
||
| it "sends the language detection prompt to the ai helper model" do | ||
| mock_prompt = instance_double(DiscourseAi::Completions::Prompt) | ||
| mock_llm = instance_double(DiscourseAi::Completions::Llm) | ||
|
|
||
| allow(DiscourseAi::Completions::Prompt).to receive(:new).and_return(mock_prompt) | ||
| allow(DiscourseAi::Completions::Llm).to receive(:proxy).with( | ||
| SiteSetting.ai_helper_model, | ||
| ).and_return(mock_llm) | ||
| allow(mock_llm).to receive(:generate).with( | ||
| mock_prompt, | ||
| user: Discourse.system_user, | ||
| feature_name: "translator-language-detect", | ||
| ) | ||
|
|
||
| described_class.new("meow").detect | ||
| end | ||
|
|
||
| it "returns the language from the llm's response in the language tag" do | ||
| DiscourseAi::Completions::Llm.with_prepared_responses(["<language>de</language>"]) do | ||
| expect(described_class.new("meow").detect).to eq "de" | ||
| end | ||
| end | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require "rails_helper" | ||
|
|
||
| describe DiscourseAi::Translator do | ||
| before do | ||
| Fabricate(:fake_model).tap do |fake_llm| | ||
| SiteSetting.public_send("ai_helper_model=", "custom:#{fake_llm.id}") | ||
| end | ||
| SiteSetting.ai_helper_enabled = true | ||
| end | ||
|
|
||
| describe ".translate" do | ||
| let(:text_to_translate) { "cats are great" } | ||
| let(:target_language) { "de" } | ||
|
|
||
| it "creates the correct prompt" do | ||
| allow(DiscourseAi::Completions::Prompt).to receive(:new).with( | ||
| <<~TEXT, | ||
| You are a highly skilled linguist and web programmer, with expertise in many languages, and very well versed in HTML. | ||
| 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. | ||
| The text will contain html tags, which must absolutely be preserved in the translation. | ||
| Maintain proper grammar, spelling, and punctuation in the translated version. | ||
| Wrap the translated text in a <translation> tag. | ||
| TEXT | ||
| messages: [{ type: :user, content: text_to_translate, id: "user" }], | ||
| ).and_call_original | ||
|
|
||
| described_class.new(text_to_translate, target_language).translate | ||
| end | ||
|
|
||
| it "sends the translation prompt to the selected ai helper model" do | ||
| mock_prompt = instance_double(DiscourseAi::Completions::Prompt) | ||
| mock_llm = instance_double(DiscourseAi::Completions::Llm) | ||
|
|
||
| allow(DiscourseAi::Completions::Prompt).to receive(:new).and_return(mock_prompt) | ||
| allow(DiscourseAi::Completions::Llm).to receive(:proxy).with( | ||
| SiteSetting.ai_helper_model, | ||
| ).and_return(mock_llm) | ||
| allow(mock_llm).to receive(:generate).with( | ||
| mock_prompt, | ||
| user: Discourse.system_user, | ||
| feature_name: "translator-translate", | ||
| ) | ||
|
|
||
| described_class.new(text_to_translate, target_language).translate | ||
| end | ||
|
|
||
| it "returns the translation from the llm's response in the translation tag" do | ||
| DiscourseAi::Completions::Llm.with_prepared_responses( | ||
| ["<translation>hur dur hur dur!</translation>"], | ||
| ) do | ||
| expect( | ||
| described_class.new(text_to_translate, target_language).translate, | ||
| ).to eq "hur dur hur dur!" | ||
| end | ||
| end | ||
|
|
||
| it "returns the raw response if the translation tag is not present" do | ||
| DiscourseAi::Completions::Llm.with_prepared_responses(["raw response."]) do | ||
| expect( | ||
| described_class.new(text_to_translate, target_language).translate, | ||
| ).to eq "raw response." | ||
| end | ||
| end | ||
| end | ||
| end |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.