-
-
![]()
-
-
-
{{ authorName }}
-
{{ authorDesignation }}
+
+
![]()
+
+
+ {{ authorName }}
+
+
{{ authorDesignation }}
diff --git a/app/models/channel/whatsapp.rb b/app/models/channel/whatsapp.rb
index 7318cd978..5905c54f7 100644
--- a/app/models/channel/whatsapp.rb
+++ b/app/models/channel/whatsapp.rb
@@ -34,6 +34,7 @@ class Channel::Whatsapp < ApplicationRecord
after_create :sync_templates
before_destroy :teardown_webhooks
+ after_commit :setup_webhooks, on: :create, if: :should_auto_setup_webhooks?
def name
'Whatsapp'
@@ -86,4 +87,10 @@ class Channel::Whatsapp < ApplicationRecord
def teardown_webhooks
Whatsapp::WebhookTeardownService.new(self).perform
end
+
+ def should_auto_setup_webhooks?
+ # Only auto-setup webhooks for whatsapp_cloud provider with manual setup
+ # Embedded signup calls setup_webhooks explicitly in EmbeddedSignupService
+ provider == 'whatsapp_cloud' && provider_config['source'] != 'embedded_signup'
+ end
end
diff --git a/app/models/conversation.rb b/app/models/conversation.rb
index ac0985416..ca53238e8 100644
--- a/app/models/conversation.rb
+++ b/app/models/conversation.rb
@@ -167,6 +167,10 @@ class Conversation < ApplicationRecord
agent_last_seen_at.present? ? messages.created_since(agent_last_seen_at) : messages
end
+ def assignee_unread_messages
+ assignee_last_seen_at.present? ? messages.created_since(assignee_last_seen_at) : messages
+ end
+
def unread_incoming_messages
unread_messages.where(account_id: account_id).incoming.last(10)
end
diff --git a/app/models/integrations/hook.rb b/app/models/integrations/hook.rb
index 97d3f91ae..518b405da 100644
--- a/app/models/integrations/hook.rb
+++ b/app/models/integrations/hook.rb
@@ -64,13 +64,10 @@ class Integrations::Hook < ApplicationRecord
update(status: 'disabled')
end
- def process_event(event)
- case app_id
- when 'openai'
- Integrations::Openai::ProcessorService.new(hook: self, event: event).perform if app_id == 'openai'
- else
- { error: 'No processor found' }
- end
+ def process_event(_event)
+ # OpenAI integration migrated to Captain::EditorService
+ # Other integrations (slack, dialogflow, etc.) handled via HookJob
+ { error: 'No processor found' }
end
def feature_allowed?
diff --git a/app/policies/captain/tasks_policy.rb b/app/policies/captain/tasks_policy.rb
new file mode 100644
index 000000000..997b8fcda
--- /dev/null
+++ b/app/policies/captain/tasks_policy.rb
@@ -0,0 +1,21 @@
+class Captain::TasksPolicy < ApplicationPolicy
+ def rewrite?
+ true
+ end
+
+ def summarize?
+ true
+ end
+
+ def reply_suggestion?
+ true
+ end
+
+ def label_suggestion?
+ true
+ end
+
+ def follow_up?
+ true
+ end
+end
diff --git a/app/presenters/messages/search_data_presenter.rb b/app/presenters/messages/search_data_presenter.rb
index 7d0638add..7a6260686 100644
--- a/app/presenters/messages/search_data_presenter.rb
+++ b/app/presenters/messages/search_data_presenter.rb
@@ -51,7 +51,6 @@ class Messages::SearchDataPresenter < SimpleDelegator
def additional_attributes_data
{
- campaign_id: additional_attributes&.dig('campaign_id'),
automation_rule_id: content_attributes&.dig('automation_rule_id')
}
end
diff --git a/app/services/llm_formatter/conversation_llm_formatter.rb b/app/services/llm_formatter/conversation_llm_formatter.rb
index 38d7c9e26..1e71ccbbc 100644
--- a/app/services/llm_formatter/conversation_llm_formatter.rb
+++ b/app/services/llm_formatter/conversation_llm_formatter.rb
@@ -26,10 +26,18 @@ class LlmFormatter::ConversationLlmFormatter < LlmFormatter::DefaultLlmFormatter
def build_messages(config = {})
return "No messages in this conversation\n" if @record.messages.empty?
- message_text = ''
- messages = @record.messages.where.not(message_type: :activity).order(created_at: :asc)
+ messages = @record.messages.where.not(message_type: [:activity, :template])
- messages.each do |message|
+ if config[:token_limit]
+ build_limited_messages(messages, config)
+ else
+ build_all_messages(messages, config)
+ end
+ end
+
+ def build_all_messages(messages, config)
+ message_text = ''
+ messages.order(created_at: :asc).each do |message|
# Skip private messages unless explicitly included in config
next if message.private? && !config[:include_private_messages]
@@ -38,6 +46,24 @@ class LlmFormatter::ConversationLlmFormatter < LlmFormatter::DefaultLlmFormatter
message_text
end
+ def build_limited_messages(messages, config)
+ selected = []
+ character_count = 0
+
+ messages.reorder(created_at: :desc).each do |message|
+ # Skip private messages unless explicitly included in config
+ next if message.private? && !config[:include_private_messages]
+
+ formatted = format_message(message)
+ break if character_count + formatted.length > config[:token_limit]
+
+ selected.prepend(formatted)
+ character_count += formatted.length
+ end
+
+ selected.join
+ end
+
def format_message(message)
sender = case message.sender_type
when 'User'
diff --git a/app/services/messages/markdown_renderers/whats_app_renderer.rb b/app/services/messages/markdown_renderers/whats_app_renderer.rb
index 8f98218cf..3b4517b4b 100644
--- a/app/services/messages/markdown_renderers/whats_app_renderer.rb
+++ b/app/services/messages/markdown_renderers/whats_app_renderer.rb
@@ -1,4 +1,9 @@
class Messages::MarkdownRenderers::WhatsAppRenderer < Messages::MarkdownRenderers::BaseMarkdownRenderer
+ def initialize
+ super
+ @list_item_number = 0
+ end
+
def strong(_node)
out('*', :children, '*')
end
@@ -15,13 +20,20 @@ class Messages::MarkdownRenderers::WhatsAppRenderer < Messages::MarkdownRenderer
out(node.url)
end
- def list(_node)
+ def list(node)
+ @list_type = node.list_type
+ @list_item_number = @list_type == :ordered_list ? node.list_start : 0
out(:children)
cr
end
def list_item(_node)
- out('- ', :children)
+ if @list_type == :ordered_list
+ out("#{@list_item_number}. ", :children)
+ @list_item_number += 1
+ else
+ out('- ', :children)
+ end
cr
end
diff --git a/app/services/whatsapp/embedded_signup_service.rb b/app/services/whatsapp/embedded_signup_service.rb
index 4379d0b74..52273bc5d 100644
--- a/app/services/whatsapp/embedded_signup_service.rb
+++ b/app/services/whatsapp/embedded_signup_service.rb
@@ -16,6 +16,10 @@ class Whatsapp::EmbeddedSignupService
validate_token_access(access_token)
channel = create_or_reauthorize_channel(access_token, phone_info)
+ # NOTE: We call setup_webhooks explicitly here instead of relying on after_commit callback because:
+ # 1. Reauthorization flow updates an existing channel (not a create), so after_commit on: :create won't trigger
+ # 2. We need to run check_channel_health_and_prompt_reauth after webhook setup completes
+ # 3. The channel is marked with source: 'embedded_signup' to skip the after_commit callback
channel.setup_webhooks
check_channel_health_and_prompt_reauth(channel)
channel
diff --git a/app/services/whatsapp/incoming_message_whatsapp_cloud_service.rb b/app/services/whatsapp/incoming_message_whatsapp_cloud_service.rb
index f8ac8c85a..164c3ac12 100644
--- a/app/services/whatsapp/incoming_message_whatsapp_cloud_service.rb
+++ b/app/services/whatsapp/incoming_message_whatsapp_cloud_service.rb
@@ -10,10 +10,7 @@ class Whatsapp::IncomingMessageWhatsappCloudService < Whatsapp::IncomingMessageB
def download_attachment_file(attachment_payload)
url_response = HTTParty.get(
- inbox.channel.media_url(
- attachment_payload[:id],
- inbox.channel.provider_config['phone_number_id']
- ),
+ inbox.channel.media_url(attachment_payload[:id]),
headers: inbox.channel.api_headers
)
# This url response will be failure if the access token has expired.
diff --git a/app/services/whatsapp/providers/whatsapp_cloud_service.rb b/app/services/whatsapp/providers/whatsapp_cloud_service.rb
index 6f2ead579..5b4c26196 100644
--- a/app/services/whatsapp/providers/whatsapp_cloud_service.rb
+++ b/app/services/whatsapp/providers/whatsapp_cloud_service.rb
@@ -75,10 +75,8 @@ class Whatsapp::Providers::WhatsappCloudService < Whatsapp::Providers::BaseServi
csat_template_service.get_template_status(template_name)
end
- def media_url(media_id, phone_number_id = nil)
- url = "#{api_base_path}/v13.0/#{media_id}"
- url += "?phone_number_id=#{phone_number_id}" if phone_number_id
- url
+ def media_url(media_id)
+ "#{api_base_path}/v13.0/#{media_id}"
end
private
diff --git a/app/views/public/api/v1/portals/sitemap.xml.erb b/app/views/public/api/v1/portals/sitemap.xml.erb
index d3e2b8301..1ea828165 100644
--- a/app/views/public/api/v1/portals/sitemap.xml.erb
+++ b/app/views/public/api/v1/portals/sitemap.xml.erb
@@ -1,9 +1,9 @@
-
+
<% @portal.articles.where(status: :published).each do |article| %>
-
+
<%= @help_center_url %><%= generate_article_link(@portal.slug, article.slug, false, false) %>
- <%= article.updated_at.strftime("%Y-%m-%d") %>
-
+ <%= article.updated_at.to_date.iso8601 %>
+
<% end %>
-
\ No newline at end of file
+
diff --git a/config/app.yml b/config/app.yml
index 98e523795..c81f2102f 100644
--- a/config/app.yml
+++ b/config/app.yml
@@ -1,5 +1,5 @@
shared: &shared
- version: '4.10.0'
+ version: '4.10.1'
development:
<<: *shared
diff --git a/config/features.yml b/config/features.yml
index 36943ceff..703d3cb8c 100644
--- a/config/features.yml
+++ b/config/features.yml
@@ -234,3 +234,6 @@
display_name: CSAT Review Notes
enabled: false
premium: true
+- name: captain_tasks
+ display_name: Captain Tasks
+ enabled: true
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 61a80d827..f8d5b119e 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -345,6 +345,9 @@ en:
copilot_message_required: Message is required
copilot_error: 'Please connect an assistant to this inbox to use Copilot'
copilot_limit: 'You are out of Copilot credits. You can buy more credits from the billing section.'
+ upgrade: 'Upgrade your plan to enable Captain AI'
+ disabled: 'Captain AI is disabled for this account.'
+ api_key_missing: 'Captain AI API key is not configured.'
copilot:
using_tool: 'Using tool %{function_name}'
completed_tool_call: 'Completed %{function_name} tool call'
diff --git a/config/routes.rb b/config/routes.rb
index 50b426554..95b77d323 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -73,6 +73,13 @@ Rails.application.routes.draw do
end
resources :custom_tools
resources :documents, only: [:index, :show, :create, :destroy]
+ resource :tasks, only: [], controller: 'tasks' do
+ post :rewrite
+ post :summarize
+ post :reply_suggestion
+ post :label_suggestion
+ post :follow_up
+ end
end
resource :saml_settings, only: [:show, :create, :update, :destroy]
resources :agent_bots, only: [:index, :create, :show, :update, :destroy] do
diff --git a/db/migrate/20260120121402_enable_captain_tasks_for_existing_accounts.rb b/db/migrate/20260120121402_enable_captain_tasks_for_existing_accounts.rb
new file mode 100644
index 000000000..5305559c8
--- /dev/null
+++ b/db/migrate/20260120121402_enable_captain_tasks_for_existing_accounts.rb
@@ -0,0 +1,12 @@
+# Enable captain_tasks for existing accounts.
+# Unlike 20250416182131_flip_chatwoot_v4_default_feature_flag_installation_config.rb,
+# we don't need to update ACCOUNT_LEVEL_FEATURE_DEFAULTS or clear GlobalConfig cache
+# because captain_tasks already has `enabled: true` in features.yml - ConfigLoader
+# handles the defaults on deploy automatically.
+class EnableCaptainTasksForExistingAccounts < ActiveRecord::Migration[7.0]
+ def up
+ Account.find_in_batches(batch_size: 100) do |accounts|
+ accounts.each { |account| account.enable_features!('captain_tasks') }
+ end
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index e30f7cd8d..148e7769c 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[7.1].define(version: 2026_01_14_201315) do
+ActiveRecord::Schema[7.1].define(version: 2026_01_20_121402) do
# These extensions should be enabled to support this database
enable_extension "pg_stat_statements"
enable_extension "pg_trgm"
diff --git a/enterprise/app/controllers/api/v1/accounts/captain/tasks_controller.rb b/enterprise/app/controllers/api/v1/accounts/captain/tasks_controller.rb
new file mode 100644
index 000000000..d7208d678
--- /dev/null
+++ b/enterprise/app/controllers/api/v1/accounts/captain/tasks_controller.rb
@@ -0,0 +1,71 @@
+class Api::V1::Accounts::Captain::TasksController < Api::V1::Accounts::BaseController
+ before_action :check_authorization
+
+ def rewrite
+ result = Captain::RewriteService.new(
+ account: Current.account,
+ content: params[:content],
+ operation: params[:operation],
+ conversation_display_id: params[:conversation_display_id]
+ ).perform
+
+ render_result(result)
+ end
+
+ def summarize
+ result = Captain::SummaryService.new(
+ account: Current.account,
+ conversation_display_id: params[:conversation_display_id]
+ ).perform
+
+ render_result(result)
+ end
+
+ def reply_suggestion
+ result = Captain::ReplySuggestionService.new(
+ account: Current.account,
+ conversation_display_id: params[:conversation_display_id],
+ user: Current.user
+ ).perform
+
+ render_result(result)
+ end
+
+ def label_suggestion
+ result = Captain::LabelSuggestionService.new(
+ account: Current.account,
+ conversation_display_id: params[:conversation_display_id]
+ ).perform
+
+ render_result(result)
+ end
+
+ def follow_up
+ result = Captain::FollowUpService.new(
+ account: Current.account,
+ follow_up_context: params[:follow_up_context]&.to_unsafe_h,
+ user_message: params[:message],
+ conversation_display_id: params[:conversation_display_id]
+ ).perform
+
+ render_result(result)
+ end
+
+ private
+
+ def render_result(result)
+ if result.nil?
+ render json: { message: nil }
+ elsif result[:error]
+ render json: { error: result[:error] }, status: :unprocessable_entity
+ else
+ response_data = { message: result[:message] }
+ response_data[:follow_up_context] = result[:follow_up_context] if result[:follow_up_context]
+ render json: response_data
+ end
+ end
+
+ def check_authorization
+ authorize(:'captain/tasks')
+ end
+end
diff --git a/enterprise/config/premium_features.yml b/enterprise/config/premium_features.yml
index dbe50614f..9465a6e11 100644
--- a/enterprise/config/premium_features.yml
+++ b/enterprise/config/premium_features.yml
@@ -3,6 +3,6 @@
- audit_logs
- response_bot
- sla
-- captain_integration
- custom_roles
+- captain_integration
- csat_review_notes
diff --git a/enterprise/lib/enterprise/captain/base_task_service.rb b/enterprise/lib/enterprise/captain/base_task_service.rb
new file mode 100644
index 000000000..9845359f5
--- /dev/null
+++ b/enterprise/lib/enterprise/captain/base_task_service.rb
@@ -0,0 +1,32 @@
+module Enterprise::Captain::BaseTaskService
+ def perform
+ return { error: I18n.t('captain.copilot_limit'), error_code: 429 } unless responses_available?
+
+ unless captain_tasks_enabled?
+ return { error: I18n.t('captain.upgrade') } if ChatwootApp.chatwoot_cloud?
+
+ return { error: I18n.t('captain.disabled') }
+ end
+
+ result = super
+ increment_usage if successful_result?(result)
+ result
+ end
+
+ private
+
+ def responses_available?
+ return true unless ChatwootApp.chatwoot_cloud?
+
+ account.usage_limits[:captain][:responses][:current_available].positive?
+ end
+
+ def successful_result?(result)
+ result.is_a?(Hash) && result[:message].present? && !result[:error]
+ end
+
+ def increment_usage
+ Rails.logger.info("[CAPTAIN][#{self.class.name}] Incrementing response usage for account #{account.id}")
+ account.increment_response_usage
+ end
+end
diff --git a/enterprise/lib/enterprise/integrations/openai_processor_service.rb b/enterprise/lib/enterprise/integrations/openai_processor_service.rb
deleted file mode 100644
index 5a98ad4c4..000000000
--- a/enterprise/lib/enterprise/integrations/openai_processor_service.rb
+++ /dev/null
@@ -1,82 +0,0 @@
-module Enterprise::Integrations::OpenaiProcessorService
- ALLOWED_EVENT_NAMES = %w[rephrase summarize reply_suggestion label_suggestion fix_spelling_grammar shorten expand
- make_friendly make_formal simplify].freeze
- CACHEABLE_EVENTS = %w[label_suggestion].freeze
-
- def label_suggestion_message
- payload = label_suggestion_body
- return nil if payload.blank?
-
- response = make_api_call(label_suggestion_body)
-
- return response if response[:error].present?
-
- # LLMs are not deterministic, so this is bandaid solution
- # To what you ask? Sometimes, the response includes
- # "Labels:" in it's response in some format. This is a hacky way to remove it
- # TODO: Fix with with a better prompt
- { message: response[:message] ? response[:message].gsub(/^(label|labels):/i, '') : '' }
- end
-
- private
-
- def labels_with_messages
- return nil unless valid_conversation?(conversation)
-
- labels = hook.account.labels.pluck(:title).join(', ')
- character_count = labels.length
-
- messages = init_messages_body(false)
- add_messages_until_token_limit(conversation, messages, false, character_count)
-
- return nil if messages.blank? || labels.blank?
-
- "Messages:\n#{messages}\nLabels:\n#{labels}"
- end
-
- def valid_conversation?(conversation)
- return false if conversation.nil?
- return false if conversation.messages.incoming.count < 3
-
- # Think Mark think, at this point the conversation is beyond saving
- return false if conversation.messages.count > 100
-
- # if there are more than 20 messages, only trigger this if the last message is from the client
- return false if conversation.messages.count > 20 && !conversation.messages.last.incoming?
-
- true
- end
-
- def summarize_body
- {
- model: self.class::GPT_MODEL,
- messages: [
- { role: 'system',
- content: prompt_from_file('summary', enterprise: true) },
- { role: 'user', content: conversation_messages }
- ]
- }.to_json
- end
-
- def label_suggestion_body
- return unless label_suggestions_enabled?
-
- content = labels_with_messages
- return value_from_cache if content.blank?
-
- {
- model: self.class::GPT_MODEL,
- messages: [
- {
- role: 'system',
- content: prompt_from_file('label_suggestion', enterprise: true)
- },
- { role: 'user', content: content }
- ]
- }.to_json
- end
-
- def label_suggestions_enabled?
- hook.settings['label_suggestion'].present?
- end
-end
diff --git a/lib/captain/base_task_service.rb b/lib/captain/base_task_service.rb
new file mode 100644
index 000000000..b0cf7d240
--- /dev/null
+++ b/lib/captain/base_task_service.rb
@@ -0,0 +1,181 @@
+class Captain::BaseTaskService
+ include Integrations::LlmInstrumentation
+
+ # gpt-4o-mini supports 128,000 tokens
+ # 1 token is approx 4 characters
+ # sticking with 120000 to be safe
+ # 120000 * 4 = 480,000 characters (rounding off downwards to 400,000 to be safe)
+ TOKEN_LIMIT = 400_000
+ GPT_MODEL = Llm::Config::DEFAULT_MODEL
+
+ # Prepend enterprise module to subclasses when they're defined.
+ # This ensures the enterprise perform wrapper is applied even when
+ # subclasses define their own perform method, since prepend puts
+ # the module before the class in the ancestor chain.
+ def self.inherited(subclass)
+ super
+ subclass.prepend_mod_with('Captain::BaseTaskService')
+ end
+
+ pattr_initialize [:account!, { conversation_display_id: nil }]
+
+ private
+
+ def event_name
+ raise NotImplementedError, "#{self.class} must implement #event_name"
+ end
+
+ def conversation
+ @conversation ||= account.conversations.find_by(display_id: conversation_display_id)
+ end
+
+ def api_base
+ endpoint = InstallationConfig.find_by(name: 'CAPTAIN_OPEN_AI_ENDPOINT')&.value.presence || 'https://api.openai.com/'
+ endpoint = endpoint.chomp('/')
+ "#{endpoint}/v1"
+ end
+
+ def make_api_call(model:, messages:)
+ # Community edition prerequisite checks
+ # Enterprise module handles these with more specific error messages (cloud vs self-hosted)
+ return { error: I18n.t('captain.disabled'), error_code: 403 } unless captain_tasks_enabled?
+ return { error: I18n.t('captain.api_key_missing'), error_code: 401 } unless api_key_configured?
+
+ instrumentation_params = build_instrumentation_params(model, messages)
+
+ response = instrument_llm_call(instrumentation_params) do
+ execute_ruby_llm_request(model: model, messages: messages)
+ end
+
+ # Build follow-up context for client-side refinement, when applicable
+ if build_follow_up_context? && response[:message].present?
+ response.merge(follow_up_context: build_follow_up_context(messages, response))
+ else
+ response
+ end
+ end
+
+ def execute_ruby_llm_request(model:, messages:)
+ Llm::Config.with_api_key(api_key, api_base: api_base) do |context|
+ chat = context.chat(model: model)
+ system_msg = messages.find { |m| m[:role] == 'system' }
+ chat.with_instructions(system_msg[:content]) if system_msg
+
+ conversation_messages = messages.reject { |m| m[:role] == 'system' }
+ return { error: 'No conversation messages provided', error_code: 400, request_messages: messages } if conversation_messages.empty?
+
+ add_messages_if_needed(chat, conversation_messages)
+ response = chat.ask(conversation_messages.last[:content])
+ build_ruby_llm_response(response, messages)
+ end
+ rescue StandardError => e
+ ChatwootExceptionTracker.new(e, account: account).capture_exception
+ { error: e.message, request_messages: messages }
+ end
+
+ def add_messages_if_needed(chat, conversation_messages)
+ return if conversation_messages.length == 1
+
+ conversation_messages[0...-1].each do |msg|
+ chat.add_message(role: msg[:role].to_sym, content: msg[:content])
+ end
+ end
+
+ def build_ruby_llm_response(response, messages)
+ {
+ message: response.content,
+ usage: {
+ 'prompt_tokens' => response.input_tokens,
+ 'completion_tokens' => response.output_tokens,
+ 'total_tokens' => (response.input_tokens || 0) + (response.output_tokens || 0)
+ },
+ request_messages: messages
+ }
+ end
+
+ def build_instrumentation_params(model, messages)
+ {
+ span_name: "llm.#{event_name}",
+ account_id: account.id,
+ conversation_id: conversation&.display_id,
+ feature_name: event_name,
+ model: model,
+ messages: messages,
+ temperature: nil,
+ metadata: instrumentation_metadata
+ }
+ end
+
+ def instrumentation_metadata
+ {
+ channel_type: conversation&.inbox&.channel_type
+ }.compact
+ end
+
+ def conversation_messages(start_from: 0)
+ messages = []
+ character_count = start_from
+
+ conversation.messages
+ .where(message_type: [:incoming, :outgoing])
+ .where(private: false)
+ .reorder('id desc')
+ .each do |message|
+ content = message.content_for_llm
+ break unless content.present? && character_count + content.length <= TOKEN_LIMIT
+
+ messages.prepend({ role: (message.incoming? ? 'user' : 'assistant'), content: content })
+ character_count += content.length
+ end
+
+ messages
+ end
+
+ def captain_tasks_enabled?
+ account.feature_enabled?('captain_tasks')
+ end
+
+ def api_key_configured?
+ api_key.present?
+ end
+
+ def api_key
+ @api_key ||= openai_hook&.settings&.dig('api_key') || system_api_key
+ end
+
+ def openai_hook
+ @openai_hook ||= account.hooks.find_by(app_id: 'openai', status: 'enabled')
+ end
+
+ def system_api_key
+ @system_api_key ||= InstallationConfig.find_by(name: 'CAPTAIN_OPEN_AI_API_KEY')&.value
+ end
+
+ def prompt_from_file(file_name)
+ Rails.root.join('lib/integrations/openai/openai_prompts', "#{file_name}.liquid").read
+ end
+
+ # Follow-up context for client-side refinement
+ def build_follow_up_context?
+ # FollowUpService should return its own updated context
+ !is_a?(Captain::FollowUpService)
+ end
+
+ def build_follow_up_context(messages, response)
+ {
+ event_name: event_name,
+ original_context: extract_original_context(messages),
+ last_response: response[:message],
+ conversation_history: [],
+ channel_type: conversation&.inbox&.channel_type
+ }
+ end
+
+ def extract_original_context(messages)
+ # Get the most recent user message for follow-up context
+ user_msg = messages.reverse.find { |m| m[:role] == 'user' }
+ user_msg ? user_msg[:content] : nil
+ end
+end
+
+Captain::BaseTaskService.prepend_mod_with('Captain::BaseTaskService')
diff --git a/lib/captain/follow_up_service.rb b/lib/captain/follow_up_service.rb
new file mode 100644
index 000000000..f02ba9408
--- /dev/null
+++ b/lib/captain/follow_up_service.rb
@@ -0,0 +1,106 @@
+class Captain::FollowUpService < Captain::BaseTaskService
+ pattr_initialize [:account!, :follow_up_context!, :user_message!, { conversation_display_id: nil }]
+
+ ALLOWED_EVENT_NAMES = %w[
+ professional
+ casual
+ friendly
+ confident
+ straightforward
+ fix_spelling_grammar
+ improve
+ summarize
+ reply_suggestion
+ label_suggestion
+ ].freeze
+
+ def perform
+ return { error: 'Follow-up context missing', error_code: 400 } unless valid_follow_up_context?
+
+ # Build context-aware system prompt
+ system_prompt = build_follow_up_system_prompt(follow_up_context)
+
+ # Build full message array (convert history from string keys to symbol keys)
+ history = follow_up_context['conversation_history'].to_a.map do |msg|
+ { role: msg['role'], content: msg['content'] }
+ end
+
+ messages = [
+ { role: 'system', content: system_prompt },
+ { role: 'user', content: follow_up_context['original_context'] },
+ { role: 'assistant', content: follow_up_context['last_response'] },
+ *history,
+ { role: 'user', content: user_message }
+ ]
+
+ response = make_api_call(model: GPT_MODEL, messages: messages)
+ return response if response[:error]
+
+ response.merge(follow_up_context: update_follow_up_context(user_message, response[:message]))
+ end
+
+ private
+
+ def build_follow_up_system_prompt(session_data)
+ action_context = describe_previous_action(session_data['event_name'])
+
+ <<~PROMPT
+ You just performed a #{action_context} action for a customer support agent.
+ Your job now is to help them refine the result based on their feedback.
+ Be concise and focused on their specific request.
+ Output only the reply, no preamble, tags, or explanation.
+ PROMPT
+ end
+
+ def describe_previous_action(event_name)
+ case event_name
+ when 'professional', 'casual', 'friendly', 'confident', 'straightforward'
+ "tone rewrite (#{event_name})"
+ when 'fix_spelling_grammar'
+ 'spelling and grammar correction'
+ when 'improve'
+ 'message improvement'
+ when 'summarize'
+ 'conversation summary'
+ when 'reply_suggestion'
+ 'reply suggestion'
+ when 'label_suggestion'
+ 'label suggestion'
+ else
+ event_name
+ end
+ end
+
+ def valid_follow_up_context?
+ return false unless follow_up_context.is_a?(Hash)
+ return false unless ALLOWED_EVENT_NAMES.include?(follow_up_context['event_name'])
+
+ required_keys = %w[event_name original_context last_response]
+ required_keys.all? { |key| follow_up_context[key].present? }
+ end
+
+ def update_follow_up_context(user_msg, assistant_msg)
+ updated_history = follow_up_context['conversation_history'].to_a + [
+ { 'role' => 'user', 'content' => user_msg },
+ { 'role' => 'assistant', 'content' => assistant_msg }
+ ]
+
+ {
+ 'event_name' => follow_up_context['event_name'],
+ 'original_context' => follow_up_context['original_context'],
+ 'last_response' => assistant_msg,
+ 'conversation_history' => updated_history,
+ 'channel_type' => follow_up_context['channel_type']
+ }
+ end
+
+ def instrumentation_metadata
+ {
+ channel_type: conversation&.inbox&.channel_type || follow_up_context['channel_type']
+ }.compact
+ end
+
+ def event_name
+ 'follow_up'
+ end
+end
diff --git a/lib/captain/label_suggestion_service.rb b/lib/captain/label_suggestion_service.rb
new file mode 100644
index 000000000..02f8bd89a
--- /dev/null
+++ b/lib/captain/label_suggestion_service.rb
@@ -0,0 +1,93 @@
+class Captain::LabelSuggestionService < Captain::BaseTaskService
+ pattr_initialize [:account!, :conversation_display_id!]
+
+ def perform
+ # Check cache first
+ cached_response = read_from_cache
+ return cached_response if cached_response.present?
+
+ # Build content
+ content = labels_with_messages
+ return nil if content.blank?
+
+ # Make API call
+ response = make_api_call(
+ model: GPT_MODEL, # TODO: Use separate model for label suggestion
+ messages: [
+ { role: 'system', content: prompt_from_file('label_suggestion') },
+ { role: 'user', content: content }
+ ]
+ )
+ return response if response[:error].present?
+
+ # Clean up response
+ result = { message: response[:message] ? response[:message].gsub(/^(label|labels):/i, '') : '' }
+
+ # Cache successful result
+ write_to_cache(result)
+
+ result
+ end
+
+ private
+
+ def cache_key
+ return nil unless conversation
+
+ format(
+ ::Redis::Alfred::OPENAI_CONVERSATION_KEY,
+ event_name: 'label_suggestion',
+ conversation_id: conversation.id,
+ updated_at: conversation.last_activity_at.to_i
+ )
+ end
+
+ def read_from_cache
+ return nil unless cache_key
+
+ cached = Redis::Alfred.get(cache_key)
+ JSON.parse(cached, symbolize_names: true) if cached.present?
+ rescue JSON::ParserError
+ nil
+ end
+
+ def write_to_cache(response)
+ Redis::Alfred.setex(cache_key, response.to_json) if cache_key
+ end
+
+ def labels_with_messages
+ return nil unless valid_conversation?(conversation)
+
+ labels = account.labels.pluck(:title).join(', ')
+ messages = format_messages_as_string(start_from: labels.length)
+
+ return nil if messages.blank? || labels.blank?
+
+ "Messages:\n#{messages}\nLabels:\n#{labels}"
+ end
+
+ def format_messages_as_string(start_from: 0)
+ messages = conversation_messages(start_from: start_from)
+ messages.map do |msg|
+ sender_type = msg[:role] == 'user' ? 'Customer' : 'Agent'
+ "#{sender_type}: #{msg[:content]}\n"
+ end.join
+ end
+
+ def valid_conversation?(conversation)
+ return false if conversation.nil?
+ return false if conversation.messages.incoming.count < 3
+ return false if conversation.messages.count > 100
+ return false if conversation.messages.count > 20 && !conversation.messages.last.incoming?
+
+ true
+ end
+
+ def event_name
+ 'label_suggestion'
+ end
+
+ def build_follow_up_context?
+ false
+ end
+end
diff --git a/lib/captain/reply_suggestion_service.rb b/lib/captain/reply_suggestion_service.rb
new file mode 100644
index 000000000..8582258a8
--- /dev/null
+++ b/lib/captain/reply_suggestion_service.rb
@@ -0,0 +1,40 @@
+class Captain::ReplySuggestionService < Captain::BaseTaskService
+ pattr_initialize [:account!, :conversation_display_id!, :user!]
+
+ def perform
+ make_api_call(
+ model: GPT_MODEL,
+ messages: [
+ { role: 'system', content: system_prompt },
+ { role: 'user', content: formatted_conversation }
+ ]
+ )
+ end
+
+ private
+
+ def system_prompt
+ template = prompt_from_file('reply')
+ render_liquid_template(template, prompt_variables)
+ end
+
+ def prompt_variables
+ {
+ 'channel_type' => conversation.inbox.channel_type,
+ 'agent_name' => user.name,
+ 'agent_signature' => user.message_signature.presence
+ }
+ end
+
+ def render_liquid_template(template_content, variables = {})
+ Liquid::Template.parse(template_content).render(variables)
+ end
+
+ def formatted_conversation
+ LlmFormatter::ConversationLlmFormatter.new(conversation).format(token_limit: TOKEN_LIMIT)
+ end
+
+ def event_name
+ 'reply_suggestion'
+ end
+end
diff --git a/lib/captain/rewrite_service.rb b/lib/captain/rewrite_service.rb
new file mode 100644
index 000000000..3a217d3c6
--- /dev/null
+++ b/lib/captain/rewrite_service.rb
@@ -0,0 +1,59 @@
+class Captain::RewriteService < Captain::BaseTaskService
+ pattr_initialize [:account!, :content!, :operation!, { conversation_display_id: nil }]
+
+ TONE_OPERATIONS = %i[casual professional friendly confident straightforward].freeze
+ ALLOWED_OPERATIONS = (%i[fix_spelling_grammar improve] + TONE_OPERATIONS).freeze
+
+ def perform
+ operation_sym = operation.to_sym
+ raise ArgumentError, "Invalid operation: #{operation}" unless ALLOWED_OPERATIONS.include?(operation_sym)
+
+ send(operation_sym)
+ end
+
+ TONE_OPERATIONS.each do |tone|
+ define_method(tone) do
+ call_llm_with_prompt(tone_rewrite_prompt(tone.to_s))
+ end
+ end
+
+ private
+
+ def fix_spelling_grammar
+ call_llm_with_prompt(prompt_from_file('fix_spelling_grammar'))
+ end
+
+ def improve
+ template = prompt_from_file('improve')
+
+ system_prompt = render_liquid_template(template, {
+ 'conversation_context' => conversation.to_llm_text(include_contact_details: true),
+ 'draft_message' => content
+ })
+
+ call_llm_with_prompt(system_prompt, content)
+ end
+
+ def call_llm_with_prompt(system_content, user_content = content)
+ make_api_call(
+ model: GPT_MODEL,
+ messages: [
+ { role: 'system', content: system_content },
+ { role: 'user', content: user_content }
+ ]
+ )
+ end
+
+ def render_liquid_template(template_content, variables = {})
+ Liquid::Template.parse(template_content).render(variables)
+ end
+
+ def tone_rewrite_prompt(tone)
+ template = prompt_from_file('tone_rewrite')
+ render_liquid_template(template, 'tone' => tone)
+ end
+
+ def event_name
+ operation
+ end
+end
diff --git a/lib/captain/summary_service.rb b/lib/captain/summary_service.rb
new file mode 100644
index 000000000..16ee57b51
--- /dev/null
+++ b/lib/captain/summary_service.rb
@@ -0,0 +1,19 @@
+class Captain::SummaryService < Captain::BaseTaskService
+ pattr_initialize [:account!, :conversation_display_id!]
+
+ def perform
+ make_api_call(
+ model: GPT_MODEL,
+ messages: [
+ { role: 'system', content: prompt_from_file('summary') },
+ { role: 'user', content: conversation.to_llm_text(include_contact_details: false) }
+ ]
+ )
+ end
+
+ private
+
+ def event_name
+ 'summarize'
+ end
+end
diff --git a/lib/integrations/llm_base_service.rb b/lib/integrations/llm_base_service.rb
index ca9459fc8..397888b83 100644
--- a/lib/integrations/llm_base_service.rb
+++ b/lib/integrations/llm_base_service.rb
@@ -7,7 +7,8 @@ class Integrations::LlmBaseService
# 120000 * 4 = 480,000 characters (rounding off downwards to 400,000 to be safe)
TOKEN_LIMIT = 400_000
GPT_MODEL = Llm::Config::DEFAULT_MODEL
- ALLOWED_EVENT_NAMES = %w[rephrase summarize reply_suggestion fix_spelling_grammar shorten expand make_friendly make_formal simplify].freeze
+ ALLOWED_EVENT_NAMES = %w[summarize reply_suggestion fix_spelling_grammar casual professional friendly confident
+ straightforward improve].freeze
CACHEABLE_EVENTS = %w[].freeze
pattr_initialize [:hook!, :event!]
diff --git a/lib/integrations/openai/openai_prompts/fix_spelling_grammar.liquid b/lib/integrations/openai/openai_prompts/fix_spelling_grammar.liquid
new file mode 100644
index 000000000..2a0e8c6d2
--- /dev/null
+++ b/lib/integrations/openai/openai_prompts/fix_spelling_grammar.liquid
@@ -0,0 +1,18 @@
+You are an AI writing assistant integrated into Chatwoot, an omnichannel customer support platform. Your task is to fix grammar and spelling in a customer support message while preserving the original meaning, intent, and tone.
+
+You will receive a message and must return a corrected version with only grammar, spelling, and punctuation fixes applied.
+
+Important guidelines:
+- Preserve the original meaning, intent, and tone exactly
+- Do not rephrase, rewrite, or change wording beyond grammar, spelling, and punctuation
+- Do not add or remove any information
+- Do not simplify, shorten, or expand the message
+- Ensure the output remains appropriate for customer support
+
+Super Important:
+- If the message has some markdown formatting, keep the formatting as it is.
+- Block quotes (lines starting with >) contain quoted text from the customer's previous message. Preserve this quoted text exactly as written (do not modify the customer's words inside the block quote), but DO improve the agent's reply that follows the block quote.
+- Ensure the output is in the user's original language
+- If the message contains a signature block (text after a `--` line), preserve the signature exactly as written without any modification. Do not add a signature if one is not already present.
+
+Output only the corrected message, with no preamble, tags, or explanation.
diff --git a/lib/integrations/openai/openai_prompts/improve.liquid b/lib/integrations/openai/openai_prompts/improve.liquid
new file mode 100644
index 000000000..8730d1b0f
--- /dev/null
+++ b/lib/integrations/openai/openai_prompts/improve.liquid
@@ -0,0 +1,44 @@
+You are a writing assistant for customer support agents. Your task is to improve a draft message by enhancing its language, clarity, and tone—not by adding new content.
+
+
+{{ conversation_context }}
+
+
+
+{{ draft_message }}
+
+
+## Your Task
+
+Rewrite the draft to be clearer, warmer, and more professional while preserving the agent's intent.
+
+## What "Improve" Means
+
+Improve the **quality** of the message, not the **quantity** of information:
+
+| DO | DON'T |
+|-----|--------|
+| Fix grammar, spelling, punctuation | Add new information or steps |
+| Improve sentence structure and flow | Expand scope beyond the draft |
+| Make tone warmer and more professional | Add offers ("I can also...", "Would you like...") |
+| Use contact's name naturally | Invent technical details, links, or examples |
+| Make vague phrases more natural | Turn a brief answer into a long one |
+
+## Using the Context
+
+Use the conversation context to:
+- Understand what's being discussed (so improvements make sense)
+- Gauge appropriate tone (formal/casual, frustrated customer, etc.)
+- Personalize with the contact's name when natural
+
+Do NOT use the context to fill in gaps or add information the agent didn't include.
+
+## Output Rules
+
+- Keep the improved message at a similar length to the draft (brief stays brief)
+- Preserve any markdown formatting
+- Block quotes (lines starting with `>`) contain quoted customer text—keep this unchanged, only improve the agent's reply
+- If the message contains a signature block (text after a `--` line), preserve the signature exactly as written without any modification. Do not add a signature if one is not already present.
+- Output in the same language as the draft
+- Output only the improved message, no commentary
+
diff --git a/enterprise/lib/enterprise/integrations/openai_prompts/label_suggestion.txt b/lib/integrations/openai/openai_prompts/label_suggestion.liquid
similarity index 88%
rename from enterprise/lib/enterprise/integrations/openai_prompts/label_suggestion.txt
rename to lib/integrations/openai/openai_prompts/label_suggestion.liquid
index 6b0e436a4..7c76288f7 100644
--- a/enterprise/lib/enterprise/integrations/openai_prompts/label_suggestion.txt
+++ b/lib/integrations/openai/openai_prompts/label_suggestion.liquid
@@ -1 +1 @@
-Your role is as an assistant to a customer support agent. You will be provided with a transcript of a conversation between a customer and the support agent, along with a list of potential labels. Your task is to analyze the conversation and select the two labels from the given list that most accurately represent the themes or issues discussed. Ensure you preserve the exact casing of the labels as they are provided in the list. Do not create new labels; only choose from those provided. Once you have made your selections, please provide your response as a comma-separated list of the provided labels. Remember, your response should only contain the labels you\'ve selected,in their original casing, and nothing else.
\ No newline at end of file
+Your role is as an assistant to a customer support agent. You will be provided with a transcript of a conversation between a customer and the support agent, along with a list of potential labels. Your task is to analyze the conversation and select the two labels from the given list that most accurately represent the themes or issues discussed. Ensure you preserve the exact casing of the labels as they are provided in the list. Do not create new labels; only choose from those provided. Once you have made your selections, please provide your response as a comma-separated list of the provided labels. Remember, your response should only contain the labels you've selected,in their original casing, and nothing else.
diff --git a/lib/integrations/openai/openai_prompts/reply.liquid b/lib/integrations/openai/openai_prompts/reply.liquid
new file mode 100644
index 000000000..19db51a05
--- /dev/null
+++ b/lib/integrations/openai/openai_prompts/reply.liquid
@@ -0,0 +1,35 @@
+You are helping a customer support agent draft their next reply. The agent will send this message directly to the customer.
+
+You will receive a conversation with messages labeled by sender:
+- "User:" = customer messages
+- "Support Agent:" = human agent messages
+- "Bot:" = automated bot messages
+
+{% if channel_type == 'Channel::Email' %}
+This is an EMAIL conversation. Write a professional email reply that:
+- Uses appropriate email formatting (greeting, body, sign-off)
+- Is detailed and thorough where needed
+- Maintains a professional tone
+{% if agent_signature %}
+- End with the agent's signature exactly as provided below:
+
+{{ agent_signature }}
+{% else %}
+- End with a professional sign-off using the agent's name: {{ agent_name }}
+{% endif %}
+{% else %}
+This is a CHAT conversation. Write a brief, conversational reply that:
+- Is short and easy to read
+- Gets to the point quickly
+- Does not include formal greetings or sign-offs
+{% endif %}
+
+General guidelines:
+- Address the customer's most recent message directly
+- If a support agent has spoken before, match their writing style
+- If only bot messages exist, write a natural first message
+- Move the conversation forward
+- Do not invent product details, policies, or links that weren't mentioned
+- Reply in the customer's language
+
+Output only the reply.
diff --git a/lib/integrations/openai/openai_prompts/reply.txt b/lib/integrations/openai/openai_prompts/reply.txt
deleted file mode 100644
index 77ff0a72e..000000000
--- a/lib/integrations/openai/openai_prompts/reply.txt
+++ /dev/null
@@ -1 +0,0 @@
-Please suggest a reply to the following conversation between support agents and customer. Don't expose that you are an AI model, respond "Couldn't generate the reply" in cases where you can't answer. Reply in the user\'s language.
diff --git a/enterprise/lib/enterprise/integrations/openai_prompts/summary.txt b/lib/integrations/openai/openai_prompts/summary.liquid
similarity index 93%
rename from enterprise/lib/enterprise/integrations/openai_prompts/summary.txt
rename to lib/integrations/openai/openai_prompts/summary.liquid
index 5196f5b1b..4ec5ffd5b 100644
--- a/enterprise/lib/enterprise/integrations/openai_prompts/summary.txt
+++ b/lib/integrations/openai/openai_prompts/summary.liquid
@@ -1,13 +1,13 @@
-As an AI-powered summarization tool, your task is to condense lengthy interactions between customer support agents and customers into brief, digestible summaries. The objective of these summaries is to provide a quick overview, enabling any agent, even those without prior context, to grasp the essence of the conversation promptly.
+As an AI-powered summarization tool, your task is to condense lengthy interactions between customer support agents and customers into brief, digestible summaries. The objective of these summaries is to provide a quick overview, enabling any agent, even those without prior context, to grasp the essence of the conversation promptly.
Make sure you strongly adhere to the following rules when generating the summary
-1. Be brief and concise. The shorter the summary the better.
-2. Aim to summarize the conversation in approximately 200 words, formatted as multiple small paragraphs that are easier to read.
+1. Be brief and concise. The shorter the summary the better.
+2. Aim to summarize the conversation in approximately 200 words, formatted as multiple small paragraphs that are easier to read.
3. Describe the customer intent in around 50 words.
4. Remove information that is not directly relevant to the customer's problem or the agent's solution. For example, personal anecdotes, small talk, etc.
5. Don't include segments of the conversation that didn't contribute meaningful content, like greetings or farewell.
-6. The 'Action Items' should be a bullet list, arranged in order of priority if possible.
+6. The 'Action Items' should be a bullet list, arranged in order of priority if possible.
7. 'Action Items' should strictly encapsulate tasks committed to by the agent or left incomplete. Any suggestions made by the agent should not be included.
8. The 'Action Items' should be brief and concise
9. Mark important words or parts of sentences as bold.
@@ -25,4 +25,4 @@ Reply in the user's language, as a markdown of the following format.
**Action Items**
-**Follow-up Items**
\ No newline at end of file
+**Follow-up Items**
diff --git a/lib/integrations/openai/openai_prompts/summary.txt b/lib/integrations/openai/openai_prompts/summary.txt
deleted file mode 100644
index 3f1d93227..000000000
--- a/lib/integrations/openai/openai_prompts/summary.txt
+++ /dev/null
@@ -1 +0,0 @@
-Please summarize the key points from the following conversation between support agents and customer as bullet points for the next support agent looking into the conversation. Reply in the user's language.
\ No newline at end of file
diff --git a/lib/integrations/openai/openai_prompts/tone_rewrite.liquid b/lib/integrations/openai/openai_prompts/tone_rewrite.liquid
new file mode 100644
index 000000000..6b62617f0
--- /dev/null
+++ b/lib/integrations/openai/openai_prompts/tone_rewrite.liquid
@@ -0,0 +1,36 @@
+You are an AI writing assistant integrated into Chatwoot, an omnichannel customer support platform. Your task is to rewrite customer support message to match a specific tone while preserving the original meaning and intent.
+
+Here is the tone to apply to the message you will receive:
+
+{% case tone %}
+{% when 'friendly' %}
+Warm, approachable, and personable. Use conversational language, positive words, and show empathy. May include phrases like "Happy to help!" or "I'd be glad to..."
+{% when 'confident' %}
+Assertive and assured. Use definitive language, avoid hedging words like "maybe" or "I think". Be direct and authoritative while remaining helpful.
+{% when 'straightforward' %}
+Clear, direct, and to-the-point. Remove unnecessary words, get straight to the information or solution. No fluff or extra pleasantries.
+{% when 'casual' %}
+Relaxed and informal. Use contractions, simpler words, and a conversational style. Friendly but less formal than professional tone.
+{% when 'professional' %}
+Formal, polished, and business-appropriate. Use complete sentences, proper grammar, and maintain respectful distance. Avoid slang or overly casual language.
+{% else %}
+Warm, approachable, and personable. Use conversational language, positive words, and show empathy. May include phrases like "Happy to help!" or "I'd be glad to..."
+{% endcase %}
+
+
+Your task is to rewrite the message according to the specified tone instructions.
+
+Important guidelines:
+- Preserve the core meaning and all important information from the original message
+- Keep the rewritten message concise and appropriate for customer support
+- Maintain helpfulness and respect regardless of tone
+- Do not add information that wasn't in the original message
+- Do not remove critical details or instructions
+
+Super Important:
+- If the message has some markdown formatting, keep the formatting as it is.
+- Block quotes (lines starting with >) contain quoted text from the customer's previous message. Preserve this quoted text exactly as written (do not modify the customer's words inside the block quote), but DO improve the agent's reply that follows the block quote.
+- Ensure the output is in the user's original language
+- If the message contains a signature block (text after a `--` line), preserve the signature exactly as written without any modification. Do not add a signature if one is not already present.
+
+Output only the rewritten message without any preamble, tags or explanation.
diff --git a/lib/integrations/openai/processor_service.rb b/lib/integrations/openai/processor_service.rb
deleted file mode 100644
index 2f0180701..000000000
--- a/lib/integrations/openai/processor_service.rb
+++ /dev/null
@@ -1,138 +0,0 @@
-class Integrations::Openai::ProcessorService < Integrations::LlmBaseService
- AGENT_INSTRUCTION = 'You are a helpful support agent.'.freeze
- LANGUAGE_INSTRUCTION = 'Ensure that the reply should be in user language.'.freeze
- def reply_suggestion_message
- make_api_call(reply_suggestion_body)
- end
-
- def summarize_message
- make_api_call(summarize_body)
- end
-
- def rephrase_message
- make_api_call(build_api_call_body("#{AGENT_INSTRUCTION} Please rephrase the following response. " \
- "#{LANGUAGE_INSTRUCTION}"))
- end
-
- def fix_spelling_grammar_message
- make_api_call(build_api_call_body("#{AGENT_INSTRUCTION} Please fix the spelling and grammar of the following response. " \
- "#{LANGUAGE_INSTRUCTION}"))
- end
-
- def shorten_message
- make_api_call(build_api_call_body("#{AGENT_INSTRUCTION} Please shorten the following response. " \
- "#{LANGUAGE_INSTRUCTION}"))
- end
-
- def expand_message
- make_api_call(build_api_call_body("#{AGENT_INSTRUCTION} Please expand the following response. " \
- "#{LANGUAGE_INSTRUCTION}"))
- end
-
- def make_friendly_message
- make_api_call(build_api_call_body("#{AGENT_INSTRUCTION} Please make the following response more friendly. " \
- "#{LANGUAGE_INSTRUCTION}"))
- end
-
- def make_formal_message
- make_api_call(build_api_call_body("#{AGENT_INSTRUCTION} Please make the following response more formal. " \
- "#{LANGUAGE_INSTRUCTION}"))
- end
-
- def simplify_message
- make_api_call(build_api_call_body("#{AGENT_INSTRUCTION} Please simplify the following response. " \
- "#{LANGUAGE_INSTRUCTION}"))
- end
-
- private
-
- def prompt_from_file(file_name, enterprise: false)
- path = enterprise ? 'enterprise/lib/enterprise/integrations/openai_prompts' : 'lib/integrations/openai/openai_prompts'
- Rails.root.join(path, "#{file_name}.txt").read
- end
-
- def build_api_call_body(system_content, user_content = event['data']['content'])
- {
- model: GPT_MODEL,
- messages: [
- { role: 'system', content: system_content },
- { role: 'user', content: user_content }
- ]
- }.to_json
- end
-
- def conversation_messages(in_array_format: false)
- messages = init_messages_body(in_array_format)
-
- add_messages_until_token_limit(conversation, messages, in_array_format)
- end
-
- def add_messages_until_token_limit(conversation, messages, in_array_format, start_from = 0)
- character_count = start_from
- conversation.messages.where(message_type: [:incoming, :outgoing]).where(private: false).reorder('id desc').each do |message|
- character_count, message_added = add_message_if_within_limit(character_count, message, messages, in_array_format)
- break unless message_added
- end
- messages
- end
-
- def add_message_if_within_limit(character_count, message, messages, in_array_format)
- content = message.content_for_llm
- if valid_message?(content, character_count)
- add_message_to_list(message, messages, in_array_format, content)
- character_count += content.length
- [character_count, true]
- else
- [character_count, false]
- end
- end
-
- def valid_message?(content, character_count)
- content.present? && character_count + content.length <= TOKEN_LIMIT
- end
-
- def add_message_to_list(message, messages, in_array_format, content)
- formatted_message = format_message(message, in_array_format, content)
- messages.prepend(formatted_message)
- end
-
- def init_messages_body(in_array_format)
- in_array_format ? [] : ''
- end
-
- def format_message(message, in_array_format, content)
- in_array_format ? format_message_in_array(message, content) : format_message_in_string(message, content)
- end
-
- def format_message_in_array(message, content)
- { role: (message.incoming? ? 'user' : 'assistant'), content: content }
- end
-
- def format_message_in_string(message, content)
- sender_type = message.incoming? ? 'Customer' : 'Agent'
- "#{sender_type} #{message.sender&.name} : #{content}\n"
- end
-
- def summarize_body
- {
- model: GPT_MODEL,
- messages: [
- { role: 'system',
- content: prompt_from_file('summary', enterprise: false) },
- { role: 'user', content: conversation_messages }
- ]
- }.to_json
- end
-
- def reply_suggestion_body
- {
- model: GPT_MODEL,
- messages: [
- { role: 'system',
- content: prompt_from_file('reply', enterprise: false) }
- ].concat(conversation_messages(in_array_format: true))
- }.to_json
- end
-end
-
-Integrations::Openai::ProcessorService.prepend_mod_with('Integrations::OpenaiProcessorService')
diff --git a/lib/llm/config.rb b/lib/llm/config.rb
index 94836d746..48de51022 100644
--- a/lib/llm/config.rb
+++ b/lib/llm/config.rb
@@ -1,7 +1,8 @@
require 'ruby_llm'
module Llm::Config
- DEFAULT_MODEL = 'gpt-4o-mini'.freeze
+ DEFAULT_MODEL = 'gpt-4.1-mini'.freeze
+
class << self
def initialized?
@initialized ||= false
diff --git a/lib/tasks/download_report.rake b/lib/tasks/download_report.rake
new file mode 100644
index 000000000..c68418432
--- /dev/null
+++ b/lib/tasks/download_report.rake
@@ -0,0 +1,183 @@
+# Download Report Rake Tasks
+#
+# Usage:
+# POSTGRES_STATEMENT_TIMEOUT=600s NEW_RELIC_AGENT_ENABLED=false bundle exec rake download_report:agent
+# POSTGRES_STATEMENT_TIMEOUT=600s NEW_RELIC_AGENT_ENABLED=false bundle exec rake download_report:inbox
+# POSTGRES_STATEMENT_TIMEOUT=600s NEW_RELIC_AGENT_ENABLED=false bundle exec rake download_report:label
+#
+# The task will prompt for:
+# - Account ID
+# - Start Date (YYYY-MM-DD)
+# - End Date (YYYY-MM-DD)
+# - Timezone Offset (e.g., 0, 5.5, -5)
+# - Business Hours (y/n) - whether to use business hours for time metrics
+#
+# Output:
___.csv
+
+require 'csv'
+
+# rubocop:disable Metrics/CyclomaticComplexity
+# rubocop:disable Metrics/AbcSize
+# rubocop:disable Metrics/MethodLength
+# rubocop:disable Metrics/ModuleLength
+module DownloadReportTasks
+ def self.prompt(message)
+ print "#{message}: "
+ $stdin.gets.chomp
+ end
+
+ def self.collect_params
+ account_id = prompt('Enter Account ID')
+ abort 'Error: Account ID is required' if account_id.blank?
+
+ account = Account.find_by(id: account_id)
+ abort "Error: Account with ID '#{account_id}' not found" unless account
+
+ start_date = prompt('Enter Start Date (YYYY-MM-DD)')
+ abort 'Error: Start date is required' if start_date.blank?
+
+ end_date = prompt('Enter End Date (YYYY-MM-DD)')
+ abort 'Error: End date is required' if end_date.blank?
+
+ timezone_offset = prompt('Enter Timezone Offset (e.g., 0, 5.5, -5)')
+ timezone_offset = timezone_offset.blank? ? 0 : timezone_offset.to_f
+
+ business_hours = prompt('Use Business Hours? (y/n)')
+ business_hours = business_hours.downcase == 'y'
+
+ begin
+ tz = ActiveSupport::TimeZone[timezone_offset]
+ abort "Error: Invalid timezone offset '#{timezone_offset}'" unless tz
+
+ since = tz.parse("#{start_date} 00:00:00").to_i.to_s
+ until_date = tz.parse("#{end_date} 23:59:59").to_i.to_s
+ rescue StandardError => e
+ abort "Error parsing dates: #{e.message}"
+ end
+
+ {
+ account: account,
+ params: { since: since, until: until_date, timezone_offset: timezone_offset, business_hours: business_hours },
+ start_date: start_date,
+ end_date: end_date
+ }
+ end
+
+ def self.save_csv(filename, headers, rows)
+ CSV.open(filename, 'w') do |csv|
+ csv << headers
+ rows.each { |row| csv << row }
+ end
+ puts "Report saved to: #{filename}"
+ end
+
+ def self.format_time(seconds)
+ return '' if seconds.nil? || seconds.zero?
+
+ seconds.round(2)
+ end
+
+ def self.download_agent_report
+ data = collect_params
+ account = data[:account]
+
+ puts "\nGenerating agent report..."
+ builder = V2::Reports::AgentSummaryBuilder.new(account: account, params: data[:params])
+ report = builder.build
+
+ users = account.users.index_by(&:id)
+ headers = %w[id name email conversations_count resolved_conversations_count avg_resolution_time avg_first_response_time avg_reply_time]
+
+ rows = report.map do |row|
+ user = users[row[:id]]
+ [
+ row[:id],
+ user&.name || 'Unknown',
+ user&.email || 'Unknown',
+ row[:conversations_count],
+ row[:resolved_conversations_count],
+ format_time(row[:avg_resolution_time]),
+ format_time(row[:avg_first_response_time]),
+ format_time(row[:avg_reply_time])
+ ]
+ end
+
+ filename = "#{account.id}_agent_#{data[:start_date]}_#{data[:end_date]}.csv"
+ save_csv(filename, headers, rows)
+ end
+
+ def self.download_inbox_report
+ data = collect_params
+ account = data[:account]
+
+ puts "\nGenerating inbox report..."
+ builder = V2::Reports::InboxSummaryBuilder.new(account: account, params: data[:params])
+ report = builder.build
+
+ inboxes = account.inboxes.index_by(&:id)
+ headers = %w[id name conversations_count resolved_conversations_count avg_resolution_time avg_first_response_time avg_reply_time]
+
+ rows = report.map do |row|
+ inbox = inboxes[row[:id]]
+ [
+ row[:id],
+ inbox&.name || 'Unknown',
+ row[:conversations_count],
+ row[:resolved_conversations_count],
+ format_time(row[:avg_resolution_time]),
+ format_time(row[:avg_first_response_time]),
+ format_time(row[:avg_reply_time])
+ ]
+ end
+
+ filename = "#{account.id}_inbox_#{data[:start_date]}_#{data[:end_date]}.csv"
+ save_csv(filename, headers, rows)
+ end
+
+ def self.download_label_report
+ data = collect_params
+ account = data[:account]
+
+ puts "\nGenerating label report..."
+ builder = V2::Reports::LabelSummaryBuilder.new(account: account, params: data[:params])
+ report = builder.build
+
+ headers = %w[id name conversations_count resolved_conversations_count avg_resolution_time avg_first_response_time avg_reply_time]
+
+ rows = report.map do |row|
+ [
+ row[:id],
+ row[:name],
+ row[:conversations_count],
+ row[:resolved_conversations_count],
+ format_time(row[:avg_resolution_time]),
+ format_time(row[:avg_first_response_time]),
+ format_time(row[:avg_reply_time])
+ ]
+ end
+
+ filename = "#{account.id}_label_#{data[:start_date]}_#{data[:end_date]}.csv"
+ save_csv(filename, headers, rows)
+ end
+end
+# rubocop:enable Metrics/CyclomaticComplexity
+# rubocop:enable Metrics/AbcSize
+# rubocop:enable Metrics/MethodLength
+# rubocop:enable Metrics/ModuleLength
+
+namespace :download_report do
+ desc 'Download agent summary report as CSV'
+ task agent: :environment do
+ DownloadReportTasks.download_agent_report
+ end
+
+ desc 'Download inbox summary report as CSV'
+ task inbox: :environment do
+ DownloadReportTasks.download_inbox_report
+ end
+
+ desc 'Download label summary report as CSV'
+ task label: :environment do
+ DownloadReportTasks.download_label_report
+ end
+end
diff --git a/package.json b/package.json
index 75b6c3d38..04821480d 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@chatwoot/chatwoot",
- "version": "4.10.0",
+ "version": "4.10.1",
"license": "MIT",
"scripts": {
"eslint": "eslint app/**/*.{js,vue}",
@@ -31,14 +31,16 @@
}
],
"dependencies": {
+ "@amplitude/analytics-browser": "^2.11.10",
"@breezystack/lamejs": "^1.2.7",
"@chatwoot/ninja-keys": "1.2.3",
- "@chatwoot/prosemirror-schema": "1.3.5",
+ "@chatwoot/prosemirror-schema": "1.3.6",
"@chatwoot/utils": "^0.0.51",
"@formkit/core": "^1.6.7",
"@formkit/vue": "^1.6.7",
"@hcaptcha/vue3-hcaptcha": "^1.3.0",
"@highlightjs/vue-plugin": "^2.1.0",
+ "@iconify-json/fluent": "^1.2.32",
"@iconify-json/material-symbols": "^1.2.10",
"@lk77/vue3-color": "^3.0.6",
"@radix-ui/colors": "^3.0.0",
@@ -83,7 +85,6 @@
"mitt": "^3.0.1",
"opus-recorder": "^8.0.5",
"pinia": "^3.0.4",
- "@amplitude/analytics-browser": "^2.11.10",
"qrcode": "^1.5.4",
"semver": "7.6.3",
"snakecase-keys": "^8.0.1",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 27d0281a6..7a1b6f35f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -23,8 +23,8 @@ importers:
specifier: 1.2.3
version: 1.2.3
'@chatwoot/prosemirror-schema':
- specifier: 1.3.5
- version: 1.3.5
+ specifier: 1.3.6
+ version: 1.3.6
'@chatwoot/utils':
specifier: ^0.0.51
version: 0.0.51
@@ -40,6 +40,9 @@ importers:
'@highlightjs/vue-plugin':
specifier: ^2.1.0
version: 2.1.0(highlight.js@11.10.0)(vue@3.5.12(typescript@5.6.2))
+ '@iconify-json/fluent':
+ specifier: ^1.2.32
+ version: 1.2.36
'@iconify-json/material-symbols':
specifier: ^1.2.10
version: 1.2.10
@@ -454,8 +457,8 @@ packages:
'@chatwoot/ninja-keys@1.2.3':
resolution: {integrity: sha512-xM8d9P5ikDMZm2WbaCTk/TW5HFauylrU3cJ75fq5je6ixKwyhl/0kZbVN/vbbZN4+AUX/OaSIn6IJbtCgIF67g==}
- '@chatwoot/prosemirror-schema@1.3.5':
- resolution: {integrity: sha512-3Koj3jwO1qOxJG84D4FqPOJ6o8k6ehZi1zedO3vKRERATm2Cy1p+ET6FEvVYWUpoBvDwR6hNVScXrcNNVobhsA==}
+ '@chatwoot/prosemirror-schema@1.3.6':
+ resolution: {integrity: sha512-sHRtWqbtiow9mVF1ixim0eGUXfhGK5tuLOdF9Vf53aepjJ+ngEiNVkxQT6FohlEOd886ZsdQxMvmI92IDaUXAQ==}
'@chatwoot/utils@0.0.51':
resolution: {integrity: sha512-WlEmWfOTzR7YZRUWzn5Wpm15/BRudpwqoNckph8TohyDbiim1CP4UZGa+qjajxTbNGLLhtKlm0Xl+X16+5Wceg==}
@@ -961,6 +964,9 @@ packages:
resolution: {integrity: sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==}
deprecated: Use @eslint/object-schema instead
+ '@iconify-json/fluent@1.2.36':
+ resolution: {integrity: sha512-DhxwOu5Qiq09o2ehHeUK0I9lC01OeWFlxXP7pIslM0vbi8VuplrrJ7kMg21GJy87iOCevzxf6gTU7TLPGgSknw==}
+
'@iconify-json/logos@1.2.10':
resolution: {integrity: sha512-qxaXKJ6fu8jzTMPQdHtNxlfx6tBQ0jXRbHZIYy5Ilh8Lx9US9FsAdzZWUR8MXV8PnWTKGDFO4ZZee9VwerCyMA==}
@@ -4993,7 +4999,7 @@ snapshots:
hotkeys-js: 3.8.7
lit: 2.2.6
- '@chatwoot/prosemirror-schema@1.3.5':
+ '@chatwoot/prosemirror-schema@1.3.6':
dependencies:
markdown-it-sup: 2.0.0
prosemirror-commands: 1.6.0
@@ -5513,6 +5519,10 @@ snapshots:
'@humanwhocodes/object-schema@2.0.3': {}
+ '@iconify-json/fluent@1.2.36':
+ dependencies:
+ '@iconify/types': 2.0.0
+
'@iconify-json/logos@1.2.10':
dependencies:
'@iconify/types': 2.0.0
diff --git a/public/brand-assets/logo.svg b/public/brand-assets/logo.svg
index 438f2b4b0..63adcde76 100644
--- a/public/brand-assets/logo.svg
+++ b/public/brand-assets/logo.svg
@@ -1,15 +1,5 @@
-
-
\ No newline at end of file
+
diff --git a/public/brand-assets/logo_dark.svg b/public/brand-assets/logo_dark.svg
index a0f7ac881..679ae4687 100644
--- a/public/brand-assets/logo_dark.svg
+++ b/public/brand-assets/logo_dark.svg
@@ -1,13 +1,5 @@
-
-