Skip to content

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

2.5 KB
Raw Blame
# frozen_string_literal: true

module DiscourseAi
  module Summarization
    module Strategies
      # Objects inheriting from this class will get passed as a dependency to `DiscourseAi::Summarization::FoldContent`.
      # This collaborator knows how to source the content to summarize and the prompts used in the process,
      # one for summarizing a chunk and another for concatenating them if necessary.
      class Base
        def initialize(target)
          @target = target
        end

        attr_reader :target, :opts

        def locale
          nil
        end

        def output_tool
          nil
        end

        # The summary type differentiates instances of `AiSummary` pointing to a single target.
        # See the `summary_type` enum for available options.
        def type
          raise NotImplementedError
        end

        # @returns { Array<Hash> } - Content to summarize.
        #
        # This method returns an array of hashes with the content to summarize using the following structure:
        #
        # {
        #  poster: A way to tell who write the content,
        #  id: A number to signal order,
        #  text: Text to summarize
        # }
        #
        def targets_data
          raise NotImplementedError
        end

        # @returns { Array } - Prompt messages to send to the LLM for summarizing content.
        def as_llm_messages(_input)
          raise NotImplementedError
        end

        # Optional lightweight fingerprint for stale cache checks.
        # Return a hash with:
        # - :original_content_sha (String)
        # - :latest_version_at (Time | nil)
        # or nil to fallback to full-content stale detection.
        def summary_fingerprint
          nil
        end

        # We'll pass this as the feature_name when doing LLM calls.
        def feature
          "summarize"
        end

        private

        def output_locale
          LocaleNormalizer.normalize_to_i18n(
            locale || target.locale.presence || SiteSetting.default_locale,
          ).to_s
        end

        def output_language
          language =
            LocaleSiteSetting.language_names[output_locale] ||
              LocaleSiteSetting.language_names[output_locale.split("_").first]
          names = [language&.dig("name"), language&.dig("nativeName")].compact_blank.uniq

          if names.length > 1
            "#{names.first} (#{names.second})"
          else
            names.first || output_locale
          end
        end
      end
    end
  end
end