Skip to content

Open-source live-chat, email support, omni-channel desk. An alternative to Intercom, Zendesk, Salesforce Service Cloud etc. 🔥💬

4.3 KB
Raw Blame
class Captain::Copilot::ChatService < Llm::BaseAiService
  include Captain::ChatHelper
  include Captain::Copilot::ConversationAccess

  attr_reader :assistant, :account, :user, :copilot_thread, :previous_history, :messages

  def initialize(assistant, config)
    super(feature: 'copilot', account: assistant.account, fallback_model: Llm::Models.default_model_for('copilot'))

    @assistant = assistant
    @account = assistant.account
    @user = nil
    @copilot_thread = nil
    @previous_history = []
    @conversation = nil
    @conversation_id = nil

    setup_user(config)
    setup_conversation(config)
    setup_message_history(config)
    @tools = build_tools
    @messages = build_messages
  end

  def generate_response(input)
    @messages << { role: 'user', content: input } if input.present?
    response = request_chat_completion

    Rails.logger.debug { "#{self.class.name} Assistant: #{@assistant.id}, Received response #{response}" }
    Rails.logger.info(
      "#{self.class.name} Assistant: #{@assistant.id}, Incrementing response usage for account #{@account.id}"
    )
    @account.increment_response_usage

    response
  end

  private

  def setup_user(config)
    @user = @account.users.find_by(id: config[:user_id]) if config[:user_id].present?
  end

  def setup_conversation(config)
    return if @user.blank? || config[:conversation_id].blank?

    @conversation = accessible_conversation(account: @account, user: @user, display_id: config[:conversation_id])
    @conversation_id = @conversation&.display_id
  end

  def build_messages
    messages = [system_message]
    messages << account_id_context
    messages += @previous_history if @previous_history.present?
    messages += current_viewing_history
    messages
  end

  def setup_message_history(config)
    Rails.logger.info(
      "#{self.class.name} Assistant: #{@assistant.id}, Previous History: #{config[:previous_history]&.length || 0}, Language: #{config[:language]}"
    )

    @copilot_thread = @account.copilot_threads.find_by(id: config[:copilot_thread_id]) if config[:copilot_thread_id].present?
    @previous_history = if @copilot_thread.present?
                          @copilot_thread.previous_history
                        else
                          config[:previous_history].presence || []
                        end
  end

  def build_tools
    tools = []

    tools << Captain::Tools::SearchDocumentationService.new(@assistant, user: @user)
    tools << Captain::Tools::Copilot::GetConversationService.new(@assistant, user: @user)
    tools << Captain::Tools::Copilot::SearchConversationsService.new(@assistant, user: @user)
    tools << Captain::Tools::Copilot::GetContactService.new(@assistant, user: @user)
    tools << Captain::Tools::Copilot::GetArticleService.new(@assistant, user: @user)
    tools << Captain::Tools::Copilot::SearchArticlesService.new(@assistant, user: @user)
    tools << Captain::Tools::Copilot::SearchContactsService.new(@assistant, user: @user)
    tools << Captain::Tools::Copilot::SearchLinearIssuesService.new(@assistant, user: @user)

    tools.select(&:active?)
  end

  def system_message
    {
      role: 'system',
      content: Captain::Llm::SystemPromptsService.copilot_response_generator(
        @assistant.config['product_name'],
        tools_summary,
        @assistant.config
      )
    }
  end

  def tools_summary
    @tools.map { |tool| "- #{tool.class.name}: #{tool.class.description}" }.join("\n")
  end

  def account_id_context
    {
      role: 'system',
      content: "The current account id is #{@account.id}. The account is using #{@account.locale_english_name} as the language."
    }
  end

  def current_viewing_history
    return [] if @conversation.blank?

    Rails.logger.info("#{self.class.name} Assistant: #{@assistant.id}, Setting viewing history for conversation_id=#{@conversation_id}")
    [{
      role: 'system',
      content: <<~HISTORY.strip
        You are currently viewing the conversation with the following details:
        Conversation ID: #{@conversation_id}
        Contact ID: #{@conversation.contact_id}
      HISTORY
    }]
  end

  def persist_message(message, message_type = 'assistant')
    return if @copilot_thread.blank?

    @copilot_thread.copilot_messages.create!(
      message: message,
      message_type: message_type
    )
  end

  def feature_name
    'copilot'
  end
end