A platform for community discussion. Free, open, simple.
FIX: Prevent sending chat/PMs to bots when LLM has exceeded credit limits (#36496)
Keegan George04b404bf99cc
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex 6b02aadd0a0..ba15017294d 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -6,7 +6,7 @@ en:max_prompt_tokens: "Context window"dashboard:problem:- ai_llm_status:+ ai_llm_status:one: "<a href='%{base_path}/admin/plugins/discourse-ai/ai-llms/%{target}/edit'>%{model_name}</a> needs attention. In the past hour, it failed to respond %{failed_calls} out of %{total_calls} times."other: "<a href='%{base_path}/admin/plugins/discourse-ai/ai-llms/%{target}/edit'>%{model_name}</a> needs attention. Over the last %{count} hours, it failed to respond %{failed_calls} out of %{total_calls} times."ai_credit_soft_limit: "%{model_name} has only %{percentage_remaining}% of credits remaining. Credits will reset at %{reset_date}. <a href='%{url}'>View AI models</a>"@@ -302,8 +302,6 @@ en:ai_helper:errors:completion_request_failed: "Something went wrong while trying to provide suggestions. Please, try again."- credit_limit_exceeded_user: "You've hit the AI credit limit for your plan. Responses will be unavailable until your limit resets %{reset_time}."- credit_limit_exceeded_bot: "AI responses are currently unavailable due to credit limits. Please try again %{reset_time}."no_illustrator_persona: "Post Illustrator persona is not configured. Please check your site settings."no_image_generation_tool: "Post Illustrator persona must have an image generation tool attached. Please configure an image generation tool for this persona in the admin panel."no_image_generated: "Failed to generate image. Please try again or check your tool configuration."diff --git a/plugins/discourse-ai/lib/ai_bot/playground.rb b/plugins/discourse-ai/lib/ai_bot/playground.rbindex f6ce8c26388..9a56b59444b 100644--- a/plugins/discourse-ai/lib/ai_bot/playground.rb+++ b/plugins/discourse-ai/lib/ai_bot/playground.rb@@ -374,6 +374,36 @@ module DiscourseAiendreply+ rescue LlmCreditAllocation::CreditLimitExceeded => e+ if streamer && streamer.instance_variable_get(:@client_id)+ ChatSDK::Channel.stop_reply(+ channel_id: channel.id,+ client_id: streamer.instance_variable_get(:@client_id),+ guardian: guardian,+ thread_id: message.thread_id,+ )+ end++ reset_time = e.allocation&.relative_reset_time || ""+ locale_key = message.user.admin? ? "limit_exceeded_admin" : "limit_exceeded_user"+ error_message =+ I18n.t("discourse_ai.llm_credit_allocation.#{locale_key}", reset_time: reset_time)++ # Convert HTML links to markdown format for chat+ error_message =+ error_message.gsub(%r{<a\s+href=['"]([^'"]+)['"][^>]*>([^<]+)</a>}i, '[\2](\1)')++ ChatSDK::Message.create(+ raw: error_message,+ channel_id: channel.id,+ guardian: guardian,+ thread_id: message.thread_id,+ in_reply_to_id: in_reply_to_id,+ force_thread: force_thread,+ enforce_membership: !channel.direct_message_channel?,+ )++ nilensurestreamer.done if streamerend@@ -593,6 +623,31 @@ module DiscourseAiendreply_post+ rescue LlmCreditAllocation::CreditLimitExceeded => e+ reset_time = e.allocation&.relative_reset_time || ""+ locale_key = post.user.admin? ? "limit_exceeded_admin" : "limit_exceeded_user"+ error_message =+ I18n.t("discourse_ai.llm_credit_allocation.#{locale_key}", reset_time: reset_time)++ if reply_post+ reply = "#{reply}#{started_thinking ? "\n\n</details>" : ""}\n\n#{error_message}"+ reply_post.revise(+ bot.bot_user,+ { raw: reply },+ skip_validations: true,+ skip_revision: true,+ )+ else+ PostCreator.create!(+ bot.bot_user,+ topic_id: post.topic_id,+ raw: error_message,+ skip_validations: true,+ skip_guardian: true,+ )+ end++ nilrescue => eif reply_postdetails = e.message.to_sdiff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rbindex 42ace82b0eb..b198741184e 100644--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb@@ -448,6 +448,101 @@ RSpec.describe DiscourseAi::AiBot::Playground dolast_message = Chat::Message.where(chat_channel_id: channel.id).order("id desc").firstexpect(last_message.message).to eq("world")end++ it "sends error message when credit limit is exceeded" do+ # Create allocation to include in the exception+ seeded_llm = Fabricate(:seeded_model)+ allocation =+ Fabricate(+ :llm_credit_allocation,+ llm_model: seeded_llm,+ daily_credits: 1000,+ daily_used: 1000,+ )++ # Add some chat history first (before stubbing to avoid side effects)+ ChatSDK::Message.create(+ channel_id: channel.id,+ raw: "This is some background conversation",+ guardian: guardian,+ )++ # Stub check_credits! to raise the exception (after background message is created)+ exception =+ LlmCreditAllocation::CreditLimitExceeded.new("Credit limit exceeded", allocation:)+ allow(LlmCreditAllocation).to receive(:check_credits!).and_raise(exception)++ ChatSDK::Message.create(+ channel_id: channel.id,+ raw: "Hello @#{persona.user.username}",+ guardian: guardian,+ )++ last_message = Chat::Message.where(chat_channel_id: channel.id).order("id desc").first++ # Error message has HTML links converted to markdown for chat+ expected_message =+ I18n.t(+ "discourse_ai.llm_credit_allocation.limit_exceeded_user",+ reset_time: allocation.relative_reset_time,+ ).gsub(%r{<a\s+href=['"]([^'"]+)['"][^>]*>([^<]+)</a>}i, '[\2](\1)')+ expect(last_message.message).to eq(expected_message)+ expect(last_message.user_id).to eq(persona.user_id)+ end++ it "sends admin error message when credit limit is exceeded for admin users" do+ # Stub external URL fetches that may be triggered by message processing+ stub_request(:get, /meta\.discourse\.org/).to_return(+ status: 200,+ body: "",+ headers: {+ "Discourse-No-Onebox" => "1",+ },+ )++ # Create allocation to include in the exception+ seeded_llm = Fabricate(:seeded_model)+ allocation =+ Fabricate(+ :llm_credit_allocation,+ llm_model: seeded_llm,+ daily_credits: 1000,+ daily_used: 1000,+ )++ admin_membership =+ Fabricate(:user_chat_channel_membership, user: admin, chat_channel: channel)+ admin_guardian = Guardian.new(admin)++ # Add some chat history first (before stubbing to avoid side effects)+ ChatSDK::Message.create(+ channel_id: channel.id,+ raw: "This is some background conversation",+ guardian: admin_guardian,+ )++ # Stub check_credits! to raise the exception (after background message is created)+ exception =+ LlmCreditAllocation::CreditLimitExceeded.new("Credit limit exceeded", allocation:)+ allow(LlmCreditAllocation).to receive(:check_credits!).and_raise(exception)++ ChatSDK::Message.create(+ channel_id: channel.id,+ raw: "Hello @#{persona.user.username}",+ guardian: admin_guardian,+ )++ last_message = Chat::Message.where(chat_channel_id: channel.id).order("id desc").first++ # Error message has HTML links converted to markdown for chat+ expected_message =+ I18n.t(+ "discourse_ai.llm_credit_allocation.limit_exceeded_admin",+ reset_time: allocation.relative_reset_time,+ ).gsub(%r{<a\s+href=['"]([^'"]+)['"][^>]*>([^<]+)</a>}i, '[\2](\1)')+ expect(last_message.message).to eq(expected_message)+ expect(last_message.user_id).to eq(persona.user_id)+ endendcontext "with chat dms" do@@ -1056,6 +1151,64 @@ RSpec.describe DiscourseAi::AiBot::Playground doexpect(custom_prompt.last.first).to eq(response2)expect(custom_prompt.last.last).to eq(bot_user.username)end++ it "sends credit limit error message when credit limit is exceeded in PM" do+ seeded_llm = Fabricate(:seeded_model)+ allocation =+ Fabricate(+ :llm_credit_allocation,+ llm_model: seeded_llm,+ daily_credits: 1000,+ daily_used: 1000,+ )++ exception = LlmCreditAllocation::CreditLimitExceeded.new("Credit limit exceeded", allocation:)+ allow(LlmCreditAllocation).to receive(:check_credits!).and_raise(exception)++ expect { playground.reply_to(third_post) }.not_to raise_error++ last_post = pm.reload.posts.order(:post_number).last++ expected_message =+ I18n.t(+ "discourse_ai.llm_credit_allocation.limit_exceeded_user",+ reset_time: allocation.relative_reset_time,+ )+ expect(last_post.raw).to include(expected_message)+ expect(last_post.user_id).to eq(bot_user.id)+ end++ it "sends admin credit limit error message when credit limit is exceeded for admin users" do+ seeded_llm = Fabricate(:seeded_model)+ allocation =+ Fabricate(+ :llm_credit_allocation,+ llm_model: seeded_llm,+ daily_credits: 1000,+ daily_used: 1000,+ )++ # Add admin to existing PM+ pm.topic_allowed_users.create!(user_id: admin.id)++ admin_post =+ Fabricate(:post, topic: pm, user: admin, post_number: 4, raw: "Hello bot from admin")++ exception = LlmCreditAllocation::CreditLimitExceeded.new("Credit limit exceeded", allocation:)+ allow(LlmCreditAllocation).to receive(:check_credits!).and_raise(exception)++ expect { playground.reply_to(admin_post) }.not_to raise_error++ last_post = pm.reload.posts.order(:post_number).last++ expected_message =+ I18n.t(+ "discourse_ai.llm_credit_allocation.limit_exceeded_admin",+ reset_time: allocation.relative_reset_time,+ )+ expect(last_post.raw).to include(expected_message)+ expect(last_post.user_id).to eq(bot_user.id)+ endenddescribe "#canceling a completions" do