A platform for community discussion. Free, open, simple.
FEATURE: Add Prometheus metrics for LLM API calls (#35636)
Rafael dos Santos Silva4fb6767c832d
diff --git a/plugins/discourse-ai/lib/completions/endpoints/base.rb b/plugins/discourse-ai/lib/completions/endpoints/base.rbindex d3cf1b6e339..0e9c7292f83 100644--- a/plugins/discourse-ai/lib/completions/endpoints/base.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/base.rb@@ -135,6 +135,7 @@ module DiscourseAicancel_manager_callback = nilcancelled = false+ call_status = :errorFinalDestination::HTTP.start(model_uri.host,@@ -228,6 +229,7 @@ module DiscourseAiresponse_raw: response_raw,structured_output: structured_output,)+ call_status = :successreturn response_dataend@@ -270,6 +272,7 @@ module DiscourseAiblk.call("")endend+ call_status = :successreturn response_dataensureif log@@ -288,6 +291,16 @@ module DiscourseAilog.response_tokens,)+ # Record Prometheus metrics+ DiscourseAi::Completions::LlmMetric.record(+ llm_model: @llm_model,+ feature_name: feature_name,+ request_tokens: log.request_tokens || 0,+ response_tokens: log.response_tokens || 0,+ duration_ms: log.duration_msecs,+ status: call_status,+ )+if Rails.env.development? && ENV["DISCOURSE_AI_DEBUG"]puts "#{self.class.name}: request_tokens #{log.request_tokens} response_tokens #{log.response_tokens}"enddiff --git a/plugins/discourse-ai/lib/completions/llm_metric.rb b/plugins/discourse-ai/lib/completions/llm_metric.rbnew file mode 100644index 00000000000..0299a693d95--- /dev/null+++ b/plugins/discourse-ai/lib/completions/llm_metric.rb@@ -0,0 +1,88 @@+# frozen_string_literal: true++module DiscourseAi+ module Completions+ class LlmMetric+ class << self+ # Records metrics for an LLM API call+ #+ # @param llm_model [LlmModel] The LLM model used for the call+ # @param feature_name [String] The feature that initiated the call+ # @param request_tokens [Integer] Number of input tokens+ # @param response_tokens [Integer] Number of output tokens+ # @param duration_ms [Float] Duration of the call in milliseconds+ # @param status [Symbol] Status of the call (:success or :error)+ def record(+ llm_model:,+ feature_name:,+ request_tokens:,+ response_tokens:,+ duration_ms:,+ status: :success+ )+ return if !defined?(::DiscoursePrometheus)++ labels = {+ db: RailsMultisite::ConnectionManagement.current_db,+ provider: llm_model.provider,+ model_name: llm_model.name,+ feature: feature_name || "unknown",+ seeded: llm_model.seeded?,+ }++ increment_counter(+ "discourse_ai_llm_calls_total",+ "Total number of LLM API calls",+ labels.merge(status: status),+ )++ if status == :success+ increment_counter(+ "discourse_ai_llm_request_tokens_total",+ "Total number of input tokens sent to LLM APIs",+ labels,+ request_tokens,+ )++ increment_counter(+ "discourse_ai_llm_response_tokens_total",+ "Total number of output tokens received from LLM APIs",+ labels,+ response_tokens,+ )++ # TODO: Enable duration histogram when supported in DiscoursePrometheus+ # observe_histogram(+ # "discourse_ai_llm_duration_seconds",+ # "Duration of LLM API calls in seconds",+ # labels,+ # duration_ms / 1000.0,+ # )+ end+ end++ private++ def increment_counter(name, description, labels, value = 1)+ metric = ::DiscoursePrometheus::InternalMetric::Custom.new+ metric.name = name+ metric.type = "Counter"+ metric.description = description+ metric.labels = labels+ metric.value = value+ $prometheus_client.send_json(metric.to_h) # rubocop:disable Style/GlobalVars+ end++ def observe_histogram(name, description, labels, value)+ metric = ::DiscoursePrometheus::InternalMetric::Custom.new+ metric.name = name+ metric.type = "Summary"+ metric.description = description+ metric.labels = labels+ metric.value = value+ $prometheus_client.send_json(metric.to_h) # rubocop:disable Style/GlobalVars+ end+ end+ end+ end+enddiff --git a/plugins/discourse-ai/spec/lib/completions/llm_metric_spec.rb b/plugins/discourse-ai/spec/lib/completions/llm_metric_spec.rbnew file mode 100644index 00000000000..29c60804a1b--- /dev/null+++ b/plugins/discourse-ai/spec/lib/completions/llm_metric_spec.rb@@ -0,0 +1,46 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::Completions::LlmMetric do+ fab!(:llm_model)++ describe ".record" do+ it "does not raise an error when DiscoursePrometheus is not defined" do+ expect do+ described_class.record(+ llm_model: llm_model,+ feature_name: "test_feature",+ request_tokens: 100,+ response_tokens: 50,+ duration_ms: 1500,+ status: :success,+ )+ end.not_to raise_error+ end++ it "accepts nil feature_name" do+ expect do+ described_class.record(+ llm_model: llm_model,+ feature_name: nil,+ request_tokens: 100,+ response_tokens: 50,+ duration_ms: 1500.0,+ status: :success,+ )+ end.not_to raise_error+ end++ it "accepts error status" do+ expect do+ described_class.record(+ llm_model: llm_model,+ feature_name: "test_feature",+ request_tokens: 0,+ response_tokens: 0,+ duration_ms: 500.0,+ status: :error,+ )+ end.not_to raise_error+ end+ end+end