Skip to content

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

DEV: Adjustments in usage page for LLM's with credit allocations (#36566)

Keegan George131a6e1afb8d
diff --git a/plugins/discourse-ai/app/serializers/ai_usage_serializer.rb b/plugins/discourse-ai/app/serializers/ai_usage_serializer.rb
index 3d5b930be3c..87c8b7a1cec 100644
--- a/plugins/discourse-ai/app/serializers/ai_usage_serializer.rb
+++ b/plugins/discourse-ai/app/serializers/ai_usage_serializer.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
class AiUsageSerializer < ApplicationSerializer
- attributes :data, :features, :models, :users, :summary, :period
+ attributes :data, :features, :feature_models, :models, :users, :summary, :period
def data
object.tokens_by_period.map do |row|
@@ -42,33 +42,35 @@ class AiUsageSerializer < ApplicationSerializer
end
end
+ def feature_models
+ result = {}
+ breakdown_rows = object.feature_model_breakdown.to_a
+
+ llm_ids = breakdown_rows.map(&:llm_id).compact.select { |id| numeric_id?(id) }.map(&:to_i)
+ llm_models = LlmModel.where(id: llm_ids).includes(:llm_credit_allocation).index_by(&:id)
+
+ breakdown_rows.each do |row|
+ feature_name = row.feature_name.presence || "unknown"
+ result[feature_name] ||= []
+
+ model_data = build_model_data(row)
+ enrich_with_credit_allocation!(model_data, row.llm_id, llm_models)
+
+ result[feature_name] << model_data
+ end
+
+ result
+ end
+
def models
- object.model_breakdown.map do |row|
- model_data = {
- 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,
- }
+ breakdown_rows = object.model_breakdown.to_a
- if row.llm_id.present? && row.llm_id.to_i.negative?
- llm_model = LlmModel.find_by(id: row.llm_id)
- if llm_model&.llm_credit_allocation.present?
- model_data[:credit_allocation] = LlmCreditAllocationSerializer.new(
- llm_model.llm_credit_allocation,
- root: false,
- ).as_json
- end
- end
+ llm_ids = breakdown_rows.map(&:llm_id).compact.select { |id| numeric_id?(id) }.map(&:to_i)
+ llm_models = LlmModel.where(id: llm_ids).includes(:llm_credit_allocation).index_by(&:id)
+ breakdown_rows.map do |row|
+ model_data = build_model_data(row, id_key: :id)
+ enrich_with_credit_allocation!(model_data, row.llm_id, llm_models)
model_data
end
end
@@ -107,4 +109,39 @@ class AiUsageSerializer < ApplicationSerializer
},
}
end
+
+ private
+
+ def numeric_id?(value)
+ value.to_s.match?(DiscourseAi::Completions::Report::LLM_MODEL_ID_PATTERN)
+ end
+
+ def build_model_data(row, id_key: :llm_id)
+ {
+ id_key => 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
+
+ def enrich_with_credit_allocation!(model_data, llm_id, llm_models_index)
+ return if llm_id.blank? || !numeric_id?(llm_id)
+
+ llm_model = llm_models_index[llm_id.to_i]
+ return if llm_model&.llm_credit_allocation.blank?
+
+ model_data[:credit_allocation] = LlmCreditAllocationSerializer.new(
+ llm_model.llm_credit_allocation,
+ root: false,
+ ).as_json
+ 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 61694a58294..b8e3e2acce4 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-usage.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-usage.gjs
@@ -14,8 +14,10 @@ import DButton from "discourse/components/d-button";
import DPageSubheader from "discourse/components/d-page-subheader";
import DStatTiles from "discourse/components/d-stat-tiles";
import DateTimeInputRange from "discourse/components/date-time-input-range";
+import DTooltip from "discourse/float-kit/components/d-tooltip";
import avatar from "discourse/helpers/avatar";
import concatClass from "discourse/helpers/concat-class";
+import icon from "discourse/helpers/d-icon";
import { ajax } from "discourse/lib/ajax";
import { bind } from "discourse/lib/decorators";
import { number } from "discourse/lib/formatter";
@@ -277,18 +279,27 @@ export default class AiUsage extends Component {
get featuresTotals() {
const features = this.data?.features || [];
- return {
- usage_count: features.reduce((sum, f) => sum + (f.usage_count || 0), 0),
- total_tokens: features.reduce((sum, f) => sum + (f.total_tokens || 0), 0),
- total_spending: features.reduce(
- (sum, f) =>
- sum +
+ let totalSpending = 0;
+
+ features.forEach((f) => {
+ const costType = this.getFeatureCostType(f.feature_name);
+ if (costType === "included") {
+ // Don't add to total - included in plan
+ } else if (costType === "mixed") {
+ totalSpending += this.getCostOnlySpending(f.feature_name);
+ } else {
+ totalSpending +=
(f.input_spending || 0) +
(f.cache_read_spending || 0) +
(f.cache_write_spending || 0) +
- (f.output_spending || 0),
- 0
- ),
+ (f.output_spending || 0);
+ }
+ });
+
+ return {
+ usage_count: features.reduce((sum, f) => sum + (f.usage_count || 0), 0),
+ total_tokens: features.reduce((sum, f) => sum + (f.total_tokens || 0), 0),
+ total_spending: totalSpending,
};
}
@@ -326,10 +337,68 @@ export default class AiUsage extends Component {
};
}
+ @bind
formatSpending(value) {
return `$${(value || 0).toFixed(2)}`;
}
+ @bind
+ getFeatureCostType(featureName) {
+ const models = this.data?.feature_models?.[featureName] || [];
+ if (models.length === 0) {
+ return "cost";
+ }
+
+ const hasIncluded = models.some((m) => m.credit_allocation);
+ const hasCost = models.some((m) => !m.credit_allocation);
+
+ if (hasIncluded && !hasCost) {
+ return "included";
+ }
+ if (!hasIncluded && hasCost) {
+ return "cost";
+ }
+ return "mixed";
+ }
+
+ @bind
+ getIncludedModelsForFeature(featureName) {
+ return (this.data?.feature_models?.[featureName] || []).filter(
+ (m) => m.credit_allocation
+ );
+ }
+
+ @bind
+ getCostModelsForFeature(featureName) {
+ return (this.data?.feature_models?.[featureName] || []).filter(
+ (m) => !m.credit_allocation
+ );
+ }
+
+ @bind
+ getCostOnlySpending(featureName) {
+ const costModels = this.getCostModelsForFeature(featureName);
+ return costModels.reduce(
+ (sum, m) =>
+ sum +
+ (m.input_spending || 0) +
+ (m.cache_read_spending || 0) +
+ (m.cache_write_spending || 0) +
+ (m.output_spending || 0),
+ 0
+ );
+ }
+
+ @bind
+ hasIncludedModelsForFeature(featureName) {
+ return this.getIncludedModelsForFeature(featureName).length > 0;
+ }
+
+ @bind
+ hasCostModelsForFeature(featureName) {
+ return this.getCostModelsForFeature(featureName).length > 0;
+ }
+
get availableFeatures() {
// when you switch we don't want the list to change
// only when you switch durations
@@ -428,6 +497,7 @@ export default class AiUsage extends Component {
return this._endDate || this.endDate;
}
+ @bind
totalSpending(
inputSpending,
cacheReadSpending,
@@ -579,13 +649,165 @@ export default class AiUsage extends Component {
class="ai-usage__features-cell"
title={{feature.total_tokens}}
>{{number feature.total_tokens}}</td>
- <td>
- {{this.totalSpending
- feature.input_spending
- feature.cache_read_spending
- feature.cache_write_spending
- feature.output_spending
+ <td class="ai-usage__features-cell">
+ {{#if
+ (eq
+ (this.getFeatureCostType feature.feature_name)
+ "included"
+ )
+ }}
+ <span class="ai-usage__included-label">
+ {{i18n "discourse_ai.usage.included_in_plan"}}
+ </span>
+ {{else if
+ (eq
+ (this.getFeatureCostType feature.feature_name)
+ "cost"
+ )
}}
+ {{this.totalSpending
+ feature.input_spending
+ feature.cache_read_spending
+ feature.cache_write_spending
+ feature.output_spending
+ }}
+ {{else}}
+ <span class="ai-usage__mixed-cost">
+ {{this.formatSpending
+ (this.getCostOnlySpending
+ feature.feature_name
+ )
+ }}
+ <DTooltip
+ @identifier="ai-usage-feature-breakdown"
+ @placement="top"
+ @interactive={{true}}
+ @maxWidth={{600}}
+ >
+ <:trigger>
+ {{icon
+ "circle-question"
+ class="ai-usage__info-icon"
+ }}
+ </:trigger>
+ <:content>
+ <div class="ai-usage__cost-breakdown">
+ {{#if
+ (this.hasIncludedModelsForFeature
+ feature.feature_name
+ )
+ }}
+ <div
+ class="ai-usage__breakdown-section"
+ >
+ <h4>{{i18n
+ "discourse_ai.usage.included_models"
+ }}</h4>
+ <table
+ class="ai-usage__breakdown-table"
+ >
+ <thead>
+ <tr>
+ <th>{{i18n
+ "discourse_ai.usage.model"
+ }}</th>
+ <th>{{i18n
+ "discourse_ai.usage.usage_count"
+ }}</th>
+ <th>{{i18n
+ "discourse_ai.usage.total_tokens"
+ }}</th>
+ <th>{{i18n
+ "discourse_ai.usage.cost"
+ }}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {{#each
+ (this.getIncludedModelsForFeature
+ feature.feature_name
+ )
+ as |model|
+ }}
+ <tr>
+ <td>{{model.llm}}</td>
+ <td>{{number
+ model.usage_count
+ }}</td>
+ <td>{{number
+ model.total_tokens
+ }}</td>
+ <td>{{i18n
+ "discourse_ai.usage.included_in_plan"
+ }}</td>
+ </tr>
+ {{/each}}
+ </tbody>
+ </table>
+ </div>
+ {{/if}}
+ {{#if
+ (this.hasCostModelsForFeature
+ feature.feature_name
+ )
+ }}
+ <div
+ class="ai-usage__breakdown-section"
+ >
+ <h4>{{i18n
+ "discourse_ai.usage.billed_models"
+ }}</h4>
+ <table
+ class="ai-usage__breakdown-table"
+ >
+ <thead>
+ <tr>
+ <th>{{i18n
+ "discourse_ai.usage.model"
+ }}</th>
+ <th>{{i18n
+ "discourse_ai.usage.usage_count"
+ }}</th>
+ <th>{{i18n
+ "discourse_ai.usage.total_tokens"
+ }}</th>
+ <th>{{i18n
+ "discourse_ai.usage.cost"
+ }}</th>
+ </tr>
+ </thead>
+ <tbody>
+ {{#each
+ (this.getCostModelsForFeature
+ feature.feature_name
+ )
+ as |model|
+ }}
+ <tr>
+ <td>{{model.llm}}</td>
+ <td>{{number
+ model.usage_count
+ }}</td>
+ <td>{{number
+ model.total_tokens
+ }}</td>
+ <td>{{this.totalSpending
+ model.input_spending
+ model.cache_read_spending
+ model.cache_write_spending
+ model.output_spending
+ }}</td>
+ </tr>
+ {{/each}}
+ </tbody>
+ </table>
+ </div>
+ {{/if}}
+ </div>
+ </:content>
+ </DTooltip>
+ </span>
+ {{/if}}
</td>
</tr>
{{/each}}
diff --git a/plugins/discourse-ai/assets/stylesheets/modules/llms/common/usage.scss b/plugins/discourse-ai/assets/stylesheets/modules/llms/common/usage.scss
index dd24eb53554..75e9891e50e 100644
--- a/plugins/discourse-ai/assets/stylesheets/modules/llms/common/usage.scss
+++ b/plugins/discourse-ai/assets/stylesheets/modules/llms/common/usage.scss
@@ -200,4 +200,59 @@
&__models-table + &__models-table {
margin-top: var(--space-6);
}
+
+ &__included-label {
+ color: var(--primary);
+ }
+
+ &__mixed-cost {
+ display: inline-flex;
+ align-items: center;
+ }
+
+ &__info-icon {
+ color: var(--tertiary);
+ cursor: help;
+ margin-left: var(--space-2);
+ font-size: var(--font-down-1);
+ }
+
+ &__cost-breakdown {
+ padding: var(--space-2);
+ max-height: 400px;
+ overflow-y: auto;
+ }
+
+ &__breakdown-section {
+ margin-bottom: var(--space-4);
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+
+ h4 {
+ margin: 0 0 var(--space-2) 0;
+ font-size: var(--font-down-1);
+ font-weight: bold;
+ }
+ }
+
+ &__breakdown-table {
+ width: 100%;
+ font-size: var(--font-down-1);
+
+ th,
+ td {
+ padding: var(--space-1) var(--space-2);
+ text-align: left;
+ }
+
+ th {
+ border-bottom: 1px solid var(--primary-low);
+ }
+
+ td {
+ border-bottom: 1px solid var(--primary-very-low);
+ }
+ }
}
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index 0d2b3a9c091..7093b1c3506 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -444,6 +444,10 @@ en:
no_models: "No model usage data found"
no_features: "No feature usage data found"
total: "Total"
+ included_in_plan: "Included in plan"
+ included_models: "Included usage"
+ billed_models: "Billed usage"
+ cost: "Cost"
subheader_description: "Tokens are the basic units that LLMs use to understand and generate text, usage data may affect costs"
stat_tooltips:
total_requests: "All requests made to LLMs through Discourse"
diff --git a/plugins/discourse-ai/lib/completions/report.rb b/plugins/discourse-ai/lib/completions/report.rb
index c60180a0a2a..5006700164b 100644
--- a/plugins/discourse-ai/lib/completions/report.rb
+++ b/plugins/discourse-ai/lib/completions/report.rb
@@ -5,6 +5,7 @@ module DiscourseAi
UNKNOWN_FEATURE = "unknown"
USER_LIMIT = 50
LLM_MODEL_JOIN = "LEFT JOIN llm_models ON llm_models.id = ai_api_request_stats.llm_id"
+ LLM_MODEL_ID_PATTERN = /^-?\d+$/
attr_reader :start_date, :end_date, :base_query, :timezone
@@ -168,6 +169,28 @@ module DiscourseAi
)
end
+ def feature_model_breakdown
+ base_query
+ .joins(LLM_MODEL_JOIN)
+ .group(
+ :feature_name,
+ "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",
+ "llm_models.cache_write_cost",
+ )
+ .order("feature_name, usage_count DESC")
+ .select(
+ "CASE WHEN COALESCE(feature_name, '') = '' THEN '#{UNKNOWN_FEATURE}' ELSE feature_name END as feature_name",
+ "COALESCE(llm_models.id::text, ai_api_request_stats.language_model) as llm_id",
+ "COALESCE(llm_models.display_name, ai_api_request_stats.language_model) as llm_label",
+ "SUM(usage_count) as usage_count",
+ *token_count_and_total_columns,
+ )
+ end
+
def tokens_per_hour
tokens_by_period(:hour)
end
@@ -190,7 +213,7 @@ module DiscourseAi
end
def filter_by_model(model_identifier)
- if model_identifier.to_s.match?(/^-?\d+$/)
+ if model_identifier.to_s.match?(LLM_MODEL_ID_PATTERN)
model = LlmModel.find_by(id: model_identifier)
if model
@base_query =
diff --git a/plugins/discourse-ai/spec/lib/completions/report_spec.rb b/plugins/discourse-ai/spec/lib/completions/report_spec.rb
index 71cba8840a6..caad64a0bba 100644
--- a/plugins/discourse-ai/spec/lib/completions/report_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/report_spec.rb
@@ -217,6 +217,111 @@ RSpec.describe DiscourseAi::Completions::Report do
end
end
+ describe "#feature_model_breakdown" do
+ fab!(:gpt_model) do
+ Fabricate(:llm_model, name: "gpt-4", provider: "open_ai", input_cost: 10.0, output_cost: 30.0)
+ end
+
+ it "returns breakdown grouped by both feature and model" do
+ 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,
+ response_tokens: 500,
+ created_at: 1.day.ago,
+ )
+
+ AiApiRequestStat.create!(
+ provider_id: AiApiAuditLog::Provider::OpenAI,
+ user_id: user.id,
+ llm_id: gpt_model.id,
+ language_model: "gpt-4",
+ feature_name: "ai_bot",
+ request_tokens: 2000,
+ response_tokens: 1000,
+ created_at: 1.day.ago,
+ )
+
+ AiApiRequestStat.create!(
+ provider_id: AiApiAuditLog::Provider::Anthropic,
+ user_id: user.id,
+ llm_id: claude_model.id,
+ language_model: "claude-3-opus",
+ feature_name: "ai_helper",
+ request_tokens: 500,
+ response_tokens: 250,
+ created_at: 1.day.ago,
+ )
+
+ report = described_class.new(start_date: 2.days.ago, end_date: Time.current)
+ breakdown = report.feature_model_breakdown.to_a
+
+ expect(breakdown.size).to eq(3)
+
+ ai_bot_claude =
+ breakdown.find { |b| b.feature_name == "ai_bot" && b.llm_id.to_i == claude_model.id }
+ expect(ai_bot_claude).to be_present
+ expect(ai_bot_claude.total_request_tokens).to eq(1000)
+ expect(ai_bot_claude.total_response_tokens).to eq(500)
+
+ ai_bot_gpt =
+ breakdown.find { |b| b.feature_name == "ai_bot" && b.llm_id.to_i == gpt_model.id }
+ expect(ai_bot_gpt).to be_present
+ expect(ai_bot_gpt.total_request_tokens).to eq(2000)
+ expect(ai_bot_gpt.total_response_tokens).to eq(1000)
+
+ ai_helper_claude =
+ breakdown.find { |b| b.feature_name == "ai_helper" && b.llm_id.to_i == claude_model.id }
+ expect(ai_helper_claude).to be_present
+ expect(ai_helper_claude.total_request_tokens).to eq(500)
+ expect(ai_helper_claude.total_response_tokens).to eq(250)
+ end
+
+ it "includes spending calculations per feature-model combination" do
+ 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,
+ response_tokens: 500,
+ cache_read_tokens: 2000,
+ cache_write_tokens: 1000,
+ created_at: 1.day.ago,
+ )
+
+ report = described_class.new(start_date: 2.days.ago, end_date: Time.current)
+ breakdown = report.feature_model_breakdown.first
+
+ expect(breakdown.input_spending).to be_within(0.001).of(0.015)
+ expect(breakdown.output_spending).to be_within(0.001).of(0.0375)
+ expect(breakdown.cache_read_spending).to be_within(0.001).of(0.003)
+ expect(breakdown.cache_write_spending).to be_within(0.001).of(0.01875)
+ end
+
+ it "handles unknown features" do
+ AiApiRequestStat.create!(
+ provider_id: AiApiAuditLog::Provider::Anthropic,
+ user_id: user.id,
+ llm_id: claude_model.id,
+ language_model: "claude-3-opus",
+ feature_name: nil,
+ request_tokens: 1000,
+ response_tokens: 500,
+ created_at: 1.day.ago,
+ )
+
+ report = described_class.new(start_date: 2.days.ago, end_date: Time.current)
+ breakdown = report.feature_model_breakdown.first
+
+ expect(breakdown.feature_name).to eq("unknown")
+ end
+ end
+
describe "#tokens_by_period" do
it "includes cache token counts in period breakdowns" do
AiApiRequestStat.create!(
diff --git a/plugins/discourse-ai/spec/serializers/ai_usage_serializer_spec.rb b/plugins/discourse-ai/spec/serializers/ai_usage_serializer_spec.rb
new file mode 100644
index 00000000000..f4e5bae62fa
--- /dev/null
+++ b/plugins/discourse-ai/spec/serializers/ai_usage_serializer_spec.rb
@@ -0,0 +1,128 @@
+# frozen_string_literal: true
+
+RSpec.describe AiUsageSerializer do
+ fab!(:user)
+ fab!(:claude_model) do
+ Fabricate(
+ :llm_model,
+ name: "claude-3-opus",
+ provider: "anthropic",
+ input_cost: 15.0,
+ output_cost: 75.0,
+ )
+ end
+
+ fab!(:gpt_model) do
+ Fabricate(:llm_model, name: "gpt-4", provider: "open_ai", input_cost: 10.0, output_cost: 30.0)
+ end
+
+ before { enable_current_plugin }
+
+ describe "#feature_models" do
+ it "returns a hash mapping feature names to model breakdowns" do
+ 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,
+ response_tokens: 500,
+ created_at: 1.day.ago,
+ )
+
+ AiApiRequestStat.create!(
+ provider_id: AiApiAuditLog::Provider::OpenAI,
+ user_id: user.id,
+ llm_id: gpt_model.id,
+ language_model: "gpt-4",
+ feature_name: "ai_bot",
+ request_tokens: 2000,
+ response_tokens: 1000,
+ created_at: 1.day.ago,
+ )
+
+ report = DiscourseAi::Completions::Report.new(start_date: 2.days.ago, end_date: Time.current)
+ serialized = described_class.new(report, root: false)
+ json = JSON.parse(serialized.to_json)
+
+ expect(json).to have_key("feature_models")
+ expect(json["feature_models"]).to be_a(Hash)
+ expect(json["feature_models"]).to have_key("ai_bot")
+ expect(json["feature_models"]["ai_bot"].size).to eq(2)
+ end
+
+ it "includes credit_allocation for models with LlmCreditAllocation" do
+ seeded_model = Fabricate(:seeded_model)
+ Fabricate(:llm_credit_allocation, llm_model: seeded_model)
+
+ AiApiRequestStat.create!(
+ provider_id: AiApiAuditLog::Provider::Anthropic,
+ user_id: user.id,
+ llm_id: seeded_model.id,
+ language_model: seeded_model.name,
+ feature_name: "ai_helper",
+ request_tokens: 500,
+ response_tokens: 250,
+ created_at: 1.day.ago,
+ )
+
+ report = DiscourseAi::Completions::Report.new(start_date: 2.days.ago, end_date: Time.current)
+ serialized = described_class.new(report, root: false)
+ json = JSON.parse(serialized.to_json)
+
+ ai_helper_models = json["feature_models"]["ai_helper"]
+ seeded_model_data = ai_helper_models.find { |m| m["llm_id"].to_i == seeded_model.id }
+
+ expect(seeded_model_data).to have_key("credit_allocation")
+ expect(seeded_model_data["credit_allocation"]).to be_present
+ end
+
+ it "does not include credit_allocation for models without LlmCreditAllocation" do
+ 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,
+ response_tokens: 500,
+ created_at: 1.day.ago,
+ )
+
+ report = DiscourseAi::Completions::Report.new(start_date: 2.days.ago, end_date: Time.current)
+ serialized = described_class.new(report, root: false)
+ json = JSON.parse(serialized.to_json)
+
+ ai_bot_models = json["feature_models"]["ai_bot"]
+ claude_model_data = ai_bot_models.find { |m| m["llm_id"].to_i == claude_model.id }
+
+ expect(claude_model_data).not_to have_key("credit_allocation")
+ end
+
+ it "includes spending data for each model in the breakdown" do
+ 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,
+ response_tokens: 500,
+ created_at: 1.day.ago,
+ )
+
+ report = DiscourseAi::Completions::Report.new(start_date: 2.days.ago, end_date: Time.current)
+ serialized = described_class.new(report, root: false)
+ json = JSON.parse(serialized.to_json)
+
+ ai_bot_models = json["feature_models"]["ai_bot"]
+ model_data = ai_bot_models.first
+
+ expect(model_data).to have_key("input_spending")
+ expect(model_data).to have_key("output_spending")
+ expect(model_data).to have_key("total_tokens")
+ expect(model_data).to have_key("usage_count")
+ end
+ end
+end