Skip to content

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

FEATURE: improve performance of llm usage report (#36177)

Same966072092d8
diff --git a/plugins/discourse-ai/app/jobs/scheduled/purge_ai_api_audit_logs.rb b/plugins/discourse-ai/app/jobs/scheduled/purge_ai_api_audit_logs.rb
new file mode 100644
index 00000000000..95a7769293d
--- /dev/null
+++ b/plugins/discourse-ai/app/jobs/scheduled/purge_ai_api_audit_logs.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+module Jobs
+ class PurgeAiApiAuditLogs < ::Jobs::Scheduled
+ every 1.day
+
+ def execute(_args)
+ return unless SiteSetting.discourse_ai_enabled
+
+ retention_days = SiteSetting.ai_audit_logs_purge_after_days.to_i
+ return if retention_days <= 0
+
+ cutoff = retention_days.days.ago
+ AiApiAuditLog.where("created_at < ?", cutoff).delete_all
+ end
+ end
+end
diff --git a/plugins/discourse-ai/app/jobs/scheduled/rollup_ai_api_request_stats.rb b/plugins/discourse-ai/app/jobs/scheduled/rollup_ai_api_request_stats.rb
new file mode 100644
index 00000000000..77bd16e0170
--- /dev/null
+++ b/plugins/discourse-ai/app/jobs/scheduled/rollup_ai_api_request_stats.rb
@@ -0,0 +1,14 @@
+# frozen_string_literal: true
+
+module Jobs
+ class RollupAiApiRequestStats < ::Jobs::Scheduled
+ every 1.day
+
+ def execute(_args)
+ return unless SiteSetting.discourse_ai_enabled
+ return if SiteSetting.ai_usage_rollup_after_days.to_i <= 0
+
+ AiApiRequestStat.rollup!
+ end
+ end
+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 4f41d82d9f7..44bb7d3b726 100644
--- a/plugins/discourse-ai/app/models/ai_api_audit_log.rb
+++ b/plugins/discourse-ai/app/models/ai_api_audit_log.rb
@@ -5,6 +5,7 @@ class AiApiAuditLog < ActiveRecord::Base
belongs_to :post
belongs_to :topic
belongs_to :user
+ belongs_to :llm_model, foreign_key: :llm_id, optional: true
module Provider
OpenAI = 1
@@ -45,6 +46,7 @@ end
# response_tokens :integer
# created_at :datetime not null
# updated_at :datetime not null
+# llm_id :bigint
# post_id :integer
# provider_id :integer not null
# topic_id :integer
@@ -55,5 +57,6 @@ end
# index_ai_api_audit_logs_on_created_at_and_feature_name (created_at,feature_name)
# index_ai_api_audit_logs_on_created_at_and_language_model (created_at,language_model)
# index_ai_api_audit_logs_on_created_at_and_user_id (created_at,user_id)
+# index_ai_api_audit_logs_on_llm_id (llm_id)
# index_ai_api_audit_logs_on_topic_id (topic_id)
#
diff --git a/plugins/discourse-ai/app/models/ai_api_request_stat.rb b/plugins/discourse-ai/app/models/ai_api_request_stat.rb
new file mode 100644
index 00000000000..31279a623a1
--- /dev/null
+++ b/plugins/discourse-ai/app/models/ai_api_request_stat.rb
@@ -0,0 +1,139 @@
+# frozen_string_literal: true
+
+class AiApiRequestStat < ActiveRecord::Base
+ before_validation :set_bucket_date
+ scope :between, ->(from, to) { where(bucket_date: from..to) }
+
+ class << self
+ def record_from_audit_log(log, llm_model:)
+ timestamp = log.created_at || Time.zone.now
+
+ create!(
+ bucket_date: timestamp,
+ user_id: log.user_id,
+ provider_id: log.provider_id,
+ llm_id: log.llm_id || llm_model&.id,
+ language_model: log.language_model,
+ feature_name: log.feature_name.presence,
+ request_tokens: log.request_tokens || 0,
+ response_tokens: log.response_tokens || 0,
+ cache_read_tokens: log.cache_read_tokens || 0,
+ cache_write_tokens: log.cache_write_tokens || 0,
+ usage_count: 1,
+ rolled_up: false,
+ created_at: timestamp,
+ updated_at: Time.zone.now,
+ )
+ rescue StandardError => e
+ Rails.logger.warn("Failed to persist AiApiRequestStat: #{e.message}")
+ end
+
+ def rollup!
+ cutoff = SiteSetting.ai_usage_rollup_after_days.days.ago.end_of_day
+
+ # We can't easily group by DATE(bucket_date) and delete efficiently in one go if we use slice on dates.
+ # Instead, let's pick distinct dates that need rolling up.
+
+ target_dates =
+ where(rolled_up: false).where("bucket_date <= ?", cutoff).pluck(
+ "DISTINCT DATE(bucket_date)",
+ )
+
+ target_dates.each do |date|
+ start_time = date.beginning_of_day
+ end_time = date.end_of_day
+
+ transaction do
+ DB.exec(<<~SQL, start_time: start_time, end_time: end_time, now: Time.zone.now)
+ INSERT INTO ai_api_request_stats (
+ bucket_date,
+ user_id,
+ provider_id,
+ llm_id,
+ language_model,
+ feature_name,
+ request_tokens,
+ response_tokens,
+ cache_read_tokens,
+ cache_write_tokens,
+ usage_count,
+ rolled_up,
+ created_at,
+ updated_at
+ )
+ SELECT
+ :start_time,
+ user_id,
+ provider_id,
+ llm_id,
+ language_model,
+ feature_name,
+ SUM(request_tokens),
+ SUM(response_tokens),
+ SUM(cache_read_tokens),
+ SUM(cache_write_tokens),
+ SUM(usage_count),
+ true,
+ :start_time,
+ :now
+ FROM ai_api_request_stats
+ WHERE bucket_date >= :start_time
+ AND bucket_date <= :end_time
+ AND rolled_up = false
+ GROUP BY
+ user_id,
+ provider_id,
+ llm_id,
+ language_model,
+ feature_name
+ SQL
+
+ DB.exec(<<~SQL, start_time: start_time, end_time: end_time)
+ DELETE FROM ai_api_request_stats
+ WHERE bucket_date >= :start_time
+ AND bucket_date <= :end_time
+ AND rolled_up = false
+ SQL
+ end
+ end
+ end
+ end
+
+ private
+
+ def set_bucket_date
+ self.bucket_date ||= created_at || Time.zone.now
+ end
+end
+
+# == Schema Information
+#
+# Table name: ai_api_request_stats
+#
+# id :bigint not null, primary key
+# bucket_date :datetime not null
+# cache_read_tokens :integer default(0), not null
+# cache_write_tokens :integer default(0), not null
+# feature_name :string(255)
+# language_model :string(255)
+# request_tokens :integer default(0), not null
+# response_tokens :integer default(0), not null
+# rolled_up :boolean default(FALSE), not null
+# usage_count :integer default(1), not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# llm_id :bigint
+# provider_id :integer not null
+# user_id :bigint
+#
+# Indexes
+#
+# index_ai_api_request_stats_on_bucket_date_and_feature_name (bucket_date,feature_name)
+# index_ai_api_request_stats_on_bucket_date_and_language_model (bucket_date,language_model)
+# index_ai_api_request_stats_on_bucket_date_and_llm_id (bucket_date,llm_id)
+# index_ai_api_request_stats_on_bucket_date_and_rolled_up (bucket_date,rolled_up) WHERE (rolled_up = false)
+# index_ai_api_request_stats_on_bucket_date_and_user_id (bucket_date,user_id)
+# index_ai_api_request_stats_on_created_at_and_feature_name (created_at,feature_name)
+# index_ai_api_request_stats_on_created_at_and_language_model (created_at,language_model)
+# index_ai_api_request_stats_on_created_at_and_user_id (created_at,user_id)
+#
diff --git a/plugins/discourse-ai/app/serializers/ai_api_audit_log_serializer.rb b/plugins/discourse-ai/app/serializers/ai_api_audit_log_serializer.rb
index 0baab08d545..923bbc01f6a 100644
--- a/plugins/discourse-ai/app/serializers/ai_api_audit_log_serializer.rb
+++ b/plugins/discourse-ai/app/serializers/ai_api_audit_log_serializer.rb
@@ -13,6 +13,7 @@ class AiApiAuditLogSerializer < ApplicationSerializer
:topic_id,
:post_id,
:feature_name,
+ :llm_id,
:language_model,
:created_at,
:prev_log_id,
diff --git a/plugins/discourse-ai/app/serializers/ai_usage_serializer.rb b/plugins/discourse-ai/app/serializers/ai_usage_serializer.rb
index 436d4a0d4cf..c1a46d4c54b 100644
--- a/plugins/discourse-ai/app/serializers/ai_usage_serializer.rb
+++ b/plugins/discourse-ai/app/serializers/ai_usage_serializer.rb
@@ -44,21 +44,20 @@ class AiUsageSerializer < ApplicationSerializer
def models
object.model_breakdown.map do |row|
- row.as_json(
- only: %i[
- llm
- usage_count
- total_tokens
- total_cache_read_tokens
- total_cache_write_tokens
- total_request_tokens
- total_response_tokens
- input_spending
- output_spending
- cache_read_spending
- cache_write_spending
- ],
- )
+ {
+ id: row.llm_id,
+ llm: row.llm_label,
+ usage_count: row.usage_count,
+ total_tokens: row.total_tokens,
+ total_cache_read_tokens: row.total_cache_read_tokens,
+ total_cache_write_tokens: row.total_cache_write_tokens,
+ total_request_tokens: row.total_request_tokens,
+ total_response_tokens: row.total_response_tokens,
+ input_spending: row.input_spending,
+ output_spending: row.output_spending,
+ cache_read_spending: row.cache_read_spending,
+ cache_write_spending: row.cache_write_spending,
+ }
end
end
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-usage.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-usage.gjs
index 3799d94e01e..fcd8c92bf23 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-usage.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-usage.gjs
@@ -304,7 +304,7 @@ export default class AiUsage extends Component {
this._cachedModels =
this._cachedModels ||
(this.data?.models || []).map((m) => ({
- id: m.llm,
+ id: m.id,
name: m.llm,
}));
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index 59eac872fb5..9ea8ba32668 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -150,6 +150,8 @@ en:
ai_translation_backfill_max_age_days: "The maximum age of a post and topic to be translated. Posts and topics older than this will not be translated. 0 disables backfilling, but will not disable translation of new posts."
ai_translation_backfill_hourly_rate: "The number of posts and topics to translate per hour during backfill operations. Set to 0 to disable automatic backfilling of translations for existing content."
ai_translation_max_tokens_multiplier: "Multiplier to determine the maximum number of tokens to use for translation. By default, we set the max tokens to approximately two to five times the number of characters in the post. This multiplier can be adjusted to allow for thinking or reasoning models which will use more tokens."
+ ai_usage_rollup_after_days: "Number of days to keep per-request AI usage stats before rolling them into daily aggregates. Set to 0 to disable rollups."
+ ai_audit_logs_purge_after_days: "Delete AI API audit logs older than this many days. Defaults to about 6 months. Set to 0 to keep indefinitely."
reviewables:
reasons:
diff --git a/plugins/discourse-ai/config/settings.yml b/plugins/discourse-ai/config/settings.yml
index 02e49b1bb9d..753386b9a9e 100644
--- a/plugins/discourse-ai/config/settings.yml
+++ b/plugins/discourse-ai/config/settings.yml
@@ -583,3 +583,14 @@ discourse_ai:
ai_artifact_max_keys_per_user_per_artifact:
default: 100
hidden: true
+
+ ai_usage_rollup_after_days:
+ default: 7
+ min: 0
+ client: false
+ hidden: true
+
+ ai_audit_logs_purge_after_days:
+ default: 180
+ min: 0
+ client: false
diff --git a/plugins/discourse-ai/db/migrate/20251120090000_add_llm_id_to_ai_api_audit_logs.rb b/plugins/discourse-ai/db/migrate/20251120090000_add_llm_id_to_ai_api_audit_logs.rb
new file mode 100644
index 00000000000..74a27cdf97f
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20251120090000_add_llm_id_to_ai_api_audit_logs.rb
@@ -0,0 +1,8 @@
+# frozen_string_literal: true
+
+class AddLlmIdToAiApiAuditLogs < ActiveRecord::Migration[8.0]
+ def change
+ add_column :ai_api_audit_logs, :llm_id, :bigint
+ add_index :ai_api_audit_logs, [:llm_id]
+ end
+end
diff --git a/plugins/discourse-ai/db/migrate/20251120090500_create_ai_api_request_stats.rb b/plugins/discourse-ai/db/migrate/20251120090500_create_ai_api_request_stats.rb
new file mode 100644
index 00000000000..3d2b02d1c09
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20251120090500_create_ai_api_request_stats.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+class CreateAiApiRequestStats < ActiveRecord::Migration[8.0]
+ def change
+ create_table :ai_api_request_stats do |t|
+ t.datetime :bucket_date, null: false
+ t.bigint :user_id
+ t.integer :provider_id, null: false
+ t.bigint :llm_id
+ t.string :language_model, limit: 255
+ t.string :feature_name, limit: 255
+ t.integer :request_tokens, default: 0, null: false
+ t.integer :response_tokens, default: 0, null: false
+ t.integer :cache_read_tokens, default: 0, null: false
+ t.integer :cache_write_tokens, default: 0, null: false
+ t.integer :usage_count, default: 1, null: false
+ t.boolean :rolled_up, default: false, null: false
+ t.timestamps
+ end
+
+ add_index :ai_api_request_stats, %i[bucket_date feature_name]
+ add_index :ai_api_request_stats, %i[bucket_date language_model]
+ add_index :ai_api_request_stats, %i[bucket_date user_id]
+ add_index :ai_api_request_stats, %i[bucket_date llm_id]
+ add_index :ai_api_request_stats, %i[created_at feature_name]
+ add_index :ai_api_request_stats, %i[created_at language_model]
+ add_index :ai_api_request_stats, %i[created_at user_id]
+ add_index :ai_api_request_stats, %i[bucket_date rolled_up], where: "rolled_up = false"
+ end
+end
diff --git a/plugins/discourse-ai/db/migrate/20251122000000_backfill_ai_api_request_stats.rb b/plugins/discourse-ai/db/migrate/20251122000000_backfill_ai_api_request_stats.rb
new file mode 100644
index 00000000000..00636e3787e
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20251122000000_backfill_ai_api_request_stats.rb
@@ -0,0 +1,119 @@
+# frozen_string_literal: true
+
+class BackfillAiApiRequestStats < ActiveRecord::Migration[8.0]
+ disable_ddl_transaction!
+
+ def up
+ return unless table_exists?(:ai_api_audit_logs)
+ return unless table_exists?(:ai_api_request_stats)
+
+ # Default to 7 days if SiteSetting is not available or configured
+ rollup_days = 7
+ begin
+ rollup_days = SiteSetting.ai_usage_rollup_after_days if defined?(SiteSetting)
+ rescue StandardError
+ # Keep default
+ end
+
+ cutoff = rollup_days.days.ago.beginning_of_day
+
+ puts "Backfilling AI API Request Stats..."
+ puts "Cutoff for rollup: #{cutoff}"
+
+ # 1. Backfill rolled up stats (older than cutoff)
+ # Process day by day to avoid massive transactions/locks
+
+ min_created_at = connection.select_value("SELECT MIN(created_at) FROM ai_api_audit_logs")
+ if min_created_at
+ current_date = min_created_at.to_date
+ end_date = cutoff.to_date
+
+ while current_date < end_date
+ puts "Processing rollup for #{current_date}"
+
+ execute <<~SQL
+ INSERT INTO ai_api_request_stats (
+ bucket_date, user_id, provider_id, llm_id, language_model, feature_name,
+ request_tokens, response_tokens, cache_read_tokens, cache_write_tokens, usage_count,
+ rolled_up, created_at, updated_at
+ )
+ SELECT
+ date_trunc('day', created_at),
+ user_id,
+ provider_id,
+ llm_id,
+ language_model,
+ feature_name,
+ SUM(COALESCE(request_tokens, 0)),
+ SUM(COALESCE(response_tokens, 0)),
+ SUM(COALESCE(cache_read_tokens, 0)),
+ SUM(COALESCE(cache_write_tokens, 0)),
+ COUNT(*),
+ true,
+ date_trunc('day', created_at),
+ NOW()
+ FROM ai_api_audit_logs
+ WHERE created_at >= '#{current_date}'::timestamp
+ AND created_at < '#{current_date + 1.day}'::timestamp
+ GROUP BY date_trunc('day', created_at), user_id, provider_id, llm_id, language_model, feature_name
+ SQL
+
+ current_date += 1.day
+ end
+ end
+
+ # 2. Backfill recent stats (newer than cutoff)
+ # Process in batches by ID
+
+ batch_size = 2000
+ max_id =
+ connection.select_value(
+ "SELECT MAX(id) FROM ai_api_audit_logs WHERE created_at >= '#{cutoff}'::timestamp",
+ )
+
+ if max_id
+ min_id =
+ connection.select_value(
+ "SELECT MIN(id) FROM ai_api_audit_logs WHERE created_at >= '#{cutoff}'::timestamp",
+ )
+ current_id = min_id
+
+ while current_id <= max_id
+ puts "Processing recent stats batch starting at #{current_id}"
+
+ execute <<~SQL
+ INSERT INTO ai_api_request_stats (
+ bucket_date, user_id, provider_id, llm_id, language_model, feature_name,
+ request_tokens, response_tokens, cache_read_tokens, cache_write_tokens, usage_count,
+ rolled_up, created_at, updated_at
+ )
+ SELECT
+ created_at,
+ user_id,
+ provider_id,
+ llm_id,
+ language_model,
+ feature_name,
+ COALESCE(request_tokens, 0),
+ COALESCE(response_tokens, 0),
+ COALESCE(cache_read_tokens, 0),
+ COALESCE(cache_write_tokens, 0),
+ 1,
+ false,
+ created_at,
+ NOW()
+ FROM ai_api_audit_logs
+ WHERE id >= #{current_id} AND id < #{current_id + batch_size}
+ AND created_at >= '#{cutoff}'::timestamp
+ SQL
+
+ current_id += batch_size
+ sleep 0.01
+ end
+ end
+ end
+
+ def down
+ execute "TRUNCATE TABLE ai_api_request_stats"
+ end
+end
diff --git a/plugins/discourse-ai/lib/completions/endpoints/base.rb b/plugins/discourse-ai/lib/completions/endpoints/base.rb
index 6b6511925b1..c3a6c0d1f83 100644
--- a/plugins/discourse-ai/lib/completions/endpoints/base.rb
+++ b/plugins/discourse-ai/lib/completions/endpoints/base.rb
@@ -286,6 +286,7 @@ module DiscourseAi
log.updated_at = Time.now
log.duration_msecs = (Time.now - start_time) * 1000
log.save!
+ AiApiRequestStat.record_from_audit_log(log, llm_model: @llm_model)
LlmQuota.log_usage(@llm_model, user, log.request_tokens, log.response_tokens)
LlmCreditAllocation.deduct_credits!(
@llm_model,
@@ -449,6 +450,7 @@ module DiscourseAi
topic_id: dialect.prompt.topic_id,
post_id: dialect.prompt.post_id,
feature_name: feature_name,
+ llm_id: llm_model&.id,
language_model: llm_model.name,
feature_context: feature_context.present? ? feature_context.as_json : nil,
)
diff --git a/plugins/discourse-ai/lib/completions/report.rb b/plugins/discourse-ai/lib/completions/report.rb
index 81c1c65ebd4..2cbe496c840 100644
--- a/plugins/discourse-ai/lib/completions/report.rb
+++ b/plugins/discourse-ai/lib/completions/report.rb
@@ -15,7 +15,7 @@ module DiscourseAi
@end_date = end_date.end_of_day
Time.zone = nil # Reset to default timezone
- @base_query = AiApiAuditLog.where(created_at: @start_date..@end_date)
+ @base_query = AiApiRequestStat.between(@start_date, @end_date)
end
def total_tokens
@@ -72,13 +72,17 @@ module DiscourseAi
end
def stats
- @stats ||= base_query.select("COUNT(*) as total_requests", *token_total_columns)[0]
+ @stats ||= base_query.select("SUM(usage_count) as total_requests", *token_total_columns)[0]
end
def model_costs
@model_costs ||=
base_query
- .joins("LEFT JOIN llm_models ON llm_models.name = language_model")
+ .joins(<<~SQL)
+ LEFT JOIN llm_models
+ ON llm_models.id = ai_api_request_stats.llm_id
+ OR llm_models.name = ai_api_request_stats.language_model
+ SQL
.group(
"llm_models.name, llm_models.input_cost, llm_models.output_cost, llm_models.cached_input_cost, llm_models.cache_write_cost",
)
@@ -123,11 +127,15 @@ module DiscourseAi
def user_breakdown
stats =
base_query
- .joins("LEFT JOIN llm_models ON llm_models.name = language_model")
+ .joins(<<~SQL)
+ LEFT JOIN llm_models
+ ON llm_models.id = ai_api_request_stats.llm_id
+ OR llm_models.name = ai_api_request_stats.language_model
+ SQL
.group(:user_id)
.order("usage_count DESC")
.limit(USER_LIMIT)
- .select(:user_id, "COUNT(*) as usage_count", *token_count_and_total_columns)
+ .select(:user_id, "SUM(usage_count) as usage_count", *token_count_and_total_columns)
User
.joins("JOIN (#{stats.to_sql}) as stats ON stats.user_id = users.id")
@@ -137,21 +145,30 @@ module DiscourseAi
def feature_breakdown
base_query
- .joins("LEFT JOIN llm_models ON llm_models.name = language_model")
+ .joins(<<~SQL)
+ LEFT JOIN llm_models
+ ON llm_models.id = ai_api_request_stats.llm_id
+ OR llm_models.name = ai_api_request_stats.language_model
+ SQL
.group(:feature_name)
.order("usage_count DESC")
.select(
"case when coalesce(feature_name, '') = '' then '#{UNKNOWN_FEATURE}' else feature_name end as feature_name",
- "COUNT(*) as usage_count",
+ "SUM(usage_count) as usage_count",
*token_count_and_total_columns,
)
end
def model_breakdown
base_query
- .joins("LEFT JOIN llm_models ON llm_models.name = language_model")
+ .joins(<<~SQL)
+ LEFT JOIN llm_models
+ ON llm_models.id = ai_api_request_stats.llm_id
+ OR llm_models.name = ai_api_request_stats.language_model
+ SQL
.group(
- :language_model,
+ "COALESCE(llm_models.id::text, ai_api_request_stats.language_model)",
+ "COALESCE(llm_models.display_name, ai_api_request_stats.language_model)",
"llm_models.input_cost",
"llm_models.output_cost",
"llm_models.cached_input_cost",
@@ -159,8 +176,9 @@ module DiscourseAi
)
.order("usage_count DESC")
.select(
- "language_model as llm",
- "COUNT(*) as usage_count",
+ "COALESCE(llm_models.display_name, ai_api_request_stats.language_model) as llm_label",
+ "COALESCE(llm_models.id::text, ai_api_request_stats.language_model) as llm_id",
+ "SUM(usage_count) as usage_count",
*token_count_and_total_columns,
)
end
@@ -186,8 +204,22 @@ module DiscourseAi
self
end
- def filter_by_model(model_name)
- @base_query = base_query.where(language_model: model_name)
+ def filter_by_model(model_identifier)
+ if model_identifier.to_s.match?(/^\d+$/)
+ model = LlmModel.find_by(id: model_identifier)
+ if model
+ @base_query =
+ base_query.where(
+ "llm_id = ? OR (llm_id IS NULL AND language_model = ?)",
+ model.id,
+ model.name,
+ )
+ else
+ @base_query = base_query.where(llm_id: model_identifier)
+ end
+ else
+ @base_query = base_query.where(language_model: model_identifier)
+ end
self
end
diff --git a/plugins/discourse-ai/spec/jobs/scheduled/purge_ai_api_audit_logs_spec.rb b/plugins/discourse-ai/spec/jobs/scheduled/purge_ai_api_audit_logs_spec.rb
new file mode 100644
index 00000000000..fe7848fabaa
--- /dev/null
+++ b/plugins/discourse-ai/spec/jobs/scheduled/purge_ai_api_audit_logs_spec.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+RSpec.describe Jobs::PurgeAiApiAuditLogs do
+ before do
+ enable_current_plugin
+ SiteSetting.ai_audit_logs_purge_after_days = 180
+ freeze_time Time.zone.parse("2025-11-22 12:00:00 UTC")
+ end
+
+ let(:job) { described_class.new }
+
+ it "removes audit logs older than the retention window" do
+ recent = AiApiAuditLog.create!(provider_id: 1, created_at: 10.days.ago)
+ stale = AiApiAuditLog.create!(provider_id: 1, created_at: 181.days.ago)
+
+ expect { job.execute({}) }.to change { AiApiAuditLog.count }.by(-1)
+
+ expect(AiApiAuditLog.exists?(recent.id)).to be(true)
+ expect(AiApiAuditLog.exists?(stale.id)).to be(false)
+ end
+
+ it "does nothing when retention is disabled" do
+ SiteSetting.ai_audit_logs_purge_after_days = 0
+ AiApiAuditLog.create!(provider_id: 1, created_at: 400.days.ago)
+
+ expect { job.execute({}) }.not_to change { AiApiAuditLog.count }
+ end
+end
diff --git a/plugins/discourse-ai/spec/jobs/scheduled/rollup_ai_api_request_stats_spec.rb b/plugins/discourse-ai/spec/jobs/scheduled/rollup_ai_api_request_stats_spec.rb
new file mode 100644
index 00000000000..5c8e9e09521
--- /dev/null
+++ b/plugins/discourse-ai/spec/jobs/scheduled/rollup_ai_api_request_stats_spec.rb
@@ -0,0 +1,54 @@
+# frozen_string_literal: true
+
+RSpec.describe Jobs::RollupAiApiRequestStats do
+ before do
+ enable_current_plugin
+ SiteSetting.ai_usage_rollup_after_days = 7
+ freeze_time Time.zone.parse("2025-11-22 12:00:00 UTC")
+ end
+
+ let(:job) { described_class.new }
+
+ it "rolls up stats older than the configured window" do
+ old_time = 8.days.ago
+ newer_time = 2.days.ago
+
+ 2.times do |idx|
+ AiApiRequestStat.create!(
+ provider_id: AiApiAuditLog::Provider::Anthropic,
+ user_id: 1,
+ feature_name: "ai_bot",
+ language_model: "claude-3-opus",
+ request_tokens: 100 + idx,
+ response_tokens: 50,
+ cache_read_tokens: 10,
+ cache_write_tokens: 5,
+ created_at: old_time,
+ )
+ end
+
+ AiApiRequestStat.create!(
+ provider_id: AiApiAuditLog::Provider::Anthropic,
+ user_id: 2,
+ feature_name: "ai_helper",
+ language_model: "claude-3-opus",
+ request_tokens: 10,
+ response_tokens: 5,
+ created_at: newer_time,
+ )
+
+ expect { job.execute({}) }.to change { AiApiRequestStat.where(rolled_up: true).count }.by(1)
+
+ rolled_up = AiApiRequestStat.find_by(rolled_up: true, bucket_date: old_time.to_date, user_id: 1)
+
+ expect(rolled_up.request_tokens).to eq(201)
+ expect(rolled_up.response_tokens).to eq(100)
+ expect(rolled_up.cache_read_tokens).to eq(20)
+ expect(rolled_up.cache_write_tokens).to eq(10)
+ expect(rolled_up.usage_count).to eq(2)
+ expect(rolled_up.created_at).to eq_time(old_time.beginning_of_day)
+
+ expect(AiApiRequestStat.where(rolled_up: false, bucket_date: old_time.to_date).count).to eq(0)
+ expect(AiApiRequestStat.where(rolled_up: false, bucket_date: newer_time).count).to eq(1)
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/completions/llm_spec.rb b/plugins/discourse-ai/spec/lib/completions/llm_spec.rb
index 814a4053e1c..6e95a670bf3 100644
--- a/plugins/discourse-ai/spec/lib/completions/llm_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/llm_spec.rb
@@ -89,6 +89,38 @@ RSpec.describe DiscourseAi::Completions::Llm do
expect(log.feature_name).to eq("llm_triage")
expect(log.feature_context).to eq({ "foo" => "bar" })
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)
+ end
end
describe "#generate with fake model" do
diff --git a/plugins/discourse-ai/spec/lib/completions/report_spec.rb b/plugins/discourse-ai/spec/lib/completions/report_spec.rb
index 5a60d9d972c..82d999527df 100644
--- a/plugins/discourse-ai/spec/lib/completions/report_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/report_spec.rb
@@ -19,9 +19,10 @@ RSpec.describe DiscourseAi::Completions::Report do
describe "#total_spending" do
it "calculates spending with separate cache read and write costs" do
# Create logs with different cache patterns
- AiApiAuditLog.create!(
+ AiApiRequestStat.create!(
provider_id: AiApiAuditLog::Provider::Anthropic,
user_id: user.id,
+ llm_id: claude_model.id,
language_model: "claude-3-opus",
request_tokens: 1000,
response_tokens: 500,
@@ -46,9 +47,10 @@ RSpec.describe DiscourseAi::Completions::Report do
end
it "handles logs without cache tokens" do
- AiApiAuditLog.create!(
+ AiApiRequestStat.create!(
provider_id: AiApiAuditLog::Provider::Anthropic,
user_id: user.id,
+ llm_id: claude_model.id,
language_model: "claude-3-opus",
request_tokens: 1000,
response_tokens: 500,
@@ -66,9 +68,10 @@ RSpec.describe DiscourseAi::Completions::Report do
describe "#model_breakdown" do
it "includes separate cache read and write token counts" do
- AiApiAuditLog.create!(
+ AiApiRequestStat.create!(
provider_id: AiApiAuditLog::Provider::Anthropic,
user_id: user.id,
+ llm_id: claude_model.id,
language_model: "claude-3-opus",
request_tokens: 1000,
response_tokens: 500,
@@ -91,9 +94,10 @@ RSpec.describe DiscourseAi::Completions::Report do
describe "#user_breakdown" do
it "includes cache spending for users" do
- AiApiAuditLog.create!(
+ AiApiRequestStat.create!(
provider_id: AiApiAuditLog::Provider::Anthropic,
user_id: user.id,
+ llm_id: claude_model.id,
language_model: "claude-3-opus",
request_tokens: 1000,
response_tokens: 500,
@@ -114,9 +118,10 @@ RSpec.describe DiscourseAi::Completions::Report do
describe "#feature_breakdown" do
it "includes cache spending for features" do
- AiApiAuditLog.create!(
+ AiApiRequestStat.create!(
provider_id: AiApiAuditLog::Provider::Anthropic,
user_id: user.id,
+ llm_id: claude_model.id,
language_model: "claude-3-opus",
feature_name: "ai_bot",
request_tokens: 1000,
@@ -138,9 +143,10 @@ RSpec.describe DiscourseAi::Completions::Report do
describe "#tokens_by_period" do
it "includes cache token counts in period breakdowns" do
- AiApiAuditLog.create!(
+ AiApiRequestStat.create!(
provider_id: AiApiAuditLog::Provider::Anthropic,
user_id: user.id,
+ llm_id: claude_model.id,
language_model: "claude-3-opus",
request_tokens: 1000,
response_tokens: 500,
diff --git a/plugins/discourse-ai/spec/models/ai_api_request_stat_spec.rb b/plugins/discourse-ai/spec/models/ai_api_request_stat_spec.rb
new file mode 100644
index 00000000000..54599373938
--- /dev/null
+++ b/plugins/discourse-ai/spec/models/ai_api_request_stat_spec.rb
@@ -0,0 +1,112 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe AiApiRequestStat do
+ describe ".record_from_audit_log" do
+ let(:user) { Fabricate(:user) }
+ let(:llm_model) { Fabricate(:llm_model) }
+ let(:log) do
+ AiApiAuditLog.create!(
+ user: user,
+ provider_id: 1,
+ language_model: "gpt-4",
+ feature_name: "test",
+ request_tokens: 10,
+ response_tokens: 20,
+ created_at: 1.hour.ago,
+ )
+ end
+
+ it "creates a stat record with full timestamp" do
+ expect { described_class.record_from_audit_log(log, llm_model: llm_model) }.to change {
+ described_class.count
+ }.by(1)
+
+ stat = described_class.last
+ expect(stat.bucket_date).to eq_time(log.created_at)
+ expect(stat.rolled_up).to eq(false)
+ expect(stat.usage_count).to eq(1)
+ end
+ end
+
+ describe ".rollup!" do
+ before { SiteSetting.ai_usage_rollup_after_days = 1 }
+
+ it "rolls up stats older than cutoff into daily aggregates" do
+ # Old data - to be rolled up (Day 1)
+ day1 = 3.days.ago.beginning_of_day
+ _stat1 =
+ AiApiRequestStat.create!(
+ bucket_date: day1 + 1.hour,
+ created_at: day1 + 1.hour,
+ user_id: 1,
+ provider_id: 1,
+ feature_name: "test",
+ usage_count: 1,
+ request_tokens: 10,
+ response_tokens: 10,
+ )
+ _stat2 =
+ AiApiRequestStat.create!(
+ bucket_date: day1 + 2.hours,
+ created_at: day1 + 2.hours,
+ user_id: 1,
+ provider_id: 1,
+ feature_name: "test",
+ usage_count: 1,
+ request_tokens: 20,
+ response_tokens: 20,
+ )
+
+ # Old data - Day 2
+ day2 = 2.days.ago.beginning_of_day
+ _stat3 =
+ AiApiRequestStat.create!(
+ bucket_date: day2 + 1.hour,
+ created_at: day2 + 1.hour,
+ user_id: 1,
+ provider_id: 1,
+ feature_name: "test",
+ usage_count: 1,
+ request_tokens: 5,
+ response_tokens: 5,
+ )
+
+ # Recent data - should not be rolled up
+ recent_time = 1.hour.ago
+ _stat4 =
+ AiApiRequestStat.create!(
+ bucket_date: recent_time,
+ created_at: recent_time,
+ user_id: 1,
+ provider_id: 1,
+ feature_name: "test",
+ usage_count: 1,
+ request_tokens: 5,
+ response_tokens: 5,
+ )
+
+ described_class.rollup!
+
+ # Expect 3 records:
+ # 1. Rolled up Day 1
+ # 2. Rolled up Day 2
+ # 3. Recent unrolled
+ expect(described_class.count).to eq(3)
+
+ day1_rollup = described_class.find_by(bucket_date: day1.beginning_of_day)
+ expect(day1_rollup.rolled_up).to eq(true)
+ expect(day1_rollup.usage_count).to eq(2)
+ expect(day1_rollup.request_tokens).to eq(30)
+
+ day2_rollup = described_class.find_by(bucket_date: day2.beginning_of_day)
+ expect(day2_rollup.rolled_up).to eq(true)
+ expect(day2_rollup.usage_count).to eq(1)
+ expect(day2_rollup.request_tokens).to eq(5)
+
+ recent = described_class.find_by(rolled_up: false)
+ expect(recent.bucket_date).to eq_time(recent_time)
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/requests/admin/ai_usage_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_usage_controller_spec.rb
index dbe24250fe7..3fcbd695eb6 100644
--- a/plugins/discourse-ai/spec/requests/admin/ai_usage_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/admin/ai_usage_controller_spec.rb
@@ -13,7 +13,7 @@ RSpec.describe DiscourseAi::Admin::AiUsageController do
describe "#show" do
fab!(:log1) do
- AiApiAuditLog.create!(
+ AiApiRequestStat.create!(
provider_id: 1,
feature_name: "summarize",
language_model: "gpt-4",
@@ -24,7 +24,7 @@ RSpec.describe DiscourseAi::Admin::AiUsageController do
end
fab!(:log2) do
- AiApiAuditLog.create!(
+ AiApiRequestStat.create!(
provider_id: 1,
feature_name: "translate",
language_model: "gpt-3.5",
@@ -35,10 +35,11 @@ RSpec.describe DiscourseAi::Admin::AiUsageController do
end
fab!(:log3) do
- AiApiAuditLog.create!(
+ AiApiRequestStat.create!(
provider_id: 1,
feature_name: "ai_helper",
language_model: llm_model.name,
+ llm_id: llm_model.id,
request_tokens: 300,
response_tokens: 150,
cache_read_tokens: 50,
@@ -112,10 +113,11 @@ RSpec.describe DiscourseAi::Admin::AiUsageController do
it "includes cache_read_tokens and cache_write_tokens in response" do
log_with_cache =
- AiApiAuditLog.create!(
+ AiApiRequestStat.create!(
provider_id: 1,
feature_name: "ai_bot",
language_model: llm_model.name,
+ llm_id: llm_model.id,
request_tokens: 500,
response_tokens: 250,
cache_read_tokens: 100,
@@ -134,7 +136,7 @@ RSpec.describe DiscourseAi::Admin::AiUsageController do
expect(ai_bot_feature["total_cache_read_tokens"]).to eq(100)
expect(ai_bot_feature["total_cache_write_tokens"]).to eq(200)
- model_data = json["models"].find { |m| m["llm"] == llm_model.name }
+ model_data = json["models"].find { |m| m["llm"] == llm_model.display_name }
expect(model_data["total_cache_read_tokens"]).to eq(150)
expect(model_data["total_cache_write_tokens"]).to eq(200)
@@ -166,7 +168,7 @@ RSpec.describe DiscourseAi::Admin::AiUsageController do
freeze_time Time.parse("2021-02-01 00:00:00")
# Create data points across different hours
[23.hours.ago, 22.hours.ago, 21.hours.ago, 20.hours.ago].each do |time|
- AiApiAuditLog.create!(
+ AiApiRequestStat.create!(
provider_id: 1,
feature_name: "summarize",
language_model: "gpt-4",
@@ -203,7 +205,7 @@ RSpec.describe DiscourseAi::Admin::AiUsageController do
let(:singapore_tz) { "Asia/Singapore" }
let!(:log_sg1) do
- AiApiAuditLog.create!(
+ AiApiRequestStat.create!(
provider_id: 1,
feature_name: "summarize",
language_model: "gpt-4",
@@ -214,7 +216,7 @@ RSpec.describe DiscourseAi::Admin::AiUsageController do
end
let!(:log_sg2) do
- AiApiAuditLog.create!(
+ AiApiRequestStat.create!(
provider_id: 1,
feature_name: "summarize",
language_model: "gpt-4",