A platform for community discussion. Free, open, simple.
FEATURE: add configurable age penalty for semantic related topics (#34842)
Rafael dos Santos Silva281d0c3e1177
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex a1a05955a5d..5023cb85970 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -102,6 +102,8 @@ en:ai_embeddings_semantic_search_use_hyde: "Use HyDE for semantic full page search. Uses an LLM to create an hypothetical post from the user search term to help with matches."ai_embeddings_semantic_quick_search_enabled: "Enable semantic search option in search menu popup."ai_embeddings_semantic_related_include_closed_topics: "Include closed topics in semantic search results"+ ai_embeddings_semantic_related_age_penalty: "Apply exponential age penalty to topics in semantic search results. 0.0 = no penalty, 0.3 = gentle bias toward recently active content, 1.0+ = strong recency bias."+ ai_embeddings_semantic_related_age_time_scale: "Time scale in days for age penalty calculation. Topics inactive this many days receive ~50% penalty with penalty=1.0. Use 365 for yearly scale, 90 for quarterly scale."ai_embeddings_semantic_search_hyde_model: "Model used to expand keywords to get better results during a semantic search"ai_embeddings_per_post_enabled: Generate embeddings for each postdiff --git a/plugins/discourse-ai/config/settings.yml b/plugins/discourse-ai/config/settings.ymlindex 33a29b52720..a40641ba1bb 100644--- a/plugins/discourse-ai/config/settings.yml+++ b/plugins/discourse-ai/config/settings.yml@@ -250,6 +250,18 @@ discourse_ai:ai_embeddings_semantic_related_include_closed_topics:default: truearea: "ai-features/embeddings"+ ai_embeddings_semantic_related_age_penalty:+ default: 0.3+ type: float+ min: 0.0+ max: 2.0+ area: "ai-features/embeddings"+ ai_embeddings_semantic_related_age_time_scale:+ default: 365+ type: integer+ min: 1+ max: 3650+ area: "ai-features/embeddings"ai_embeddings_backfill_batch_size:default: 250hidden: truediff --git a/plugins/discourse-ai/lib/embeddings/schema.rb b/plugins/discourse-ai/lib/embeddings/schema.rbindex a43dbbf4c4c..0f37247be96 100644--- a/plugins/discourse-ai/lib/embeddings/schema.rb+++ b/plugins/discourse-ai/lib/embeddings/schema.rb@@ -192,10 +192,13 @@ module DiscourseAiraise MissingEmbeddingErrorend- def symmetric_similarity_search(record)+ def symmetric_similarity_search(record, age_penalty: 0.0)limit = 200before_query = hnsw_search_workaround(limit)+ # For topics table, we can apply age penalty. For other tables, ignore the penalty.+ use_age_penalty = age_penalty > 0.0 && table == TOPICS_TABLE+builder = DB.build(<<~SQL)WITH le_target AS (SELECT@@ -210,10 +213,11 @@ module DiscourseAi)SELECT #{target_column} FROM (SELECT- #{target_column}, embeddings+ #{target_column}, embeddings /*extra_columns*/FROM#{table}/*join*/+ /*extra_join*//*where*/ORDER BYbinary_quantize(embeddings)::bit(#{dimensions}) <~> (@@ -225,7 +229,30 @@ module DiscourseAi)LIMIT #{limit}) AS widenet- ORDER BY+ /*ordering*/+ LIMIT #{limit / 2};+ SQL++ builder.where("model_id = :vid AND strategy_id = :vsid")++ if use_age_penalty+ builder.sql_literal(+ extra_join: "INNER JOIN topics ON topics.id = #{table}.#{target_column}",+ extra_columns: ", topics.bumped_at",+ ordering: <<~SQL,+ ORDER BY+ (embeddings::halfvec(#{dimensions}) #{pg_function} (+ SELECT+ embeddings::halfvec(#{dimensions})+ FROM+ le_target+ LIMIT 1+ )) / POWER(EXTRACT(EPOCH FROM NOW() - bumped_at) / 86400 / :time_scale + 1, :age_penalty)+ SQL+ )+ else+ builder.sql_literal(ordering: <<~SQL)+ ORDER BYembeddings::halfvec(#{dimensions}) #{pg_function} (SELECTembeddings::halfvec(#{dimensions})@@ -233,16 +260,20 @@ module DiscourseAile_targetLIMIT 1)- LIMIT #{limit / 2};- SQL-- builder.where("model_id = :vid AND strategy_id = :vsid")+ SQL+ endyield(builder) if block_given?+ query_params = { vid: vector_def.id, vsid: vector_def.strategy_id, target_id: record.id }+ if use_age_penalty+ query_params[:age_penalty] = age_penalty+ query_params[:time_scale] = SiteSetting.ai_embeddings_semantic_related_age_time_scale+ end+ActiveRecord::Base.transaction doDB.exec(before_query) if before_query.present?- builder.query(vid: vector_def.id, vsid: vector_def.strategy_id, target_id: record.id)+ builder.query(query_params)endrescue PG::Error => eRails.logger.error("Error #{e} querying embeddings for model #{vector_def.display_name}")diff --git a/plugins/discourse-ai/lib/embeddings/semantic_related.rb b/plugins/discourse-ai/lib/embeddings/semantic_related.rbindex 8c0376cc124..efc35cd08ed 100644--- a/plugins/discourse-ai/lib/embeddings/semantic_related.rb+++ b/plugins/discourse-ai/lib/embeddings/semantic_related.rb@@ -21,7 +21,10 @@ module DiscourseAi.fetch(semantic_suggested_key(topic.id), expires_in: cache_for) doDiscourseAi::Embeddings::Schema.for(Topic)- .symmetric_similarity_search(topic)+ .symmetric_similarity_search(+ topic,+ age_penalty: SiteSetting.ai_embeddings_semantic_related_age_penalty,+ ).map(&:topic_id).tap do |candidate_ids|# Happens when the topic doesn't have any embeddings@@ -91,7 +94,7 @@ module DiscourseAiprivatedef semantic_suggested_key(topic_id)- "#{CACHE_PREFIX}#{topic_id}"+ "#{CACHE_PREFIX}#{topic_id}-#{SiteSetting.ai_embeddings_semantic_related_age_penalty}-#{SiteSetting.ai_embeddings_selected_model}-#{SiteSetting.ai_embeddings_semantic_related_age_time_scale}"enddef build_semantic_suggested_key(topic_id)diff --git a/plugins/discourse-ai/spec/lib/modules/embeddings/semantic_related_spec.rb b/plugins/discourse-ai/spec/lib/modules/embeddings/semantic_related_spec.rbindex a28af4f7c7b..b17f069bca3 100644--- a/plugins/discourse-ai/spec/lib/modules/embeddings/semantic_related_spec.rb+++ b/plugins/discourse-ai/spec/lib/modules/embeddings/semantic_related_spec.rb@@ -84,5 +84,67 @@ describe DiscourseAi::Embeddings::SemanticRelated doexpect(results).to eq([])endend++ describe "age penalty functionality" do+ let(:newer_topic) { Fabricate(:topic, bumped_at: 1.day.ago) }+ let(:older_topic) { Fabricate(:topic, bumped_at: 30.days.ago) }++ before do+ SiteSetting.ai_embeddings_semantic_related_age_penalty = 1.5+ SiteSetting.ai_embeddings_semantic_related_age_time_scale = 30 # Use 30 days for more dramatic effect in tests++ # Create embeddings for test topics+ embedding = Array.new(1024) { rand }+ schema = DiscourseAi::Embeddings::Schema.for(Topic)++ [target, newer_topic, older_topic].each do |topic|+ schema.store(topic, embedding, "test_digest_#{topic.id}")+ end++ described_class.clear_cache_for(target)+ end++ it "prioritizes newer topics over older ones with same similarity" do+ # Mock the similarity search to return consistent embeddings for all topics+ allow_any_instance_of(DiscourseAi::Embeddings::Schema).to receive(+ :symmetric_similarity_search,+ ).and_call_original++ results = semantic_related.related_topic_ids_for(target)++ expect(results).to include(newer_topic.id)+ expect(results).to include(older_topic.id)++ # Newer topic should appear before older topic due to age penalty+ newer_index = results.index(newer_topic.id)+ older_index = results.index(older_topic.id)+ expect(newer_index).to be < older_index if newer_index && older_index+ end++ it "uses no age penalty when setting is 0.0" do+ SiteSetting.ai_embeddings_semantic_related_age_penalty = 0.0+ described_class.clear_cache_for(target)++ # Should work the same as without age penalty+ expect { semantic_related.related_topic_ids_for(target) }.not_to raise_error+ end++ it "handles age penalty parameter correctly in schema" do+ schema = DiscourseAi::Embeddings::Schema.for(Topic)++ expect { schema.symmetric_similarity_search(target, age_penalty: 1.5) }.not_to raise_error++ expect { schema.symmetric_similarity_search(target, age_penalty: 0.0) }.not_to raise_error+ end++ it "respects different time scale settings" do+ # Test with a different time scale that makes the penalty less aggressive+ SiteSetting.ai_embeddings_semantic_related_age_time_scale = 365 # 1 year time scale+ SiteSetting.ai_embeddings_semantic_related_age_penalty = 0.3 # Gentle penalty+ described_class.clear_cache_for(target)++ expect { semantic_related.related_topic_ids_for(target) }.not_to raise_error+ end+ endendend