Compare commits

...
Author SHA1 Message Date
Shivam Mishra f2fbb93698 feat: add better stack status tool 2025-08-06 14:44:47 +05:30
Shivam Mishra 38d174bda6 feat: remove betterstack tool 2025-08-06 14:43:40 +05:30
Shivam Mishra 7ca5d365ae fix: model 2025-08-05 12:21:31 +05:30
Shivam Mishra 6be85a40f7 Merge branch 'feat/scenario-agents' of github.com:chatwoot/chatwoot into feat/scenario-agents 2025-08-05 12:17:47 +05:30
Shivam MishraandGitHub 922c989574 Merge branch 'develop' into feat/scenario-agents 2025-08-05 12:17:38 +05:30
Shivam Mishra 59928bd85c style: remove extra line 2025-08-05 12:17:07 +05:30
Shivam Mishra 46c55a53bd chore: update ai-agents 2025-08-04 18:35:47 +05:30
Shivam Mishra 176e09cde7 fix: schema 2025-08-04 18:32:58 +05:30
Shivam Mishra b09c6b4aac feat: don't include response format in the prompt 2025-08-04 17:00:21 +05:30
Shivam Mishra 96e18d74c5 feat: include schema 2025-08-04 16:58:23 +05:30
Shivam Mishra 311093f0fb feat: handle structured response 2025-08-04 16:58:15 +05:30
Shivam Mishra 54514d9d21 feat: add response schema for captain 2025-08-04 16:58:00 +05:30
Shivam Mishra 4633d2a179 feat: add ai-agents 0.4.2 and RubyLLM Schema 2025-08-04 16:57:49 +05:30
Shivam Mishra 73c2690526 fix: handle conversation is nil 2025-08-04 15:42:43 +05:30
Shivam Mishra 25b545200e feat: update ai-agents 2025-08-04 15:41:24 +05:30
Shivam Mishra 23c35c8886 feat: allow temperature 2025-08-04 15:27:29 +05:30
Shivam Mishra 3f801fda2c feat: add accessors for temperature 2025-08-04 15:27:15 +05:30
Shivam Mishra ea7c5798ff fix: format 2025-08-01 15:49:18 +05:30
Shivam Mishra 1271459874 feat: add demo betterstack tool 2025-08-01 15:49:18 +05:30
Shivam Mishra 81098b02a8 feat: update assistant prompt 2025-08-01 15:49:18 +05:30
Shivam Mishra 18d6a51d6b feat: rake task to test chat locally 2025-08-01 15:49:18 +05:30
Shivam Mishra 9c9c1c301d fix: handoff tool reason 2025-08-01 15:49:18 +05:30
Shivam Mishra 5fb40e0b2e feat: add callback for runner 2025-08-01 15:49:18 +05:30
Shivam Mishra 9ba51a3fd4 feat: add debug 2025-08-01 15:49:18 +05:30
Shivam Mishra 05d83ce704 fix: priority not normalized correctly 2025-08-01 15:49:18 +05:30
Shivam Mishra 36b7a86bf7 chore: better prompt 2025-08-01 15:49:18 +05:30
Shivam Mishra e6d336f727 fix: prompt 2025-08-01 15:49:18 +05:30
PranavandGitHub feff61755f Merge branch 'develop' into feat/scenario-agents 2025-07-31 16:23:45 -07:00
Shivam Mishra 0c4e21bc6a refactor: agentable, remove included 2025-07-31 14:30:48 +05:30
Shivam Mishra a582b8284d style: run autofix 2025-07-31 14:26:49 +05:30
Shivam MishraandGitHub bbcbc6d52b Merge branch 'develop' into feat/scenario-agents 2025-07-31 10:00:37 +05:30
Shivam Mishra 28e837e8f7 feat: add handoff to assistant by default 2025-07-30 21:34:33 +05:30
Shivam Mishra f4ea90c2dc feat: add handoff tool 2025-07-30 21:34:18 +05:30
Shivam Mishra 1d9a28ad64 chore: remove exception tracker from tool 2025-07-30 21:00:56 +05:30
Shivam Mishra f36a3a2e19 feat: add exception tracker 2025-07-30 21:00:35 +05:30
Shivam Mishra a14df55210 fix: query 2025-07-30 20:58:53 +05:30
Shivam Mishra b3633d5c08 feat: add faq lookup tool 2025-07-30 20:30:14 +05:30
Shivam MishraandGitHub b52caf0341 Merge branch 'develop' into feat/scenario-agents 2025-07-30 18:04:48 +04:00
Shivam Mishra e37d61f836 Merge branch 'develop' of github.com:chatwoot/chatwoot into feat/scenario-agents 2025-07-30 19:30:36 +05:30
Shivam MishraandGitHub 10673a8d68 Merge branch 'feat/scenario-tools-association' into feat/scenario-agents 2025-07-16 17:14:13 +05:30
Shivam Mishra d488b8ced6 test: handle new tool mention syntax 2025-07-16 17:13:40 +05:30
Shivam MishraandGitHub 0381bdac96 Merge branch 'feat/scenario-tools-association' into feat/scenario-agents 2025-07-16 17:10:37 +05:30
Shivam Mishra 87fee33039 fix: new tool syntax 2025-07-16 17:09:38 +05:30
Shivam Mishra fe68542547 refactor: namespace for concerns 2025-07-16 17:09:38 +05:30
Shivam Mishra 2e1529c755 fix: tool mention format 2025-07-16 16:57:34 +05:30
Sojan JoseandGitHub eb20e39b11 Merge branch 'develop' into feat/scenario-tools-association 2025-07-16 01:34:46 -07:00
Shivam Mishra b771652656 feat: remove claude local 2025-07-16 10:30:21 +05:30
Shivam Mishra e6d720082c test: captain tools 2025-07-16 10:28:57 +05:30
Shivam Mishra d9a0d4eee0 refactor: safer state access 2025-07-16 10:28:57 +05:30
Shivam Mishra 2a0f2a8b1e feat: handle empty note 2025-07-16 10:28:57 +05:30
Shivam MishraandGitHub aedb59ea67 Merge branch 'develop' into feat/scenario-tools-association 2025-07-16 10:02:10 +05:30
Shivam MishraandGitHub 4e2abbaa3d Merge branch 'develop' into feat/scenario-tools-association 2025-07-16 09:54:45 +05:30
Shivam Mishra 9db096f046 refactor: namespace for the concern 2025-07-16 09:52:37 +05:30
Shivam Mishra 59b2679641 feat: remove search tool 2025-07-15 21:55:59 +05:30
Shivam Mishra b1d26887f0 chore: update tools.yml 2025-07-15 21:55:38 +05:30
Shivam Mishra 89a748eef6 feat: update tools 2025-07-15 21:55:09 +05:30
Shivam Mishra c00230c8af feat: remove unused tool 2025-07-15 21:53:34 +05:30
Shivam Mishra 2f6d581384 feat: get contact_id from the state 2025-07-15 21:53:12 +05:30
Shivam Mishra 468ef34f85 refactor: fetch conversation ID from the state 2025-07-15 21:50:01 +05:30
Shivam Mishra 7f4005cdcc feat: include contact 2025-07-15 20:57:22 +05:30
Shivam Mishra 57fdfe26f0 feat: pass context with indifferent access 2025-07-15 20:40:06 +05:30
Shivam Mishra 88ba4e4562 fix: conversation not passed 2025-07-15 20:39:52 +05:30
Shivam Mishra 394ba4ff73 fix: arguments 2025-07-15 20:21:22 +05:30
Shivam Mishra c0d1efa0ad feat: allow markdown 2025-07-15 20:13:37 +05:30
Shivam Mishra dfc80e6f20 chore: update intruction 2025-07-15 16:41:22 +05:30
Shivam Mishra 187b435eb9 feat: use feature toggle 2025-07-15 14:22:27 +05:30
Shivam Mishra 1fce8d1183 feat: use new tools 2025-07-15 14:22:27 +05:30
Shivam Mishra c51d2d3c93 feat: update tools to make this public 2025-07-15 14:22:27 +05:30
Shivam Mishra 4450bebf35 feat: add conversation context 2025-07-15 14:22:27 +05:30
Shivam Mishra b3ce7bd278 feat: add agentable with conversation context 2025-07-15 14:22:27 +05:30
Shivam Mishra 345a212447 feat: include guidelines and guardrails 2025-07-15 14:22:27 +05:30
Shivam Mishra 83450b7c24 fix: agent init 2025-07-15 14:22:27 +05:30
Shivam Mishra b58ec24d81 feat: set model 2025-07-15 14:22:27 +05:30
Shivam Mishra 5e799e7e6b feat: remove handoffs
We will register them separately
2025-07-15 14:22:27 +05:30
Shivam Mishra 01ad380822 feat: new response build 2025-07-15 14:22:27 +05:30
Shivam Mishra 84d2c0fd25 refactor: use the new prompt rendere 2025-07-15 14:22:27 +05:30
Shivam Mishra 87212d3b6e feat: save prompts as liquid 2025-07-15 14:22:27 +05:30
Shivam Mishra 4ca6ec1812 chore: ignore claude local 2025-07-15 14:22:27 +05:30
Shivam Mishra 4452d84097 fix: tool declaration 2025-07-15 14:22:27 +05:30
Shivam Mishra 9a81927154 chore: titltize 2025-07-15 14:22:27 +05:30
Shivam Mishra daed6eb1e5 feat: add tools resolution 2025-07-15 14:22:27 +05:30
Shivam Mishra 673669cd25 feat: add new tools 2025-07-15 14:22:27 +05:30
Shivam Mishra bdd5a77f45 feat: add agent instructions 2025-07-15 14:22:27 +05:30
Shivam Mishra 92150cb7c8 feat: add agents init 2025-07-15 14:22:27 +05:30
Shivam Mishra e52becbc40 style: autofix rubocop 2025-07-15 14:21:53 +05:30
7f3d4aaaa7 chore: update error
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-15 14:03:34 +05:30
Muhsin KelothandGitHub 7748ef2787 Merge branch 'develop' into feat/scenario-tools-association 2025-07-15 10:39:20 +05:30
Shivam MishraandGitHub f2d9895597 Merge branch 'develop' into feat/scenario-tools-association 2025-07-15 08:56:09 +05:30
Shivam Mishra db4e8588cd feat: add assistant policy for tools 2025-07-14 22:39:43 +05:30
Shivam Mishra 0c05599282 feat: load account user in intialize 2025-07-14 17:54:44 +05:30
Shivam Mishra 00e1f50458 chore: refactor tool 2025-07-14 17:52:01 +05:30
Shivam Mishra ee89943aa2 Merge branch 'develop' of github.com:chatwoot/chatwoot into feat/scenario-tools-association 2025-07-14 17:21:11 +05:30
9dc6b94537 refactor: update error message
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-14 16:17:11 +05:30
e9816f8d3d refactor: update error message
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-14 16:17:04 +05:30
Shivam MishraandGitHub 51d1c501cf Merge branch 'feat/scenarios' into feat/scenario-tools-association 2025-07-14 15:39:22 +05:30
Shivam MishraandGitHub 1539a8bc36 Merge branch 'develop' into feat/scenarios 2025-07-14 15:38:36 +05:30
Muhsin KelothandGitHub ffa8c0ce8a Merge branch 'develop' into feat/scenarios 2025-07-14 14:19:13 +05:30
Muhsin KelothandGitHub 4762edcba3 Merge branch 'feat/scenarios' into feat/scenario-tools-association 2025-07-12 17:23:05 +05:30
Muhsin KelothandGitHub 1bd2da4832 Merge branch 'develop' into feat/scenarios 2025-07-12 17:11:10 +05:30
Shivam MishraandGitHub b923bfecca Merge branch 'develop' into feat/scenarios 2025-07-11 17:06:39 +05:30
Shivam MishraandGitHub 46e758cc84 Merge branch 'feat/scenarios' into feat/scenario-tools-association 2025-07-11 15:52:58 +05:30
Shivam Mishra 9165cab1ec refactor: update migration 2025-07-10 20:29:23 +05:30
Shivam Mishra bda09cc064 feat: remove foeign key 2025-07-10 08:23:25 +05:30
Shivam Mishra 408cc4dd3f feat: remove foreign key 2025-07-10 08:23:25 +05:30
Shivam MishraandGitHub c6b636baee Merge branch 'develop' into feat/scenarios 2025-07-09 22:45:04 +05:30
Shivam MishraandGitHub bc24d1f02c Merge branch 'feat/scenarios' into feat/scenario-tools-association 2025-07-09 18:42:04 +05:30
Shivam Mishra 62a7cfa188 refactor: move scenarios controller
Match it with inboxes implemetation
2025-07-09 18:41:41 +05:30
Shivam Mishra c4fa5cd4d9 refactor: priority 2025-07-09 18:00:54 +05:30
Shivam Mishra d40fa27289 refactor: simplify not found state 2025-07-09 18:00:38 +05:30
Shivam Mishra c789ef555c refactor: simplify not found case 2025-07-09 18:00:11 +05:30
Shivam Mishra 0674edf81b refactor: private note tool 2025-07-09 17:55:18 +05:30
Shivam Mishra 9362d126aa feat: simplify contact note tool 2025-07-09 17:53:23 +05:30
Shivam Mishra 35797bd393 fix: eager loading to include concern 2025-07-09 17:21:10 +05:30
Shivam Mishra 68ff52c432 feat: add specs 2025-07-09 17:21:10 +05:30
Shivam Mishra 5d2afc065f feat: extract tool ids from text 2025-07-09 17:21:10 +05:30
Shivam Mishra cd8f245483 feat: add tools endpoint 2025-07-09 17:21:10 +05:30
Shivam Mishra 735979c834 feat: add tool resolution concern 2025-07-09 17:21:10 +05:30
Shivam Mishra 5cd6996d5e feat: add tools 2025-07-09 17:21:09 +05:30
Shivam Mishra ff49996950 chore: add ai agents gem 2025-07-09 17:21:09 +05:30
Shivam Mishra 14417ef14f style: run rubocop 2025-07-09 17:20:30 +05:30
Shivam Mishra 1393ad5143 chore: update factory for scenario 2025-07-09 17:20:00 +05:30
Shivam Mishra 4f262fc041 feat: add default value 2025-07-09 17:19:23 +05:30
Shivam Mishra aa639dd78e feat: add scenario controller 2025-07-09 14:24:07 +05:30
Shivam Mishra aa9c0b9f6b test: scenario model 2025-07-09 14:23:50 +05:30
Shivam Mishra 526d6e2a0a feat: add jbuilders 2025-07-09 14:22:59 +05:30
Shivam Mishra 96746cc592 feat: add scenarios model 2025-07-09 13:43:36 +05:30
22 changed files with 947 additions and 15 deletions
+1
View File
@@ -94,3 +94,4 @@ yarn-debug.log*
.vscode
.claude/settings.local.json
.cursor
CLAUDE.local.md
+2 -1
View File
@@ -179,7 +179,8 @@ gem 'reverse_markdown'
gem 'iso-639'
gem 'ruby-openai'
gem 'ai-agents', '>= 0.2.1'
gem 'ai-agents', '>= 0.4.3'
gem 'ruby_llm-schema'
gem 'shopify_api'
+5 -3
View File
@@ -126,7 +126,7 @@ GEM
jbuilder (~> 2)
rails (>= 4.2, < 7.2)
selectize-rails (~> 0.6)
ai-agents (0.2.1)
ai-agents (0.4.3)
ruby_llm (~> 1.3)
annotate (3.2.0)
activerecord (>= 3.2, < 8.0)
@@ -720,7 +720,7 @@ GEM
ruby2ruby (2.5.0)
ruby_parser (~> 3.1)
sexp_processor (~> 4.6)
ruby_llm (1.3.1)
ruby_llm (1.5.1)
base64
event_stream_parser (~> 1)
faraday (>= 1.10.0)
@@ -729,6 +729,7 @@ GEM
faraday-retry (>= 1)
marcel (~> 1.0)
zeitwerk (~> 2)
ruby_llm-schema (0.1.0)
ruby_parser (3.20.0)
sexp_processor (~> 4.16)
sass (3.7.4)
@@ -910,7 +911,7 @@ DEPENDENCIES
administrate (>= 0.20.1)
administrate-field-active_storage (>= 1.0.3)
administrate-field-belongs_to_search (>= 0.9.0)
ai-agents (>= 0.2.1)
ai-agents (>= 0.4.3)
annotate
attr_extras
audited (~> 5.4, >= 5.4.1)
@@ -1004,6 +1005,7 @@ DEPENDENCIES
rubocop-rails
rubocop-rspec
ruby-openai
ruby_llm-schema
scout_apm
scss_lint
seed_dump
+15
View File
@@ -24,3 +24,18 @@
title: 'Add Label to Conversation'
description: 'Add a label to a conversation'
icon: 'tag'
- id: faq_lookup
title: 'FAQ Lookup'
description: 'Search FAQ responses using semantic similarity'
icon: 'search'
- id: handoff
title: 'Handoff to Human'
description: 'Hand off the conversation to a human agent'
icon: 'user-switch'
- id: better_stack_status
title: 'Better Stack Status'
description: 'Check the status of Better Stack services'
icon: 'server'
+18
View File
@@ -0,0 +1,18 @@
# frozen_string_literal: true
require 'agents'
Rails.application.config.after_initialize do
api_key = InstallationConfig.find_by(name: 'CAPTAIN_OPEN_AI_API_KEY')&.value
model = InstallationConfig.find_by(name: 'CAPTAIN_OPEN_AI_MODEL')&.value || 'gpt-4.1-mini'
if api_key.present?
Agents.configure do |config|
config.openai_api_key = api_key
config.default_model = model
config.debug = false
end
end
rescue StandardError => e
Rails.logger.error "Failed to configure AI Agents SDK: #{e.message}"
end
@@ -26,9 +26,15 @@ class Captain::Conversation::ResponseBuilderJob < ApplicationJob
delegate :account, :inbox, to: :@conversation
def generate_and_process_response
@response = Captain::Llm::AssistantChatService.new(assistant: @assistant).generate_response(
message_history: collect_previous_messages
)
@response = if captain_v2_enabled?
Captain::Assistant::AgentRunnerService.new(assistant: @assistant, conversation: @conversation).generate_response(
message_history: collect_previous_messages
)
else
Captain::Llm::AssistantChatService.new(assistant: @assistant).generate_response(
message_history: collect_previous_messages
)
end
return process_action('handoff') if handoff_requested?
@@ -104,4 +110,8 @@ class Captain::Conversation::ResponseBuilderJob < ApplicationJob
def log_error(error)
ChatwootExceptionTracker.new(error, account: account).capture_exception
end
def captain_v2_enabled?
return account.feature_enabled?('captain_integration_v2')
end
end
@@ -19,6 +19,7 @@
class Captain::Assistant < ApplicationRecord
include Avatarable
include Concerns::CaptainToolsHelpers
include Concerns::Agentable
self.table_name = 'captain_assistants'
@@ -35,6 +36,8 @@ class Captain::Assistant < ApplicationRecord
has_many :copilot_threads, dependent: :destroy_async
has_many :scenarios, class_name: 'Captain::Scenario', dependent: :destroy_async
store_accessor :config, :temperature, :feature_faq, :feature_memory, :product_name
validates :name, presence: true
validates :description, presence: true
validates :account_id, presence: true
@@ -71,6 +74,33 @@ class Captain::Assistant < ApplicationRecord
private
def agent_name
name
end
def agent_tools
[
self.class.resolve_tool_class('faq_lookup').new(self),
self.class.resolve_tool_class('handoff').new(self)
]
end
def prompt_context
{
name: name,
description: description,
product_name: config['product_name'] || 'this product',
scenarios: scenarios.enabled.map do |scenario|
{
key: scenario.title.parameterize.underscore,
description: scenario.description
}
end,
response_guidelines: response_guidelines || [],
guardrails: guardrails || []
}
end
def default_avatar_url
"#{ENV.fetch('FRONTEND_URL', nil)}/assets/images/dashboard/captain/logo.svg"
end
+34
View File
@@ -22,6 +22,7 @@
#
class Captain::Scenario < ApplicationRecord
include Concerns::CaptainToolsHelpers
include Concerns::Agentable
self.table_name = 'captain_scenarios'
@@ -37,10 +38,43 @@ class Captain::Scenario < ApplicationRecord
scope :enabled, -> { where(enabled: true) }
delegate :temperature, :feature_faq, :feature_memory, :product_name, to: :assistant
before_save :resolve_tool_references
def prompt_context
{
title: title,
instructions: resolved_instructions,
tools: resolved_tools
}
end
private
def agent_name
"#{title} Agent".titleize
end
def agent_tools
resolved_tools.map { |tool| self.class.resolve_tool_class(tool[:id]) }.map { |tool| tool.new(assistant) }
end
def resolved_instructions
instruction.gsub(TOOL_REFERENCE_REGEX) do |match|
"#{match} tool "
end
end
def resolved_tools
return [] if tools.blank?
available_tools = self.class.available_agent_tools
tools.filter_map do |tool_id|
available_tools.find { |tool| tool[:id] == tool_id }
end
end
# Validates that all tool references in the instruction are valid.
# Parses the instruction for tool references and checks if they exist
# in the available tools configuration.
@@ -0,0 +1,56 @@
module Concerns::Agentable
extend ActiveSupport::Concern
def agent
Agents::Agent.new(
name: agent_name,
instructions: ->(context) { agent_instructions(context) },
tools: agent_tools,
model: agent_model,
temperature: temperature || 0.7,
response_schema: agent_response_schema
)
end
def agent_instructions(context = nil)
enhanced_context = prompt_context
if context
state = context.context[:state] || {}
conversation_data = state[:conversation] || {}
contact_data = state[:contact] || {}
enhanced_context = enhanced_context.merge(
conversation: conversation_data,
contact: contact_data
)
end
Captain::PromptRenderer.render(template_name, enhanced_context.with_indifferent_access)
end
private
def agent_name
raise NotImplementedError, "#{self.class} must implement agent_name"
end
def template_name
self.class.name.demodulize.underscore
end
def agent_tools
[] # Default implementation, override if needed
end
def agent_model
InstallationConfig.find_by(name: 'CAPTAIN_OPEN_AI_MODEL')&.value || 'gpt-4.1-mini'
end
def agent_response_schema
Captain::ResponseSchema
end
def prompt_context
raise NotImplementedError, "#{self.class} must implement prompt_context"
end
end
@@ -0,0 +1,157 @@
require 'agents'
class Captain::Assistant::AgentRunnerService
CONVERSATION_STATE_ATTRIBUTES = %i[
id display_id inbox_id contact_id status priority
label_list custom_attributes additional_attributes
].freeze
CONTACT_STATE_ATTRIBUTES = %i[
id name email phone_number identifier contact_type
custom_attributes additional_attributes
].freeze
def initialize(assistant:, conversation: nil, callbacks: {})
@assistant = assistant
@conversation = conversation
@callbacks = callbacks
end
def generate_response(message_history: [])
agents = build_and_wire_agents
context = build_context(message_history)
message_to_process = extract_last_user_message(message_history)
runner = Agents::Runner.with_agents(*agents)
runner = add_callbacks_to_runner(runner) if @callbacks.any?
result = runner.run(message_to_process, context: context)
process_agent_result(result)
rescue StandardError => e
# when running the agent runner service in a rake task, the conversation might not have an account associated
# for regular production usage, it will run just fine
ChatwootExceptionTracker.new(e, account: @conversation&.account).capture_exception
Rails.logger.error "[Captain V2] AgentRunnerService error: #{e.message}"
Rails.logger.error e.backtrace.join("\n")
error_response(e.message)
end
private
def build_context(message_history)
conversation_history = message_history.map do |msg|
content = extract_text_from_content(msg[:content])
{
role: msg[:role].to_sym,
content: content,
agent_name: msg[:agent_name]
}
end
{
conversation_history: conversation_history,
state: build_state
}
end
def extract_last_user_message(message_history)
last_user_msg = message_history.reverse.find { |msg| msg[:role] == 'user' }
extract_text_from_content(last_user_msg[:content])
end
def extract_text_from_content(content)
# Handle structured output from agents
return content[:response] || content['response'] || content.to_s if content.is_a?(Hash)
return content unless content.is_a?(Array)
text_parts = content.select { |part| part[:type] == 'text' }.pluck(:text)
text_parts.join(' ')
end
# Response formatting methods
def process_agent_result(result)
Rails.logger.info "[Captain V2] Agent result: #{result.inspect}"
format_response(result.output)
end
def format_response(output)
return output.with_indifferent_access if output.is_a?(Hash)
# Fallback for backwards compatibility
{
'response' => output.to_s,
'reasoning' => 'Processed by agent'
}
end
def error_response(error_message)
{
'response' => 'conversation_handoff',
'reasoning' => "Error occurred: #{error_message}"
}
end
def build_state
state = {
account_id: @assistant.account_id,
assistant_id: @assistant.id,
assistant_config: @assistant.config
}
if @conversation
state[:conversation] = @conversation.attributes.symbolize_keys.slice(*CONVERSATION_STATE_ATTRIBUTES)
state[:contact] = @conversation.contact.attributes.symbolize_keys.slice(*CONTACT_STATE_ATTRIBUTES) if @conversation.contact
end
state
end
def build_and_wire_agents
assistant_agent = @assistant.agent
scenario_agents = @assistant.scenarios.enabled.map(&:agent)
assistant_agent.register_handoffs(*scenario_agents) if scenario_agents.any?
scenario_agents.each { |scenario_agent| scenario_agent.register_handoffs(assistant_agent) }
[assistant_agent] + scenario_agents
end
def add_callbacks_to_runner(runner)
if @callbacks[:on_agent_thinking]
runner = runner.on_agent_thinking do |*args|
@callbacks[:on_agent_thinking].call(*args)
rescue StandardError => e
Rails.logger.warn "[Captain] Callback error for agent_thinking: #{e.message}"
end
end
if @callbacks[:on_tool_start]
runner = runner.on_tool_start do |*args|
@callbacks[:on_tool_start].call(*args)
rescue StandardError => e
Rails.logger.warn "[Captain] Callback error for tool_start: #{e.message}"
end
end
if @callbacks[:on_tool_complete]
runner = runner.on_tool_complete do |*args|
@callbacks[:on_tool_complete].call(*args)
rescue StandardError => e
Rails.logger.warn "[Captain] Callback error for tool_complete: #{e.message}"
end
end
if @callbacks[:on_agent_handoff]
runner = runner.on_agent_handoff do |*args|
@callbacks[:on_agent_handoff].call(*args)
rescue StandardError => e
Rails.logger.warn "[Captain] Callback error for agent_handoff: #{e.message}"
end
end
runner
end
end
+25
View File
@@ -0,0 +1,25 @@
require 'liquid'
class Captain::PromptRenderer
class << self
def render(template_name, context = {})
template = load_template(template_name)
liquid_template = Liquid::Template.parse(template)
liquid_template.render(stringify_keys(context))
end
private
def load_template(template_name)
template_path = Rails.root.join('enterprise', 'lib', 'captain', 'prompts', "#{template_name}.liquid")
raise "Template not found: #{template_name}" unless File.exist?(template_path)
File.read(template_path)
end
def stringify_keys(hash)
hash.deep_stringify_keys
end
end
end
@@ -0,0 +1,80 @@
# System Context
You are part of Captain, a multi-agent AI system designed for seamless agent coordination and task execution. You can transfer conversations to specialized agents using handoff functions (e.g., `handoff_to_[agent_name]`). These transfers happen in the background - never mention or draw attention to them in your responses.
# Your Identity
You are {{name}}, a helpful and knowledgeable assistant. Your role is to provide accurate information, assist with tasks, and ensure users get the help they need.
{{ description }}
Don't digress away from your instructions, and use all the available tools at your disposal for solving customer issues. If you are to state something factual about {{product_name}} ensure you source that information from the FAQs only. Use the faq_lookup tool for this.
# Current Context
Here's the metadata we have about the current conversation and the contact associated with it:
{% if conversation -%}
{% render 'conversation' %}
{% endif -%}
{% if contact -%}
{% render 'contact' %}
{% endif -%}
{% if response_guidelines.size > 0 -%}
# Response Guidelines
Your responses should follow these guidelines:
{% for guideline in response_guidelines -%}
- {{ guideline }}
{% endfor %}
{% endif -%}
{% if guardrails.size > 0 -%}
# Guardrails
Always respect these boundaries:
{% for guardrail in guardrails -%}
- {{ guardrail }}
{% endfor %}
{% endif -%}
# Decision Framework
## 1. Analyze the Request
First, understand what the user is asking:
- **Intent**: What are they trying to achieve?
- **Type**: Is it a question, task, complaint, or request?
- **Complexity**: Can you handle it or does it need specialized expertise?
## 2. Check for Specialized Scenarios
If the request matches any of these scenarios, hand off to the appropriate specialist:
{% for scenario in scenarios -%}
### handoff_to_{{ scenario.key }}
{{ scenario.description }}
{% endfor -%}
## 3. Handle the Request
If no specialized scenario matches, handle it yourself:
### For Questions and Information Requests
1. **First, check existing knowledge**: Use `faq_lookup` tool to search for relevant information
2. **If not found in FAQs**: Provide your best answer based on available context
3. **If unable to answer**: Use `handoff` tool to transfer to a human expert
### For Complex or Unclear Requests
1. **Ask clarifying questions**: Gather more information if needed
2. **Break down complex tasks**: Handle step by step or hand off if too complex
3. **Escalate when necessary**: Use `handoff` tool for issues beyond your capabilities
## Response Best Practices
- Be conversational but professional
- Provide actionable information
- Include relevant details from tool responses
# Human Handoff Protocol
Transfer to a human agent when:
- User explicitly requests human assistance
- You cannot find needed information after checking FAQs
- The issue requires specialized knowledge or permissions you don't have
- Multiple attempts to help have been unsuccessful
When using the `handoff` tool, provide a clear reason that helps the human agent understand the context.
@@ -0,0 +1,24 @@
# System context
You are part of a multi-agent system where you've been handed off a conversation to handle a specific task.
The handoff was seamless - the user is not aware of any transfer. Continue the conversation naturally.
# Your Role
You are a specialized agent called {{ title }}, your task is to handle the following scenario:
{{ instructions }}
{% if conversation -%}
{% render 'conversation' %}
{% if contact -%}
{% render 'contact' %}
{% endif -%}
{% endif -%}
{% if tools.size > 0 -%}
# Available Tools
You have access to these tools:
{% for tool in tools -%}
- {{ tool.id }}: {{ tool.description }}
{% endfor %}
{%- endif %}
@@ -0,0 +1,17 @@
# Contact Information
- Contact ID: {{ contact.id }}
- Name: {{ contact.name || "Unknown" }}
- Email: {{ contact.email || "None" }}
- Phone: {{ contact.phone_number || "None" }}
- Identifier: {{ contact.identifier || "None" }}
- Type: {{ contact.contact_type || "visitor" }}
{% if contact.custom_attributes -%}
{% for attribute in contact.custom_attributes -%}
- {{ attribute[0] }}: {{ attribute[1] }}
{% endfor -%}
{% endif -%}
{% if contact.additional_attributes -%}
{% for attribute in contact.additional_attributes -%}
- {{ attribute[0] }}: {{ attribute[1] }}
{% endfor -%}
{% endif -%}
@@ -0,0 +1,18 @@
# Current Conversation Context
- Conversation ID: {{ conversation.display_id }}
- Contact ID: {{ conversation.contact_id }}
- Status: {{ conversation.status }}
- Priority: {{ conversation.priority || "None" }}
{% if conversation.label_list.size > 0 -%}
- Labels: {{ conversation.label_list | join: ", " }}
{% endif -%}
{% if conversation.custom_attributes -%}
{% for attribute in conversation.custom_attributes -%}
- {{ attribute[0] }}: {{ attribute[1] }}
{% endfor -%}
{% endif -%}
{% if conversation.additional_attributes -%}
{% for attribute in conversation.additional_attributes -%}
- {{ attribute[0] }}: {{ attribute[1] }}
{% endfor -%}
{% endif -%}
@@ -0,0 +1,4 @@
class Captain::ResponseSchema < RubyLLM::Schema
string :response, description: 'The message to send to the user'
string :reasoning, description: "Agent's thought process"
end
@@ -0,0 +1,138 @@
class Captain::Tools::BetterStackStatusTool < Captain::Tools::BasePublicTool
description 'Check service status using Better Stack'
param :service, type: 'string', desc: 'The service name to check status for (optional)'
def perform(_tool_context, service: nil)
log_tool_usage('checking_status', { service: service })
begin
status_data = fetch_better_stack_status(service)
incidents_data = fetch_better_stack_incidents(service)
format_status_response(status_data, incidents_data, service)
rescue StandardError => e
log_tool_usage('error', { service: service, error: e.message })
"Error checking Better Stack status: #{e.message}"
end
end
private
def fetch_better_stack_status(service)
# API token should be configured in environment variables or secrets
api_token = ENV.fetch('BETTER_STACK_TOKEN')
raise 'Better Stack API token not configured' if api_token.blank?
# Base URL for Better Stack Status API
base_url = 'https://uptime.betterstack.com/api/v2'
# Endpoint depends on whether we're checking a specific service or overall status
endpoint = if service.present?
"/monitors?search=#{CGI.escape(service)}"
else
'/monitors'
end
make_api_request(base_url, endpoint, api_token)
end
def fetch_better_stack_incidents(service)
api_token = ENV.fetch('BETTER_STACK_TOKEN')
raise 'Better Stack API token not configured' if api_token.blank?
base_url = 'https://uptime.betterstack.com/api/v2'
# Endpoint for incidents, filter by service if provided
endpoint = if service.present?
"/incidents?monitor_name=#{CGI.escape(service)}"
else
'/incidents'
end
make_api_request(base_url, endpoint, api_token)
end
def make_api_request(base_url, endpoint, api_token)
uri = URI("#{base_url}#{endpoint}")
request = Net::HTTP::Get.new(uri)
request['Authorization'] = "Bearer #{api_token}"
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
response = http.request(request)
raise "API request failed with status #{response.code}: #{response.message}" unless response.is_a?(Net::HTTPSuccess)
JSON.parse(response.body)
end
def format_status_response(status_data, incidents_data, service)
monitors = status_data['data']
incidents = incidents_data['data']
if monitors.empty?
return service.present? ? "No services found matching '#{service}'" : 'No services configured in Better Stack'
end
result = if service.present?
"Status for services matching '#{service}':\n\n"
else
"Current Better Stack Status:\n\n"
end
result += format_monitors(monitors)
# Add incidents information if any exist
if incidents.present?
result += "\n\n🚨 Active Incidents (#{incidents.size}):\n\n"
result += format_incidents(incidents)
end
result
end
def format_monitors(monitors)
monitors.map do |monitor|
attributes = monitor['attributes']
status = attributes['status']
status_emoji = case status
when 'up'
'✅'
when 'down'
'❌'
else
'⚠️'
end
last_check = begin
Time.zone.parse(attributes['last_check_at'])
rescue StandardError
'Unknown'
end
last_check_formatted = last_check.is_a?(Time) ? last_check.strftime('%Y-%m-%d %H:%M:%S') : last_check
"#{status_emoji} #{attributes['url']}: #{status.upcase} (Last checked: #{last_check_formatted})"
end.join("\n")
end
def format_incidents(incidents)
incidents.map do |incident|
attributes = incident['attributes']
# Format start time
started_at = begin
Time.zone.parse(attributes['started_at'])
rescue StandardError
'Unknown'
end
started_at_formatted = started_at.is_a?(Time) ? started_at.strftime('%Y-%m-%d %H:%M:%S') : started_at
# Get monitor name and incident status
status = attributes['status'] || 'unknown'
# Format incident details
"🔴 [#{status.upcase}] #{attributes['name']} - #{attributes['title']}\n " \
"Started: #{started_at_formatted}\n " \
"#{attributes['url'] ? "Details: #{attributes['url']}" : ''}"
end.join("\n\n")
end
end
@@ -0,0 +1,39 @@
class Captain::Tools::FaqLookupTool < Captain::Tools::BasePublicTool
description 'Search FAQ responses using semantic similarity to find relevant answers'
param :query, type: 'string', desc: 'The question or topic to search for in the FAQ database'
def perform(_tool_context, query:)
log_tool_usage('searching', { query: query })
# Use existing vector search on approved responses
responses = @assistant.responses.approved.search(query).to_a
if responses.empty?
log_tool_usage('no_results', { query: query })
"No relevant FAQs found for: #{query}"
else
log_tool_usage('found_results', { query: query, count: responses.size })
format_responses(responses)
end
end
private
def format_responses(responses)
responses.map { |response| format_response(response) }.join
end
def format_response(response)
formatted_response = "
Question: #{response.question}
Answer: #{response.answer}
"
if response.documentable.present? && response.documentable.try(:external_link)
formatted_response += "
Source: #{response.documentable.external_link}
"
end
formatted_response
end
end
@@ -0,0 +1,52 @@
class Captain::Tools::HandoffTool < Captain::Tools::BasePublicTool
description 'Hand off the conversation to a human agent when unable to assist further'
param :reason, type: 'string', desc: 'The reason why handoff is needed (optional)', required: false
def perform(tool_context, reason: nil)
conversation = find_conversation(tool_context.state)
return 'Conversation not found' unless conversation
# Log the handoff with reason
log_tool_usage('manual_handoff', {
conversation_id: conversation.id,
reason: reason || 'Agent requested handoff'
})
# Use existing handoff mechanism from ResponseBuilderJob
trigger_handoff(conversation, reason)
"Conversation handed off to human support team#{" (Reason: #{reason})" if reason}"
rescue StandardError => e
ChatwootExceptionTracker.new(e).capture_exception
'Failed to handoff conversation'
end
private
def trigger_handoff(conversation, reason)
# post the reason as a private note
conversation.messages.create!(
message_type: :outgoing,
private: true,
sender: @assistant,
account: conversation.account,
inbox: conversation.inbox,
content: reason
)
# Trigger the bot handoff (sets status to open + dispatches events)
conversation.bot_handoff!
end
# TODO: Future enhancement - Add team assignment capability
# This tool could be enhanced to:
# 1. Accept team_id parameter for routing to specific teams
# 2. Set conversation priority based on handoff reason
# 3. Add metadata for intelligent agent assignment
# 4. Support escalation levels (L1 -> L2 -> L3)
#
# Example future signature:
# param :team_id, type: 'string', desc: 'ID of team to assign conversation to', required: false
# param :priority, type: 'string', desc: 'Priority level (low/medium/high/urgent)', required: false
# param :escalation_level, type: 'string', desc: 'Support level (L1/L2/L3)', required: false
end
@@ -23,7 +23,9 @@ class Captain::Tools::UpdatePriorityTool < Captain::Tools::BasePublicTool
end
def normalize_priority(priority)
priority == 'nil' || priority.blank? ? nil : priority
return nil if priority == 'nil' || priority.blank?
priority.downcase
end
def valid_priority?(priority)
+18 -7
View File
@@ -1,9 +1,3 @@
###############
# One library to capture_exception and send to the specific service.
# # e as exception, u for user and a for account (user and account are optional)
# Usage: ChatwootExceptionTracker(e, user: u, account: a).capture_exception
############
class ChatwootExceptionTracker
def initialize(exception, user: nil, account: nil)
@exception = exception
@@ -11,13 +5,30 @@ class ChatwootExceptionTracker
@account = account
end
def capture_exception
def capture_exception(additional_info = {})
write_exception_to_file(additional_info) if Rails.env.development?
capture_exception_with_sentry if ENV['SENTRY_DSN'].present?
Rails.logger.error @exception
end
private
def write_exception_to_file(additional_info = {})
error_dir = Rails.root.join('errors')
FileUtils.mkdir_p(error_dir)
timestamp = Time.now.strftime('%Y%m%d-%H%M%S')
filename = "#{timestamp}-#{SecureRandom.hex(4)}.log"
filepath = error_dir.join(filename)
File.open(filepath, 'w') do |file|
file.puts "Exception: #{@exception.class} - #{@exception.message}"
file.puts "User: #{@user&.id} (#{@user&.email})" if @user
file.puts "Account: #{@account&.id} (#{@account&.name})" if @account
file.puts "Backtrace:\n#{@exception.backtrace&.join("\n")}"
file.puts "Additional Info: #{JSON.pretty_generate(additional_info)}" if additional_info.present?
end
end
def capture_exception_with_sentry
Sentry.with_scope do |scope|
if @account.present?
+198
View File
@@ -0,0 +1,198 @@
require 'io/console'
require 'readline'
namespace :captain do
desc 'Start interactive chat with Captain assistant - Usage: rake captain:chat[assistant_id] or rake captain:chat -- assistant_id'
task :chat, [:assistant_id] => :environment do |_, args|
assistant_id = args[:assistant_id] || ARGV[1]
unless assistant_id
puts '❌ Please provide an assistant ID'
puts 'Usage: rake captain:chat[assistant_id]'
puts "\nAvailable assistants:"
Captain::Assistant.includes(:account).each do |assistant|
puts " ID: #{assistant.id} - #{assistant.name} (Account: #{assistant.account.name})"
end
exit 1
end
assistant = Captain::Assistant.find_by(id: assistant_id)
unless assistant
puts "❌ Assistant with ID #{assistant_id} not found"
exit 1
end
# Clear ARGV to prevent gets from reading files
ARGV.clear
chat_session = CaptainChatSession.new(assistant)
chat_session.start
end
end
class CaptainChatSession
def initialize(assistant)
@assistant = assistant
@message_history = []
end
def start
show_assistant_info
puts "💡 Type 'exit', 'quit', or 'bye' to end the session"
puts "💡 Type 'clear' to clear message history"
puts "#{'-' * 50}"
loop do
puts '' # Add spacing before prompt
user_input = Readline.readline('👤 You: ', true)
next unless user_input # Handle Ctrl+D
user_input = user_input.strip
case user_input.downcase
when 'exit', 'quit', 'bye'
break
when 'clear'
clear_history
next
when ''
next
end
process_user_message(user_input)
end
puts "\nChat session ended"
puts "Final conversation log has #{@message_history.length} messages"
end
private
def show_assistant_info
puts "🤖 Starting chat with #{@assistant.name}"
puts "🏢 Account: #{@assistant.account.name}"
puts "🆔 Assistant ID: #{@assistant.id}"
# Show scenarios
scenarios = @assistant.scenarios.enabled
if scenarios.any?
puts "⚡ Enabled Scenarios (#{scenarios.count}):"
scenarios.each do |scenario|
tools_count = scenario.tools&.length || 0
puts "#{scenario.title} (#{tools_count} tools)"
if scenario.description.present?
description = scenario.description.length > 60 ? "#{scenario.description[0..60]}..." : scenario.description
puts " #{description}"
end
end
else
puts '⚡ No scenarios enabled'
end
# Show available tools
available_tools = Captain::Assistant.available_tool_ids
if available_tools.any?
puts "🔧 Available Tools (#{available_tools.count}): #{available_tools.join(', ')}"
else
puts '🔧 No tools available'
end
puts ''
end
def process_user_message(user_input)
# Add user message to history
add_to_history('user', user_input)
begin
print "🤖 #{@assistant.name}: "
# Track system messages to group them
@current_system_messages = []
# Define callbacks for detailed visibility
callbacks = {
on_agent_thinking: proc { |agent, input|
agent_name = extract_name(agent)
@current_system_messages << "#{agent_name} is thinking..."
add_to_history('system', "#{agent_name} is thinking...")
},
on_tool_start: proc { |tool, args|
tool_name = extract_tool_name(tool)
@current_system_messages << "Using tool: #{tool_name}"
add_to_history('system', "Using tool: #{tool_name}")
},
on_tool_complete: proc { |tool, result|
tool_name = extract_tool_name(tool)
@current_system_messages << "Tool #{tool_name} completed"
add_to_history('system', "Tool #{tool_name} completed")
},
on_agent_handoff: proc { |from, to, reason|
@current_system_messages << "Handoff: #{extract_name(from)}#{extract_name(to)} (#{reason})"
add_to_history('system', "Agent handoff: #{extract_name(from)}#{extract_name(to)} (#{reason})")
}
}
# Generate response using AgentRunnerService with callbacks
runner = Captain::Assistant::AgentRunnerService.new(assistant: @assistant, callbacks: callbacks)
result = runner.generate_response(message_history: @message_history)
response_text = result['response'] || 'No response generated'
reasoning = result['reasoning']
# Print grouped system messages with dimmer styling
puts dim_text("\n" + @current_system_messages.join("\n")) if @current_system_messages.any?
# Print the response
puts response_text
puts dim_italic_text("(Reasoning: #{reasoning})") if reasoning && reasoning != 'Processed by agent'
# Add assistant response to history
add_to_history('assistant', response_text, reasoning: reasoning)
rescue StandardError => e
error_msg = "Error: #{e.message}"
puts "#{error_msg}"
add_to_history('system', error_msg)
end
end
def add_to_history(role, content, agent_name: nil, reasoning: nil)
message = {
role: role,
content: content,
timestamp: Time.current,
agent_name: agent_name || (role == 'assistant' ? @assistant.name : nil)
}
message[:reasoning] = reasoning if reasoning
@message_history << message
end
def clear_history
@message_history.clear
puts 'Message history cleared'
end
def dim_text(text)
# ANSI escape code for very dim gray text (bright black/dark gray)
"\e[90m#{text}\e[0m"
end
def dim_italic_text(text)
# ANSI escape codes for dim gray + italic text
"\e[90m\e[3m#{text}\e[0m"
end
def extract_tool_name(tool)
return tool if tool.is_a?(String)
tool.class.name.split('::').last.gsub('Tool', '')
rescue StandardError
tool.to_s
end
def extract_name(obj)
obj.respond_to?(:name) ? obj.name : obj.to_s
end
end