Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: create AI tagging automation (#34587)

Krise470f3df9f2d
diff --git a/plugins/automation/admin/assets/javascripts/admin/components/fields/da-tags-field.gjs b/plugins/automation/admin/assets/javascripts/admin/components/fields/da-tags-field.gjs
index c2eb178bc02..943c628dfc5 100644
--- a/plugins/automation/admin/assets/javascripts/admin/components/fields/da-tags-field.gjs
+++ b/plugins/automation/admin/assets/javascripts/admin/components/fields/da-tags-field.gjs
@@ -25,6 +25,7 @@ export default class TagsField extends BaseField {
<TagChooser
@tags={{readonly @field.metadata.value}}
@everyTag={{true}}
+ @unlimitedTagCount={{true}}
@options={{hash allowAny=false [email protected]}}
@onChange={{this.onChangeTags}}
/>
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index 0cefa5ce54e..0d471b2df92 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -177,6 +177,35 @@ en:
max_output_tokens:
label: "Max output tokens"
description: "When specified, sets an upper bound to the maximum number of tokens the model can generate. Respects LLM's max output tokens limit"
+ llm_tagger:
+ tag_mode:
+ manual: "Use specific tag list (configured below)"
+ discover: "Let AI discover and use any site tags"
+ fields:
+ tagger_persona:
+ label: "AI Persona"
+ description: "The AI persona to use for analyzing and tagging posts"
+ tag_mode:
+ label: "Tag Selection Mode"
+ description: "Choose how the AI selects tags"
+ available_tags:
+ label: "Available Tags"
+ description: "Tags that the AI can choose from (only used in manual mode)"
+ confidence_threshold:
+ label: "Confidence Threshold"
+ description: "Minimum confidence level (0.0-1.0) required to apply suggested tags"
+ max_tags_per_post:
+ label: "Maximum Tags Per Post"
+ description: "Maximum number of tags that can be applied to a single post"
+ max_post_tokens:
+ label: "Maximum Post Tokens"
+ description: "Maximum number of tokens from the post content to analyze"
+ allow_restricted_tags:
+ label: "Allow Restricted Tags"
+ description: "Allow AI to suggest and apply tags with restricted permissions or visibility."
+ max_posts_for_context:
+ label: "Maximum Posts for Context"
+ description: "Maximum number of posts from the topic to include for analysis context (default: 5)"
discourse_ai:
title: "AI"
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index 19fdbbe8e3f..94f178d31c8 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -23,6 +23,9 @@ en:
llm_report:
title: Periodic report using AI
description: "Periodic report based on a large language model"
+ llm_tagger:
+ title: Tag topics using AI
+ description: "Automatically tag topics using AI"
site_settings:
discourse_ai_enabled: "Enable the discourse AI plugin."
ai_default_llm_model: "The default LLM model to use for all AI features"
diff --git a/plugins/discourse-ai/discourse_automation/llm_tagger.rb b/plugins/discourse-ai/discourse_automation/llm_tagger.rb
new file mode 100644
index 00000000000..06c1c5ab765
--- /dev/null
+++ b/plugins/discourse-ai/discourse_automation/llm_tagger.rb
@@ -0,0 +1,133 @@
+# frozen_string_literal: true
+
+if defined?(DiscourseAutomation)
+ DiscourseAutomation::Scriptable.add("llm_tagger") do
+ version 1
+ run_in_background
+
+ placeholder :post
+
+ triggerables %i[post_created_edited]
+
+ field :tagger_persona,
+ component: :choices,
+ required: true,
+ extra: {
+ content:
+ DiscourseAi::Automation.available_persona_choices(
+ require_user: false,
+ require_default_llm: true,
+ ),
+ }
+
+ field :tag_mode,
+ component: :choices,
+ required: true,
+ default: "manual",
+ extra: {
+ content: [
+ {
+ id: "manual",
+ name: "js.discourse_automation.scriptables.llm_tagger.tag_mode.manual",
+ },
+ {
+ id: "discover",
+ name: "js.discourse_automation.scriptables.llm_tagger.tag_mode.discover",
+ },
+ ],
+ }
+
+ # Available tags only used when tag_mode is "manual"
+ field :available_tags, component: :tags, required: false
+
+ field :confidence_threshold, component: :text, default: "0.7"
+
+ field :max_tags_per_post, component: :text, default: "3"
+
+ field :max_post_tokens, component: :text, default: "4000"
+
+ field :allow_restricted_tags, component: :boolean, default: false
+
+ field :max_posts_for_context, component: :text, default: "5"
+
+ script do |context, fields|
+ post = context["post"]
+ next if post&.user&.bot?
+
+ next if post.post_number != 1
+
+ next if post.topic.custom_fields["llm_tagger_processed"]
+
+ # Skip if tags were manually edited in the most recent revision
+ if post.version > 1
+ latest_revision = post.post_revisions.order(:number).last
+ next if latest_revision&.modifications&.has_key?("tags")
+ end
+
+ tagger_persona_id = fields.dig("tagger_persona", "value")
+ tag_mode = fields.dig("tag_mode", "value") || "manual"
+ manual_tags = fields.dig("available_tags", "value") || []
+ confidence_threshold = fields.dig("confidence_threshold", "value").to_f
+ max_tags = fields.dig("max_tags_per_post", "value").to_i
+ max_post_tokens = fields.dig("max_post_tokens", "value").to_i
+ allow_restricted_tags = fields.dig("allow_restricted_tags", "value") || false
+ max_posts_for_context = fields.dig("max_posts_for_context", "value").to_i
+
+ confidence_threshold = 0.7 if confidence_threshold <= 0
+ max_tags = 3 if max_tags <= 0
+ max_post_tokens = 4000 if max_post_tokens <= 0
+ max_posts_for_context = 5 if max_posts_for_context <= 0
+
+ # Skip if manual mode but no tags configured
+ if tag_mode == "manual"
+ next if manual_tags.empty?
+ end
+
+ begin
+ per_post_limiter =
+ RateLimiter.new(
+ Discourse.system_user,
+ "llm_tagger_#{post.id}",
+ 3, # max 3 per post per minute
+ 1.minute,
+ )
+
+ global_limiter =
+ RateLimiter.new(
+ Discourse.system_user,
+ "llm_tagger",
+ 30, # max 30 per minute globally
+ 1.minute,
+ )
+
+ # Check if we can perform the action before proceeding
+ next unless per_post_limiter.can_perform? && global_limiter.can_perform?
+
+ # Only perform the rate limiting if we're going to proceed
+ per_post_limiter.performed!
+ global_limiter.performed!
+
+ DiscourseAi::Automation::LlmTagger.handle(
+ post: post,
+ tagger_persona_id: tagger_persona_id,
+ tag_mode: tag_mode,
+ available_tags: manual_tags,
+ confidence_threshold: confidence_threshold,
+ max_tags: max_tags,
+ max_post_tokens: max_post_tokens,
+ allow_restricted_tags: allow_restricted_tags,
+ max_posts_for_context: max_posts_for_context,
+ automation: self.automation,
+ )
+
+ post.topic.custom_fields["llm_tagger_processed"] = true
+ post.topic.save_custom_fields
+ rescue => e
+ Discourse.warn_exception(
+ e,
+ message: "llm_tagger: failed to process post #{post.id} #{post.url}",
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/automation/llm_tagger.rb b/plugins/discourse-ai/lib/automation/llm_tagger.rb
new file mode 100644
index 00000000000..03a02e5dbc9
--- /dev/null
+++ b/plugins/discourse-ai/lib/automation/llm_tagger.rb
@@ -0,0 +1,190 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Automation
+ module LlmTagger
+ def self.handle(
+ post:,
+ tagger_persona_id:,
+ tag_mode: "manual",
+ available_tags: [],
+ confidence_threshold:,
+ max_tags:,
+ max_post_tokens:,
+ allow_restricted_tags: false,
+ max_posts_for_context: 5,
+ automation: nil
+ )
+ # Skip if manual mode but no tags provided
+ return if tag_mode == "manual" && available_tags.empty?
+
+ tagger_persona = AiPersona.find(tagger_persona_id)
+ model_id = tagger_persona.default_llm_id || SiteSetting.ai_default_llm_model
+ return if model_id.blank?
+ model = LlmModel.find(model_id)
+
+ topic_posts = post.topic.posts.order(:post_number).limit(max_posts_for_context)
+ posts_content = topic_posts.map { |p| "Post #{p.post_number}: #{p.raw}" }.join("\n\n")
+
+ if tag_mode == "manual"
+ # Manual mode: provide specific tag list in prompt
+ available_tags_text = "Available tags: #{available_tags.join(", ")}\n\n"
+ input =
+ "#{available_tags_text}Topic to analyze:\ntitle: #{post.topic.title}\n\n#{posts_content}"
+ else
+ # Discover mode: instruct AI to use list_tags tool
+ input =
+ "Topic to analyze:\ntitle: #{post.topic.title}\n\n#{posts_content}\n\nUse the list_tags tool to see available tags, then suggest appropriate ones."
+ end
+
+ if max_post_tokens.present?
+ input =
+ model.tokenizer_class.truncate(
+ input,
+ max_post_tokens,
+ strict: SiteSetting.ai_strict_token_counting,
+ )
+ end
+
+ all_upload_ids = topic_posts.flat_map(&:upload_ids).compact.uniq
+ if all_upload_ids.present?
+ input = [input]
+ input.concat(all_upload_ids.map { |upload_id| { upload_id: upload_id } })
+ end
+
+ bot =
+ DiscourseAi::Personas::Bot.as(
+ Discourse.system_user,
+ persona: tagger_persona.class_instance.new,
+ model: model,
+ )
+
+ persona_response_format = tagger_persona.response_format
+
+ bot_ctx =
+ DiscourseAi::Personas::BotContext.new(
+ user: Discourse.system_user,
+ skip_tool_details: true,
+ feature_name: "llm_tagger",
+ messages: [{ type: :user, content: input }],
+ )
+
+ llm_args = {
+ feature_context: {
+ automation_id: automation&.id,
+ automation_name: automation&.name,
+ },
+ }
+
+ llm_args[:response_format] = persona_response_format if persona_response_format.present?
+
+ result = +""
+ bot.reply(bot_ctx, llm_args: llm_args) do |partial, _, type|
+ if type == :structured_output
+ result = partial.to_s
+ elsif type.blank?
+ result << partial
+ end
+ end
+
+ begin
+ response = JSON.parse(result)
+ suggested_tags = response["tags"] || []
+ confidence = response["confidence"] || 0.0
+
+ return if confidence < confidence_threshold
+
+ if tag_mode == "manual"
+ # Manual mode: validate against configured tag list
+ valid_tags = suggested_tags.select { |tag| available_tags.include?(tag) }
+ else
+ # Discover mode: validate against site tags (with safe caching)
+ cache_key =
+ (
+ if allow_restricted_tags
+ "discourse_ai_all_tag_names"
+ else
+ "discourse_ai_visible_tag_names"
+ end
+ )
+ all_site_tags =
+ begin
+ Rails
+ .cache
+ .fetch(cache_key, expires_in: 30.minutes) do
+ if allow_restricted_tags
+ Tag.order(public_topic_count: :desc).limit(300).pluck(:name)
+ else
+ # Use anonymous user guardian to respect tag restrictions
+ DiscourseTagging
+ .visible_tags(Guardian.new)
+ .order(public_topic_count: :desc)
+ .limit(300)
+ .pluck(:name)
+ end
+ end
+ rescue => e
+ # Fallback to direct query if cache fails
+ Rails.logger.warn("llm_tagger: Cache failed (#{e.message}), using direct query")
+ if allow_restricted_tags
+ Tag.order(public_topic_count: :desc).limit(300).pluck(:name)
+ else
+ # Use anonymous user guardian to respect tag restrictions
+ DiscourseTagging
+ .visible_tags(Guardian.new)
+ .order(public_topic_count: :desc)
+ .limit(300)
+ .pluck(:name)
+ end
+ end
+ valid_tags = suggested_tags.select { |tag| all_site_tags.include?(tag) }
+ end
+ valid_tags = valid_tags.first(max_tags)
+
+ if valid_tags.present?
+ existing_tag_count = post.topic.tags.count
+ site_max_tags = SiteSetting.max_tags_per_topic
+ available_slots = site_max_tags - existing_tag_count
+
+ if available_slots > 0
+ # Only take as many tags as we have slots for
+ tags_to_add = valid_tags.first(available_slots)
+ apply_tags_to_topic(post.topic, tags_to_add)
+
+ Rails.logger.debug(
+ "llm_tagger: Applied tags #{tags_to_add.inspect} to topic #{post.topic.id} " \
+ "with confidence #{confidence}",
+ )
+ else
+ end
+ end
+ rescue JSON::ParserError => e
+ Rails.logger.warn(
+ "llm_tagger: Failed to parse JSON response for post #{post.id}: #{e.message}. " \
+ "Response was: #{result.truncate(500)}",
+ )
+ end
+ end
+
+ private
+
+ def self.apply_tags_to_topic(topic, new_tags)
+ return unless SiteSetting.tagging_enabled?
+
+ existing_tags = topic.tags.map(&:name)
+
+ tags_to_add = new_tags - existing_tags
+ return if tags_to_add.empty?
+
+ all_tags = existing_tags + tags_to_add
+
+ first_post = topic.posts.where(post_number: 1).first
+ return unless first_post
+
+ changes = { tags: all_tags, bypass_bump: true, skip_validations: true }
+
+ first_post.revise(Discourse.system_user, changes)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/plugin.rb b/plugins/discourse-ai/plugin.rb
index 3095704b7e9..5dc2d014aff 100644
--- a/plugins/discourse-ai/plugin.rb
+++ b/plugins/discourse-ai/plugin.rb
@@ -80,6 +80,7 @@ after_initialize do
require_relative "discourse_automation/llm_report"
require_relative "discourse_automation/llm_tool_triage"
require_relative "discourse_automation/llm_persona_triage"
+ require_relative "discourse_automation/llm_tagger"
add_admin_route("discourse_ai.title", "discourse-ai", { use_new_show_route: true })
diff --git a/plugins/discourse-ai/spec/lib/automation/llm_tagger_spec.rb b/plugins/discourse-ai/spec/lib/automation/llm_tagger_spec.rb
new file mode 100644
index 00000000000..4b8413f8887
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/automation/llm_tagger_spec.rb
@@ -0,0 +1,361 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::Automation::LlmTagger do
+ fab!(:user)
+ fab!(:topic) { Fabricate(:topic, user: user) }
+ fab!(:post) { Fabricate(:post, topic: topic, user: user, post_number: 1) }
+ fab!(:ai_persona)
+ fab!(:llm_model)
+
+ before do
+ enable_current_plugin
+ SiteSetting.tagging_enabled = true
+ ai_persona.update!(default_llm: llm_model)
+
+ Fabricate(:tag, name: "bug")
+ Fabricate(:tag, name: "feature")
+ Fabricate(:tag, name: "question")
+ end
+
+ describe ".handle" do
+ let(:available_tags) { %w[bug feature question] }
+
+ before do
+ Tag.find_by(name: "bug")&.update!(public_topic_count: 5)
+ Tag.find_by(name: "feature")&.update!(public_topic_count: 3)
+ Tag.find_by(name: "question")&.update!(public_topic_count: 1)
+ end
+
+ it "processes a post and applies appropriate tags" do
+ mock_response = { "tags" => ["bug"], "confidence" => 0.9 }.to_json
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([mock_response]) do
+ described_class.handle(
+ post: post,
+ tagger_persona_id: ai_persona.id,
+ available_tags: available_tags,
+ confidence_threshold: 0.7,
+ max_tags: 3,
+ max_post_tokens: 4000,
+ allow_restricted_tags: false,
+ max_posts_for_context: 5,
+ )
+ end
+
+ expect(topic.reload.tags.map(&:name)).to include("bug")
+ end
+
+ it "respects confidence threshold" do
+ mock_response = { "tags" => ["bug"], "confidence" => 0.5 }.to_json
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([mock_response]) do
+ described_class.handle(
+ post: post,
+ tagger_persona_id: ai_persona.id,
+ available_tags: available_tags,
+ confidence_threshold: 0.7,
+ max_tags: 3,
+ max_post_tokens: 4000,
+ allow_restricted_tags: false,
+ max_posts_for_context: 5,
+ )
+ end
+
+ expect(topic.reload.tags).to be_empty
+ end
+
+ it "filters out invalid tags" do
+ mock_response = { "tags" => %w[bug invalid_tag], "confidence" => 0.9 }.to_json
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([mock_response]) do
+ described_class.handle(
+ post: post,
+ tagger_persona_id: ai_persona.id,
+ available_tags: available_tags,
+ confidence_threshold: 0.7,
+ max_tags: 3,
+ max_post_tokens: 4000,
+ allow_restricted_tags: false,
+ max_posts_for_context: 5,
+ )
+ end
+
+ tags = topic.reload.tags.map(&:name)
+ expect(tags).to include("bug")
+ expect(tags).not_to include("invalid_tag")
+ end
+
+ it "respects max tags limit" do
+ mock_response = { "tags" => %w[bug feature question extra], "confidence" => 0.9 }.to_json
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([mock_response]) do
+ described_class.handle(
+ post: post,
+ tagger_persona_id: ai_persona.id,
+ available_tags: available_tags,
+ confidence_threshold: 0.7,
+ max_tags: 2,
+ max_post_tokens: 4000,
+ )
+ end
+
+ expect(topic.reload.tags.count).to eq(2)
+ end
+
+ it "handles malformed JSON gracefully" do
+ allow(Rails.logger).to receive(:warn)
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(["invalid json"]) do
+ described_class.handle(
+ post: post,
+ tagger_persona_id: ai_persona.id,
+ available_tags: available_tags,
+ confidence_threshold: 0.7,
+ max_tags: 3,
+ max_post_tokens: 4000,
+ allow_restricted_tags: false,
+ max_posts_for_context: 5,
+ )
+ end
+
+ expect(Rails.logger).to have_received(:warn).with(/Failed to parse JSON response/)
+ expect(topic.reload.tags).to be_empty
+ end
+
+ describe "discover mode" do
+ it "processes a post using discover mode with all site tags" do
+ mock_response = { "tags" => ["feature"], "confidence" => 0.8 }.to_json
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([mock_response]) do
+ described_class.handle(
+ post: post,
+ tagger_persona_id: ai_persona.id,
+ tag_mode: "discover",
+ available_tags: [],
+ confidence_threshold: 0.7,
+ max_tags: 3,
+ max_post_tokens: 4000,
+ allow_restricted_tags: false,
+ )
+ end
+
+ expect(topic.reload.tags.map(&:name)).to include("feature")
+ end
+
+ it "validates against all site tags in discover mode" do
+ # Create an additional tag that's not in manual list
+ Fabricate(:tag, name: "discovery", public_topic_count: 2)
+
+ mock_response = { "tags" => ["discovery"], "confidence" => 0.8 }.to_json
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([mock_response]) do
+ described_class.handle(
+ post: post,
+ tagger_persona_id: ai_persona.id,
+ tag_mode: "discover",
+ available_tags: %w[bug feature], # discovery tag not in this list
+ confidence_threshold: 0.7,
+ max_tags: 3,
+ max_post_tokens: 4000,
+ allow_restricted_tags: false,
+ )
+ end
+
+ expect(topic.reload.tags.map(&:name)).to include("discovery")
+ end
+
+ it "filters out invalid tags in discover mode" do
+ mock_response = { "tags" => %w[feature nonexistent_tag], "confidence" => 0.8 }.to_json
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([mock_response]) do
+ described_class.handle(
+ post: post,
+ tagger_persona_id: ai_persona.id,
+ tag_mode: "discover",
+ available_tags: [],
+ confidence_threshold: 0.7,
+ max_tags: 3,
+ max_post_tokens: 4000,
+ allow_restricted_tags: false,
+ )
+ end
+
+ tags = topic.reload.tags.map(&:name)
+ expect(tags).to include("feature")
+ expect(tags).not_to include("nonexistent_tag")
+ end
+
+ it "handles cache errors in discover mode" do
+ allow(Rails.cache).to receive(:fetch).and_raise(StandardError.new("Cache error"))
+ allow(Rails.logger).to receive(:warn)
+
+ mock_response = { "tags" => ["bug"], "confidence" => 0.8 }.to_json
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([mock_response]) do
+ described_class.handle(
+ post: post,
+ tagger_persona_id: ai_persona.id,
+ tag_mode: "discover",
+ available_tags: [],
+ confidence_threshold: 0.7,
+ max_tags: 3,
+ max_post_tokens: 4000,
+ allow_restricted_tags: false,
+ )
+ end
+
+ expect(Rails.logger).to have_received(:warn).with(/Cache failed.*using direct query/)
+ expect(topic.reload.tags.map(&:name)).to include("bug")
+ end
+
+ context "with restricted tags" do
+ fab!(:staff_group) { Group.find(Group::AUTO_GROUPS[:staff]) }
+ fab!(:restricted_tag_group) { Fabricate(:tag_group, name: "Staff Only Tags") }
+ fab!(:restricted_tag) { Fabricate(:tag, name: "restricted") }
+
+ before do
+ restricted_tag_group.tags = [restricted_tag]
+ restricted_tag_group.save!
+
+ restricted_tag_group.permissions = [
+ [staff_group, TagGroupPermission.permission_types[:full]],
+ ]
+ restricted_tag_group.save!
+ end
+
+ it "excludes restricted tags when allow_restricted_tags is false" do
+ mock_response = { "tags" => ["restricted"], "confidence" => 0.8 }.to_json
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([mock_response]) do
+ described_class.handle(
+ post: post,
+ tagger_persona_id: ai_persona.id,
+ tag_mode: "discover",
+ available_tags: [],
+ confidence_threshold: 0.7,
+ max_tags: 3,
+ max_post_tokens: 4000,
+ allow_restricted_tags: false,
+ )
+ end
+
+ expect(topic.reload.tags.map(&:name)).not_to include("restricted")
+ end
+
+ it "includes restricted tags when allow_restricted_tags is true" do
+ mock_response = { "tags" => ["restricted"], "confidence" => 0.8 }.to_json
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([mock_response]) do
+ described_class.handle(
+ post: post,
+ tagger_persona_id: ai_persona.id,
+ tag_mode: "discover",
+ available_tags: [],
+ confidence_threshold: 0.7,
+ max_tags: 3,
+ max_post_tokens: 4000,
+ allow_restricted_tags: true,
+ max_posts_for_context: 5,
+ )
+ end
+
+ expect(topic.reload.tags.map(&:name)).to include("restricted")
+ end
+ end
+ end
+
+ describe "tag mode selection" do
+ it "uses manual mode by default" do
+ mock_response = { "tags" => ["bug"], "confidence" => 0.8 }.to_json
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([mock_response]) do
+ described_class.handle(
+ post: post,
+ tagger_persona_id: ai_persona.id,
+ available_tags: available_tags,
+ confidence_threshold: 0.7,
+ max_tags: 3,
+ max_post_tokens: 4000,
+ )
+ end
+
+ expect(topic.reload.tags.map(&:name)).to include("bug")
+ end
+
+ it "skips processing when manual mode has no available tags" do
+ described_class.handle(
+ post: post,
+ tagger_persona_id: ai_persona.id,
+ tag_mode: "manual",
+ available_tags: [],
+ confidence_threshold: 0.7,
+ max_tags: 3,
+ max_post_tokens: 4000,
+ allow_restricted_tags: false,
+ max_posts_for_context: 5,
+ )
+
+ expect(topic.reload.tags).to be_empty
+ end
+ end
+
+ describe "multi-post context" do
+ let!(:reply_post1) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ post_number: 2,
+ raw: "This is about features and performance",
+ )
+ end
+ let!(:reply_post2) do
+ Fabricate(
+ :post,
+ topic: topic,
+ user: user,
+ post_number: 3,
+ raw: "Definitely a bug report here",
+ )
+ end
+
+ it "includes multiple posts for context when max_posts_for_context > 1" do
+ mock_response = { "tags" => %w[bug feature], "confidence" => 0.9 }.to_json
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([mock_response]) do
+ described_class.handle(
+ post: post,
+ tagger_persona_id: ai_persona.id,
+ available_tags: available_tags,
+ confidence_threshold: 0.7,
+ max_tags: 3,
+ max_post_tokens: 4000,
+ allow_restricted_tags: false,
+ max_posts_for_context: 3,
+ )
+ end
+
+ expect(topic.reload.tags.map(&:name)).to include("bug", "feature")
+ end
+
+ it "limits context to max_posts_for_context setting" do
+ mock_response = { "tags" => ["question"], "confidence" => 0.8 }.to_json
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([mock_response]) do
+ described_class.handle(
+ post: post,
+ tagger_persona_id: ai_persona.id,
+ available_tags: available_tags,
+ confidence_threshold: 0.7,
+ max_tags: 3,
+ max_post_tokens: 4000,
+ allow_restricted_tags: false,
+ max_posts_for_context: 1,
+ )
+ end
+
+ expect(topic.reload.tags.map(&:name)).to include("question")
+ end
+ end
+ end
+end