A platform for community discussion. Free, open, simple.
FIX: skip failure tracking for unsaved LLM models (#36735)
Régis Hanolb03ef525536c
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.rbindex 34815a71a20..92581bb3a29 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@@ -21,7 +21,7 @@ class ProblemCheck::AiLlmStatus < ProblemCheckenddef self.fast_track_problem!(model, failed_calls, lookback_hours)- return if model.blank?+ return if model.blank? || model.new_record?tracker = ProblemCheckTracker[:ai_llm_status, model.id]details = problem_details(model, failed_calls, failed_calls, lookback_hours)diff --git a/plugins/discourse-ai/lib/completions/endpoints/base.rb b/plugins/discourse-ai/lib/completions/endpoints/base.rbindex 37d700671ca..c89156cfe83 100644--- a/plugins/discourse-ai/lib/completions/endpoints/base.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/base.rb@@ -450,7 +450,7 @@ module DiscourseAidef track_failures(call_status)return if call_status == :cancelled- return if llm_model.blank? || llm_model.seeded?+ return if llm_model.blank? || llm_model.seeded? || llm_model.new_record?key = "ai_llm_status_fast_fail:#{llm_model.id}"if call_status == :successdiff --git a/plugins/discourse-ai/spec/lib/completions/llm_spec.rb b/plugins/discourse-ai/spec/lib/completions/llm_spec.rbindex 6ae140dae60..ecf0ddea754 100644--- a/plugins/discourse-ai/spec/lib/completions/llm_spec.rb+++ b/plugins/discourse-ai/spec/lib/completions/llm_spec.rb@@ -1,296 +1,176 @@# frozen_string_literal: trueRSpec.describe DiscourseAi::Completions::Llm do- subject(:llm) do- described_class.new(- DiscourseAi::Completions::Dialects::OpenAiCompatible,- canned_response,- model,- gateway: canned_response,- )- end-fab!(:user)fab!(:model, :llm_model)- before { enable_current_plugin }+ let(:llm) { described_class.proxy(model) }- describe ".proxy" do- it "raises an exception when we can't proxy the model" do- fake_model = "unknown:unknown_v2"+ before { enable_current_plugin }- expect { described_class.proxy(fake_model) }.to(- raise_error(DiscourseAi::Completions::Llm::UNKNOWN_MODEL),- )- end+ def stub_response(status: 200, body: success_body)+ WebMock.stub_request(:post, model.url).to_return(+ status:,+ body: body.is_a?(Hash) ? body.to_json : body,+ )end- describe "AiApiAuditLog" do- it "is able to keep track of post and topic id" do- prompt =- DiscourseAi::Completions::Prompt.new(- "You are fake",- messages: [{ type: :user, content: "fake orders" }],- topic_id: 123,- post_id: 1,- )-- result = <<~TEXT- data: {"id":"chatcmpl-8xoPOYRmiuBANTmGqdCGVk4ZA3Orz","object":"chat.completion.chunk","created":1709265814,"model":"gpt-4-0125-preview","system_fingerprint":"fp_70b2088885","choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}]}-- data: {"id":"chatcmpl-8xoPOYRmiuBANTmGqdCGVk4ZA3Orz","object":"chat.completion.chunk","created":1709265814,"model":"gpt-4-0125-preview","system_fingerprint":"fp_70b2088885","choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]}+ def success_body(content: "test", prompt_tokens: 10, completion_tokens: 5)+ {+ model: model.name,+ usage: {+ prompt_tokens:,+ completion_tokens:,+ total_tokens: prompt_tokens + completion_tokens,+ },+ choices: [{ message: { role: "assistant", content: }, finish_reason: "stop" }],+ }+ end- data: [DONE]- TEXT+ def streaming_body(content: "Hello")+ <<~SSE+ data: {"id":"1","object":"chat.completion.chunk","choices":[{"delta":{"content":"#{content}"}}]}- WebMock.stub_request(:post, "https://api.openai.com/v1/chat/completions").to_return(- status: 200,- body: result,- )- result = +""- described_class.proxy(model).generate(prompt, user: user) { |partial| result << partial }+ data: [DONE]+ SSE+ end- expect(result).to eq("Hello")- log = AiApiAuditLog.order("id desc").first- expect(log.topic_id).to eq(123)- expect(log.post_id).to eq(1)+ describe ".proxy" do+ it "raises for unknown model identifiers" do+ expect { described_class.proxy("unknown:v2") }.to raise_error(described_class::UNKNOWN_MODEL)end+ end- it "can track feature_name and feature_context" do- body = {- model: "gpt-3.5-turbo-0301",- usage: {- prompt_tokens: 337,- completion_tokens: 162,- total_tokens: 499,- },- choices: [- { message: { role: "assistant", content: "test" }, finish_reason: "stop", index: 0 },- ],- }.to_json-- WebMock.stub_request(:post, "https://api.openai.com/v1/chat/completions").to_return(- status: 200,- body: body,- )-- result =- described_class.proxy(model).generate(- "Hello",- user: user,- feature_name: "llm_triage",- feature_context: {- foo: "bar",- },- )+ describe "#generate" do+ context "with different prompt formats" do+ before { stub_response(body: success_body(content: "world")) }- expect(result).to eq("test")- log = AiApiAuditLog.order("id desc").first- expect(log.feature_name).to eq("llm_triage")- expect(log.feature_context).to eq({ "foo" => "bar" })- end+ it "accepts a simple string" do+ expect(llm.generate("hello", user:)).to eq("world")+ end- it "records a usage stat row for reporting" do- body = {- model: "gpt-3.5-turbo-0301",- usage: {- prompt_tokens: 20,- completion_tokens: 10,- total_tokens: 30,- },- choices: [- { message: { role: "assistant", content: "stat-test" }, finish_reason: "stop", index: 0 },- ],- }.to_json-- WebMock.stub_request(:post, "https://api.openai.com/v1/chat/completions").to_return(- status: 200,- body: body,- )-- expect do- described_class.proxy(model).generate("Hello", user: user, feature_name: "llm_triage")- end.to change { AiApiRequestStat.count }.by(1)-- log = AiApiAuditLog.order("id desc").first- stat = AiApiRequestStat.order("id desc").first-- expect(stat.bucket_date).to eq(log.created_at)- expect(stat.language_model).to eq(log.language_model)- expect(stat.llm_id).to eq(model.id)- expect(stat.usage_count).to eq(1)- expect(stat.rolled_up).to be(false)+ it "accepts an array of messages" do+ messages = [{ type: :system, content: "bot" }, { type: :user, content: "hello" }]+ expect(llm.generate(messages, user:)).to eq("world")+ endend- 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+ context "with streaming" do+ it "yields partials via block" do+ stub_response(body: streaming_body(content: "Hi"))- 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+ result = +""+ llm.generate("hi", user:) { |partial| result << partial }+ expect(result).to eq("Hi")end+ end- tracker = ProblemCheckTracker[:ai_llm_status, model.id]- expect(tracker.reload.failing?).to eq(true)+ context "with a fake model" do+ fab!(:fake_model)- expect do- described_class.proxy(model).generate("Hello", user: user, feature_name: "llm_triage")- end.not_to raise_error+ before do+ DiscourseAi::Completions::Endpoints::Fake.delays = []+ DiscourseAi::Completions::Endpoints::Fake.chunk_count = 10+ end- expect(Discourse.redis.get(key)).to be_nil- end- end+ it "generates and streams responses" do+ fake_llm = described_class.proxy(fake_model)+ prompt =+ DiscourseAi::Completions::Prompt.new("System", messages: [{ type: :user, content: "hi" }])- describe "#generate with fake model" do- fab!(:fake_model)+ expect(fake_llm.generate(prompt, user:)).to be_present- before do- DiscourseAi::Completions::Endpoints::Fake.delays = []- DiscourseAi::Completions::Endpoints::Fake.chunk_count = 10+ partials = []+ response = fake_llm.generate(prompt, user:) { |p| partials << p }+ expect(partials.size).to eq(10)+ expect(partials.join).to eq(response)+ endend- let(:llm) { described_class.proxy(fake_model) }+ context "when auditing" do+ it "logs topic_id, post_id, feature_name, and feature_context" do+ stub_response(body: success_body)- let(:prompt) do- DiscourseAi::Completions::Prompt.new(- "You are fake",- messages: [{ type: :user, content: "fake orders" }],- )- end-- it "can generate a response" do- response = llm.generate(prompt, user: user)- expect(response).to be_present- end+ llm.generate(+ DiscourseAi::Completions::Prompt.new(+ "sys",+ messages: [{ type: :user, content: "hi" }],+ topic_id: 123,+ post_id: 1,+ ),+ user:,+ feature_name: "triage",+ feature_context: {+ foo: "bar",+ },+ )- it "can generate content via a block" do- partials = []- response = llm.generate(prompt, user: user) { |partial| partials << partial }+ expect(AiApiAuditLog.last).to have_attributes(+ topic_id: 123,+ post_id: 1,+ feature_name: "triage",+ feature_context: {+ "foo" => "bar",+ },+ )+ end- expect(partials.length).to eq(10)- expect(response).to eq(DiscourseAi::Completions::Endpoints::Fake.fake_content)+ it "records response status" do+ stub_response(status: 200)+ llm.generate("Hello", user:)+ expect(AiApiAuditLog.last.response_status).to eq(200)- expect(partials.join).to eq(response)- end- end+ stub_response(status: 401, body: "error")+ expect { llm.generate("Hello", user:) }.to raise_error(+ DiscourseAi::Completions::Endpoints::Base::CompletionFailed,+ )+ expect(AiApiAuditLog.last).to have_attributes(response_status: 401, response_tokens: 0)+ end- describe "#generate with various style prompts" do- let :canned_response do- DiscourseAi::Completions::Endpoints::CannedResponse.new(["world"])- end+ it "creates usage stats" do+ stub_response(body: success_body(prompt_tokens: 20, completion_tokens: 10))- it "can generate a response to a simple string" do- response = llm.generate("hello", user: user)- expect(response).to eq("world")- end+ expect { llm.generate("Hello", user:) }.to change { AiApiRequestStat.count }.by(1)- it "can generate a response from an array" do- response =- llm.generate(- [{ type: :system, content: "you are a bot" }, { type: :user, content: "hello" }],- user: user,+ expect(AiApiRequestStat.last).to have_attributes(+ llm_id: model.id,+ usage_count: 1,+ rolled_up: false,)- expect(response).to eq("world")- end- end-- describe "#generate" do- let(:prompt) do- system_insts = (<<~TEXT).strip- I want you to act as a title generator for written pieces. I will provide you with a text,- and you will generate five attention-grabbing titles. Please keep the title concise and under 20 words,- and ensure that the meaning is maintained. Replies will utilize the language type of the topic.- TEXT-- DiscourseAi::Completions::Prompt- .new(system_insts)- .tap { |a_prompt| a_prompt.push(type: :user, content: (<<~TEXT).strip) }- Here is the text, inside <input></input> XML tags:- <input>- To perfect his horror, Caesar, surrounded at the base of the statue by the impatient daggers of his friends,- discovers among the faces and blades that of Marcus Brutus, his protege, perhaps his son, and he no longer- defends himself, but instead exclaims: 'You too, my son!' Shakespeare and Quevedo capture the pathetic cry.- </input>- TEXT+ endend- let(:canned_response) do- DiscourseAi::Completions::Endpoints::CannedResponse.new(- [- "<ai>The solitary horse.,The horse etched in gold.,A horse's infinite journey.,A horse lost in time.,A horse's last ride.</ai>",- ],- )- end+ context "when tracking failures" do+ it "fast-tracks problem check after threshold and resets on success" do+ WebMock.stub_request(:post, model.url).to_return(+ { status: 500, body: "fail" },+ { status: 500, body: "fail" },+ { status: 200, body: success_body.to_json },+ )- context "when getting the full response" do- it "processes the prompt and return the response" do- llm_response = llm.generate(prompt, user: user)+ stub_const(DiscourseAi::Completions::Endpoints::Base, "FAIL_THRESHOLD", 2) do+ 2.times do+ expect { llm.generate("Hello", user:) }.to raise_error(+ DiscourseAi::Completions::Endpoints::Base::CompletionFailed,+ )+ end+ end- expect(llm_response).to eq(canned_response.responses[0])+ expect(ProblemCheckTracker[:ai_llm_status, model.id].reload).to be_failing+ expect { llm.generate("Hello", user:) }.not_to raise_error+ expect(Discourse.redis.get("ai_llm_status_fast_fail:#{model.id}")).to be_nilend- end- context "when getting a streamed response" do- it "processes the prompt and call the given block with the partial response" do- llm_response = +""+ it "skips tracking for unsaved models" do+ stub_response(status: 500, body: "fail")- llm.generate(prompt, user: user) { |partial, cancel_fn| llm_response << partial }+ unsaved = LlmModel.new(model.attributes.except("id", "created_at", "updated_at"))- expect(llm_response).to eq(canned_response.responses[0])+ stub_const(DiscourseAi::Completions::Endpoints::Base, "FAIL_THRESHOLD", 1) do+ expect { described_class.proxy(unsaved).generate("Hello", user:) }.to raise_error(+ DiscourseAi::Completions::Endpoints::Base::CompletionFailed,+ )+ endendendenddiff --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.rbindex 4c4f85c3eba..2f1310f6f67 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@@ -7,7 +7,6 @@ RSpec.describe ProblemCheck::AiLlmStatus dofab!(:ai_persona) { Fabricate(:ai_persona, default_llm_id: llm_model.id) }let(:target) { llm_model.id }- let(:provider) { AiApiAuditLog::Provider::OpenAI }before doassign_fake_provider_to(:ai_default_llm_model)@@ -15,55 +14,62 @@ RSpec.describe ProblemCheck::AiLlmStatus doSiteSetting.ai_summarization_enabled = trueend+ def create_log(+ response_tokens:,+ response_status:,+ created_at: Time.zone.now,+ llm_id: llm_model.id+ )+ AiApiAuditLog.create!(+ provider_id: AiApiAuditLog::Provider::OpenAI,+ llm_id:,+ response_tokens:,+ response_status:,+ created_at:,+ )+ end++ describe ".fast_track_problem!" do+ it "does nothing for unsaved models" do+ unsaved = LlmModel.new(llm_model.attributes.except("id", "created_at", "updated_at"))++ expect { described_class.fast_track_problem!(unsaved, 5, 1) }.not_to raise_error+ expect(ProblemCheckTracker.where(identifier: "ai_llm_status").count).to eq(0)+ end+ end+describe "#call" doit "does nothing if discourse-ai plugin disabled" doSiteSetting.discourse_ai_enabled = falseexpect(check).to be_chill_about_itend- context "with discourse-ai plugin enabled for the site" do+ context "with plugin enabled" dobefore { enable_current_plugin }it "returns a problem when recent calls frequently fail" do3.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,- target: llm_model.id,- base_path: Discourse.base_path,- count: (ProblemCheck::AiLlmStatus::LOOKBACK_WINDOW / 1.hour),- failed_calls: 3,- total_calls: 5,- },- )-- expect(check).to have_a_problem- .with_priority("high")- .with_target(llm_model.id)- .with_message(message)+ expect(check).to have_a_problem.with_priority("high").with_target(llm_model.id)end- it "does not return a problem when failures are below the threshold" do+ it "no problem when failures below threshold" do2.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_itend- it "ignores stale failures outside the lookback window" do+ it "ignores stale failures outside lookback window" do3.times { create_log(response_tokens: 0, response_status: 500, created_at: 2.days.ago) }3.times { create_log(response_tokens: 12, response_status: 200) }expect(check).to be_chill_about_itend- 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) }+ it "does not count zero-token 2xx as failures" do+ 6.times { create_log(response_tokens: 0, response_status: 200) }expect(check).to be_chill_about_itend@@ -77,10 +83,9 @@ RSpec.describe ProblemCheck::AiLlmStatus doit "skips seeded LLMs" doSiteSetting.ai_summarization_enabled = false-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_persona =+ Fabricate(:ai_persona, default_llm_id: seeded_llm.id).idSiteSetting.ai_summarization_enabled = true3.times { create_log(response_tokens: 0, response_status: 500, llm_id: seeded_llm.id) }@@ -89,19 +94,4 @@ RSpec.describe ProblemCheck::AiLlmStatus doendendend-- 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,- )- endend