Skip to content

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

4.0 KB
Raw Blame
# frozen_string_literal: true

module DiscourseAi
  module Summarization
    module Strategies
      class TopicSummary < Base
        attr_reader :locale

        def initialize(target, locale: nil)
          @locale = LocaleNormalizer.normalize_to_i18n(locale)&.to_s
          super(target)
        end

        def type
          AiSummary.summary_types[:complete]
        end

        def highest_target_number
          target.highest_post_number
        end

        def targets_data
          post_attributes = %i[post_number raw username last_version_at]
          if SiteSetting.enable_names && !SiteSetting.prioritize_username_in_ux
            post_attributes.push(:name)
          end

          posts_data = selected_posts.pluck(post_attributes)

          posts_data.reduce([]) do |memo, (pn, raw, username, last_version_at, name)|
            raw_text = raw

            if pn == 1 && target.topic_embed&.embed_content_cache.present?
              raw_text = target.topic_embed&.embed_content_cache
            end

            display_name = name.presence || username

            memo << {
              poster: display_name,
              id: pn,
              text: raw_text,
              last_version_at: last_version_at,
            }
          end
        end

        def summary_fingerprint
          posts_data = selected_posts.pluck(:post_number, :last_version_at)
          {
            original_content_sha:
              AiSummary.build_sha(posts_data.map { |post_number, _| post_number }.join),
            latest_version_at: posts_data.map { |_, last_version_at| last_version_at }.compact.max,
          }
        end

        def as_llm_messages(contents)
          content_title = target.title
          category_name = target.category&.name
          # Only include public tags in summaries since summaries are cached and shared across users
          # Use anonymous guardian to get most restrictive tag visibility
          tags = target.visible_tags(Guardian.new(nil)).map(&:name).sort
          input =
            contents.map { |item| "(#{item[:id]} #{item[:poster]} said: #{item[:text]} " }.join

          [{ type: :user, content: <<~TEXT.strip }]
            #{content_title.present? ? "The discussion title is: " + content_title + ".\n" : ""}
            #{category_name.present? ? "Category: " + category_name + ".\n" : ""}
            #{tags.present? ? "Tags: " + tags.join(", ") + ".\n" : ""}
            Here are the posts, inside <input></input> XML tags:

            <input>
              #{input}
            </input>

            Generate a concise, coherent summary of the text above.
            #{output_instructions}
          TEXT
        end

        private

        def output_instructions
          if locale.present?
            "Write the summary in #{output_language}, regardless of the language used in the input."
          else
            "Maintain the original language."
          end
        end

        def selected_posts
          target.has_summary? ? best_replies : pick_selection
        end

        def best_replies
          Post
            .summary(target.id)
            .where("post_type = ?", Post.types[:regular])
            .where("NOT hidden")
            .joins(:user)
            .order(:post_number)
        end

        def pick_selection
          posts =
            Post
              .where(topic_id: target.id)
              .where("post_type = ?", Post.types[:regular])
              .where("NOT hidden")
              .order(:post_number)
              .select(:post_number)

          opening = posts.limit(5)
          highest_scored = posts.reorder("posts.score desc").limit(50)
          latest = posts.reorder("post_number desc").limit(5)

          Post
            .where(topic_id: target.id)
            .joins(:user)
            .where(
              "post_number IN ((#{opening.to_sql}) UNION (#{highest_scored.to_sql}) UNION (#{latest.to_sql}))",
            )
            .order(:post_number)
        end
      end
    end
  end
end