A platform for community discussion. Free, open, simple.
FEATURE: add support for tracking write tokens and anthropic caching and Gemini Pro 3 (#36113)
Sam0e6482fcf4d2
diff --git a/plugins/discourse-ai/app/models/ai_api_audit_log.rb b/plugins/discourse-ai/app/models/ai_api_audit_log.rbindex 69f72267752..4f41d82d9f7 100644--- a/plugins/discourse-ai/app/models/ai_api_audit_log.rb+++ b/plugins/discourse-ai/app/models/ai_api_audit_log.rb@@ -1,6 +1,7 @@# frozen_string_literal: trueclass AiApiAuditLog < ActiveRecord::Base+ self.ignored_columns = %w[cached_tokens] # TODO: Remove when 20251118000500_drop_cached_tokens_from_ai_api_audit_logs has been promoted to pre-deploybelongs_to :postbelongs_to :topicbelongs_to :user@@ -32,24 +33,27 @@ end# Table name: ai_api_audit_logs## id :bigint not null, primary key-# provider_id :integer not null-# user_id :integer-# request_tokens :integer-# response_tokens :integer+# cache_read_tokens :integer+# cache_write_tokens :integer+# duration_msecs :integer+# feature_context :jsonb+# feature_name :string(255)+# language_model :string(255)# raw_request_payload :string# raw_response_payload :string+# request_tokens :integer+# response_tokens :integer# created_at :datetime not null# updated_at :datetime not null-# topic_id :integer# post_id :integer-# feature_name :string(255)-# language_model :string(255)-# feature_context :jsonb-# cached_tokens :integer-# duration_msecs :integer+# provider_id :integer not null+# topic_id :integer+# user_id :integer## Indexes## 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_topic_id (topic_id)#diff --git a/plugins/discourse-ai/app/models/llm_model.rb b/plugins/discourse-ai/app/models/llm_model.rbindex c1d58aa47db..2f3d11bc8b8 100644--- a/plugins/discourse-ai/app/models/llm_model.rb+++ b/plugins/discourse-ai/app/models/llm_model.rb@@ -17,6 +17,7 @@ class LlmModel < ActiveRecord::Basevalidates :max_prompt_tokens, numericality: { greater_than: 0 }validates :input_cost,:cached_input_cost,+ :cache_write_cost,:output_cost,:max_output_tokens,numericality: {@@ -41,6 +42,11 @@ class LlmModel < ActiveRecord::Basedisable_top_p: :checkbox,enable_reasoning: :checkbox,reasoning_tokens: :number,+ prompt_caching: {+ type: :enum,+ values: %w[never tool_results always],+ default: "never",+ },},anthropic: {disable_native_tools: :checkbox,@@ -48,6 +54,11 @@ class LlmModel < ActiveRecord::Basedisable_top_p: :checkbox,enable_reasoning: :checkbox,reasoning_tokens: :number,+ prompt_caching: {+ type: :enum,+ values: %w[never tool_results always],+ default: "never",+ },},open_ai: {organization: :text,@@ -236,21 +247,22 @@ end# Table name: llm_models## id :bigint not null, primary key+# api_key :string+# cache_write_cost :float default(0.0)+# cached_input_cost :float# display_name :string+# enabled_chat_bot :boolean default(FALSE), not null+# input_cost :float+# max_output_tokens :integer+# max_prompt_tokens :integer not null# name :string not null+# output_cost :float# provider :string not null+# provider_params :jsonb# tokenizer :string not null-# max_prompt_tokens :integer not null+# url :string+# vision_enabled :boolean default(FALSE), not null# created_at :datetime not null# updated_at :datetime not null-# url :string-# api_key :string# user_id :integer-# enabled_chat_bot :boolean default(FALSE), not null-# provider_params :jsonb-# vision_enabled :boolean default(FALSE), not null-# input_cost :float-# cached_input_cost :float-# output_cost :float-# max_output_tokens :integer#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.rbindex eeb3843acbe..0baab08d545 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@@ -6,6 +6,8 @@ class AiApiAuditLogSerializer < ApplicationSerializer:user_id,:request_tokens,:response_tokens,+ :cache_read_tokens,+ :cache_write_tokens,:raw_request_payload,:raw_response_payload,:topic_id,diff --git a/plugins/discourse-ai/app/serializers/ai_usage_serializer.rb b/plugins/discourse-ai/app/serializers/ai_usage_serializer.rbindex 0a99054740e..436d4a0d4cf 100644--- a/plugins/discourse-ai/app/serializers/ai_usage_serializer.rb+++ b/plugins/discourse-ai/app/serializers/ai_usage_serializer.rb@@ -4,9 +4,18 @@ class AiUsageSerializer < ApplicationSerializerattributes :data, :features, :models, :users, :summary, :perioddef data- object.tokens_by_period.as_json(- only: %i[period total_tokens total_cached_tokens total_request_tokens total_response_tokens],- )+ object.tokens_by_period.map do |row|+ row.as_json(+ only: %i[+ period+ total_tokens+ total_cache_read_tokens+ total_cache_write_tokens+ total_request_tokens+ total_response_tokens+ ],+ )+ endenddef period@@ -14,35 +23,43 @@ class AiUsageSerializer < ApplicationSerializerenddef features- object.feature_breakdown.as_json(- only: %i[- feature_name- usage_count- total_tokens- total_cached_tokens- total_request_tokens- total_response_tokens- input_spending- output_spending- cached_input_spending- ],- )+ object.feature_breakdown.map do |row|+ row.as_json(+ only: %i[+ feature_name+ 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+ ],+ )+ endenddef models- object.model_breakdown.as_json(- only: %i[- llm- usage_count- total_tokens- total_cached_tokens- total_request_tokens- total_response_tokens- input_spending- output_spending- cached_input_spending- ],- )+ 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+ ],+ )+ endenddef users@@ -52,12 +69,14 @@ class AiUsageSerializer < ApplicationSerializerusername: user.username,usage_count: user.usage_count,total_tokens: user.total_tokens,- total_cached_tokens: user.total_cached_tokens,+ total_cache_read_tokens: user.total_cache_read_tokens,+ total_cache_write_tokens: user.total_cache_write_tokens,total_request_tokens: user.total_request_tokens,total_response_tokens: user.total_response_tokens,input_spending: user.input_spending,output_spending: user.output_spending,- cached_input_spending: user.cached_input_spending,+ cache_read_spending: user.cache_read_spending,+ cache_write_spending: user.cache_write_spending,}endend@@ -65,7 +84,8 @@ class AiUsageSerializer < ApplicationSerializerdef summary{total_tokens: object.total_tokens,- total_cached_tokens: object.total_cached_tokens,+ total_cache_read_tokens: object.total_cache_read_tokens,+ total_cache_write_tokens: object.total_cache_write_tokens,total_request_tokens: object.total_request_tokens,total_response_tokens: object.total_response_tokens,total_requests: object.total_requests,diff --git a/plugins/discourse-ai/app/serializers/llm_model_serializer.rb b/plugins/discourse-ai/app/serializers/llm_model_serializer.rbindex 2edbf6ba494..4ee59b491e7 100644--- a/plugins/discourse-ai/app/serializers/llm_model_serializer.rb+++ b/plugins/discourse-ai/app/serializers/llm_model_serializer.rb@@ -21,6 +21,7 @@ class LlmModelSerializer < ApplicationSerializer:input_cost,:output_cost,:cached_input_cost,+ :cache_write_cost,:used_byhas_one :user, serializer: BasicUserSerializer, embed: :objectdiff --git a/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-llm.js b/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-llm.jsindex cafbf3a06c1..4a142e6a43b 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-llm.js+++ b/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-llm.js@@ -18,6 +18,7 @@ export default class AiLlm extends RestModel {"vision_enabled","input_cost","cached_input_cost",+ "cache_write_cost","output_cost");}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-llm-editor-form.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-llm-editor-form.gjsindex 7ba8e03eb2f..4244be8e1b1 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-llm-editor-form.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-llm-editor-form.gjs@@ -61,6 +61,7 @@ export default class AiLlmEditorForm extends Component {output_cost: modelInfo.output_cost,cached_input_cost: modelInfo.cached_input_cost,vision_enabled: modelInfo.vision_enabled || false,+ cache_write_cost: modelInfo.cache_write_cost,};}@@ -80,6 +81,7 @@ export default class AiLlmEditorForm extends Component {input_cost: model.input_cost,output_cost: model.output_cost,cached_input_cost: model.cached_input_cost,+ cache_write_cost: model.cache_write_cost,provider_params: this.computeProviderParams(model.provider,model.provider_params@@ -439,6 +441,16 @@ export default class AiLlmEditorForm extends Component {<field.Input @type="number" step="any" min="0" lang="en" /></inputGroup.Field>+ <inputGroup.Field+ @name="cache_write_cost"+ @title={{i18n "discourse_ai.llms.cost_cache_write"}}+ @tooltip={{i18n "discourse_ai.llms.hints.cost_cache_write"}}+ @helpText={{i18n "discourse_ai.llms.hints.cost_measure"}}+ as |field|+ >+ <field.Input @type="number" step="any" min="0" lang="en" />+ </inputGroup.Field>+<inputGroup.Field@name="output_cost"@title={{i18n "discourse_ai.llms.cost_output"}}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-usage.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-usage.gjsindex 750211e7586..3799d94e01e 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-usage.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-usage.gjs@@ -164,7 +164,8 @@ export default class AiUsage extends Component {existingData || {period: currentMoment.format(),total_tokens: 0,- total_cached_tokens: 0,+ total_cache_read_tokens: 0,+ total_cache_write_tokens: 0,total_request_tokens: 0,total_response_tokens: 0,}@@ -197,9 +198,14 @@ export default class AiUsage extends Component {tooltip: i18n("discourse_ai.usage.stat_tooltips.response_tokens"),},{- label: i18n("discourse_ai.usage.cached_tokens"),- value: this.data.summary.total_cached_tokens,- tooltip: i18n("discourse_ai.usage.stat_tooltips.cached_tokens"),+ label: i18n("discourse_ai.usage.cache_read_tokens"),+ value: this.data.summary.total_cache_read_tokens,+ tooltip: i18n("discourse_ai.usage.stat_tooltips.cache_read_tokens"),+ },+ {+ label: i18n("discourse_ai.usage.cache_write_tokens"),+ value: this.data.summary.total_cache_write_tokens,+ tooltip: i18n("discourse_ai.usage.stat_tooltips.cache_write_tokens"),},{label: i18n("discourse_ai.usage.total_spending"),@@ -222,7 +228,12 @@ export default class AiUsage extends Component {const colors = {response: computedStyle.getPropertyValue("--chart-response-color").trim(),request: computedStyle.getPropertyValue("--chart-request-color").trim(),- cached: computedStyle.getPropertyValue("--chart-cached-color").trim(),+ cacheRead: computedStyle+ .getPropertyValue("--chart-cache-read-color")+ .trim(),+ cacheWrite: computedStyle+ .getPropertyValue("--chart-cache-write-color")+ .trim(),};return {@@ -245,16 +256,19 @@ export default class AiUsage extends Component {backgroundColor: colors.response,},{- label: i18n("discourse_ai.usage.net_request_tokens"),- data: normalizedData.map(- (row) => row.total_request_tokens - row.total_cached_tokens- ),+ label: i18n("discourse_ai.usage.request_tokens"),+ data: normalizedData.map((row) => row.total_request_tokens),backgroundColor: colors.request,},{- label: i18n("discourse_ai.usage.cached_request_tokens"),- data: normalizedData.map((row) => row.total_cached_tokens),- backgroundColor: colors.cached,+ label: i18n("discourse_ai.usage.cache_read_tokens"),+ data: normalizedData.map((row) => row.total_cache_read_tokens),+ backgroundColor: colors.cacheRead,+ },+ {+ label: i18n("discourse_ai.usage.cache_write_tokens"),+ data: normalizedData.map((row) => row.total_cache_write_tokens),+ backgroundColor: colors.cacheWrite,},],},@@ -371,8 +385,17 @@ export default class AiUsage extends Component {return this._endDate || this.endDate;}- totalSpending(inputSpending, cachedSpending, outputSpending) {- const total = inputSpending + cachedSpending + outputSpending;+ totalSpending(+ inputSpending,+ cacheReadSpending,+ cacheWriteSpending,+ outputSpending+ ) {+ const total =+ (inputSpending || 0) ++ (cacheReadSpending || 0) ++ (cacheWriteSpending || 0) ++ (outputSpending || 0);return `$${total.toFixed(2)}`;}@@ -516,7 +539,8 @@ export default class AiUsage extends Component {<td>{{this.totalSpendingfeature.input_spending- feature.cached_input_spending+ feature.cache_read_spending+ feature.cache_write_spendingfeature.output_spending}}</td>@@ -565,7 +589,8 @@ export default class AiUsage extends Component {<td>{{this.totalSpendingmodel.input_spending- model.cached_input_spending+ model.cache_read_spending+ model.cache_write_spendingmodel.output_spending}}</td>@@ -630,7 +655,8 @@ export default class AiUsage extends Component {<td>{{this.totalSpendinguser.input_spending- user.cached_input_spending+ user.cache_read_spending+ user.cache_write_spendinguser.output_spending}}</td>@@ -648,6 +674,7 @@ export default class AiUsage extends Component {}}</th><th>{{i18n "discourse_ai.usage.usage_count"}}</th><th>{{i18n "discourse_ai.usage.total_tokens"}}</th>+ <th>{{i18n "discourse_ai.usage.total_spending"}}</th></tr></thead><tbody>@@ -672,6 +699,14 @@ export default class AiUsage extends Component {class="ai-usage__users-cell"title={{user.total_tokens}}>{{number user.total_tokens}}</td>+ <td>+ {{this.totalSpending+ user.input_spending+ user.cache_read_spending+ user.cache_write_spending+ user.output_spending+ }}+ </td></tr>{{/each}}</tbody>diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/debug-ai-modal.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/debug-ai-modal.gjsindex 135218d36d4..785cb6c7402 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/debug-ai-modal.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/debug-ai-modal.gjs@@ -152,6 +152,18 @@ export default class DebugAiModal extends Component {{{i18n "discourse_ai.ai_bot.debug_ai_modal.response_tokens"}}{{this.info.response_tokens}}</span>+ {{#if this.info.cache_read_tokens}}+ <span class="ai-debug-modal__tokens__count">+ {{i18n "discourse_ai.ai_bot.debug_ai_modal.cache_read_tokens"}}+ {{this.info.cache_read_tokens}}+ </span>+ {{/if}}+ {{#if this.info.cache_write_tokens}}+ <span class="ai-debug-modal__tokens__count">+ {{i18n "discourse_ai.ai_bot.debug_ai_modal.cache_write_tokens"}}+ {{this.info.cache_write_tokens}}+ </span>+ {{/if}}</div><div class="debug-ai-modal__preview">{{this.htmlContext}}diff --git a/plugins/discourse-ai/assets/stylesheets/modules/llms/common/usage.scss b/plugins/discourse-ai/assets/stylesheets/modules/llms/common/usage.scssindex 420cb2b892b..9a7ab56cacb 100644--- a/plugins/discourse-ai/assets/stylesheets/modules/llms/common/usage.scss+++ b/plugins/discourse-ai/assets/stylesheets/modules/llms/common/usage.scss@@ -1,7 +1,8 @@.ai-usage {--chart-response-color: rgb(75, 192, 192, 0.8);--chart-request-color: rgb(153, 102, 255, 0.8);- --chart-cached-color: rgb(153, 102, 255, 0.4);+ --chart-cache-read-color: rgb(255, 159, 64, 0.5);+ --chart-cache-write-color: rgb(255, 159, 64, 0.9);padding: 1em;&__filters-dates {diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex f4dd93e3b24..f67e6308702 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -422,6 +422,8 @@ en:request_tokens: "Request tokens"response_tokens: "Response tokens"net_request_tokens: "Net request tokens"+ cache_read_tokens: "Cache read tokens"+ cache_write_tokens: "Cache write tokens"cached_tokens: "Cached tokens"cached_request_tokens: "Cached request tokens"total_spending: "Estimated cost"@@ -434,6 +436,8 @@ en:total_tokens: "All the tokens used when prompting an LLM"request_tokens: "Tokens used when the LLM tries to understand what you are saying"response_tokens: "Tokens used when the LLM responds to your prompt"+ cache_read_tokens: "Previously processed request tokens that the LLM reuses from cache to optimize performance and cost"+ cache_write_tokens: "Request tokens that were written to cache for potential future reuse"cached_tokens: "Previously processed request tokens that the LLM reuses to optimize performance and cost"total_spending: "Cumulative cost of all tokens used by the LLMs based on specified cost metrics added to LLM configuration settings"periods:@@ -628,6 +632,7 @@ en:ai_bot_user: "AI bot User"cost_input: "Input cost"cost_cached_input: "Cached input cost"+ cost_cache_write: "Cache write cost"cost_output: "Output cost"save: "Save"@@ -727,7 +732,8 @@ en:vision_enabled: "If enabled, the AI will attempt to understand images. It depends on the model being used supporting vision. Supported by latest models from Anthropic, Google, and OpenAI."enabled_chat_bot: "If enabled, users can select this model when creating PMs with the AI bot"cost_input: "The input cost per 1M tokens for this model"- cost_cached_input: "The cached input cost per 1M tokens for this model"+ cost_cached_input: "The cached input cost per 1M tokens for this model (when reading from prompt cache)"+ cost_cache_write: "The cache write cost per 1M tokens for this model (when writing to prompt cache)"cost_output: "The output cost per 1M tokens for this model"cost_measure: "$/1M tokens"providers:@@ -766,6 +772,10 @@ en:disable_temperature: "Disable temperature (some thinking models don't support temperature)"disable_top_p: "Disable top P (some thinking models don't support top P)"enable_responses_api: "Enable responses API (required on certain OpenAI models)"+ prompt_caching: "Prompt caching mode"+ prompt_caching_never: "Never - Do not use prompt caching"+ prompt_caching_tool_results: "Tool Results - Cache when tool results are present (recommended)"+ prompt_caching_always: "Always - Always use prompt caching"related_topics:title: "Related topics"@@ -921,6 +931,8 @@ en:copy_response: "Copy response"request_tokens: "Request tokens:"response_tokens: "Response tokens:"+ cache_read_tokens: "Cache read tokens:"+ cache_write_tokens: "Cache write tokens:"request: "Request"response: "Response"next_log: "Next"diff --git a/plugins/discourse-ai/db/migrate/20251118000001_split_cache_pricing_for_read_and_write.rb b/plugins/discourse-ai/db/migrate/20251118000001_split_cache_pricing_for_read_and_write.rbnew file mode 100644index 00000000000..97bd006b7bb--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20251118000001_split_cache_pricing_for_read_and_write.rb@@ -0,0 +1,16 @@+# frozen_string_literal: true++class SplitCachePricingForReadAndWrite < ActiveRecord::Migration[7.2]+ def up+ add_column :llm_models, :cache_write_cost, :float, default: 0.0+ add_column :ai_api_audit_logs, :cache_write_tokens, :integer+ add_column :ai_api_audit_logs, :cache_read_tokens, :integer+ execute "UPDATE ai_api_audit_logs SET cache_read_tokens = cached_tokens WHERE cached_tokens IS NOT NULL"+ end++ def down+ remove_column :ai_api_audit_logs, :cache_read_tokens+ remove_column :ai_api_audit_logs, :cache_write_tokens+ remove_column :llm_models, :cache_write_cost+ end+enddiff --git a/plugins/discourse-ai/db/migrate/20251119101732_add_user_id_index_to_ai_api_audit_logs.rb b/plugins/discourse-ai/db/migrate/20251119101732_add_user_id_index_to_ai_api_audit_logs.rbnew file mode 100644index 00000000000..6ce46423a18--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20251119101732_add_user_id_index_to_ai_api_audit_logs.rb@@ -0,0 +1,15 @@+# frozen_string_literal: true++class AddUserIdIndexToAiApiAuditLogs < ActiveRecord::Migration[7.2]+ disable_ddl_transaction!++ def change+ user_idx = "index_ai_api_audit_logs_on_created_at_and_user_id"+ execute "DROP INDEX IF EXISTS #{user_idx}"+ add_index :ai_api_audit_logs, %i[created_at user_id], name: user_idx++ topic_idx = "index_ai_api_audit_logs_on_topic_id"+ execute "DROP INDEX IF EXISTS #{topic_idx}"+ add_index :ai_api_audit_logs, [:topic_id], name: topic_idx+ end+enddiff --git a/plugins/discourse-ai/db/post_migrate/20251118000500_drop_cached_tokens_from_ai_api_audit_logs.rb b/plugins/discourse-ai/db/post_migrate/20251118000500_drop_cached_tokens_from_ai_api_audit_logs.rbnew file mode 100644index 00000000000..a4f67981a24--- /dev/null+++ b/plugins/discourse-ai/db/post_migrate/20251118000500_drop_cached_tokens_from_ai_api_audit_logs.rb@@ -0,0 +1,13 @@+# frozen_string_literal: true++class DropCachedTokensFromAiApiAuditLogs < ActiveRecord::Migration[8.0]+ def up+ if column_exists?(:ai_api_audit_logs, :cached_tokens)+ remove_column :ai_api_audit_logs, :cached_tokens+ end+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/plugins/discourse-ai/lib/completions/anthropic_message_processor.rb b/plugins/discourse-ai/lib/completions/anthropic_message_processor.rbindex 75f91ab3ffb..cdf1fd0877e 100644--- a/plugins/discourse-ai/lib/completions/anthropic_message_processor.rb+++ b/plugins/discourse-ai/lib/completions/anthropic_message_processor.rb@@ -46,7 +46,12 @@ class DiscourseAi::Completions::AnthropicMessageProcessorendend- attr_reader :tool_calls, :input_tokens, :output_tokens, :output_thinking+ attr_reader :tool_calls,+ :input_tokens,+ :output_tokens,+ :cache_creation_input_tokens,+ :cache_read_input_tokens,+ :output_thinkingdef initialize(streaming_mode:, partial_tool_calls: false, output_thinking: false)@streaming_mode = streaming_mode@@ -132,7 +137,10 @@ class DiscourseAi::Completions::AnthropicMessageProcessor@current_tool_call = nilendelsif parsed[:type] == "message_start"- @input_tokens = parsed.dig(:message, :usage, :input_tokens)+ usage = parsed.dig(:message, :usage)+ @input_tokens = usage[:input_tokens]+ @cache_creation_input_tokens = usage[:cache_creation_input_tokens]+ @cache_read_input_tokens = usage[:cache_read_input_tokens]elsif parsed[:type] == "message_delta"@output_tokens =parsed.dig(:usage, :output_tokens) || parsed.dig(:delta, :usage, :output_tokens)@@ -191,8 +199,11 @@ class DiscourseAi::Completions::AnthropicMessageProcessor.compactend- @input_tokens = parsed.dig(:usage, :input_tokens)- @output_tokens = parsed.dig(:usage, :output_tokens)+ usage = parsed.dig(:usage)+ @input_tokens = usage[:input_tokens] if usage+ @output_tokens = usage[:output_tokens] if usage+ @cache_creation_input_tokens = usage[:cache_creation_input_tokens] if usage+ @cache_read_input_tokens = usage[:cache_read_input_tokens] if usageresultenddiff --git a/plugins/discourse-ai/lib/completions/dialects/gemini.rb b/plugins/discourse-ai/lib/completions/dialects/gemini.rbindex 89386c7e9a4..e3b51dd1ff4 100644--- a/plugins/discourse-ai/lib/completions/dialects/gemini.rb+++ b/plugins/discourse-ai/lib/completions/dialects/gemini.rb@@ -25,7 +25,7 @@ module DiscourseAidef translate# Gemini complains if we don't alternate model/user roles.noop_model_response = { role: "model", parts: { text: "Ok." } }- messages = super+ messages = merge_tool_batches(super)interleving_messages = []previous_message = nil@@ -128,18 +128,25 @@ module DiscourseAidef tool_call_msg(msg)if native_tool_support?call_details = JSON.parse(msg[:content], symbolize_names: true)- part = {- functionCall: {- name: msg[:name] || call_details[:name],- args: call_details[:arguments],- },+ function_call = {+ name: msg[:name] || call_details[:name],+ args: call_details[:arguments],}- if beta_api?- { role: "model", parts: [part] }- else- { role: "model", parts: part }+ part = { functionCall: function_call }+ if (thought_sig = msg.dig(:provider_data, :thought_signature))+ part[:thoughtSignature] = thought_sigend++ message =+ if beta_api?+ { role: "model", parts: [part] }+ else+ { role: "model", parts: part }+ end+ batch_id = msg.dig(:provider_data, :batch_id)+ message[:batch_id] = batch_id if batch_id+ messageelsesuperend@@ -156,15 +163,61 @@ module DiscourseAi},}- if beta_api?- { role: "function", parts: [part] }- else- { role: "function", parts: part }- end+ message =+ if beta_api?+ { role: "function", parts: [part] }+ else+ { role: "function", parts: part }+ end+ batch_id = msg.dig(:provider_data, :batch_id)+ message[:batch_id] = batch_id if batch_id+ messageelsesuperendend++ def merge_tool_batches(messages)+ merged = []+ existing_batches = {}++ messages.each do |message|+ batch_id = message.delete(:batch_id)+ parts = message[:parts]++ if batch_id && parts+ key = [batch_id, message[:role]]+ normalized_parts = parts_array(parts)++ if existing_batches[key]+ existing_batches[key][:parts].concat(normalized_parts)+ next+ else+ message[:parts] = normalized_parts+ message[:_batch_id] = batch_id+ existing_batches[key] = message+ end+ end++ merged << message+ end++ merged.each do |message|+ message.delete(:_batch_id)+ next if beta_api?+ if message[:parts].is_a?(Array) && message[:parts].length == 1+ message[:parts] = message[:parts].first+ end+ end++ merged+ end++ def parts_array(parts)+ return parts if parts.is_a?(Array)++ [parts]+ endendendenddiff --git a/plugins/discourse-ai/lib/completions/endpoints/anthropic.rb b/plugins/discourse-ai/lib/completions/endpoints/anthropic.rbindex 0ca940c5b25..5122a8585c4 100644--- a/plugins/discourse-ai/lib/completions/endpoints/anthropic.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/anthropic.rb@@ -4,6 +4,7 @@ module DiscourseAimodule Completionsmodule Endpointsclass Anthropic < Base+ include AnthropicPromptCachedef self.can_contact?(model_provider)model_provider == "anthropic"end@@ -98,26 +99,36 @@ module DiscourseAidefault_options(dialect).merge(model_params.except(:response_format)).merge(messages: prompt.messages,)- payload[:system] = prompt.system_prompt if prompt.system_prompt.present?- payload[:stream] = true if @streaming_mode-- prefilled_message = +""+ # Handle tools firstif prompt.has_tools?payload[:tools] = prompt.toolsif dialect.tool_choice.present?if dialect.tool_choice == :nonepayload[:tool_choice] = { type: "none" }-- # prefill prompt to nudge LLM to generate a response that is useful.- # without this LLM (even 3.7) can get confused and start text preambles for a tool calls.- prefilled_message << dialect.no_more_tool_calls_textelsepayload[:tool_choice] = { type: "tool", name: prompt.tool_choice }endendend+ # Apply prompt caching if enabled+ apply_anthropic_cache_control!(payload, prompt) if should_apply_prompt_caching?(prompt)++ # Set system prompt if not already set by caching+ payload[:system] = prompt.system_prompt if prompt.system_prompt.present? &&+ !payload[:system]+ payload[:stream] = true if @streaming_mode++ prefilled_message = +""++ # Handle tool choice prefilling+ if dialect.tool_choice == :none && prompt.has_tools?+ # prefill prompt to nudge LLM to generate a response that is useful.+ # without this LLM (even 3.7) can get confused and start text preambles for a tool calls.+ prefilled_message << dialect.no_more_tool_calls_text+ end+# Prefill prompt to force JSON output.if model_params[:response_format].present?prefilled_message << " " if !prefilled_message.empty?@@ -139,6 +150,9 @@ module DiscourseAi"content-type" => "application/json",}+ # Add caching headers if configured+ headers.merge!(anthropic_cache_headers)+Net::HTTP::Post.new(model_uri, headers).tap { |r| r.body = payload }end@@ -173,6 +187,10 @@ module DiscourseAidef final_log_update(log)log.request_tokens = processor.input_tokens if processor.input_tokenslog.response_tokens = processor.output_tokens if processor.output_tokens+ log.cache_read_tokens =+ processor.cache_read_input_tokens if processor.cache_read_input_tokens+ log.cache_write_tokens =+ processor.cache_creation_input_tokens if processor.cache_creation_input_tokensendendenddiff --git a/plugins/discourse-ai/lib/completions/endpoints/anthropic_prompt_cache.rb b/plugins/discourse-ai/lib/completions/endpoints/anthropic_prompt_cache.rbnew file mode 100644index 00000000000..82d95440159--- /dev/null+++ b/plugins/discourse-ai/lib/completions/endpoints/anthropic_prompt_cache.rb@@ -0,0 +1,62 @@+# frozen_string_literal: true++module DiscourseAi+ module Completions+ module Endpoints+ module AnthropicPromptCache+ def should_apply_prompt_caching?(prompt)+ caching_mode = llm_model.lookup_custom_param("prompt_caching") || "never"+ return false if caching_mode == "never"++ case caching_mode+ when "always"+ true+ when "tool_results"+ prompt+ .messages+ .last(5)+ .any? do |msg|+ content = msg[:content]++ if content.is_a?(Array)+ content.any? { |c| c.is_a?(Hash) && c[:type] == "tool_result" }+ elsif content.is_a?(Hash)+ content[:type] == "tool_result"+ else+ false+ end+ end+ else+ false+ end+ end++ def apply_anthropic_cache_control!(payload, prompt)+ if payload[:messages].present?+ last_message = payload[:messages].last++ if last_message[:content].is_a?(String)+ last_message[:content] = [+ type: "text",+ text: last_message[:content],+ cache_control: {+ type: "ephemeral",+ },+ ]+ elsif last_message[:content].is_a?(Array)+ last_content = last_message[:content].last+ last_content[:cache_control] = { type: "ephemeral" } if last_content.is_a?(Hash)+ end+ end+ end++ def anthropic_cache_headers+ caching_mode = llm_model.lookup_custom_param("prompt_caching") || "never"+ return {} if caching_mode == "never"++ { "anthropic-beta" => "prompt-caching-2024-07-31" }+ end+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/completions/endpoints/aws_bedrock.rb b/plugins/discourse-ai/lib/completions/endpoints/aws_bedrock.rbindex e3c15b43c7f..b733fe40654 100644--- a/plugins/discourse-ai/lib/completions/endpoints/aws_bedrock.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/aws_bedrock.rb@@ -6,6 +6,7 @@ module DiscourseAimodule Completionsmodule Endpointsclass AwsBedrock < Base+ include AnthropicPromptCacheattr_reader :dialectdef self.can_contact?(model_provider)@@ -129,10 +130,7 @@ module DiscourseAimessages: prompt.messages,)- payload[:system] = prompt.system_prompt if prompt.system_prompt.present?-- prefilled_message = +""-+ # Handle tools firstif prompt.has_tools?payload[:tools] = prompt.toolsif dialect.tool_choice.present?@@ -140,15 +138,27 @@ module DiscourseAi# not supported on bedrock as of 2025-03-24# retest in 6 months# payload[:tool_choice] = { type: "none" }-- # prefill prompt to nudge LLM to generate a response that is useful, instead of trying to call a tool- prefilled_message << dialect.no_more_tool_calls_textelsepayload[:tool_choice] = { type: "tool", name: prompt.tool_choice }endendend+ # Apply prompt caching if enabled (only for Anthropic models)+ apply_anthropic_cache_control!(payload, prompt) if should_apply_prompt_caching?(prompt)++ # Set system prompt if not already set by caching+ payload[:system] = prompt.system_prompt if prompt.system_prompt.present? &&+ !payload[:system]++ prefilled_message = +""++ # Handle tool choice prefilling+ if dialect.tool_choice == :none && prompt.has_tools?+ # prefill prompt to nudge LLM to generate a response that is useful, instead of trying to call a tool+ prefilled_message << dialect.no_more_tool_calls_text+ end+# Prefill prompt to force JSON output.if model_params[:response_format].present?prefilled_message << " " if !prefilled_message.empty?@@ -263,6 +273,14 @@ module DiscourseAilog.request_tokens = processor.input_tokens if processor.input_tokenslog.response_tokens = processor.output_tokens if processor.output_tokenslog.raw_response_payload = @raw_response if @raw_response++ # Handle cache tokens for Anthropic models+ if dialect.is_a?(DiscourseAi::Completions::Dialects::Claude)+ log.cache_read_tokens =+ processor.cache_read_input_tokens if processor.cache_read_input_tokens+ log.cache_write_tokens =+ processor.cache_creation_input_tokens if processor.cache_creation_input_tokens+ endenddef processordiff --git a/plugins/discourse-ai/lib/completions/endpoints/gemini.rb b/plugins/discourse-ai/lib/completions/endpoints/gemini.rbindex ea7892ae7b9..97680fb29f9 100644--- a/plugins/discourse-ai/lib/completions/endpoints/gemini.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/gemini.rb@@ -60,6 +60,7 @@ module DiscourseAidef prepare_payload(prompt, model_params, dialect)@native_tool_support = dialect.native_tool_support?+ @current_batch_token = niltools = dialect.tools if @native_tool_support@@ -127,7 +128,14 @@ module DiscourseAiif response_h@has_function_call ||= response_h.dig(:functionCall).present?if @has_function_call- response_h.dig(:functionCall)+ function_call = response_h.dig(:functionCall)+ provider_data = provider_data_from_part(response_h)+ ToolCall.new(+ id: "tool_0",+ name: function_call[:name],+ parameters: function_call[:args],+ provider_data: provider_data,+ )elsif response_h[:text]response_h.dig(:text)elsif response_h[:inlineData]@@ -179,27 +187,30 @@ module DiscourseAijson = JSON.parse(chunk, symbolize_names: true)idx = -1- json- .dig(:candidates, 0, :content, :parts)- .map do |part|- if part[:functionCall]- idx += 1- ToolCall.new(- id: "tool_#{idx}",- name: part[:functionCall][:name],- parameters: part[:functionCall][:args],- )- elsif part[:inlineData]- inline_data_to_upload_markdown(part[:inlineData])+ parts = json.dig(:candidates, 0, :content, :parts)+ batch_token = current_batch_token_for(parts)++ parts&.map do |part|+ if part[:functionCall]+ idx += 1+ provider_data = provider_data_from_part(part, batch_token:)+ ToolCall.new(+ id: "tool_#{idx}",+ name: part[:functionCall][:name],+ parameters: part[:functionCall][:args],+ provider_data: provider_data,+ )+ elsif part[:inlineData]+ inline_data_to_upload_markdown(part[:inlineData])+ else+ part = part[:text]+ if part != ""+ partelse- part = part[:text]- if part != ""- part- else- nil- end+ nilendend+ endenddef decode_chunk(chunk)@@ -209,6 +220,7 @@ module DiscourseAi.map do |parsed|update_usage(parsed)parts = parsed.dig(:candidates, 0, :content, :parts)+ batch_token = current_batch_token_for(parts)parts&.map do |part|if part[:text]part = part[:text]@@ -219,10 +231,12 @@ module DiscourseAiendelsif part[:functionCall]@tool_index += 1+ provider_data = provider_data_from_part(part, batch_token:)ToolCall.new(id: "tool_#{@tool_index}",name: part[:functionCall][:name],parameters: part[:functionCall][:args],+ provider_data: provider_data,)elsif part[:inlineData]inline_data_to_upload_markdown(part[:inlineData])@@ -254,6 +268,28 @@ module DiscourseAi@decoder ||= GeminiStreamingDecoder.newend+ def provider_data_from_part(part, batch_token: nil)+ thought_signature = part[:thoughtSignature] || part[:thought_signature]+ provider_data = {}+ provider_data[:thought_signature] = thought_signature if thought_signature+ provider_data[:batch_id] = batch_token if batch_token+ provider_data+ end++ def contains_function_call?(parts)+ parts&.any? { |p| p[:functionCall].present? }+ end++ def current_batch_token_for(parts)+ if contains_function_call?(parts)+ @current_batch_token ||= SecureRandom.hex(8)+ else+ @current_batch_token = nil+ end++ @current_batch_token+ end+def extract_prompt_for_tokenizer(prompt)prompt.to_senddiff --git a/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb b/plugins/discourse-ai/lib/completions/endpoints/open_ai.rbindex e57ff201ce7..019e146d3e9 100644--- a/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb+++ b/plugins/discourse-ai/lib/completions/endpoints/open_ai.rb@@ -167,7 +167,7 @@ module DiscourseAidef final_log_update(log)log.request_tokens = processor.prompt_tokens if processor.prompt_tokenslog.response_tokens = processor.completion_tokens if processor.completion_tokens- log.cached_tokens = processor.cached_tokens if processor.cached_tokens+ log.cache_read_tokens = processor.cache_read_tokens if processor.cache_read_tokensenddef decode(response_raw)diff --git a/plugins/discourse-ai/lib/completions/llm.rb b/plugins/discourse-ai/lib/completions/llm.rbindex 7819d413d8b..f9dd52177dd 100644--- a/plugins/discourse-ai/lib/completions/llm.rb+++ b/plugins/discourse-ai/lib/completions/llm.rb@@ -31,6 +31,7 @@ module DiscourseAidisplay_name: "Claude 4.5 Sonnet",input_cost: 3,cached_input_cost: 0.30,+ cache_write_cost: 3.75,output_cost: 15,vision_enabled: true,},@@ -39,8 +40,9 @@ module DiscourseAitokens: 200_000,display_name: "Claude 4.5 Haiku",input_cost: 1,- cached_input_cost: 0.1,output_cost: 5,+ cached_input_cost: 0.1,+ cache_write_cost: 1.25,vision_enabled: true,},{@@ -49,6 +51,7 @@ module DiscourseAidisplay_name: "Claude 4.1 Opus",input_cost: 15,cached_input_cost: 1.50,+ cache_write_cost: 18.75,output_cost: 75,vision_enabled: true,},diff --git a/plugins/discourse-ai/lib/completions/open_ai_message_processor.rb b/plugins/discourse-ai/lib/completions/open_ai_message_processor.rbindex eb12353e159..bd733246129 100644--- a/plugins/discourse-ai/lib/completions/open_ai_message_processor.rb+++ b/plugins/discourse-ai/lib/completions/open_ai_message_processor.rb@@ -1,14 +1,14 @@# frozen_string_literal: truemodule DiscourseAi::Completionsclass OpenAiMessageProcessor- attr_reader :prompt_tokens, :completion_tokens, :cached_tokens+ attr_reader :prompt_tokens, :completion_tokens, :cache_read_tokensdef initialize(partial_tool_calls: false)@tool = nil@tool_arguments = +""@prompt_tokens = nil@completion_tokens = nil- @cached_tokens = nil+ @cache_read_tokens = nil@partial_tool_calls = partial_tool_callsend@@ -122,9 +122,17 @@ module DiscourseAi::Completionsenddef update_usage(json)- @prompt_tokens ||= json.dig(:usage, :prompt_tokens)- @completion_tokens ||= json.dig(:usage, :completion_tokens)- @cached_tokens ||= json.dig(:usage, :prompt_tokens_details, :cached_tokens)+ usage = json.dig(:usage)+ return if !usage++ cached_tokens = usage.dig(:prompt_tokens_details, :cached_tokens).to_i++ prompt_tokens = usage[:prompt_tokens].to_i+ completion_tokens = usage[:completion_tokens].to_i++ @prompt_tokens ||= prompt_tokens - cached_tokens+ @completion_tokens ||= completion_tokens if completion_tokens.positive?+ @cache_read_tokens ||= cached_tokensendendenddiff --git a/plugins/discourse-ai/lib/completions/open_ai_responses_message_processor.rb b/plugins/discourse-ai/lib/completions/open_ai_responses_message_processor.rbindex a0a673b34a5..a386d10d632 100644--- a/plugins/discourse-ai/lib/completions/open_ai_responses_message_processor.rb+++ b/plugins/discourse-ai/lib/completions/open_ai_responses_message_processor.rb@@ -3,14 +3,14 @@ module DiscourseAi::Completionsclass OpenAiResponsesMessageProcessorPROVIDER_KEY = :open_ai_responses- attr_reader :prompt_tokens, :completion_tokens, :cached_tokens+ attr_reader :prompt_tokens, :completion_tokens, :cache_read_tokensdef initialize(partial_tool_calls: false, output_thinking: false)@tool = nil # currently streaming ToolCall@tool_arguments = +""@prompt_tokens = nil@completion_tokens = nil- @cached_tokens = nil+ @cache_read_tokens = nil@partial_tool_calls = partial_tool_calls@streaming_parser = nil # JsonStreamingTracker, if used@has_new_data = false@@ -203,7 +203,7 @@ module DiscourseAi::Completions@prompt_tokens ||= usage[:input_tokens] - cached_tokens@completion_tokens ||= usage[:output_tokens]- @cached_tokens ||= cached_tokens+ @cache_read_tokens ||= cached_tokensenddef build_partial_reasoning_delta(json, prefix: nil)diff --git a/plugins/discourse-ai/lib/completions/prompt.rb b/plugins/discourse-ai/lib/completions/prompt.rbindex 82ec4f7c9fc..b6598f8ea31 100644--- a/plugins/discourse-ai/lib/completions/prompt.rb+++ b/plugins/discourse-ai/lib/completions/prompt.rb@@ -87,6 +87,7 @@ module DiscourseAicontent: { arguments: message.parameters }.to_json,id: message.id,name: message.name,+ provider_data: message.provider_data,)elsif message.is_a?(String)push(type: :model, content: message)@@ -103,12 +104,24 @@ module DiscourseAiendend- def push(type:, content:, id: nil, name: nil, thinking: nil, thinking_provider_info: nil)+ def push(+ type:,+ content:,+ id: nil,+ name: nil,+ thinking: nil,+ thinking_provider_info: nil,+ provider_data: nil+ )return if type == :systemnew_message = { type: type, content: content }new_message[:name] = name.to_s if namenew_message[:id] = id.to_s if idnew_message[:thinking] = thinking if thinking+ if provider_data+ raise ArgumentError, "provider_data must be a hash" unless provider_data.is_a?(Hash)+ new_message[:provider_data] = provider_data.deep_symbolize_keys+ endif thinking_provider_infonew_message[:thinking_provider_info] = Thinking.normalize_provider_info(thinking_provider_info,@@ -189,6 +202,7 @@ module DiscourseAithinking_provider_infothinking_signatureredacted_thinking_signature+ provider_data]if (invalid_keys = message.keys - valid_keys).any?raise ArgumentError, "message contains invalid keys: #{invalid_keys}"diff --git a/plugins/discourse-ai/lib/completions/prompt_messages_builder.rb b/plugins/discourse-ai/lib/completions/prompt_messages_builder.rbindex 581cc25c6b0..ffe4e48d728 100644--- a/plugins/discourse-ai/lib/completions/prompt_messages_builder.rb+++ b/plugins/discourse-ai/lib/completions/prompt_messages_builder.rb@@ -140,6 +140,8 @@ module DiscourseAithinking = message[4]custom_context[:thinking] = thinking if thinking+ provider_data = message[5]+ custom_context[:provider_data] = provider_data if provider_data.is_a?(Hash)custom_context[:created_at] = created_atbuilder.push(**custom_context)@@ -209,16 +211,29 @@ module DiscourseAiendend- def push(type:, content:, name: nil, upload_ids: nil, id: nil, thinking: nil, created_at: nil)+ def push(+ type:,+ content:,+ name: nil,+ upload_ids: nil,+ id: nil,+ thinking: nil,+ created_at: nil,+ provider_data: nil+ )if !%i[user model tool tool_call system].include?(type)raise ArgumentError, "type must be either :user, :model, :tool, :tool_call or :system"endraise ArgumentError, "upload_ids must be an array" if upload_ids && !upload_ids.is_a?(Array)+ if provider_data && !provider_data.is_a?(Hash)+ raise ArgumentError, "provider_data must be a hash"+ endcontent = [content, *upload_ids.map { |upload_id| { upload_id: upload_id } }] if upload_idsmessage = { type: type, content: content }message[:name] = name.to_s if namemessage[:id] = id.to_s if id+ message[:provider_data] = provider_data.deep_symbolize_keys if provider_data.present?if thinkingif thinking["message"] || thinking["provider_info"]message[:thinking] = thinking["message"] if thinking["message"]diff --git a/plugins/discourse-ai/lib/completions/report.rb b/plugins/discourse-ai/lib/completions/report.rbindex 46f0c573837..81c1c65ebd4 100644--- a/plugins/discourse-ai/lib/completions/report.rb+++ b/plugins/discourse-ai/lib/completions/report.rb@@ -22,8 +22,12 @@ module DiscourseAistats.total_tokens || 0end- def total_cached_tokens- stats.total_cached_tokens || 0+ def total_cache_read_tokens+ stats.total_cache_read_tokens || 0+ end++ def total_cache_write_tokens+ stats.total_cache_write_tokens || 0enddef total_request_tokens@@ -39,7 +43,9 @@ module DiscourseAienddef total_spending- total = total_input_spending + total_output_spending + total_cached_input_spending+ total =+ total_input_spending + total_output_spending + total_cache_read_spending ++ total_cache_write_spendingtotal.round(2)end@@ -53,23 +59,20 @@ module DiscourseAiendend- def total_cached_input_spending+ def total_cache_read_spending+ model_costs.sum do |row|+ row.cached_input_cost.to_f * row.total_cache_read_tokens.to_i / 1_000_000.0+ end+ end++ def total_cache_write_spendingmodel_costs.sum do |row|- row.cached_input_cost.to_f * row.total_cached_tokens.to_i / 1_000_000.0+ row.cache_write_cost.to_f * row.total_cache_write_tokens.to_i / 1_000_000.0endenddef stats- @stats ||=- base_query.select(- "COUNT(*) as total_requests",- "SUM(COALESCE(request_tokens + response_tokens, 0)) as total_tokens",- "SUM(COALESCE(cached_tokens,0)) as total_cached_tokens",- "SUM(COALESCE(request_tokens,0)) as total_request_tokens",- "SUM(COALESCE(response_tokens,0)) as total_response_tokens",- )[- 0- ]+ @stats ||= base_query.select("COUNT(*) as total_requests", *token_total_columns)[0]enddef model_costs@@ -77,16 +80,15 @@ module DiscourseAibase_query.joins("LEFT JOIN llm_models ON llm_models.name = language_model").group(- "llm_models.name, llm_models.input_cost, llm_models.output_cost, llm_models.cached_input_cost",+ "llm_models.name, llm_models.input_cost, llm_models.output_cost, llm_models.cached_input_cost, llm_models.cache_write_cost",).select("llm_models.name","llm_models.input_cost","llm_models.output_cost","llm_models.cached_input_cost",- "SUM(COALESCE(request_tokens, 0)) as total_request_tokens",- "SUM(COALESCE(response_tokens, 0)) as total_response_tokens",- "SUM(COALESCE(cached_tokens, 0)) as total_cached_tokens",+ "llm_models.cache_write_cost",+ *token_total_columns,)end@@ -109,13 +111,7 @@ module DiscourseAibase_query.group("DATE_TRUNC('#{period}', created_at)").order("DATE_TRUNC('#{period}', created_at)")- .select(- "DATE_TRUNC('#{period}', created_at) as period",- "SUM(COALESCE(request_tokens + response_tokens, 0)) as total_tokens",- "SUM(COALESCE(cached_tokens,0)) as total_cached_tokens",- "SUM(COALESCE(request_tokens,0)) as total_request_tokens",- "SUM(COALESCE(response_tokens,0)) as total_response_tokens",- )+ .select("DATE_TRUNC('#{period}', created_at) as period", *token_total_columns)# Convert periods to user's timezoneresults.map do |row|@@ -125,24 +121,18 @@ module DiscourseAienddef user_breakdown- base_query- .joins(:user)- .joins("LEFT JOIN llm_models ON llm_models.name = language_model")- .group(:user_id, "users.username", "users.uploaded_avatar_id")- .order("usage_count DESC")- .limit(USER_LIMIT)- .select(- "users.username",- "users.uploaded_avatar_id",- "COUNT(*) as usage_count",- "SUM(COALESCE(request_tokens + response_tokens, 0)) as total_tokens",- "SUM(COALESCE(cached_tokens,0)) as total_cached_tokens",- "SUM(COALESCE(request_tokens,0)) as total_request_tokens",- "SUM(COALESCE(response_tokens,0)) as total_response_tokens",- "SUM(COALESCE(request_tokens, 0) * COALESCE(llm_models.input_cost, 0)) / 1000000.0 as input_spending",- "SUM(COALESCE(response_tokens, 0) * COALESCE(llm_models.output_cost, 0)) / 1000000.0 as output_spending",- "SUM(COALESCE(cached_tokens, 0) * COALESCE(llm_models.cached_input_cost, 0)) / 1000000.0 as cached_input_spending",- )+ stats =+ base_query+ .joins("LEFT JOIN llm_models ON llm_models.name = language_model")+ .group(:user_id)+ .order("usage_count DESC")+ .limit(USER_LIMIT)+ .select(:user_id, "COUNT(*) as usage_count", *token_count_and_total_columns)++ User+ .joins("JOIN (#{stats.to_sql}) as stats ON stats.user_id = users.id")+ .select("users.*", "stats.*")+ .order("stats.usage_count DESC")enddef feature_breakdown@@ -153,13 +143,7 @@ module DiscourseAi.select("case when coalesce(feature_name, '') = '' then '#{UNKNOWN_FEATURE}' else feature_name end as feature_name","COUNT(*) as usage_count",- "SUM(COALESCE(request_tokens + response_tokens, 0)) as total_tokens",- "SUM(COALESCE(cached_tokens,0)) as total_cached_tokens",- "SUM(COALESCE(request_tokens,0)) as total_request_tokens",- "SUM(COALESCE(response_tokens,0)) as total_response_tokens",- "SUM(COALESCE(request_tokens, 0) * COALESCE(llm_models.input_cost, 0)) / 1000000.0 as input_spending",- "SUM(COALESCE(response_tokens, 0) * COALESCE(llm_models.output_cost, 0)) / 1000000.0 as output_spending",- "SUM(COALESCE(cached_tokens, 0) * COALESCE(llm_models.cached_input_cost, 0)) / 1000000.0 as cached_input_spending",+ *token_count_and_total_columns,)end@@ -171,18 +155,13 @@ module DiscourseAi"llm_models.input_cost","llm_models.output_cost","llm_models.cached_input_cost",+ "llm_models.cache_write_cost",).order("usage_count DESC").select("language_model as llm","COUNT(*) as usage_count",- "SUM(COALESCE(request_tokens + response_tokens, 0)) as total_tokens",- "SUM(COALESCE(cached_tokens,0)) as total_cached_tokens",- "SUM(COALESCE(request_tokens,0)) as total_request_tokens",- "SUM(COALESCE(response_tokens,0)) as total_response_tokens",- "SUM(COALESCE(request_tokens, 0)) * COALESCE(llm_models.input_cost, 0) / 1000000.0 as input_spending",- "SUM(COALESCE(response_tokens, 0)) * COALESCE(llm_models.output_cost, 0) / 1000000.0 as output_spending",- "SUM(COALESCE(cached_tokens, 0)) * COALESCE(llm_models.cached_input_cost, 0) / 1000000.0 as cached_input_spending",+ *token_count_and_total_columns,)end@@ -211,6 +190,26 @@ module DiscourseAi@base_query = base_query.where(language_model: model_name)selfend++ def token_total_columns+ [+ "SUM(COALESCE(request_tokens, 0) + COALESCE(response_tokens, 0) + COALESCE(cache_read_tokens, 0) + COALESCE(cache_write_tokens, 0)) as total_tokens",+ "SUM(COALESCE(cache_read_tokens, 0)) as total_cache_read_tokens",+ "SUM(COALESCE(cache_write_tokens,0)) as total_cache_write_tokens",+ "SUM(COALESCE(request_tokens,0)) as total_request_tokens",+ "SUM(COALESCE(response_tokens,0)) as total_response_tokens",+ ]+ end++ def token_count_and_total_columns+ [+ *token_total_columns,+ "SUM(COALESCE(request_tokens, 0) * COALESCE(llm_models.input_cost, 0)) / 1000000.0 as input_spending",+ "SUM(COALESCE(response_tokens, 0) * COALESCE(llm_models.output_cost, 0)) / 1000000.0 as output_spending",+ "SUM(COALESCE(cache_read_tokens, 0) * COALESCE(llm_models.cached_input_cost, 0)) / 1000000.0 as cache_read_spending",+ "SUM(COALESCE(cache_write_tokens, 0) * COALESCE(llm_models.cache_write_cost, 0)) / 1000000.0 as cache_write_spending",+ ]+ endendendenddiff --git a/plugins/discourse-ai/lib/completions/tool_call.rb b/plugins/discourse-ai/lib/completions/tool_call.rbindex c3aa047bc96..270c1a7c922 100644--- a/plugins/discourse-ai/lib/completions/tool_call.rb+++ b/plugins/discourse-ai/lib/completions/tool_call.rb@@ -3,18 +3,20 @@module DiscourseAimodule Completionsclass ToolCall- attr_reader :id, :name, :parameters+ attr_reader :id, :name, :parameters, :provider_dataattr_accessor :partialdef partial?!!@partialend- def initialize(id:, name:, parameters: nil)+ def initialize(id:, name:, parameters: nil, provider_data: nil)@id = id@name = nameself.parameters = parameters if parameters@parameters ||= {}+ self.provider_data = provider_data if provider_data+ @provider_data ||= {}@partial = falseend@@ -23,8 +25,15 @@ module DiscourseAi@parameters = parameters.symbolize_keysend+ def provider_data=(data)+ raise ArgumentError, "provider_data must be a hash" unless data.is_a?(Hash)++ @provider_data = data.deep_symbolize_keys+ end+def ==(other)- id == other.id && name == other.name && parameters == other.parameters+ id == other.id && name == other.name && parameters == other.parameters &&+ provider_data == other.provider_dataenddef to_s@@ -32,7 +41,13 @@ module DiscourseAienddef dup- call = ToolCall.new(id: id, name: name, parameters: parameters.deep_dup)+ call =+ ToolCall.new(+ id: id,+ name: name,+ parameters: parameters.deep_dup,+ provider_data: provider_data.deep_dup,+ )call.partial = partialcallenddiff --git a/plugins/discourse-ai/lib/configuration/llm_validator.rb b/plugins/discourse-ai/lib/configuration/llm_validator.rbindex ed56abea894..daa8c138bbb 100644--- a/plugins/discourse-ai/lib/configuration/llm_validator.rb+++ b/plugins/discourse-ai/lib/configuration/llm_validator.rb@@ -33,7 +33,11 @@ module DiscourseAidef run_test(val)DiscourseAi::Completions::Llm.proxy(val)- .generate("How much is 1 + 1?", user: nil, feature_name: "llm_validator")+ .generate(+ "How much is 1 + 1?",+ user: @opts[:user] || Discourse.system_user,+ feature_name: "llm_validator",+ ).present?enddiff --git a/plugins/discourse-ai/lib/personas/bot.rb b/plugins/discourse-ai/lib/personas/bot.rbindex f130d4f69c4..17c4b247c2b 100644--- a/plugins/discourse-ai/lib/personas/bot.rb+++ b/plugins/discourse-ai/lib/personas/bot.rb@@ -252,6 +252,7 @@ module DiscourseAicontent: { arguments: tool.parameters }.to_json,name: tool.name,}+ tool_call_message[:provider_data] = tool.provider_data if tool.provider_data.present?if current_thinking.present?thinking_message = nil@@ -276,11 +277,19 @@ module DiscourseAicontent: invocation_result_json,name: tool.name,}+ tool_message[:provider_data] = tool.provider_data if tool.provider_data.present?prompt.push(**tool_call_message)prompt.push(**tool_message)- raw_context << [tool_call_message[:content], tool_call_id, "tool_call", tool.name]+ raw_context << [+ tool_call_message[:content],+ tool_call_id,+ "tool_call",+ tool.name,+ nil,+ tool.provider_data.presence,+ ]raw_context << [invocation_result_json, tool_call_id, "tool", tool.name]enddiff --git a/plugins/discourse-ai/lib/personas/persona.rb b/plugins/discourse-ai/lib/personas/persona.rbindex fa71ecace2a..97664d2ba12 100644--- a/plugins/discourse-ai/lib/personas/persona.rb+++ b/plugins/discourse-ai/lib/personas/persona.rb@@ -327,6 +327,9 @@ module DiscourseAiif tool_instancetool_instance.parameters = arguments+ tool_instance.provider_data = tool_call.provider_data if tool_instance.respond_to?(+ :provider_data=,+ )tool_instanceelsetool_klass.new(@@ -336,6 +339,7 @@ module DiscourseAibot_user: bot_user,llm: llm,context: context,+ provider_data: tool_call.provider_data,)endenddiff --git a/plugins/discourse-ai/lib/personas/tools/github_file_content.rb b/plugins/discourse-ai/lib/personas/tools/github_file_content.rbindex 5072bb85b24..3360e597b6a 100644--- a/plugins/discourse-ai/lib/personas/tools/github_file_content.rb+++ b/plugins/discourse-ai/lib/personas/tools/github_file_content.rb@@ -50,11 +50,9 @@ module DiscourseAienddef description_args- {- repo_name: repo_name,- file_paths: file_paths.join(", "),- branch: branch || default_branch,- }+ paths = ""+ paths = file_paths.join(", ") if file_paths.is_a?(Array)+ { repo_name: repo_name, file_paths: paths, branch: branch || default_branch }enddef invoke@@ -64,6 +62,9 @@ module DiscourseAireturn { error: "Invalid repo_name format. Expected 'owner/repo'." }end+ return { error: "file_paths cannot be empty." } if file_paths.blank?+ return { error: "file_paths must be an array." } if !file_paths.is_a?(Array)+ref = branch || default_branchretrieved_entries = []missing_files = []diff --git a/plugins/discourse-ai/lib/personas/tools/tool.rb b/plugins/discourse-ai/lib/personas/tools/tool.rbindex da535e54262..1b44d754b9a 100644--- a/plugins/discourse-ai/lib/personas/tools/tool.rb+++ b/plugins/discourse-ai/lib/personas/tools/tool.rb@@ -48,7 +48,7 @@ module DiscourseAiend# llm being public makes it a bit easier to test- attr_accessor :custom_raw, :parameters, :llm+ attr_accessor :custom_raw, :parameters, :llm, :provider_dataattr_reader :tool_call_id, :persona_options, :bot_user, :contextdef initialize(@@ -57,7 +57,8 @@ module DiscourseAipersona_options: {},bot_user:,llm:,- context: nil+ context: nil,+ provider_data: {})@parameters = parameters@tool_call_id = tool_call_id@@ -65,6 +66,7 @@ module DiscourseAi@bot_user = bot_user@llm = llm@context = context.nil? ? DiscourseAi::Personas::BotContext.new(messages: []) : context+ @provider_data = provider_data.is_a?(Hash) ? provider_data.deep_symbolize_keys : {}if [email protected]_a?(DiscourseAi::Personas::BotContext)raise ArgumentError, "context must be a DiscourseAi::Personas::Context"end@@ -219,7 +221,7 @@ module DiscourseAiendFinalDestination::HTTP.start(uri.hostname, uri.port, use_ssl: uri.port != 80) do |http|- http.request(request) { |response| yield response }+ http.request(request) { |response| yield response, uri }endenddiff --git a/plugins/discourse-ai/lib/personas/tools/web_browser.rb b/plugins/discourse-ai/lib/personas/tools/web_browser.rbindex 15d5ed1eb94..fd5500a6547 100644--- a/plugins/discourse-ai/lib/personas/tools/web_browser.rb+++ b/plugins/discourse-ai/lib/personas/tools/web_browser.rb@@ -33,12 +33,16 @@ module DiscourseAienddef invoke- send_http_request(url, follow_redirects: true) do |response|+ send_http_request(url, follow_redirects: true) do |response, resolved_uri|if response.code == "200"html = read_response_body(response)text = extract_main_content(html)text = truncate(text, max_length: 50_000, percent_length: 0.3, llm: llm)- return { url: response.uri.to_s, text: text.strip }+ final_url =+ resolved_uri&.to_s ||+ (response.respond_to?(:uri) && response.uri ? response.uri.to_s : nil)++ return { url: final_url || url, text: text.strip }elsereturn { url: url, error: "Failed to retrieve the web page: #{response.code}" }enddiff --git a/plugins/discourse-ai/spec/lib/completions/dialects/gemini_spec.rb b/plugins/discourse-ai/spec/lib/completions/dialects/gemini_spec.rbindex 6052d0c6a6e..4e254054a51 100644--- a/plugins/discourse-ai/spec/lib/completions/dialects/gemini_spec.rb+++ b/plugins/discourse-ai/spec/lib/completions/dialects/gemini_spec.rb@@ -122,6 +122,87 @@ RSpec.describe DiscourseAi::Completions::Dialects::Gemini do)end+ it "includes thoughtSignature for tool calls when provider data is present" do+ prompt = context.prompt+ prompt.push(type: :user, id: "user1", content: "call a tool")+ prompt.push(+ type: :tool_call,+ id: "tool_id",+ name: "get_weather",+ content: { arguments: { location: "Sydney" } }.to_json,+ provider_data: {+ thought_signature: "sig-123",+ },+ )+ prompt.push(type: :tool, id: "tool_id", name: "get_weather", content: { ok: true }.to_json)++ translated = context.dialect(prompt).translate++ tool_call_parts =+ translated[:messages].find { |message| message[:role] == "model" }.fetch(:parts).first++ expect(tool_call_parts[:thoughtSignature]).to eq("sig-123")+ end++ it "merges multiple tool calls from the same batch into a single model message" do+ prompt = context.prompt+ prompt.push(type: :user, id: "user1", content: "do two things")+ prompt.push(+ type: :tool_call,+ id: "tool_id_1",+ name: "get_weather",+ content: { arguments: { city: "Paris" } }.to_json,+ provider_data: {+ batch_id: "batch-1",+ thought_signature: "sig-A",+ },+ )+ prompt.push(+ type: :tool,+ id: "tool_id_1",+ name: "get_weather",+ content: { temp: "15C" }.to_json,+ provider_data: {+ batch_id: "batch-1",+ },+ )+ prompt.push(+ type: :tool_call,+ id: "tool_id_2",+ name: "get_weather",+ content: { arguments: { city: "London" } }.to_json,+ provider_data: {+ batch_id: "batch-1",+ },+ )+ prompt.push(+ type: :tool,+ id: "tool_id_2",+ name: "get_weather",+ content: { temp: "12C" }.to_json,+ provider_data: {+ batch_id: "batch-1",+ },+ )++ translated = context.dialect(prompt).translate++ model_message = translated[:messages].find { |m| m[:role] == "model" }+ function_message = translated[:messages].find { |m| m[:role] == "function" }++ expect(model_message[:parts].length).to eq(2)+ expect(model_message[:parts].first[:thoughtSignature]).to eq("sig-A")+ expect(model_message[:parts].second[:thoughtSignature]).to be_nil++ expect(function_message[:parts].length).to eq(2)+ expect(function_message[:parts].first.dig(:functionResponse, :response, :content)).to eq(+ { temp: "15C" }.to_json,+ )+ expect(function_message[:parts].second.dig(:functionResponse, :response, :content)).to eq(+ { temp: "12C" }.to_json,+ )+ end+it "trims content if it's getting too long" do# testing truncation on 800k tokens is slow use model with lessmodel.max_prompt_tokens = 16_384diff --git a/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rb b/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rbindex c6b15482091..3f7913ab583 100644--- a/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rb+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/anthropic_spec.rb@@ -452,6 +452,203 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Anthropic doexpect(log.response_tokens).to eq(25)end+ it "handles prompt caching with always mode" do+ body = {+ id: "msg_013Zva2CMHLNnXjNJJKqJ2EF",+ type: "message",+ role: "assistant",+ content: [{ type: "text", text: "Using cached context!" }],+ model: "claude-3-opus-20240229",+ stop_reason: "end_turn",+ usage: {+ input_tokens: 6,+ cache_creation_input_tokens: 2063,+ cache_read_input_tokens: 5159,+ output_tokens: 486,+ },+ }.to_json++ model.update!(provider_params: { prompt_caching: "always" })++ parsed_body = nil+ stub_request(:post, url).with(+ body:+ proc do |req_body|+ parsed_body = JSON.parse(req_body, symbolize_names: true)+ true+ end,+ headers: {+ "Content-Type" => "application/json",+ "X-Api-Key" => "123",+ "Anthropic-Version" => "2023-06-01",+ "Anthropic-Beta" => "prompt-caching-2024-07-31",+ },+ ).to_return(status: 200, body: body)++ proxy = DiscourseAi::Completions::Llm.proxy(model)+ result = proxy.generate(prompt, user: Discourse.system_user)++ expect(result).to eq("Using cached context!")++ expect(parsed_body[:messages].last[:content]).to eq(+ [type: "text", text: "user1: hello", cache_control: { type: "ephemeral" }],+ )++ log = AiApiAuditLog.order(:id).last+ expect(log.request_tokens).to eq(6)+ expect(log.response_tokens).to eq(486)+ expect(log.cache_write_tokens).to eq(2063)+ expect(log.cache_read_tokens).to eq(5159)+ end++ it "does not include caching header when caching mode is never" do+ body = {+ id: "msg_013Zva2CMHLNnXjNJJKqJ2EF",+ type: "message",+ role: "assistant",+ content: [{ type: "text", text: "No caching!" }],+ model: "claude-3-opus-20240229",+ stop_reason: "end_turn",+ usage: {+ input_tokens: 10,+ output_tokens: 25,+ },+ }.to_json++ model.update!(provider_params: { prompt_caching: "never" })++ parsed_body = nil+ stub_request(:post, url).with(+ body:+ proc do |req_body|+ parsed_body = JSON.parse(req_body, symbolize_names: true)+ true+ end,+ headers: {+ "Content-Type" => "application/json",+ "X-Api-Key" => "123",+ "Anthropic-Version" => "2023-06-01",+ },+ ).to_return(status: 200, body: body)++ proxy = DiscourseAi::Completions::Llm.proxy(model)+ result = proxy.generate(prompt, user: Discourse.system_user)++ expect(result).to eq("No caching!")++ # Verify system prompt does not have cache_control+ expect(parsed_body[:system]).to eq("You are hello bot")+ end++ it "handles streaming with cache tokens" do+ body = (<<~STRING).strip+ event: message_start+ data: {"type": "message_start", "message": {"id": "msg_1nZdL29xx5MUA1yADyHTEsnR8uuvGzszyY", "type": "message", "role": "assistant", "content": [], "model": "claude-3-opus-20240229", "stop_reason": null, "stop_sequence": null, "usage": {"input_tokens": 25, "cache_creation_input_tokens": 100, "cache_read_input_tokens": 500, "output_tokens": 1}}}++ event: content_block_start+ data: {"type": "content_block_start", "index":0, "content_block": {"type": "text", "text": ""}}++ event: content_block_delta+ data: {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Cached!"}}++ event: content_block_stop+ data: {"type": "content_block_stop", "index": 0}++ event: message_delta+ data: {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence":null, "usage":{"output_tokens": 15}}}++ event: message_stop+ data: {"type": "message_stop"}+ STRING++ model.update!(provider_params: { prompt_caching: "always" })++ stub_request(:post, url).to_return(status: 200, body: body)++ result = +""+ llm.generate(prompt, user: Discourse.system_user) { |partial| result << partial }++ expect(result).to eq("Cached!")++ log = AiApiAuditLog.order(:id).last+ expect(log.request_tokens).to eq(25)+ expect(log.response_tokens).to eq(15)+ expect(log.cache_write_tokens).to eq(100)+ expect(log.cache_read_tokens).to eq(500)+ end++ it "defaults to never mode and does not cache when mode is tool_results without tool results" do+ body = {+ id: "msg_013Zva2CMHLNnXjNJJKqJ2EF",+ type: "message",+ role: "assistant",+ content: [{ type: "text", text: "Hello!" }],+ model: "claude-3-opus-20240229",+ stop_reason: "end_turn",+ usage: {+ input_tokens: 10,+ output_tokens: 5,+ },+ }.to_json++ model.update!(provider_params: { prompt_caching: "tool_results" })++ parsed_body = nil+ stub_request(:post, url).with(+ body:+ proc do |req_body|+ parsed_body = JSON.parse(req_body, symbolize_names: true)+ true+ end,+ headers: {+ "Content-Type" => "application/json",+ "X-Api-Key" => "123",+ "Anthropic-Version" => "2023-06-01",+ "Anthropic-Beta" => "prompt-caching-2024-07-31",+ },+ ).to_return(status: 200, body: body)++ proxy = DiscourseAi::Completions::Llm.proxy(model)+ result = proxy.generate(prompt, user: Discourse.system_user)++ expect(result).to eq("Hello!")++ # Verify system prompt does not have cache_control when no tool results+ expect(parsed_body[:system]).to eq("You are hello bot")+ end++ it "detects tool results correctly in tool_results caching mode" do+ model.update!(provider_params: { prompt_caching: "tool_results" })++ test_endpoint = described_class.new(model)++ # Create a mock prompt with tool results in messages (simulating what dialect produces)+ mock_prompt = instance_double(DiscourseAi::Completions::Prompt)+ allow(mock_prompt).to receive(:messages).and_return(+ [+ { role: "user", content: "use the echo tool" },+ {+ role: "assistant",+ content: [{ type: "tool_use", id: "tool_1", name: "echo", input: { text: "hello" } }],+ },+ {+ role: "user",+ content: [{ type: "tool_result", tool_use_id: "tool_1", content: "hello" }],+ },+ ],+ )++ # Test that should_apply_prompt_caching? returns true when tool results are present+ expect(test_endpoint.send(:should_apply_prompt_caching?, mock_prompt)).to be(true)++ # Test that it returns false when no tool results+ mock_prompt_no_tools = instance_double(DiscourseAi::Completions::Prompt)+ allow(mock_prompt_no_tools).to receive(:messages).and_return(+ [{ role: "user", content: "hello" }],+ )+ expect(test_endpoint.send(:should_apply_prompt_caching?, mock_prompt_no_tools)).to be(false)+ end+it "can send through thinking tokens via a completion prompt" dobody = {id: "msg_1nZdL29xx5MUA1yADyHTEsnR8uuvGzszyY",diff --git a/plugins/discourse-ai/spec/lib/completions/endpoints/aws_bedrock_spec.rb b/plugins/discourse-ai/spec/lib/completions/endpoints/aws_bedrock_spec.rbindex 0212fe23afb..b7e581b807a 100644--- a/plugins/discourse-ai/spec/lib/completions/endpoints/aws_bedrock_spec.rb+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/aws_bedrock_spec.rb@@ -1016,4 +1016,115 @@ RSpec.describe DiscourseAi::Completions::Endpoints::AwsBedrock doendendend++ describe "prompt caching for Anthropic models" do+ it "applies caching in always mode for Claude models" do+ params = model.provider_params || {}+ params["prompt_caching"] = "always"+ model.update!(provider_params: params)++ messages =+ [+ {+ type: "message_start",+ message: {+ usage: {+ input_tokens: 10,+ cache_creation_input_tokens: 100,+ cache_read_input_tokens: 50,+ },+ },+ },+ { type: "content_block_delta", delta: { text: "Cached response" } },+ { type: "message_delta", delta: { usage: { output_tokens: 5 } } },+ ].map { |message| encode_message(message) }++ request = nil+ bedrock_mock.with_chunk_array_support do+ stub_request(+ :post,+ "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-3-sonnet-20240229-v1:0/invoke-with-response-stream",+ )+ .with do |inner_request|+ request = inner_request+ true+ end+ .to_return(status: 200, body: messages)++ prompt =+ DiscourseAi::Completions::Prompt.new(+ "You are a bot",+ messages: [{ type: :user, content: "hello" }],+ )++ result = +""+ endpoint.perform_completion!(+ DiscourseAi::Completions::Dialects::Claude.new(prompt, model),+ user,+ ) { |partial| result << partial }++ expect(result).to eq("Cached response")++ parsed_body = JSON.parse(request.body, symbolize_names: true)+ expect(parsed_body[:messages].last[:content].last[:cache_control]).to eq(+ { type: "ephemeral" },+ )++ log = AiApiAuditLog.order(:id).last+ expect(log.cache_read_tokens).to eq(50)+ expect(log.cache_write_tokens).to eq(100)+ end+ end++ it "does not apply caching in never mode" do+ params = model.provider_params || {}+ params["prompt_caching"] = "never"+ model.update!(provider_params: params)++ messages =+ [+ { type: "message_start", message: { usage: { input_tokens: 10 } } },+ { type: "content_block_delta", delta: { text: "No cache" } },+ { type: "message_delta", delta: { usage: { output_tokens: 5 } } },+ ].map { |message| encode_message(message) }++ request = nil+ bedrock_mock.with_chunk_array_support do+ stub_request(+ :post,+ "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-3-sonnet-20240229-v1:0/invoke-with-response-stream",+ )+ .with do |inner_request|+ request = inner_request+ true+ end+ .to_return(status: 200, body: messages)++ prompt =+ DiscourseAi::Completions::Prompt.new(+ "You are a bot",+ messages: [{ type: :user, content: "hello" }],+ )++ result = +""+ endpoint.perform_completion!(+ DiscourseAi::Completions::Dialects::Claude.new(prompt, model),+ user,+ ) { |partial| result << partial }++ expect(result).to eq("No cache")++ # Verify cache_control was NOT added+ parsed_body = JSON.parse(request.body, symbolize_names: true)+ expect(parsed_body[:system]).to eq("You are a bot")+ end+ end++ it "does not apply caching to non-Claude models on Bedrock" do+ # Caching should only work for Anthropic Claude models, not other Bedrock models+ # This test would need a Nova model setup to be fully tested+ # For now, we verify the logic is only applied in Claude dialect branch+ expect(endpoint.respond_to?(:should_apply_prompt_caching?)).to be(true)+ end+ endenddiff --git a/plugins/discourse-ai/spec/lib/completions/endpoints/gemini_spec.rb b/plugins/discourse-ai/spec/lib/completions/endpoints/gemini_spec.rbindex a70e2bc3043..3ee29fe51b9 100644--- a/plugins/discourse-ai/spec/lib/completions/endpoints/gemini_spec.rb+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/gemini_spec.rb@@ -309,16 +309,79 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Gemini doresponse = llm.generate(prompt, user: user)- tool =- DiscourseAi::Completions::ToolCall.new(- id: "tool_0",+ expect(response).to be_a(DiscourseAi::Completions::ToolCall)+ expect(response.parameters[:text]).to eq("<S>ydney")+ expect(response.provider_data[:batch_id]).to match(/\A[0-9a-f]{16}\z/)+ end++ it "returns tool calls with thought signatures in provider data" do+ prompt = DiscourseAi::Completions::Prompt.new("Hello", tools: [echo_tool])++ llm = DiscourseAi::Completions::Llm.proxy(model)+ url = "#{model.url}:generateContent?key=123"++ response_json = {+ "functionCall" => {name: "echo",- parameters: {- text: "<S>ydney",+ args: {+ text: "Sydney",},- )+ },+ "thoughtSignature" => "abc123",+ }+ response = gemini_mock.response(response_json, tool_call: true).to_json++ stub_request(:post, url).to_return(status: 200, body: response)++ result = llm.generate(prompt, user: user)++ expect(result).to be_a(DiscourseAi::Completions::ToolCall)+ expect(result.provider_data[:thought_signature]).to eq("abc123")+ end++ it "returns batch-aware tool calls when multiple are emitted in one message" do+ prompt = DiscourseAi::Completions::Prompt.new("Hello", tools: [echo_tool])- expect(response).to eq(tool)+ llm = DiscourseAi::Completions::Llm.proxy(model)+ url = "#{model.url}:generateContent?key=123"++ batch_response = {+ candidates: [+ {+ content: {+ parts: [+ {+ functionCall: {+ name: "get_weather",+ args: {+ city: "Paris",+ },+ },+ thoughtSignature: "Signature_A",+ },+ { functionCall: { name: "get_weather", args: { city: "London" } } },+ ],+ role: "model",+ },+ finishReason: "STOP",+ index: 0,+ },+ ],+ }++ stub_request(:post, url).to_return(status: 200, body: batch_response.to_json)++ results = llm.generate(prompt, user: user)++ expect(results).to be_an(Array)+ expect(results.size).to eq(2)++ batch_ids = results.map { |r| r.provider_data[:batch_id] }.uniq+ expect(batch_ids.length).to eq(1)+ expect(batch_ids.first).to match(/\A[0-9a-f]{16}\z/)++ expect(results.first.provider_data[:thought_signature]).to eq("Signature_A")+ expect(results.second.provider_data[:thought_signature]).to be_nilendit "Supports Vision API" do@@ -429,8 +492,12 @@ RSpec.describe DiscourseAi::Completions::Endpoints::Gemini doparameters: {text: "sam<>wh!s",},+ provider_data: {+ batch_id: output.first.provider_data[:batch_id],+ },)+ expect(output.first.provider_data[:batch_id]).to match(/\A[0-9a-f]{16}\z/)expect(output).to eq([tool_call])log = AiApiAuditLog.order(:id).lastdiff --git a/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_responses_api_spec.rb b/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_responses_api_spec.rbindex 5fc08561bea..9f90c1a58fb 100644--- a/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_responses_api_spec.rb+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_responses_api_spec.rb@@ -127,7 +127,7 @@ data: {"type":"response.reasoning_summary_part.added","sequence_number":3,"item_expect(log).to be_presentexpect(log.request_tokens).to eq(26)expect(log.response_tokens).to eq(7)- expect(log.cached_tokens).to eq(0)+ expect(log.cache_read_tokens).to eq(0)endit "can perform simple streaming completion" do@@ -185,7 +185,7 @@ data: {"type":"response.reasoning_summary_part.added","sequence_number":3,"item_expect(log).to be_presentexpect(log.request_tokens).to eq(30)expect(log.response_tokens).to eq(9)- expect(log.cached_tokens).to eq(5)+ expect(log.cache_read_tokens).to eq(5)endit "can properly stream tool calls" dodiff --git a/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_spec.rb b/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_spec.rbindex ba80be56940..5bff71bef02 100644--- a/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_spec.rb+++ b/plugins/discourse-ai/spec/lib/completions/endpoints/open_ai_spec.rb@@ -896,6 +896,28 @@ TEXTendend+ it "uses proper token accounting with cached tokens" do+ response = <<~TEXT.strip+ data: {"id":"chatcmpl-cached","object":"chat.completion.chunk","created":1715644203,"model":"gpt-4o-2024-05-13","choices":[],"usage":{"prompt_tokens":25,"completion_tokens":10,"total_tokens":35,"prompt_tokens_details":{"cached_tokens":5}}}|+ data: [DONE]+ TEXT++ chunks = response.split("|")+ open_ai_mock.with_chunk_array_support do+ open_ai_mock.stub_raw(chunks)++ dialect = compliance.dialect(prompt: compliance.generic_prompt)+ endpoint.perform_completion!(dialect, user) { |partial| }++ log = AiApiAuditLog.order("id desc").first++ # request_tokens should be prompt_tokens (25) - cached_tokens (5) = 20+ expect(log.request_tokens).to eq(20)+ expect(log.cache_read_tokens).to eq(5)+ expect(log.response_tokens).to eq(10)+ end+ end+it "properly handles multiple params in partial tool calls" do# this is not working and it is driving me nuts so I will use a sledghammer# text = plugin_file_from_fixtures("openai_artifact_call.txt", "bot")@@ -932,7 +954,7 @@ TEXTendaudit_log = AiApiAuditLog.order("id desc").first- expect(audit_log.cached_tokens).to eq(33)+ expect(audit_log.cache_read_tokens).to eq(33)endit "properly handles spaces in tools payload and partial tool calls" dodiff --git a/plugins/discourse-ai/spec/lib/completions/report_spec.rb b/plugins/discourse-ai/spec/lib/completions/report_spec.rbnew file mode 100644index 00000000000..5a60d9d972c--- /dev/null+++ b/plugins/discourse-ai/spec/lib/completions/report_spec.rb@@ -0,0 +1,159 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::Completions::Report do+ before { enable_current_plugin }++ fab!(:user)+ fab!(:claude_model) do+ Fabricate(+ :llm_model,+ name: "claude-3-opus",+ provider: "anthropic",+ input_cost: 15.0,+ output_cost: 75.0,+ cached_input_cost: 1.5,+ cache_write_cost: 18.75,+ )+ end++ describe "#total_spending" do+ it "calculates spending with separate cache read and write costs" do+ # Create logs with different cache patterns+ AiApiAuditLog.create!(+ provider_id: AiApiAuditLog::Provider::Anthropic,+ user_id: user.id,+ language_model: "claude-3-opus",+ 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)++ # Input: 1000 * $15 / 1M = $0.015+ # Output: 500 * $75 / 1M = $0.0375+ # Cache read: 2000 * $1.5 / 1M = $0.003+ # Cache write: 1000 * $18.75 / 1M = $0.01875+ # Total: $0.07425+ expect(report.total_spending).to eq(0.07)++ expect(report.total_input_spending).to eq(0.015)+ expect(report.total_output_spending).to eq(0.0375)+ expect(report.total_cache_read_spending).to eq(0.003)+ expect(report.total_cache_write_spending).to eq(0.01875)+ end++ it "handles logs without cache tokens" do+ AiApiAuditLog.create!(+ provider_id: AiApiAuditLog::Provider::Anthropic,+ user_id: user.id,+ language_model: "claude-3-opus",+ request_tokens: 1000,+ response_tokens: 500,+ created_at: 1.day.ago,+ )++ report = described_class.new(start_date: 2.days.ago, end_date: Time.current)++ # Input: 1000 * $15 / 1M = $0.015+ # Output: 500 * $75 / 1M = $0.0375+ # Total: $0.0525+ expect(report.total_spending).to eq(0.05)+ end+ end++ describe "#model_breakdown" do+ it "includes separate cache read and write token counts" do+ AiApiAuditLog.create!(+ provider_id: AiApiAuditLog::Provider::Anthropic,+ user_id: user.id,+ language_model: "claude-3-opus",+ 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.model_breakdown.first++ expect(breakdown.total_request_tokens).to eq(1000)+ expect(breakdown.total_response_tokens).to eq(500)+ expect(breakdown.total_cache_read_tokens).to eq(2000)+ expect(breakdown.total_cache_write_tokens).to eq(1000)+ 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+ end++ describe "#user_breakdown" do+ it "includes cache spending for users" do+ AiApiAuditLog.create!(+ provider_id: AiApiAuditLog::Provider::Anthropic,+ user_id: user.id,+ language_model: "claude-3-opus",+ 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.user_breakdown.first++ expect(breakdown.total_cache_read_tokens).to eq(2000)+ expect(breakdown.total_cache_write_tokens).to eq(1000)+ 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+ end++ describe "#feature_breakdown" do+ it "includes cache spending for features" do+ AiApiAuditLog.create!(+ provider_id: AiApiAuditLog::Provider::Anthropic,+ user_id: user.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_breakdown.first++ expect(breakdown.total_cache_read_tokens).to eq(2000)+ expect(breakdown.total_cache_write_tokens).to eq(1000)+ 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+ end++ describe "#tokens_by_period" do+ it "includes cache token counts in period breakdowns" do+ AiApiAuditLog.create!(+ provider_id: AiApiAuditLog::Provider::Anthropic,+ user_id: user.id,+ language_model: "claude-3-opus",+ 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)+ period_data = report.tokens_by_period(:day).first++ expect(period_data.total_cache_read_tokens).to eq(2000)+ expect(period_data.total_cache_write_tokens).to eq(1000)+ end+ end+enddiff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rbindex ab5aa3a43eb..bc731025138 100644--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb@@ -207,6 +207,8 @@ RSpec.describe DiscourseAi::AiBot::Playground do"666","tool_call","search",+ nil,+ nil,],["\"Custom tool result: Can you use the custom tool\"", "666", "tool", "search"],["custom tool did stuff (maybe)", "claude-2"],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.rbindex 01981a64fff..dbe24250fe7 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@@ -41,7 +41,7 @@ RSpec.describe DiscourseAi::Admin::AiUsageController dolanguage_model: llm_model.name,request_tokens: 300,response_tokens: 150,- cached_tokens: 50,+ cache_read_tokens: 50,created_at: 3.days.ago,)end@@ -66,7 +66,7 @@ RSpec.describe DiscourseAi::Admin::AiUsageController do}json = response.parsed_body- expect(json["summary"]["total_tokens"]).to eq(900) # sum of all tokens+ expect(json["summary"]["total_tokens"]).to eq(950) # sum of all tokensendit "filters by feature" do@@ -99,17 +99,58 @@ RSpec.describe DiscourseAi::Admin::AiUsageController doexpected_input_spending = llm_model.input_cost * log3.request_tokens / 1_000_000.0expected_cached_input_spending =- llm_model.cached_input_cost * log3.cached_tokens / 1_000_000.0+ llm_model.cached_input_cost * log3.cache_read_tokens / 1_000_000.0expected_output_spending = llm_model.output_cost * log3.response_tokens / 1_000_000.0expected_total_spending =expected_input_spending + expected_cached_input_spending + expected_output_spendingexpect(feature["input_spending"].to_s).to eq(expected_input_spending.to_s)expect(feature["output_spending"].to_s).to eq(expected_output_spending.to_s)- expect(feature["cached_input_spending"].to_s).to eq(expected_cached_input_spending.to_s)+ expect(feature["cache_read_spending"].to_s).to eq(expected_cached_input_spending.to_s)expect(summary["total_spending"].to_s).to eq(expected_total_spending.round(2).to_s)end+ it "includes cache_read_tokens and cache_write_tokens in response" do+ log_with_cache =+ AiApiAuditLog.create!(+ provider_id: 1,+ feature_name: "ai_bot",+ language_model: llm_model.name,+ request_tokens: 500,+ response_tokens: 250,+ cache_read_tokens: 100,+ cache_write_tokens: 200,+ created_at: 1.day.ago,+ )++ get usage_report_path++ json = response.parsed_body++ expect(json["summary"]["total_cache_read_tokens"]).to eq(150)+ expect(json["summary"]["total_cache_write_tokens"]).to eq(200)++ ai_bot_feature = json["features"].find { |f| f["feature_name"] == "ai_bot" }+ 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 }+ expect(model_data["total_cache_read_tokens"]).to eq(150)+ expect(model_data["total_cache_write_tokens"]).to eq(200)++ period_with_cache_data = json["data"].find { |d| d["total_cache_read_tokens"] > 0 }+ expect(period_with_cache_data["total_cache_read_tokens"]).to be > 0++ expected_cache_read_spending =+ llm_model.cached_input_cost *+ (log3.cache_read_tokens + log_with_cache.cache_read_tokens) / 1_000_000.0+ expected_cache_write_spending =+ llm_model.cache_write_cost * log_with_cache.cache_write_tokens / 1_000_000.0++ expect(model_data["cache_read_spending"].to_s).to eq(expected_cache_read_spending.to_s)+ expect(model_data["cache_write_spending"].to_s).to eq(expected_cache_write_spending.to_s)+ end+it "handles different period groupings" doget usage_report_path, params: { period: "hour" }expect(response.status).to eq(200)