A platform for community discussion. Free, open, simple.
FEATURE: Add reasoning to spam detection (#36431)
Rafael dos Santos Silva0e465acb3d2c
diff --git a/plugins/discourse-ai/app/models/ai_spam_log.rb b/plugins/discourse-ai/app/models/ai_spam_log.rbindex 242e4b29a09..03e57669dcc 100644--- a/plugins/discourse-ai/app/models/ai_spam_log.rb+++ b/plugins/discourse-ai/app/models/ai_spam_log.rb@@ -20,6 +20,7 @@ end# created_at :datetime not null# updated_at :datetime not null# error :string(3000)+# reason :text## Indexes#diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/spam-test-modal.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/spam-test-modal.gjsindex 88143cef8d1..97311fe4e43 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/spam-test-modal.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/spam-test-modal.gjs@@ -15,8 +15,12 @@ export default class SpamTestModal extends Component {@tracked testResult;@tracked isLoading = false;@tracked postUrl = "";- @tracked scanLog = "";@tracked isSpam;+ @tracked reason;+ @tracked llmName;+ @tracked systemPrompt;+ @tracked sentMessage;+ @tracked scanHistory;@actionasync runTest() {@@ -38,7 +42,11 @@ export default class SpamTestModal extends Component {this.testResult = response.is_spam? i18n("discourse_ai.spam.test_modal.spam"): i18n("discourse_ai.spam.test_modal.not_spam");- this.scanLog = response.log;+ this.reason = response.reason;+ this.llmName = response.llm_name;+ this.systemPrompt = response.system_prompt;+ this.sentMessage = response.sent_message;+ this.scanHistory = response.scan_history;} catch (error) {popupAjaxError(error);} finally {@@ -66,18 +74,78 @@ export default class SpamTestModal extends Component {</div>{{#if this.testResult}}- <div class="spam-test-modal__test-result">- <h3>{{i18n "discourse_ai.spam.test_modal.result"}}</h3>+ <div class="spam-test-modal__results"><divclass="spam-test-modal__verdict{{if this.isSpam 'is-spam' 'not-spam'}}">{{this.testResult}}</div>- {{#if this.scanLog}}- <div class="spam-test-modal__log">- <h4>{{i18n "discourse_ai.spam.test_modal.scan_log"}}</h4>- <pre>{{this.scanLog}}</pre>++ {{#if this.reason}}+ <div+ class="spam-test-modal__info-box spam-test-modal__info-box--reason"+ >+ <h4 class="spam-test-modal__info-box-title">{{i18n+ "discourse_ai.spam.test_modal.reason"+ }}</h4>+ <div class="spam-test-modal__info-box-content">+ <p>{{this.reason}}</p>+ </div>+ </div>+ {{/if}}++ <div class="spam-test-modal__info-grid">+ {{#if this.llmName}}+ <div+ class="spam-test-modal__info-box spam-test-modal__info-box--llm"+ >+ <h4 class="spam-test-modal__info-box-title">{{i18n+ "discourse_ai.spam.test_modal.llm"+ }}</h4>+ <div class="spam-test-modal__info-box-content">+ {{this.llmName}}+ </div>+ </div>+ {{/if}}++ {{#if this.scanHistory}}+ <div+ class="spam-test-modal__info-box spam-test-modal__info-box--history"+ >+ <h4 class="spam-test-modal__info-box-title">{{i18n+ "discourse_ai.spam.test_modal.scan_history"+ }}</h4>+ <div class="spam-test-modal__info-box-content">+ <pre>{{this.scanHistory}}</pre>+ </div>+ </div>+ {{/if}}+ </div>++ {{#if this.sentMessage}}+ <div+ class="spam-test-modal__info-box spam-test-modal__info-box--message"+ >+ <h4 class="spam-test-modal__info-box-title">{{i18n+ "discourse_ai.spam.test_modal.sent_message"+ }}</h4>+ <div class="spam-test-modal__info-box-content">+ <pre>{{this.sentMessage}}</pre>+ </div>+ </div>+ {{/if}}++ {{#if this.systemPrompt}}+ <div+ class="spam-test-modal__info-box spam-test-modal__info-box--prompt"+ >+ <h4 class="spam-test-modal__info-box-title">{{i18n+ "discourse_ai.spam.test_modal.system_prompt"+ }}</h4>+ <div class="spam-test-modal__info-box-content">+ <pre>{{this.systemPrompt}}</pre>+ </div></div>{{/if}}</div>diff --git a/plugins/discourse-ai/assets/stylesheets/modules/llms/common/spam.scss b/plugins/discourse-ai/assets/stylesheets/modules/llms/common/spam.scssindex 4c638007dca..e8009419ed0 100644--- a/plugins/discourse-ai/assets/stylesheets/modules/llms/common/spam.scss+++ b/plugins/discourse-ai/assets/stylesheets/modules/llms/common/spam.scss@@ -63,45 +63,100 @@.spam-test-modal {&__body {- min-width: 500px;+ min-width: 600px;+ max-width: 800px;}- &__test-result {+ &__results {margin-top: 1.5em;- padding-top: 1.5em;- border-top: 1px solid var(--primary-low);}&__verdict {font-size: var(--font-up-2);font-weight: bold;- padding: 0.5em;- border-radius: 0.25em;+ padding: 0.75em;+ border-radius: 6px;text-align: center;- margin: 1em 0;+ margin-bottom: 1.5em;&.is-spam {background: var(--danger-low);color: var(--danger);+ border: 2px solid var(--danger-medium);}&.not-spam {background: var(--success-low);color: var(--success);+ border: 2px solid var(--success-medium);}}- &__log {- margin-top: 1em;+ &__info-box {+ background: var(--primary-very-low);+ border: 1px solid var(--primary-low);+ border-radius: 6px;+ margin-bottom: 1em;+ overflow: hidden;++ &--reason {+ background: var(--highlight-bg);+ border-color: var(--tertiary-low);+ }+ }++ &__info-box-title {+ margin: 0;+ padding: 0.75em 1em;+ background: var(--primary-low);+ font-size: var(--font-0);+ font-weight: 600;+ border-bottom: 1px solid var(--primary-low);+ color: var(--primary-high);+ }++ &__info-box-content {+ padding: 1em;+ max-height: 200px;+ overflow-y: auto;+ overflow-x: hidden;++ p {+ margin: 0;+ line-height: 1.5;+ }pre {- max-height: 300px;- overflow-y: auto;- background: var(--primary-very-low);- padding: 1em;- margin: 0.5em 0;- font-family: monospace;+ margin: 0;+ padding: 0;+ background: none;+ font-family: var(--font-family-monospace);+ font-size: var(--font-down-1);white-space: pre-wrap;+ overflow-wrap: break-word;+ line-height: 1.4;}}++ &__info-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));+ gap: 1em;+ margin-bottom: 1em;+ }++ &__info-box--llm &__info-box-content {+ max-height: 60px;+ font-weight: 500;+ color: var(--primary-high);+ }++ &__info-box--history &__info-box-content {+ max-height: 150px;+ }++ &__info-box--message &__info-box-content,+ &__info-box--prompt &__info-box-content {+ max-height: 250px;+ }}diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex 6f2c29f5c7a..f061ece86ea 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -398,6 +398,11 @@ en:post_url_label: "Post URL or ID"post_url_placeholder: "https://your-forum.com/t/topic/123/4 or post ID"result: "Result"+ reason: "Reasoning"+ llm: "LLM"+ scan_history: "Scan History"+ sent_message: "Sent Message"+ system_prompt: "System Prompt"scan_log: "Scan log"run: "Run test"spam: "Spam"diff --git a/plugins/discourse-ai/db/migrate/20251203180046_add_reason_to_ai_spam_logs.rb b/plugins/discourse-ai/db/migrate/20251203180046_add_reason_to_ai_spam_logs.rbnew file mode 100644index 00000000000..ad7ed46e375--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20251203180046_add_reason_to_ai_spam_logs.rb@@ -0,0 +1,6 @@+# frozen_string_literal: true+class AddReasonToAiSpamLogs < ActiveRecord::Migration[8.0]+ def change+ add_column :ai_spam_logs, :reason, :text+ end+enddiff --git a/plugins/discourse-ai/lib/ai_moderation/spam_scanner.rb b/plugins/discourse-ai/lib/ai_moderation/spam_scanner.rbindex 25cd30fef6e..3b35fbd090d 100644--- a/plugins/discourse-ai/lib/ai_moderation/spam_scanner.rb+++ b/plugins/discourse-ai/lib/ai_moderation/spam_scanner.rb@@ -171,22 +171,14 @@ module DiscourseAi.limit(100).each do |log|history ||= +"Scan History:\n"- history << "date: #{log.created_at} is_spam: #{log.is_spam}\n"+ history << "date: #{log.created_at} is_spam: #{log.is_spam}"+ history << " reason: #{log.reason}" if log.reason.present?+ history << "\n"end- log = +"Scanning #{post.url}\n\n"-- if history- log << history- log << "\n"- end-used_llm = bot.model- log << "LLM: #{used_llm.name}\n\n"-spam_persona = bot.personaused_prompt = spam_persona.craft_prompt(ctx, llm: used_llm).system_message_text- log << "System Prompt: #{used_prompt}\n\n"text_content =if target_msg[:content].is_a?(Array)@@ -195,30 +187,18 @@ module DiscourseAitarget_msg[:content]end- log << "Context: #{text_content}\n\n"-is_spam = is_spam?(structured_output)-- reasoning_insts = {- type: :user,- content: "Don't return a JSON this time. Explain your reasoning in plain text.",+ reasoning = extract_reason(structured_output)++ {+ is_spam: is_spam,+ reason: reasoning,+ llm_name: used_llm.name,+ system_prompt: used_prompt,+ sent_message: text_content,+ scan_history: history,+ post_url: post.url,}- ctx.messages = [- target_msg,- { type: :model, content: { spam: is_spam }.to_json },- reasoning_insts,- ]- ctx.bypass_response_format = true-- reasoning = +""-- bot.reply(ctx, llm_args: llm_args.merge(max_tokens: 100)) do |partial, _, type|- reasoning << partial if type.blank?- end-- log << "#{reasoning.strip}"-- { is_spam: is_spam, log: log }enddef self.perform_scan(post)@@ -255,6 +235,7 @@ module DiscourseAiendis_spam = is_spam?(structured_output)+ reason = extract_reason(structured_output)log = AiApiAuditLog.order(id: :desc).where(feature_name: "spam_detection").firsttext_content =@@ -271,6 +252,7 @@ module DiscourseAiai_api_audit_log: log,is_spam: is_spam,payload: text_content,+ reason: reason,)handle_spam(post, log) if is_spamend@@ -331,6 +313,11 @@ module DiscourseAistructured_output.present? && structured_output.read_buffered_property(:spam)end+ def self.extract_reason(structured_output)+ return nil if structured_output.blank?+ structured_output.read_buffered_property(:reason)+ end+def self.build_target_content_msg(post, topic = nil)topic ||= post.topiccontext = []diff --git a/plugins/discourse-ai/lib/personas/spam_detector.rb b/plugins/discourse-ai/lib/personas/spam_detector.rbindex 3df11d3ef35..c87b7808d56 100644--- a/plugins/discourse-ai/lib/personas/spam_detector.rb+++ b/plugins/discourse-ai/lib/personas/spam_detector.rb@@ -44,19 +44,21 @@ module DiscourseAi- Site description: {site_description}- Site top 10 categories: {top_categories}- Format your response as a JSON object with a one key named "spam", which is a boolean that indicates if a post is spam or legitimate.+ Format your response as a JSON object with two keys:+ 1. "spam": a boolean that indicates if a post is spam (true) or legitimate (false)+ 2. "reason": a brief explanation (1-2 sentences) of why you classified it this way+Your output should be in the following format:- {"spam": xx}+ {"spam": xx, "reason": "explanation here"}- Where xx is true if the post is spam, or false if it's legitimate.- reply with valid JSON only+ Reply with valid JSON onlyPROMPTenddef response_format- [{ "key" => "spam", "type" => "boolean" }]+ [{ "key" => "spam", "type" => "boolean" }, { "key" => "reason", "type" => "string" }]endendenddiff --git a/plugins/discourse-ai/spec/lib/modules/ai_moderation/spam_scanner_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_moderation/spam_scanner_spec.rbindex e0b4c1060aa..3f4bb89c0d2 100644--- a/plugins/discourse-ai/spec/lib/modules/ai_moderation/spam_scanner_spec.rb+++ b/plugins/discourse-ai/spec/lib/modules/ai_moderation/spam_scanner_spec.rb@@ -93,9 +93,9 @@ RSpec.describe DiscourseAi::AiModeration::SpamScanner doit "scans when post should be scanned" doexpect do- DiscourseAi::Completions::Llm.with_prepared_responses(["spam"]) do- described_class.perform_scan!(post)- end+ DiscourseAi::Completions::Llm.with_prepared_responses(+ [{ spam: true, reason: "spam detected" }],+ ) { described_class.perform_scan!(post) }end.to change { AiSpamLog.count }.by(1)endend@@ -103,9 +103,9 @@ RSpec.describe DiscourseAi::AiModeration::SpamScanner dodescribe ".perform_scan!" doit "creates spam log entry when scanning post" doexpect do- DiscourseAi::Completions::Llm.with_prepared_responses(["spam"]) do- described_class.perform_scan!(post)- end+ DiscourseAi::Completions::Llm.with_prepared_responses(+ [{ spam: true, reason: "spam detected" }],+ ) { described_class.perform_scan!(post) }end.to change { AiSpamLog.count }.by(1)end@@ -253,20 +253,20 @@ RSpec.describe DiscourseAi::AiModeration::SpamScanner doprompts = nilresult =DiscourseAi::Completions::Llm.with_prepared_responses(- [true, "the reason is just because"],+ [{ spam: true, reason: "the reason is just because" }],) do |_, _, _prompts|prompts = _promptsdescribed_class.test_post(post, custom_instructions: "123")end- expect(prompts.length).to eq(2)+ expect(prompts.length).to eq(1)expect(result[:is_spam]).to eq(true)- expect(result[:log]).to include("123")- expect(result[:log]).to include("just because")+ expect(result[:system_prompt]).to include("123")+ expect(result[:reason]).to eq("the reason is just because")result =DiscourseAi::Completions::Llm.with_prepared_responses(- [false, "the reason is just because"],+ [{ spam: false, reason: "the reason is just because" }],) do |_, _, _prompts|prompts = _promptsdescribed_class.test_post(post, custom_instructions: "123")@@ -289,7 +289,9 @@ RSpec.describe DiscourseAi::AiModeration::SpamScanner dodescribed_class.new_post(post)prompt = nil- DiscourseAi::Completions::Llm.with_prepared_responses([true]) do |_, _, _prompts|+ DiscourseAi::Completions::Llm.with_prepared_responses(+ [{ spam: true, reason: "spam detected" }],+ ) do |_, _, _prompts|# force a rebake so we actually scanpost.rebake!prompt = _prompts.first@@ -341,7 +343,9 @@ RSpec.describe DiscourseAi::AiModeration::SpamScanner dodescribed_class.new_post(post)- DiscourseAi::Completions::Llm.with_prepared_responses([true]) do |_, _, _prompts|+ DiscourseAi::Completions::Llm.with_prepared_responses(+ [{ spam: true, reason: "spam detected" }],+ ) do |_, _, _prompts|# force a rebake so we actually scanpost.rebake!end@@ -369,7 +373,7 @@ RSpec.describe DiscourseAi::AiModeration::SpamScanner doprompts = nilDiscourseAi::Completions::Llm.with_prepared_responses(- [true, "just because"],+ [{ spam: true, reason: "just because" }],) do |_, _, _prompts|prompts = _promptsdescribed_class.test_post(post)diff --git a/plugins/discourse-ai/spec/requests/admin/ai_spam_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_spam_controller_spec.rbindex 2d84082d346..f8df058dcbc 100644--- a/plugins/discourse-ai/spec/requests/admin/ai_spam_controller_spec.rb+++ b/plugins/discourse-ai/spec/requests/admin/ai_spam_controller_spec.rb@@ -242,7 +242,9 @@ RSpec.describe DiscourseAi::Admin::AiSpamController dollm2 = Fabricate(:llm_model, name: "DiffLLM")- DiscourseAi::Completions::Llm.with_prepared_responses([true, "just because"]) do+ DiscourseAi::Completions::Llm.with_prepared_responses(+ [{ spam: true, reason: "just because" }],+ ) dopost "/admin/plugins/discourse-ai/ai-spam/test.json",params: {post_url: spam_post2.url,@@ -253,12 +255,15 @@ RSpec.describe DiscourseAi::Admin::AiSpamController doexpect(response.status).to eq(200)parsed = response.parsed_body- expect(parsed["log"]).to include(spam_post2.raw)- expect(parsed["log"]).to include("DiffLLM")+ expect(parsed["sent_message"]).to include(spam_post2.raw)+ expect(parsed["llm_name"]).to eq("DiffLLM")+ expect(parsed["reason"]).to eq("just because")endit "can scan using post id" do- DiscourseAi::Completions::Llm.with_prepared_responses([true, "because apples"]) do+ DiscourseAi::Completions::Llm.with_prepared_responses(+ [{ spam: true, reason: "because apples" }],+ ) dopost "/admin/plugins/discourse-ai/ai-spam/test.json",params: {post_url: spam_post.id.to_s,@@ -268,7 +273,8 @@ RSpec.describe DiscourseAi::Admin::AiSpamController doexpect(response.status).to eq(200)parsed = response.parsed_body- expect(parsed["log"]).to include(spam_post.raw)+ expect(parsed["sent_message"]).to include(spam_post.raw)+ expect(parsed["reason"]).to eq("because apples")endit "returns proper spam test results" do@@ -283,7 +289,9 @@ RSpec.describe DiscourseAi::Admin::AiSpamController doAiSpamLog.create!(post: spam_post, llm_model: llm_model, is_spam: true, created_at: 1.day.ago)- DiscourseAi::Completions::Llm.with_prepared_responses([true, "because banana"]) do+ DiscourseAi::Completions::Llm.with_prepared_responses(+ [{ spam: true, reason: "because banana" }],+ ) dopost "/admin/plugins/discourse-ai/ai-spam/test.json",params: {post_url: spam_post.url,@@ -294,11 +302,11 @@ RSpec.describe DiscourseAi::Admin::AiSpamController doexpect(response.status).to eq(200)parsed = response.parsed_body- expect(parsed["log"]).to include("special custom instructions")- expect(parsed["log"]).to include(spam_post.raw)+ expect(parsed["system_prompt"]).to include("special custom instructions")+ expect(parsed["sent_message"]).to include(spam_post.raw)expect(parsed["is_spam"]).to eq(true)- expect(parsed["log"]).to include("Scan History:")- expect(parsed["log"]).to include("banana")+ expect(parsed["scan_history"]).to include("Scan History:")+ expect(parsed["reason"]).to eq("because banana")endend