Skip to content

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

4.6 KB
Raw Blame
# frozen_string_literal: true

module DiscourseAi
  module AiBot
    class BotController < ::ApplicationController
      include AiCreditLimitHandler

      requires_plugin PLUGIN_NAME
      requires_login

      def show_debug_info_by_id
        log = AiApiAuditLog.find(params[:id])
        raise Discourse::NotFound if !log.topic

        if log.post_id.present?
          raise Discourse::NotFound if !log.post

          guardian.ensure_can_debug_ai_bot_conversation!(log.post)
        else
          guardian.ensure_can_debug_ai_bot_conversation!(log.topic)
        end
        render json: AiApiAuditLogSerializer.new(log, root: false), status: :ok
      end

      def show_debug_info
        post = Post.find(params[:post_id])
        guardian.ensure_can_debug_ai_bot_conversation!(post)

        posts =
          Post
            .secured(guardian)
            .where("post_number <= ?", post.post_number)
            .where(topic_id: post.topic_id)
            .order("post_number DESC")

        visible_post_ids = posts.select(:id)

        # topic-scoped logs (eg. title generation) are created after the reply's
        # own log, so prefer the clicked post's log over plain recency
        debug_info =
          AiApiAuditLog
            .where(topic_id: post.topic_id)
            .where("post_id IS NULL OR post_id IN (?)", visible_post_ids)
            .order(Arel.sql("post_id = #{post.id.to_i} DESC NULLS LAST"), created_at: :desc)
            .first

        render json: AiApiAuditLogSerializer.new(debug_info, root: false), status: :ok
      end

      def stop_streaming_response
        raise Discourse::InvalidAccess unless SiteSetting.ai_bot_enabled
        unless current_user.in_any_groups?(SiteSetting.ai_bot_allowed_groups_map)
          raise Discourse::InvalidAccess
        end

        post = Post.find(params[:post_id])
        guardian.ensure_can_see!(post)

        Discourse.redis.del("gpt_cancel:#{post.id}")

        render json: {}, status: :ok
      end

      def retry_response
        raise Discourse::InvalidAccess unless SiteSetting.ai_bot_enabled
        unless current_user.in_any_groups?(SiteSetting.ai_bot_allowed_groups_map)
          raise Discourse::InvalidAccess
        end

        post = Post.find(params[:post_id])
        guardian.ensure_can_see!(post)

        if !DiscourseAi::AiBot::EntryPoint.ai_response?(post)
          raise Discourse::InvalidParameters.new(:post_id)
        end

        prompt_post = find_prompt_post(post)
        raise Discourse::NotFound if prompt_post.blank?

        guardian.ensure_can_see!(prompt_post)

        agent_id = retry_agent_id(post, prompt_post)
        llm_model_id = post.custom_fields[DiscourseAi::AiBot::POST_AI_LLM_MODEL_ID_FIELD]
        authorization_user_id =
          post.custom_fields[DiscourseAi::AiBot::POST_AI_AGENT_AUTHORIZATION_USER_ID_FIELD].presence
        authorization_user_id = authorization_user_id.to_i if authorization_user_id
        authorization_user_id ||= prompt_post.topic.user_id
        raise Discourse::InvalidAccess if authorization_user_id.blank?

        args = {
          post_id: prompt_post.id,
          bot_user_id: post.user_id,
          agent_id: agent_id,
          authorization_user_id: authorization_user_id,
          visibility_user_id: current_user.id,
          reply_post_id: post.id,
        }

        args[:llm_model_id] = llm_model_id.to_i if !llm_model_id.to_i.zero?

        Jobs.enqueue(:create_ai_reply, args)

        render json: success_json
      end

      def show_bot_username
        render_json_error(
          I18n.t("discourse_ai.ai_bot.errors.model_recipient_api_retired"),
          status: :gone,
        )
      end

      private

      def find_prompt_post(bot_reply_post)
        bot_ids =
          DiscourseAi::AiBot::EntryPoint.historical_bot_user_ids(topic: bot_reply_post.topic)

        bot_reply_post
          .topic
          .posts
          .where("post_number < ?", bot_reply_post.post_number)
          .where.not(user_id: bot_ids)
          .reorder(post_number: :desc)
          .first
      end

      def retry_agent_id(bot_reply_post, prompt_post)
        agent_id = bot_reply_post.custom_fields[DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD].presence

        agent_id ||= prompt_post.topic.custom_fields["ai_agent_id"].presence

        if agent_id.blank?
          agent_name = prompt_post.topic.custom_fields["ai_agent"].presence
          agent_id = AiAgent.find_by(name: agent_name)&.id if agent_name.present?
        end

        agent_id ||= DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::General]
        agent_id.to_i
      end
    end
  end
end