Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Record OpenRouter-reported usage costs (#4549)

Hao Liu5c0285481ad1
diff --git a/app/models/provider/openai.rb b/app/models/provider/openai.rb
index 0c7211ceb4..f11e902596 100644
--- a/app/models/provider/openai.rb
+++ b/app/models/provider/openai.rb
@@ -861,10 +861,10 @@ class Provider::Openai < Provider
Rails.logger.info("Extracted tokens - prompt: #{prompt_tokens}, completion: #{completion_tokens}, total: #{total_tokens}")
- estimated_cost = LlmUsage.calculate_cost(
+ estimated_cost = UsageCost.calculate(
model: model,
- prompt_tokens: prompt_tokens,
- completion_tokens: completion_tokens
+ usage: usage,
+ uri_base: client.uri_base
)
# Log when we can't estimate the cost (e.g., custom/self-hosted models)
diff --git a/app/models/provider/openai/concerns/usage_recorder.rb b/app/models/provider/openai/concerns/usage_recorder.rb
index b6bb3afd67..9a1bad62b4 100644
--- a/app/models/provider/openai/concerns/usage_recorder.rb
+++ b/app/models/provider/openai/concerns/usage_recorder.rb
@@ -6,7 +6,6 @@ module Provider::Openai::Concerns::UsageRecorder
# Records LLM usage for a family
# Handles both old (prompt_tokens/completion_tokens) and new (input_tokens/output_tokens) API formats
# Automatically infers provider from model name
- # Returns nil if pricing is unavailable (e.g., custom/self-hosted models)
def record_usage(model_name, usage_data, operation:, metadata: {})
return unless family && usage_data
@@ -17,10 +16,10 @@ module Provider::Openai::Concerns::UsageRecorder
completion_tokens = usage_data["completion_tokens"] || usage_data["output_tokens"] || 0
total_tokens = usage_data["total_tokens"] || 0
- estimated_cost = LlmUsage.calculate_cost(
+ estimated_cost = Provider::Openai::UsageCost.calculate(
model: model_name,
- prompt_tokens: prompt_tokens,
- completion_tokens: completion_tokens
+ usage: usage_data,
+ uri_base: client.uri_base
)
# Log when we can't estimate the cost (e.g., custom/self-hosted models)
diff --git a/app/models/provider/openai/usage_cost.rb b/app/models/provider/openai/usage_cost.rb
new file mode 100644
index 0000000000..b2f0178962
--- /dev/null
+++ b/app/models/provider/openai/usage_cost.rb
@@ -0,0 +1,27 @@
+class Provider::Openai::UsageCost
+ def self.calculate(model:, usage:, uri_base:)
+ reported_cost = openrouter_cost(usage["cost"], uri_base)
+ return reported_cost unless reported_cost.nil?
+
+ LlmUsage.calculate_cost(
+ model: model,
+ prompt_tokens: usage["prompt_tokens"] || usage["input_tokens"] || 0,
+ completion_tokens: usage["completion_tokens"] || usage["output_tokens"] || 0
+ )
+ end
+
+ private_class_method def self.openrouter_cost(value, uri_base)
+ # OpenAI-compatible APIs do not share a currency contract for usage.cost.
+ # Only OpenRouter's official API reports the account charge in USD credits.
+ uri = URI.parse(uri_base.to_s)
+ return unless uri.scheme == "https" && uri.port == 443 &&
+ %w[openrouter.ai eu.openrouter.ai us.openrouter.ai].include?(uri.host&.downcase) &&
+ %w[/api/v1 /api/v1/].include?(uri.path)
+ return unless value.is_a?(Numeric)
+
+ cost = BigDecimal(value.to_s, exception: false)
+ cost if cost&.finite? && cost >= 0
+ rescue URI::InvalidURIError
+ nil
+ end
+end
diff --git a/docs/hosting/ai.md b/docs/hosting/ai.md
index 07322a2623..d3187fba81 100644
--- a/docs/hosting/ai.md
+++ b/docs/hosting/ai.md
@@ -1189,8 +1189,12 @@ and Gemini 2.5 Flash remains $0.30 / $2.50.
Claude 4.6/4.7 use standard rates throughout their context window.
Sure estimates individual requests using these tiers. Aggregate categorization
-previews assume short requests. Saved usage costs are historical estimates and
-are not recalculated by this update. Estimates exclude regional premiums,
+previews assume short requests. For [OpenRouter's official API endpoints](https://openrouter.ai/docs/cookbook/administration/usage-accounting), saved
+usage prefers a valid nonnegative provider-reported `usage.cost` in USD, including
+zero, over the token-price estimate. Other endpoints, or responses with absent or
+invalid costs, use the bundled estimates. Unknown models can therefore have a
+recorded post-call cost even when their pre-run estimate is N/A. Saved usage costs
+are not recalculated. Estimates exclude regional premiums,
alternative service tiers, tool charges and audio-specific rates. Anthropic
five-minute cache writes and reads are included when reported; OpenAI and Gemini
cache discounts and cache-write/storage charges are not currently modeled.
diff --git a/test/models/provider/openai/auto_categorizer_test.rb b/test/models/provider/openai/auto_categorizer_test.rb
index 439ff76077..ea2614e807 100644
--- a/test/models/provider/openai/auto_categorizer_test.rb
+++ b/test/models/provider/openai/auto_categorizer_test.rb
@@ -161,6 +161,27 @@ class Provider::Openai::AutoCategorizerTest < ActiveSupport::TestCase
assert_nil call_params.second[:response_format]
end
+ test "categorization records OpenRouter cost for an unknown model" do
+ client = OpenAI::Client.new(access_token: "test-token", uri_base: "https://openrouter.ai/api/v1")
+ usage = { "prompt_tokens" => 50, "completion_tokens" => 25, "total_tokens" => 75, "cost" => 0.004321 }
+ client.expects(:chat).returns(chat_response('{"categorizations":[{"transaction_id":"1","category_name":"Food"}]}').merge("usage" => usage))
+ family = families(:dylan_family)
+ subject = Provider::Openai::AutoCategorizer.new(
+ client, model: "deepseek/example-model", transactions: @transactions, user_categories: @user_categories,
+ custom_provider: true, family: family, json_mode: "none"
+ )
+
+ assert_difference -> { family.llm_usages.count }, 1 do
+ assert_equal "Food", subject.auto_categorize.first.category_name
+ end
+
+ recorded = family.llm_usages.order(:created_at).last
+ assert_equal BigDecimal("0.004321"), recorded.estimated_cost
+ assert_equal [ 50, 25, 75 ], [ recorded.prompt_tokens, recorded.completion_tokens, recorded.total_tokens ]
+ assert_equal "auto_categorize", recorded.operation
+ assert_equal 1, recorded.metadata["transaction_count"]
+ end
+
private
def categorizer(json_mode:)
diff --git a/test/models/provider/openai/usage_cost_test.rb b/test/models/provider/openai/usage_cost_test.rb
new file mode 100644
index 0000000000..031dc76e03
--- /dev/null
+++ b/test/models/provider/openai/usage_cost_test.rb
@@ -0,0 +1,62 @@
+require "test_helper"
+
+class Provider::Openai::UsageCostTest < ActiveSupport::TestCase
+ setup do
+ @usage = { "prompt_tokens" => 1000, "completion_tokens" => 100, "total_tokens" => 1100 }
+ @endpoint = "https://openrouter.ai/api/v1"
+ end
+
+ test "uses reported cost for an unknown model without looking up token prices" do
+ LlmUsage.expects(:calculate_cost).never
+
+ assert_equal BigDecimal("0.012345"), calculate({ "cost" => 0.012345 })
+ end
+
+ test "reported cost overrides a known model's token estimate" do
+ assert_equal BigDecimal("0.012345"), calculate({ "cost" => 0.012345 }, model: "gpt-4.1")
+ end
+
+ test "preserves zero" do
+ [ 0, 0.0 ].each do |cost|
+ assert_equal BigDecimal("0"), calculate({ "cost" => cost })
+ end
+ end
+
+ test "absent and invalid costs fall back to token estimates" do
+ invalid_costs = [ nil, -0.1, "-0.1", Float::NAN, Float::INFINITY, -Float::INFINITY,
+ "NaN", "Infinity", "", "0.01", "not a cost", "0.01 USD", true, false, [], {} ]
+ expected = LlmUsage.calculate_cost(model: "gpt-4.1", prompt_tokens: 1000, completion_tokens: 100)
+
+ assert_equal expected, calculate({}, model: "gpt-4.1")
+ invalid_costs.each do |cost|
+ assert_equal expected, calculate({ "cost" => cost }, model: "gpt-4.1"), cost.inspect
+ assert_nil calculate({ "cost" => cost }), cost.inspect
+ end
+ end
+
+ test "fallback accepts Responses API token names" do
+ usage = { "input_tokens" => 1000, "output_tokens" => 100, "cost" => nil }
+
+ assert_equal LlmUsage.calculate_cost(model: "gpt-4.1", prompt_tokens: 1000, completion_tokens: 100),
+ Provider::Openai::UsageCost.calculate(model: "gpt-4.1", usage: usage, uri_base: @endpoint)
+ end
+
+ test "only official OpenRouter API endpoints supply USD costs" do
+ %w[https://openrouter.ai/api/v1/ https://OPENROUTER.AI/api/v1 https://eu.openrouter.ai/api/v1 https://us.openrouter.ai/api/v1].each do |endpoint|
+ assert_equal BigDecimal("0.01"), calculate({ "cost" => 0.01 }, uri_base: endpoint)
+ end
+
+ [ nil, "https://api.openai.com/v1", "https://custom.example/v1", "http://openrouter.ai/api/v1",
+ "https://openrouter.ai.example/api/v1", "https://openrouter.ai:8443/api/v1",
+ "https://openrouter.ai/api/other", "not a URL" ].each do |endpoint|
+ assert_nil calculate({ "cost" => 0.01 }, uri_base: endpoint), endpoint.inspect
+ assert_equal LlmUsage.calculate_cost(model: "gpt-4.1", prompt_tokens: 1000, completion_tokens: 100),
+ calculate({ "cost" => 0.01 }, model: "gpt-4.1", uri_base: endpoint)
+ end
+ end
+
+ private
+ def calculate(extra_usage, model: "deepseek/example-model", uri_base: @endpoint)
+ Provider::Openai::UsageCost.calculate(model: model, usage: @usage.merge(extra_usage), uri_base: uri_base)
+ end
+end
diff --git a/test/models/provider/openai_test.rb b/test/models/provider/openai_test.rb
index a7461b6483..57a7fe69c0 100644
--- a/test/models/provider/openai_test.rb
+++ b/test/models/provider/openai_test.rb
@@ -1028,6 +1028,72 @@ class Provider::OpenaiTest < ActiveSupport::TestCase
assert_not_includes third_request.to_json, "\"round\":", "the round tag must not leak into the request"
end
+ test "OpenRouter chat records provider cost and tokens for an unknown model with a streamer" do
+ provider = Provider::Openai.new("test-token", uri_base: "https://openrouter.ai/api/v1", model: "deepseek/example-model")
+ usage = { "prompt_tokens" => 10, "completion_tokens" => 5, "total_tokens" => 15, "cost" => 0.012345 }
+ provider.send(:client).expects(:chat).returns(
+ "id" => "chatcmpl-synthetic", "choices" => [ { "message" => { "role" => "assistant", "content" => "Hello" } } ],
+ "usage" => usage
+ )
+ chunks = []
+ family = families(:dylan_family)
+
+ assert_difference -> { family.llm_usages.count }, 1 do
+ response = provider.chat_response("Hello", model: "deepseek/example-model", family: family, streamer: ->(chunk) { chunks << chunk })
+ assert response.success?
+ end
+
+ recorded = family.llm_usages.order(:created_at).last
+ assert_equal BigDecimal("0.012345"), recorded.estimated_cost
+ assert_equal [ 10, 5, 15 ], [ recorded.prompt_tokens, recorded.completion_tokens, recorded.total_tokens ]
+ assert_equal usage, chunks.last.usage
+ end
+
+ test "OpenRouter chat falls back to token estimates when reported cost is absent or invalid" do
+ provider = Provider::Openai.new("test-token", uri_base: "https://openrouter.ai/api/v1", model: "gpt-4.1")
+ family = families(:dylan_family)
+ expected = LlmUsage.calculate_cost(model: "gpt-4.1", prompt_tokens: 1000, completion_tokens: 100)
+
+ [ {}, { "cost" => -1 }, { "cost" => "NaN" }, { "cost" => "not a cost" } ].each do |extra_usage|
+ usage = { "prompt_tokens" => 1000, "completion_tokens" => 100, "total_tokens" => 1100 }.merge(extra_usage)
+ provider.send(:client).expects(:chat).returns(
+ "id" => "chatcmpl-synthetic", "choices" => [ { "message" => { "role" => "assistant", "content" => "Hello" } } ],
+ "usage" => usage
+ )
+
+ assert_difference -> { family.llm_usages.count }, 1 do
+ assert provider.chat_response("Hello", model: "gpt-4.1", family: family).success?
+ end
+
+ recorded = family.llm_usages.order(:created_at).last
+ assert_equal expected, recorded.estimated_cost
+ assert_equal [ 1000, 100, 1100 ], [ recorded.prompt_tokens, recorded.completion_tokens, recorded.total_tokens ]
+ end
+ end
+
+ test "OpenRouter Responses stream forwards reported zero cost to the ledger" do
+ provider = Provider::Openai.new("test-token", uri_base: "https://openrouter.ai/api/v1", model: "deepseek/example-model")
+ provider.stubs(:supports_responses_endpoint?).returns(true)
+ usage = { "input_tokens" => 10, "output_tokens" => 5, "total_tokens" => 15, "cost" => 0 }
+ provider.send(:client).responses.expects(:create).with do |parameters:|
+ parameters[:stream].call({
+ "type" => "response.completed",
+ "response" => { "id" => "resp-synthetic", "model" => "deepseek/example-model", "output" => [], "usage" => usage }
+ })
+ true
+ end.returns(nil)
+ family = families(:dylan_family)
+
+ assert_difference -> { family.llm_usages.count }, 1 do
+ response = provider.chat_response("Hello", model: "deepseek/example-model", family: family, streamer: ->(_) { })
+ assert response.success?
+ end
+
+ recorded = family.llm_usages.order(:created_at).last
+ assert_equal BigDecimal("0"), recorded.estimated_cost
+ assert_equal [ 10, 5, 15 ], [ recorded.prompt_tokens, recorded.completion_tokens, recorded.total_tokens ]
+ end
+
private
# Verify the response budget at the provider-to-processor boundary.
# @param limit [Integer, nil] expected explicit cap or omitted cap