Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Update LLM token cost estimates and cost-info locales (#2690)

Juan José Mata94d5ade9991d
diff --git a/app/models/llm_usage.rb b/app/models/llm_usage.rb
index 2a7189c5d2..03d8836391 100644
--- a/app/models/llm_usage.rb
+++ b/app/models/llm_usage.rb
@@ -10,18 +10,33 @@ class LlmUsage < ApplicationRecord
scope :recent, -> { order(created_at: :desc) }
scope :for_date_range, ->(start_date, end_date) { where(created_at: start_date..end_date) }
- # OpenAI pricing per 1M tokens (as of Oct 2025)
+ # OpenAI pricing per 1M tokens (as of July 2026)
# Source: https://platform.openai.com/docs/pricing
PRICING = {
"openai" => {
# GPT-4.1 and similar models
"gpt-4.1" => { prompt: 2.00, completion: 8.00 },
"gpt-4.1-mini" => { prompt: 0.40, completion: 1.60 },
- "gpt-4.1-nano" => { prompt: 0.40, completion: 1.60 },
+ "gpt-4.1-nano" => { prompt: 0.10, completion: 0.40 },
# 4o
"gpt-4o" => { prompt: 2.50, completion: 10.00 },
"gpt-4o-mini" => { prompt: 0.15, completion: 0.60 },
- # GPT-5 models (estimated pricing)
+ # GPT-5 models
+ "gpt-5.6-sol" => { prompt: 5.00, completion: 30.00 },
+ "gpt-5.6-terra" => { prompt: 2.50, completion: 15.00 },
+ "gpt-5.6-luna" => { prompt: 1.00, completion: 6.00 },
+ "gpt-5.5-pro" => { prompt: 30.00, completion: 180.00 },
+ "gpt-5.5" => { prompt: 5.00, completion: 30.00 },
+ "gpt-5.4" => { prompt: 2.50, completion: 15.00 },
+ "gpt-5.4-mini" => { prompt: 0.75, completion: 4.50 },
+ "gpt-5.4-nano" => { prompt: 0.20, completion: 1.25 },
+ "gpt-5.4-pro" => { prompt: 30.00, completion: 180.00 },
+ # GPT-5.2 Pro is published at 12x the GPT-5.2 Thinking rate.
+ "gpt-5.2-pro" => { prompt: 21.00, completion: 168.00 },
+ "gpt-5.2-chat-latest" => { prompt: 1.75, completion: 14.00 },
+ "gpt-5.2" => { prompt: 1.75, completion: 14.00 },
+ "gpt-5.1-chat-latest" => { prompt: 1.25, completion: 10.00 },
+ "gpt-5.1" => { prompt: 1.25, completion: 10.00 },
"gpt-5" => { prompt: 1.25, completion: 10.00 },
"gpt-5-mini" => { prompt: 0.25, completion: 2.00 },
"gpt-5-nano" => { prompt: 0.05, completion: 0.40 },
@@ -29,8 +44,9 @@ class LlmUsage < ApplicationRecord
# o1 models
"o1-mini" => { prompt: 1.10, completion: 4.40 },
"o1" => { prompt: 15.00, completion: 60.00 },
- # o3 models (estimated pricing)
+ # o-series models
"o3" => { prompt: 2.00, completion: 8.00 },
+ "o4-mini" => { prompt: 1.10, completion: 4.40 },
"o3-mini" => { prompt: 1.10, completion: 4.40 },
"o3-pro" => { prompt: 20.00, completion: 80.00 }
},
@@ -92,8 +108,10 @@ class LlmUsage < ApplicationRecord
# Try exact match first
return provider_pricing[model] if provider_pricing.key?(model)
- # Try prefix matching (e.g., "gpt-4.1-2024-08-06" matches "gpt-4.1")
- provider_pricing.each do |model_prefix, pricing|
+ # Try prefix matching longest-first so snapshot IDs for variants (e.g.,
+ # "gpt-5.4-mini-2026-03-17") do not match a broader family row
+ # ("gpt-5.4") before their specific pricing row.
+ provider_pricing.sort_by { |model_prefix, _pricing| -model_prefix.length }.each do |model_prefix, pricing|
return pricing if model.start_with?(model_prefix)
end
@@ -117,8 +135,8 @@ class LlmUsage < ApplicationRecord
# Try exact match first
return provider_name if provider_pricing.key?(model)
- # Try prefix matching
- provider_pricing.each_key do |model_prefix|
+ # Try prefix matching longest-first to mirror find_pricing.
+ provider_pricing.keys.sort_by { |model_prefix| -model_prefix.length }.each do |model_prefix|
return provider_name if model.start_with?(model_prefix)
end
end
diff --git a/config/locales/views/settings/ca.yml b/config/locales/views/settings/ca.yml
index a7db87d3ed..61f70140df 100644
--- a/config/locales/views/settings/ca.yml
+++ b/config/locales/views/settings/ca.yml
@@ -95,10 +95,7 @@ ca:
completion: completació
cost_by_model: Cost per model
cost_by_operation: Cost per operació
- cost_estimates_description: Els costos s'estimen segons els preus d'OpenAI
- de 2025. Els costos reals poden variar. El preu és per cada milió de tokens
- i varia segons el model. Els models personalitzats o amb self hosting mostraran
- "N/D" i no s'inclouen als totals de cost.
+ cost_estimates_description: 'Els costos s’estimen segons els preus publicats pels proveïdors, inclosos els preus d’OpenAI de juliol de 2026. Els costos reals poden variar. El preu és per cada milió de tokens i varia segons el model. Els models personalitzats o amb self hosting mostraran "N/A" i no s’inclouen als totals de cost.'
cost_estimates_title: Sobre les estimacions de cost
end_date: Data de fi
failed: Errades
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index a3b41ad22a..00cbd16714 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -67,7 +67,7 @@ en:
failed: "Failed"
no_usage_data: "No usage data found for the selected period"
cost_estimates_title: "About Cost Estimates"
- cost_estimates_description: "Costs are estimated based on OpenAI's pricing as of 2025. Actual costs may vary. Pricing is per 1 million tokens and varies by model. Custom or self-hosted models will show \"N/A\" and are not included in cost totals."
+ cost_estimates_description: "Costs are estimated from published provider pricing, including OpenAI pricing as of July 2026. Actual costs may vary. Pricing is per 1 million tokens and varies by model. Custom or self-hosted models will show \"N/A\" and are not included in cost totals."
ai_prompts:
show:
page_title: AI Prompts
diff --git a/config/locales/views/settings/fr.yml b/config/locales/views/settings/fr.yml
index 9695b84158..b935f04ff4 100644
--- a/config/locales/views/settings/fr.yml
+++ b/config/locales/views/settings/fr.yml
@@ -85,7 +85,7 @@ fr:
completion: achèvement
cost_by_model: Coût par modèle
cost_by_operation: Coût par opération
- cost_estimates_description: Les coûts sont estimés sur la base des tarifs d'OpenAI à partir de 2025. Les coûts réels peuvent varier. Le prix est par million de jetons et varie selon le modèle. Les modèles personnalisés ou auto-hébergés afficheront « N/A » et ne seront pas inclus dans le coût total.
+ cost_estimates_description: "Les coûts sont estimés d’après les tarifs publiés par les fournisseurs, y compris les tarifs OpenAI en vigueur en juillet 2026. Les coûts réels peuvent varier. Le prix est par million de jetons et varie selon le modèle. Les modèles personnalisés ou auto-hébergés afficheront « N/A » et ne seront pas inclus dans le coût total."
cost_estimates_title: À propos des estimations de coûts
end_date: Date de fin
failed: Échec
diff --git a/config/locales/views/settings/hu.yml b/config/locales/views/settings/hu.yml
index 583ef42a83..5c5b7777b7 100644
--- a/config/locales/views/settings/hu.yml
+++ b/config/locales/views/settings/hu.yml
@@ -31,7 +31,7 @@ hu:
failed: "Sikertelen"
no_usage_data: "Nem található használati adat a kiválasztott időszakra"
cost_estimates_title: "A költségbecslésekről"
- cost_estimates_description: "A költségek az OpenAI 2025-ös árazása alapján vannak becsülve. A tényleges költségek eltérhetnek. Az árazás millió tokenenként van megadva, és modellenként változik. Az egyéni vagy önállóan üzemeltetett modellek \"N/A\"-t mutatnak, és nem szerepelnek a költségösszesítőkben."
+ cost_estimates_description: "A költségek a szolgáltatók közzétett árazása alapján vannak becsülve, beleértve az OpenAI 2026. júliusi árait. A tényleges költségek eltérhetnek. Az árazás millió tokenenként van megadva, és modellenként változik. Az egyéni vagy önállóan üzemeltetett modellek \"N/A\"-t mutatnak, és nem szerepelnek a költségösszesítőkben."
ai_prompts:
show:
page_title: MI promptok
diff --git a/config/locales/views/settings/ru.yml b/config/locales/views/settings/ru.yml
index a70fab4922..afcb25a811 100644
--- a/config/locales/views/settings/ru.yml
+++ b/config/locales/views/settings/ru.yml
@@ -95,10 +95,7 @@ ru:
completion: завершение
cost_by_model: Стоимость по моделям
cost_by_operation: Стоимость по операциям
- cost_estimates_description: Стоимость оценивается на основе цен OpenAI на
- 2025 год. Фактические затраты могут отличаться. Цены указаны за 1 миллион
- токенов и варьируются в зависимости от модели. Пользовательские или самохостинг
- модели будут отображаться как "N/A" и не включены в общую стоимость.
+ cost_estimates_description: 'Стоимость оценивается на основе опубликованных цен поставщиков, включая цены OpenAI на июль 2026 года. Фактические затраты могут отличаться. Цены указаны за 1 миллион токенов и варьируются в зависимости от модели. Пользовательские или самохостинг-модели будут отображаться как "N/A" и не включаются в общую стоимость.'
cost_estimates_title: Оценка стоимости
end_date: Дата окончания
failed: Неудачно
diff --git a/config/locales/views/settings/vi.yml b/config/locales/views/settings/vi.yml
index a0ac7956fe..dc6fc26bf5 100644
--- a/config/locales/views/settings/vi.yml
+++ b/config/locales/views/settings/vi.yml
@@ -67,7 +67,7 @@ vi:
failed: "Thất bại"
no_usage_data: "Không tìm thấy dữ liệu sử dụng cho kỳ đã chọn"
cost_estimates_title: "Về ước tính chi phí"
- cost_estimates_description: "Chi phí được ước tính dựa trên bảng giá của OpenAI từ năm 2025. Chi phí thực tế có thể khác nhau. Giá tính trên 1 triệu token và thay đổi theo mô hình. Mô hình tùy chỉnh hoặc tự lưu trữ sẽ hiển thị \"N/A\" và không được tính vào tổng chi phí."
+ cost_estimates_description: "Chi phí được ước tính theo bảng giá công bố của nhà cung cấp, bao gồm bảng giá OpenAI tính đến tháng 7 năm 2026. Chi phí thực tế có thể khác nhau. Giá tính trên 1 triệu token và thay đổi theo mô hình. Mô hình tùy chỉnh hoặc tự lưu trữ sẽ hiển thị \"N/A\" và không được tính vào tổng chi phí."
ai_prompts:
show:
page_title: Câu lệnh AI
diff --git a/config/locales/views/settings/zh-CN.yml b/config/locales/views/settings/zh-CN.yml
index af218042f7..4ff5487bd5 100644
--- a/config/locales/views/settings/zh-CN.yml
+++ b/config/locales/views/settings/zh-CN.yml
@@ -67,7 +67,7 @@ zh-CN:
failed: 失败
no_usage_data: 所选时间段内未找到用量数据
cost_estimates_title: 关于费用预估
- cost_estimates_description: 费用根据 OpenAI 2025 年的定价估算。实际费用可能不同。定价按每 100 万 token 计算,并随模型而异。自定义或自托管模型将显示为“N/A”,且不计入总费用。
+ cost_estimates_description: "费用根据各提供商公布的定价估算,包括截至 2026 年 7 月的 OpenAI 定价。实际费用可能不同。定价按每 100 万 token 计算,并随模型而异。自定义或自托管模型将显示为“N/A”,且不计入总费用。"
ai_prompts:
show:
page_title: AI 提示词
diff --git a/test/models/llm_usage_test.rb b/test/models/llm_usage_test.rb
index 13a3af9ce5..cb6a7d3349 100644
--- a/test/models/llm_usage_test.rb
+++ b/test/models/llm_usage_test.rb
@@ -28,6 +28,47 @@ class LlmUsageTest < ActiveSupport::TestCase
)
end
+
+ test "calculate_cost uses current OpenAI pricing" do
+ gpt_54 = LlmUsage.calculate_cost(model: "gpt-5.4", prompt_tokens: 1_000_000, completion_tokens: 100_000)
+ assert_in_delta 4.0, gpt_54, 0.0001
+
+ nano = LlmUsage.calculate_cost(model: "gpt-4.1-nano", prompt_tokens: 1_000_000, completion_tokens: 1_000_000)
+ assert_in_delta 0.5, nano, 0.0001
+ end
+
+ test "calculate_cost prices snapshot model IDs with the most specific OpenAI prefix" do
+ mini = LlmUsage.calculate_cost(
+ model: "gpt-5.4-mini-2026-03-17",
+ prompt_tokens: 1_000_000,
+ completion_tokens: 100_000
+ )
+ assert_in_delta 1.2, mini, 0.0001
+
+ pro = LlmUsage.calculate_cost(
+ model: "gpt-5.4-pro-2026-03-17",
+ prompt_tokens: 100_000,
+ completion_tokens: 10_000
+ )
+ assert_in_delta 4.8, pro, 0.0001
+ end
+
+ test "calculate_cost uses reviewed OpenAI pricing for GPT-5.2 aliases and pro" do
+ chat_latest = LlmUsage.calculate_cost(
+ model: "gpt-5.2-chat-latest",
+ prompt_tokens: 1_000_000,
+ completion_tokens: 100_000
+ )
+ assert_in_delta 3.15, chat_latest, 0.0001
+
+ pro = LlmUsage.calculate_cost(
+ model: "gpt-5.2-pro",
+ prompt_tokens: 1_000_000,
+ completion_tokens: 100_000
+ )
+ assert_in_delta 37.8, pro, 0.0001
+ end
+
test "calculate_cost returns Anthropic pricing for Claude models" do
cost = LlmUsage.calculate_cost(model: "claude-sonnet-4-6", prompt_tokens: 1_000_000, completion_tokens: 100_000)