Open-source live-chat, email support, omni-channel desk. An alternative to Intercom, Zendesk, Salesforce Service Cloud etc. 🔥💬
Ruby actioncablechat-widgetconversationcustomer-supportdashboarddesigndockerdocker-imageherokuintercomjavascriptlivechatopensourcerailsrubysassvuejswhatsappzendesk
chore: Share Jev quotas across AI classification calls (#16094)
Sony Mathew463bf9ddb817
diff --git a/app/controllers/api/v1/accounts/conversations/suggestions_controller.rb b/app/controllers/api/v1/accounts/conversations/suggestions_controller.rbindex ee053f6f4e1..7b7c419513c 100644--- a/app/controllers/api/v1/accounts/conversations/suggestions_controller.rb+++ b/app/controllers/api/v1/accounts/conversations/suggestions_controller.rb@@ -21,3 +21,5 @@ class Api::V1::Accounts::Conversations::SuggestionsController < Api::V1::AccountCaptain::ConversationClassifierService.new(conversation: @conversation)endend++Api::V1::Accounts::Conversations::SuggestionsController.prepend_mod_with('Api::V1::Accounts::Conversations::SuggestionsController')diff --git a/app/javascript/dashboard/i18n/locale/en/report.json b/app/javascript/dashboard/i18n/locale/en/report.jsonindex 680d607fac5..8d09c10a7fb 100644--- a/app/javascript/dashboard/i18n/locale/en/report.json+++ b/app/javascript/dashboard/i18n/locale/en/report.json@@ -131,8 +131,8 @@"COVERAGE_HELP": "This range includes periods that were not fully checked. Counts may be incomplete.","REFRESHED": "Last refreshed at {time}. Updates appear automatically.","USAGE": {- "LIMIT_REACHED": "This account has used its {limit} monitor calls for this month.",- "RESETS": "New evaluations and previews are on hold until {time}. Existing results remain available.",+ "LIMIT_REACHED": "This account has used its {limit} AI classification calls for this month. Monitors, automation Captain conditions, and label and priority suggestions share this allowance.",+ "RESETS": "Monitor evaluations and previews, automation Captain conditions, and label and priority suggestions are unavailable until {time}. Existing results remain available.","REACHED_AT": "Limit reached on {time}."},"STATES": {@@ -156,7 +156,7 @@"PROVIDER_BUSY": "The evaluation provider is busy. Pending conversations need another evaluation.","PROVIDER_UNAVAILABLE": "The evaluation provider is temporarily unavailable. Updates may be delayed.","BUDGET_LIMIT": "The daily evaluation allowance has been reached. Pending work will resume after it resets.",- "MONTHLY_LIMIT": "This account has reached its monthly monitor allowance. Pending evaluations will resume next month.",+ "MONTHLY_LIMIT": "This account has reached its shared monthly AI classification allowance. Pending evaluations will resume next month.","CONTEXT_LIMIT": "Some conversations are too long to evaluate completely. They are excluded from the results.","INVALID_PARAMETERS": "Check the name, condition, date range, and interval.","TOO_MANY_BUCKETS": "Choose a shorter date range or a larger interval. A chart can show up to 744 bars.",diff --git a/app/javascript/dashboard/routes/dashboard/settings/reports/monitors/specs/MonitorUsageWarning.spec.js b/app/javascript/dashboard/routes/dashboard/settings/reports/monitors/specs/MonitorUsageWarning.spec.jsindex 81989868597..0c45e209082 100644--- a/app/javascript/dashboard/routes/dashboard/settings/reports/monitors/specs/MonitorUsageWarning.spec.js+++ b/app/javascript/dashboard/routes/dashboard/settings/reports/monitors/specs/MonitorUsageWarning.spec.js@@ -24,7 +24,7 @@ describe('MonitorUsageWarning', () => {});expect(wrapper.get('[role="status"]').text()).toContain(- '100,000 monitor calls'+ '100,000 AI classification calls');expect(wrapper.text()).toContain('Existing results remain available.');expect(wrapper.text()).toContain('Limit reached on');diff --git a/app/services/captain/automation_condition_service.rb b/app/services/captain/automation_condition_service.rbindex c2baf743e4d..48630a23690 100644--- a/app/services/captain/automation_condition_service.rb+++ b/app/services/captain/automation_condition_service.rb@@ -94,3 +94,5 @@ class Captain::AutomationConditionServicemessage ? state.merge(latest_message: latest_message) : stateendend++Captain::AutomationConditionService.prepend_mod_with('Captain::AutomationConditionService')diff --git a/app/services/captain/jev_client.rb b/app/services/captain/jev_client.rbindex 2e4176f6cc6..6230c8a360d 100644--- a/app/services/captain/jev_client.rb+++ b/app/services/captain/jev_client.rb@@ -103,3 +103,5 @@ class Captain::JevClientendendend++Captain::JevClient.prepend_mod_with('Captain::JevClient')diff --git a/enterprise/app/controllers/enterprise/api/v1/accounts/conversations/suggestions_controller.rb b/enterprise/app/controllers/enterprise/api/v1/accounts/conversations/suggestions_controller.rbnew file mode 100644index 00000000000..e769a925527--- /dev/null+++ b/enterprise/app/controllers/enterprise/api/v1/accounts/conversations/suggestions_controller.rb@@ -0,0 +1,8 @@+module Enterprise::Api::V1::Accounts::Conversations::SuggestionsController+ def self.prepended(base)+ base.rescue_from CustomExceptions::JevQuotaError do |error|+ response.set_header('Retry-After', error.retry_after.to_s)+ render json: { error: error.code, retry_after: error.retry_after }, status: :too_many_requests+ end+ end+enddiff --git a/enterprise/app/services/conversation_monitors/decision_service.rb b/enterprise/app/services/conversation_monitors/decision_service.rbindex 2deb5d5973b..83f832a8b02 100644--- a/enterprise/app/services/conversation_monitors/decision_service.rb+++ b/enterprise/app/services/conversation_monitors/decision_service.rb@@ -13,13 +13,14 @@ class ConversationMonitors::DecisionServicebody = request_body(state, monitors)raise CustomExceptions::MonitorEvaluationError, 'context_limit' if body.bytesize > ConversationMonitors::Configuration::MAX_REQUEST_BYTES- ConversationMonitors::Usage.new(@account_id).reserve!started = Process.clock_gettime(Process::CLOCK_MONOTONIC)data = request_decision(body)instrument(data, started, monitors.size)datarescue Captain::JevClient::HTTPError => eraise monitor_error(e)+ rescue CustomExceptions::JevQuotaError => e+ raise CustomExceptions::MonitorEvaluationError.new(e.code, retry_after: e.retry_after)rescue JSON::ParserErrorraise CustomExceptions::MonitorEvaluationError, 'invalid_response'rescue Faraday::Errordiff --git a/enterprise/app/services/conversation_monitors/usage.rb b/enterprise/app/services/conversation_monitors/usage.rbindex 73745d68528..e4e656b43b9 100644--- a/enterprise/app/services/conversation_monitors/usage.rb+++ b/enterprise/app/services/conversation_monitors/usage.rb@@ -1,3 +1,4 @@+# Shared by all Jev callers. Retain the existing storage to preserve account usage during rollout.class ConversationMonitors::Usagedef initialize(account_id)@account_id = account_id@@ -23,10 +24,10 @@ class ConversationMonitors::UsageAccount.find(@account_id).with_lock donow = Time.current.utcusage = snapshot(now)- raise CustomExceptions::MonitorEvaluationError.new('monthly_limit', retry_after: (usage[:resets_at] - now.to_f).ceil) if usage[:limit_reached]+ raise CustomExceptions::JevQuotaError.new('monthly_limit', retry_after: (usage[:resets_at] - now.to_f).ceil) if usage[:limit_reached]if usage[:daily].last[:calls] >= ConversationMonitors::Configuration::DAILY_CALL_LIMIT- raise CustomExceptions::MonitorEvaluationError.new('budget_limit', retry_after: (now.tomorrow.beginning_of_day - now).ceil)+ raise CustomExceptions::JevQuotaError.new('budget_limit', retry_after: (now.tomorrow.beginning_of_day - now).ceil)endlimit_reached = usage[:remaining] == 1diff --git a/enterprise/lib/custom_exceptions/jev_quota_error.rb b/enterprise/lib/custom_exceptions/jev_quota_error.rbnew file mode 100644index 00000000000..68407dd2a94--- /dev/null+++ b/enterprise/lib/custom_exceptions/jev_quota_error.rb@@ -0,0 +1,9 @@+class CustomExceptions::JevQuotaError < StandardError+ attr_reader :code, :retry_after++ def initialize(code, retry_after:)+ @code = code+ @retry_after = retry_after+ super(code)+ end+enddiff --git a/enterprise/lib/enterprise/captain/automation_condition_service.rb b/enterprise/lib/enterprise/captain/automation_condition_service.rbnew file mode 100644index 00000000000..2ea7a994d72--- /dev/null+++ b/enterprise/lib/enterprise/captain/automation_condition_service.rb@@ -0,0 +1,7 @@+module Enterprise::Captain::AutomationConditionService+ def perform+ super+ rescue CustomExceptions::JevQuotaError+ unmet+ end+enddiff --git a/enterprise/lib/enterprise/captain/jev_client.rb b/enterprise/lib/enterprise/captain/jev_client.rbnew file mode 100644index 00000000000..cb7c288b19e--- /dev/null+++ b/enterprise/lib/enterprise/captain/jev_client.rb@@ -0,0 +1,6 @@+module Enterprise::Captain::JevClient+ def call(body:, &)+ ConversationMonitors::Usage.new(@account_id).reserve!+ super+ end+enddiff --git a/spec/enterprise/services/conversation_monitors/usage_spec.rb b/spec/enterprise/services/conversation_monitors/usage_spec.rbindex 0086a0c5a19..8037d7dcd29 100644--- a/spec/enterprise/services/conversation_monitors/usage_spec.rb+++ b/spec/enterprise/services/conversation_monitors/usage_spec.rb@@ -50,7 +50,7 @@ RSpec.describe ConversationMonitors::Usage dodaily = ConversationMonitors::DailyUsage.create!(account_id: account_id, usage_date: Date.current, calls_count: 499_999)usage.reserve!- expect { usage.reserve! }.to raise_error(CustomExceptions::MonitorEvaluationError) { |error|+ expect { usage.reserve! }.to raise_error(CustomExceptions::JevQuotaError) { |error|expect(error).to have_attributes(code: 'budget_limit', retry_after: 12.hours.to_i)}expect(daily.reload).to have_attributes(calls_count: 500_000, limit_reached_at: nil)@@ -73,7 +73,7 @@ RSpec.describe ConversationMonitors::Usage doexpect(ConversationMonitors::BroadcastJob).to have_received(:schedule).with(monitor.id).oncereached_at = ConversationMonitors::DailyUsage.find_by!(account_id: account_id, usage_date: Date.current).limit_reached_at- expect { usage.reserve! }.to raise_error(CustomExceptions::MonitorEvaluationError) { |error|+ expect { usage.reserve! }.to raise_error(CustomExceptions::JevQuotaError) { |error|expect(error).to have_attributes(code: 'monthly_limit', retry_after: (Time.utc(2026, 10, 1) - Time.current).to_i)}expect(ConversationMonitors::DailyUsage.find_by!(account_id: account_id, usage_date: Date.current))@@ -110,7 +110,7 @@ RSpec.describe ConversationMonitors::Usage doit 'starts a fresh daily allowance at midnight UTC while keeping the monthly usage' dodaily = ConversationMonitors::DailyUsage.create!(account_id: account_id, usage_date: Date.current, calls_count: 500_000)- expect { usage.reserve! }.to raise_error(CustomExceptions::MonitorEvaluationError, 'budget_limit')+ expect { usage.reserve! }.to raise_error(CustomExceptions::JevQuotaError, 'budget_limit')travel_to Time.utc(2026, 9, 23)usage.reserve!diff --git a/spec/services/captain/jev_client_spec.rb b/spec/services/captain/jev_client_spec.rbindex f47a7c4ec84..1ace52a2f06 100644--- a/spec/services/captain/jev_client_spec.rb+++ b/spec/services/captain/jev_client_spec.rb@@ -2,7 +2,8 @@ require 'rails_helper'RSpec.describe Captain::JevClient dolet(:body) { described_class.request_body(model: 'jev-latest', state: { messages: [] }, questions: { test: { type: 'noul' } }) }- let(:client) { described_class.new(account_id: 7, feature: 'captain_classifier') }+ let(:account) { create(:account) }+ let(:client) { described_class.new(account_id: account.id, feature: 'captain_classifier') }before doallow(ChatwootApp).to receive(:otel_enabled?).and_return(false)@@ -42,7 +43,7 @@ RSpec.describe Captain::JevClient doallow(OpentelemetryConfig).to receive(:tracer).and_return(tracer)allow(tracer).to receive(:in_span).and_yield(span)- expect(described_class.new(account_id: 7, conversation_id: 42, feature: 'captain_classifier').call(body: body))+ expect(described_class.new(account_id: account.id, conversation_id: 42, feature: 'captain_classifier').call(body: body)).to eq(response.deep_stringify_keys)expect(tracer).to have_received(:in_span).with('llm.jev.captain_classifier', kind: :client)expect(attributes).to include(@@ -50,7 +51,7 @@ RSpec.describe Captain::JevClient do'langfuse.observation.output' => response.to_json,'langfuse.observation.model.name' => 'jev-1.13.0','langfuse.observation.cost_details' => { total: 0.000001 }.to_json,- 'langfuse.session.id' => '7_42',+ 'langfuse.session.id' => "#{account.id}_42",'gen_ai.usage.input_tokens' => 12)expect(WebMock).to have_requested(:post, 'https://openrouter.ai/api/v1/systemone').with(body: body).once