Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Use a log based heuristic to check for LLM problems. (#36432)

Roman Rizzi7a3c90d6dbeb
diff --git a/app/models/problem_check.rb b/app/models/problem_check.rb
index 14ce8f2a4aa..4efce3e045e 100644
--- a/app/models/problem_check.rb
+++ b/app/models/problem_check.rb
@@ -164,7 +164,9 @@ class ProblemCheck
end
def run
- if targeted? && (target == NO_TARGET || targets.call.exclude?(target))
+ # target is always a string when initializing this class, but the targets function
+ # could return IDs from the DB. Make everything string so we don't return early all the time.
+ if targeted? && (target == NO_TARGET || targets.call.map(&:to_s).exclude?(target))
tracker.destroy
return
end
diff --git a/plugins/discourse-ai/app/models/ai_api_audit_log.rb b/plugins/discourse-ai/app/models/ai_api_audit_log.rb
index 44bb7d3b726..5be11702f41 100644
--- a/plugins/discourse-ai/app/models/ai_api_audit_log.rb
+++ b/plugins/discourse-ai/app/models/ai_api_audit_log.rb
@@ -43,6 +43,7 @@ end
# raw_request_payload :string
# raw_response_payload :string
# request_tokens :integer
+# response_status :integer
# response_tokens :integer
# created_at :datetime not null
# updated_at :datetime not null
diff --git a/plugins/discourse-ai/app/services/problem_check/ai_llm_status.rb b/plugins/discourse-ai/app/services/problem_check/ai_llm_status.rb
index 0c2f2727448..34815a71a20 100644
--- a/plugins/discourse-ai/app/services/problem_check/ai_llm_status.rb
+++ b/plugins/discourse-ai/app/services/problem_check/ai_llm_status.rb
@@ -3,11 +3,31 @@
class ProblemCheck::AiLlmStatus < ProblemCheck
self.priority = "high"
self.perform_every = 6.hours
- self.max_retries = 2
- self.retry_after = 1.minute
- self.max_blips = 2
self.targets = -> { LlmModel.in_use.pluck(:id) }
+ LOOKBACK_WINDOW = 6.hours
+ MIN_TOTAL_CALLS = 5
+ MIN_FAILED_CALLS = 3
+ FAILURE_RATE_THRESHOLD = 0.5
+
+ def self.problem_details(model, failed_calls, total_calls, lookback_hours)
+ {
+ target: model.id,
+ model_name: model.display_name,
+ failed_calls: failed_calls,
+ total_calls: total_calls,
+ count: lookback_hours,
+ }
+ end
+
+ def self.fast_track_problem!(model, failed_calls, lookback_hours)
+ return if model.blank?
+
+ tracker = ProblemCheckTracker[:ai_llm_status, model.id]
+ details = problem_details(model, failed_calls, failed_calls, lookback_hours)
+ tracker.problem!(details: details)
+ end
+
def call
return no_problem if !SiteSetting.discourse_ai_enabled
@@ -16,88 +36,46 @@ class ProblemCheck::AiLlmStatus < ProblemCheck
return no_problem if model.blank?
return no_problem if model.seeded?
- try_validate(model) { validator.run_test(model) }
- end
+ total_calls, failed_calls = audit_log_counts(model)
- private
+ return no_problem if total_calls < MIN_TOTAL_CALLS
+ return no_problem if failed_calls < MIN_FAILED_CALLS
+ return no_problem if failure_rate(total_calls, failed_calls) < FAILURE_RATE_THRESHOLD
- def try_validate(model, &blk)
- begin
- blk.call
- no_problem
- rescue => e
- # Skip problem reporting for rate limiting and temporary service issues
- # These are expected to resolve on their own
- if rate_limit_error?(e)
- Rails.logger.info(
- "AI LLM Status Check: Rate limit detected for model #{model.display_name} (#{model.id}), skipping problem report",
- )
- return no_problem
- end
-
- # Log transient errors but still return a problem
- # The framework's max_retries and max_blips will handle retries and alert suppression
- if transient_error?(e)
- Rails.logger.info(
- "AI LLM Status Check: Transient error for model #{model.display_name} (#{model.id}): #{e.message}",
- )
- end
-
- override_data = {
- model_id: model.id,
- model_name: model.display_name,
- url: "#{Discourse.base_path}/admin/plugins/discourse-ai/ai-llms/#{model.id}/edit",
- }
-
- problem(model, override_data:, details: { error: parse_error_message(e.message) })
- end
- end
+ details =
+ self.class.problem_details(model, failed_calls, total_calls, (LOOKBACK_WINDOW / 1.hour))
- def validator
- @validator ||= DiscourseAi::Configuration::LlmValidator.new
+ problem(model, override_data: details, details: details)
end
- def parse_error_message(message)
- begin
- JSON.parse(message)["message"]
- rescue JSON::ParserError
- message.to_s
- end
- end
+ private
- def rate_limit_error?(error)
- error_message = error.message.to_s.downcase
-
- # Check for rate limit indicators in the error message
- rate_limit_indicators = [
- "rate limit",
- "rate_limit",
- "ratelimit",
- "too many requests",
- "quota exceeded",
- "retry after",
- "throttled",
- "429",
- "503",
- "temporarily unavailable",
- "service unavailable",
- "overloaded",
- ]
-
- rate_limit_indicators.any? { |indicator| error_message.include?(indicator) }
+ def audit_log_counts(model)
+ counts = DB.query_single(<<~SQL, llm_id: model.id, since: LOOKBACK_WINDOW.ago)
+ SELECT
+ COUNT(*) AS total_calls,
+ SUM(
+ CASE
+ WHEN response_status IS NOT NULL THEN
+ CASE WHEN response_status NOT BETWEEN 200 AND 299 THEN 1 ELSE 0 END
+ ELSE
+ CASE WHEN COALESCE(response_tokens, 0) <= 0 THEN 1 ELSE 0 END
+ END
+ ) AS failed_calls
+ FROM ai_api_audit_logs
+ WHERE llm_id = :llm_id
+ AND created_at >= :since
+ SQL
+
+ total_calls = counts[0].to_i
+ failed_calls = counts[1].to_i
+
+ [total_calls, failed_calls]
end
- def transient_error?(error)
- # Network errors and timeouts are transient - may succeed on retry
- transient_errors = [
- Errno::ECONNREFUSED,
- Errno::ECONNRESET,
- Errno::ETIMEDOUT,
- Net::OpenTimeout,
- Net::ReadTimeout,
- IOError,
- ]
-
- transient_errors.any? { |error_class| error.is_a?(error_class) }
+ def failure_rate(total_calls, failed_calls)
+ return 0.0 if total_calls.to_i.zero?
+
+ failed_calls.to_f / total_calls
end
end
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index 22709ea3954..994387c1d96 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -4,6 +4,13 @@ en:
llm_model:
name: "Model ID"
max_prompt_tokens: "Context window"
+ dashboard:
+ problem:
+ 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>"
+ ai_credit_hard_limit: "You have run out of AI credits for %{model_name}. AI features will be unavailable until %{reset_date}. <a href='%{url}'>View AI models</a>"
discourse_automation:
ai:
@@ -690,8 +697,4 @@ en:
custom_tool_exists:
one: "Custom tool with the name %{names} already exists."
other: "Custom tools with the names %{names} already exist."
- dashboard:
- problem:
- ai_llm_status: "The LLM model: %{model_name} is encountering issues. Please check the <a href='%{url}'>model's configuration page</a>."
- 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>"
- ai_credit_hard_limit: "You have run out of AI credits for %{model_name}. AI features will be unavailable until %{reset_date}. <a href='%{url}'>View AI models</a>"
+
diff --git a/plugins/discourse-ai/db/migrate/20251203115747_add_response_status_to_ai_api_audit_log.rb b/plugins/discourse-ai/db/migrate/20251203115747_add_response_status_to_ai_api_audit_log.rb
new file mode 100644
index 00000000000..edb95cdc4ba
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20251203115747_add_response_status_to_ai_api_audit_log.rb
@@ -0,0 +1,6 @@
+# frozen_string_literal: true
+class AddResponseStatusToAiApiAuditLog < ActiveRecord::Migration[8.0]
+ def change
+ add_column :ai_api_audit_logs, :response_status, :integer
+ end
+end
diff --git a/plugins/discourse-ai/lib/completions/endpoints/base.rb b/plugins/discourse-ai/lib/completions/endpoints/base.rb
index c3a6c0d1f83..76aed9f0344 100644
--- a/plugins/discourse-ai/lib/completions/endpoints/base.rb
+++ b/plugins/discourse-ai/lib/completions/endpoints/base.rb
@@ -7,6 +7,8 @@ module DiscourseAi
attr_reader :partial_tool_calls, :output_thinking
CompletionFailed = Class.new(StandardError)
+ FAIL_THRESHOLD = 5
+ FAIL_TTL = 1.hour
# 6 minutes
# Reasoning LLMs can take a very long time to respond, generally it will be under 5 minutes
# The alternative is to have per LLM timeouts but that would make it extra confusing for people
@@ -181,14 +183,16 @@ module DiscourseAi
)
end
- # during dev we want to log all requests even ones that fail
- start_logging.call if Rails.env.development?
+ start_logging.call
http.request(request) do |response|
+ log.response_status = response.code.to_i if log
+
if response.code.to_i != 200
Rails.logger.error(
"#{self.class.name}: status: #{response.code.to_i} - body: #{response.body}",
)
+ response_raw << response.body.to_s
raise CompletionFailed, response.body
end
@@ -217,8 +221,6 @@ module DiscourseAi
end
end
- start_logging.call if !log
-
if !@streaming_mode
response_data =
non_streaming_response(
@@ -282,6 +284,7 @@ module DiscourseAi
log.raw_response_payload = response_raw
final_log_update(log)
log.response_tokens = tokenizer.size(partials_raw) if log.response_tokens.blank?
+ log.response_status ||= 200
log.created_at = start_time
log.updated_at = Time.now
log.duration_msecs = (Time.now - start_time) * 1000
@@ -309,6 +312,9 @@ module DiscourseAi
puts "#{self.class.name}: request_tokens #{log.request_tokens} response_tokens #{log.response_tokens}"
end
end
+
+ track_failures(call_status)
+
if log && (logger = Thread.current[:llm_audit_log])
call_data = <<~LOG
#{self.class.name}: request_tokens #{log.request_tokens} response_tokens #{log.response_tokens}
@@ -433,6 +439,27 @@ module DiscourseAi
end
end
+ def track_failures(call_status)
+ return if llm_model.blank? || llm_model.seeded?
+ key = "ai_llm_status_fast_fail:#{llm_model.id}"
+
+ if call_status == :success
+ Discourse.redis.del(key)
+ return
+ end
+
+ failures_count = Discourse.redis.incr(key)
+ Discourse.redis.expire(key, FAIL_TTL.to_i)
+
+ return if failures_count < FAIL_THRESHOLD
+
+ ProblemCheck::AiLlmStatus.fast_track_problem!(
+ llm_model,
+ failures_count,
+ (FAIL_TTL / 1.hour),
+ )
+ end
+
def start_log(
provider_id:,
request_body:,
diff --git a/plugins/discourse-ai/plugin.rb b/plugins/discourse-ai/plugin.rb
index 72472350420..3cf9ec0a7fc 100644
--- a/plugins/discourse-ai/plugin.rb
+++ b/plugins/discourse-ai/plugin.rb
@@ -98,7 +98,7 @@ after_initialize do
DiscourseAi::Discover::EntryPoint.new,
].each { |a_module| a_module.inject_into(self) }
- #register_problem_check ProblemCheck::AiLlmStatus
+ register_problem_check ProblemCheck::AiLlmStatus
#register_problem_check ProblemCheck::AiCreditSoftLimit
#register_problem_check ProblemCheck::AiCreditHardLimit
diff --git a/plugins/discourse-ai/spec/lib/completions/llm_spec.rb b/plugins/discourse-ai/spec/lib/completions/llm_spec.rb
index 6e95a670bf3..6ae140dae60 100644
--- a/plugins/discourse-ai/spec/lib/completions/llm_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/llm_spec.rb
@@ -121,6 +121,78 @@ RSpec.describe DiscourseAi::Completions::Llm do
expect(stat.usage_count).to eq(1)
expect(stat.rolled_up).to be(false)
end
+
+ it "records response status for successes and failures" do
+ success_body = {
+ model: "gpt-3.5-turbo-0301",
+ usage: {
+ prompt_tokens: 10,
+ completion_tokens: 5,
+ total_tokens: 15,
+ },
+ choices: [{ message: { role: "assistant", content: "hi" } }],
+ }.to_json
+
+ WebMock.stub_request(:post, "https://api.openai.com/v1/chat/completions").to_return(
+ status: 200,
+ body: success_body,
+ )
+
+ described_class.proxy(model).generate("Hello", user: user, feature_name: "llm_triage")
+ expect(AiApiAuditLog.order("id desc").first.response_status).to eq(200)
+
+ WebMock.stub_request(:post, "https://api.openai.com/v1/chat/completions").to_return(
+ status: 401,
+ body: "invalid auth",
+ )
+
+ expect do
+ described_class.proxy(model).generate("Hello", user: user, feature_name: "llm_triage")
+ end.to raise_error(DiscourseAi::Completions::Endpoints::Base::CompletionFailed)
+
+ failure_log = AiApiAuditLog.order("id desc").first
+ expect(failure_log.response_status).to eq(401)
+ expect(failure_log.response_tokens).to eq(0)
+ end
+
+ it "fast-tracks the problem check after repeated errors and resets on success" do
+ key = "ai_llm_status_fast_fail:#{model.id}"
+ Discourse.redis.del(key)
+
+ WebMock.stub_request(:post, "https://api.openai.com/v1/chat/completions").to_return(
+ { status: 500, body: "fail" },
+ { status: 500, body: "fail" },
+ {
+ status: 200,
+ body: {
+ model: "gpt-3.5-turbo-0301",
+ usage: {
+ prompt_tokens: 10,
+ completion_tokens: 5,
+ total_tokens: 15,
+ },
+ choices: [{ message: { role: "assistant", content: "hi" } }],
+ }.to_json,
+ },
+ )
+
+ stub_const(DiscourseAi::Completions::Endpoints::Base, "FAIL_THRESHOLD", 2) do
+ 2.times do
+ expect do
+ described_class.proxy(model).generate("Hello", user: user, feature_name: "llm_triage")
+ end.to raise_error(DiscourseAi::Completions::Endpoints::Base::CompletionFailed)
+ end
+ end
+
+ tracker = ProblemCheckTracker[:ai_llm_status, model.id]
+ expect(tracker.reload.failing?).to eq(true)
+
+ expect do
+ described_class.proxy(model).generate("Hello", user: user, feature_name: "llm_triage")
+ end.not_to raise_error
+
+ expect(Discourse.redis.get(key)).to be_nil
+ end
end
describe "#generate with fake model" do
diff --git a/plugins/discourse-ai/spec/services/problem_check/ai_llm_status_spec.rb b/plugins/discourse-ai/spec/services/problem_check/ai_llm_status_spec.rb
index 0df1392a074..4c4f85c3eba 100644
--- a/plugins/discourse-ai/spec/services/problem_check/ai_llm_status_spec.rb
+++ b/plugins/discourse-ai/spec/services/problem_check/ai_llm_status_spec.rb
@@ -6,27 +6,10 @@ RSpec.describe ProblemCheck::AiLlmStatus do
fab!(:llm_model)
fab!(:ai_persona) { Fabricate(:ai_persona, default_llm_id: llm_model.id) }
- let(:post_url) { "https://api.openai.com/v1/chat/completions" }
- let(:success_response) do
- {
- model: "gpt-4-turbo",
- usage: {
- max_prompt_tokens: 131_072,
- },
- choices: [
- { message: { role: "assistant", content: "test" }, finish_reason: "stop", index: 0 },
- ],
- }.to_json
- end
-
- let(:error_response) do
- { message: "API key error! Please check you have supplied the correct API key." }.to_json
- end
-
let(:target) { llm_model.id }
+ let(:provider) { AiApiAuditLog::Provider::OpenAI }
before do
- stub_request(:post, post_url).to_return(status: 200, body: success_response, headers: {})
assign_fake_provider_to(:ai_default_llm_model)
SiteSetting.ai_summarization_persona = ai_persona.id
SiteSetting.ai_summarization_enabled = true
@@ -41,14 +24,20 @@ RSpec.describe ProblemCheck::AiLlmStatus do
context "with discourse-ai plugin enabled for the site" do
before { enable_current_plugin }
- it "returns a problem with an LLM model" do
- stub_request(:post, post_url).to_return(status: 403, body: error_response, headers: {})
+ it "returns a problem when recent calls frequently fail" do
+ 3.times { create_log(response_tokens: 0, response_status: 500) }
+ 2.times { create_log(response_tokens: 15, response_status: 200) }
+
message =
I18n.t(
"dashboard.problem.ai_llm_status",
{
model_name: llm_model.display_name,
- url: "/admin/plugins/discourse-ai/ai-llms/#{llm_model.id}/edit",
+ target: llm_model.id,
+ base_path: Discourse.base_path,
+ count: (ProblemCheck::AiLlmStatus::LOOKBACK_WINDOW / 1.hour),
+ failed_calls: 3,
+ total_calls: 5,
},
)
@@ -58,58 +47,61 @@ RSpec.describe ProblemCheck::AiLlmStatus do
.with_message(message)
end
- it "does not return a problem if the LLM models are working" do
- stub_request(:post, post_url).to_return(status: 200, body: success_response, headers: {})
+ it "does not return a problem when failures are below the threshold" do
+ 2.times { create_log(response_tokens: 0, response_status: 500) }
+ 4.times { create_log(response_tokens: 10, response_status: 200) }
+
expect(check).to be_chill_about_it
end
- it "skips seeded LLMs" do
- SiteSetting.ai_summarization_enabled = false
+ it "ignores stale failures outside the lookback window" do
+ 3.times { create_log(response_tokens: 0, response_status: 500, created_at: 2.days.ago) }
+ 3.times { create_log(response_tokens: 12, response_status: 200) }
- seeded_llm = Fabricate(:seeded_model)
- ai_persona_seeded = Fabricate(:ai_persona, default_llm_id: seeded_llm.id)
- SiteSetting.ai_summarization_persona = ai_persona_seeded.id
- SiteSetting.ai_summarization_enabled = true
-
- stub_request(:post, "https://cdck.test/").to_return(
- status: 403,
- body: error_response,
- headers: {
- },
- )
expect(check).to be_chill_about_it
end
- it "does not report problems for rate limit errors" do
- rate_limit_response = { message: "Rate limit exceeded. Please retry after 60s." }.to_json
+ it "does not count zero-token 2xx responses as failures" do
+ 3.times { create_log(response_tokens: 0, response_status: 200) }
+ 3.times { create_log(response_tokens: 12, response_status: 200) }
- stub_request(:post, post_url).to_return(status: 429, body: rate_limit_response, headers: {})
expect(check).to be_chill_about_it
end
- it "does not report problems for 503 errors (service unavailable)" do
- service_unavailable_response = { message: "Service temporarily unavailable" }.to_json
+ it "counts missing status with zero tokens as failures" do
+ 3.times { create_log(response_tokens: 0, response_status: nil) }
+ 3.times { create_log(response_tokens: 12, response_status: 200) }
- stub_request(:post, post_url).to_return(
- status: 503,
- body: service_unavailable_response,
- headers: {
- },
- )
- expect(check).to be_chill_about_it
+ expect(check).to have_a_problem.with_target(llm_model.id)
end
- it "reports problem for network timeout errors" do
- stub_request(:post, post_url).to_timeout
+ it "skips seeded LLMs" do
+ SiteSetting.ai_summarization_enabled = false
- expect(check).to have_a_problem.with_priority("high").with_target(llm_model.id)
- end
+ seeded_llm = Fabricate(:seeded_model)
+ ai_persona_seeded = Fabricate(:ai_persona, default_llm_id: seeded_llm.id)
+ SiteSetting.ai_summarization_persona = ai_persona_seeded.id
+ SiteSetting.ai_summarization_enabled = true
- it "reports problem for authentication errors" do
- stub_request(:post, post_url).to_return(status: 401, body: error_response, headers: {})
+ 3.times { create_log(response_tokens: 0, response_status: 500, llm_id: seeded_llm.id) }
- expect(check).to have_a_problem.with_priority("high").with_target(llm_model.id)
+ expect(described_class.new(seeded_llm.id)).to be_chill_about_it
end
end
end
+
+ def create_log(
+ response_tokens:,
+ response_status:,
+ created_at: Time.zone.now,
+ llm_id: llm_model.id
+ )
+ AiApiAuditLog.create!(
+ provider_id: provider,
+ llm_id: llm_id,
+ response_tokens: response_tokens,
+ response_status: response_status,
+ created_at: created_at,
+ )
+ end
end