Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Support GPT-6 Sol and GPT-6.1 Sol in the native OpenAI provider (#3771)

Artem Danilov5edddc354078
diff --git a/app/models/llm_usage.rb b/app/models/llm_usage.rb
index 03d8836391..f4ff5a713e 100644
--- a/app/models/llm_usage.rb
+++ b/app/models/llm_usage.rb
@@ -10,10 +10,26 @@ 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 July 2026)
- # Source: https://platform.openai.com/docs/pricing
+ # Last complete review of every listed model, not a provider price-change date.
+ # Sources, dated changes and estimation limits: docs/hosting/ai.md#cost-considerations
+ PRICING_VERIFIED_ON = Date.new(2026, 9, 29).freeze
+
+ # Standard USD pricing per 1M tokens, excluding regional and service-tier modifiers.
+ # Source: https://developers.openai.com/api/docs/pricing
PRICING = {
"openai" => {
+ # GPT-6.1 Sol Standard pricing, September 2026.
+ # Source: https://developers.openai.com/api/docs/models/gpt-6.1-sol
+ "gpt-6.1-sol" => {
+ prompt: 2.00, completion: 10.00,
+ long_context: { threshold: 272_000, prompt: 4.00, completion: 15.00 }
+ },
+ # GPT-6 Sol Standard pricing, September 2026.
+ # Source: https://developers.openai.com/api/docs/models/gpt-6-sol
+ "gpt-6-sol" => {
+ prompt: 2.00, completion: 10.00,
+ long_context: { threshold: 272_000, prompt: 4.00, completion: 15.00 }
+ },
# 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 },
@@ -22,15 +38,38 @@ class LlmUsage < ApplicationRecord
"gpt-4o" => { prompt: 2.50, completion: 10.00 },
"gpt-4o-mini" => { prompt: 0.15, completion: 0.60 },
# 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 },
+ # Sol promotion effective 2026-08-21, available at least through 2026-11-21.
+ "gpt-5.6-sol" => {
+ prompt: 4.00, completion: 20.00,
+ long_context: { threshold: 272_000, prompt: 8.00, completion: 30.00 }
+ },
+ # Terra and Luna price reductions effective 2026-07-30.
+ "gpt-5.6-terra" => {
+ prompt: 2.00, completion: 12.00,
+ long_context: { threshold: 272_000, prompt: 4.00, completion: 18.00 }
+ },
+ "gpt-5.6-luna" => {
+ prompt: 0.20, completion: 1.20,
+ long_context: { threshold: 272_000, prompt: 0.40, completion: 1.80 }
+ },
+ "gpt-5.5-pro" => {
+ prompt: 30.00, completion: 180.00,
+ long_context: { threshold: 272_000, prompt: 60.00, completion: 270.00 }
+ },
+ "gpt-5.5" => {
+ prompt: 5.00, completion: 30.00,
+ long_context: { threshold: 272_000, prompt: 10.00, completion: 45.00 }
+ },
+ "gpt-5.4" => {
+ prompt: 2.50, completion: 15.00,
+ long_context: { threshold: 272_000, prompt: 5.00, completion: 22.50 }
+ },
"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.4-pro" => {
+ prompt: 30.00, completion: 180.00,
+ long_context: { threshold: 272_000, prompt: 60.00, completion: 270.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 },
@@ -50,15 +89,18 @@ class LlmUsage < ApplicationRecord
"o3-mini" => { prompt: 1.10, completion: 4.40 },
"o3-pro" => { prompt: 20.00, completion: 80.00 }
},
+ # Source: https://ai.google.dev/gemini-api/docs/pricing
"google" => {
- "gemini-2.5-pro" => { prompt: 1.25, completion: 10.00 },
- "gemini-2.5-flash" => { prompt: 0.3, completion: 2.50 }
+ "gemini-2.5-pro" => {
+ prompt: 1.25, completion: 10.00,
+ long_context: { threshold: 200_000, prompt: 2.50, completion: 15.00 }
+ },
+ "gemini-2.5-flash" => { prompt: 0.30, completion: 2.50 }
},
- # Anthropic pricing per 1M tokens (Claude 4.x family, as of May 2026)
- # Source: https://www.anthropic.com/pricing
+ # Source: https://platform.claude.com/docs/en/about-claude/pricing
"anthropic" => {
- "claude-opus-4-7" => { prompt: 15.00, completion: 75.00 },
- "claude-opus-4-6" => { prompt: 15.00, completion: 75.00 },
+ "claude-opus-4-7" => { prompt: 5.00, completion: 25.00 },
+ "claude-opus-4-6" => { prompt: 5.00, completion: 25.00 },
"claude-sonnet-4-6" => { prompt: 3.00, completion: 15.00 },
"claude-sonnet-4-5" => { prompt: 3.00, completion: 15.00 },
"claude-haiku-4-5" => { prompt: 1.00, completion: 5.00 }
@@ -68,7 +110,10 @@ class LlmUsage < ApplicationRecord
# Calculate cost for a model and token usage
# Provider is automatically inferred from the model using the pricing map
# Returns nil if pricing is not available for the model (e.g., custom/self-hosted providers)
- def self.calculate_cost(model:, prompt_tokens:, completion_tokens:, cache_creation_tokens: 0, cache_read_tokens: 0)
+ # @param apply_long_context_pricing [Boolean] use per-request tiers; disable for aggregate batch estimates
+ # @return [Float, nil] estimated USD cost
+ def self.calculate_cost(model:, prompt_tokens:, completion_tokens:, cache_creation_tokens: 0, cache_read_tokens: 0,
+ apply_long_context_pricing: true)
provider = infer_provider(model)
pricing = find_pricing(provider, model)
@@ -77,6 +122,11 @@ class LlmUsage < ApplicationRecord
return nil
end
+ long_context = pricing[:long_context]
+ if apply_long_context_pricing && long_context && prompt_tokens > long_context[:threshold]
+ pricing = long_context
+ end
+
# Pricing is per 1M tokens, so divide by 1_000_000
prompt_cost = (prompt_tokens * pricing[:prompt]) / 1_000_000.0
completion_cost = (completion_tokens * pricing[:completion]) / 1_000_000.0
@@ -84,8 +134,8 @@ class LlmUsage < ApplicationRecord
# Anthropic prompt-cache tokens bill relative to the input rate: cache
# writes at 1.25x, cache reads at 0.1x. These multipliers are Anthropic's;
# gate on the provider so a non-Anthropic caller that happens to pass cache
- # counts can't be priced with the wrong (e.g. OpenAI cached-input is 0.5x,
- # no write premium) rates. Without cache pricing at all, estimated_cost
+ # counts can't be priced with the wrong rates (OpenAI cache rates vary by
+ # model). Without cache pricing at all, estimated_cost
# under-reports every cached Anthropic call vs the real bill (see #1984 review).
cache_creation_cost = 0.0
cache_read_cost = 0.0
@@ -196,6 +246,8 @@ class LlmUsage < ApplicationRecord
# - ~50 tokens per category
# - ~50 tokens for completion per transaction
# Returns nil if pricing is not available for the model
+ # Aggregate estimates assume short requests produced by the batch slicer.
+ # @return [Float, nil] approximate total USD cost across categorization requests
def self.estimate_auto_categorize_cost(transaction_count:, category_count:, model: "gpt-4.1")
return 0.0 if transaction_count.zero?
@@ -213,7 +265,8 @@ class LlmUsage < ApplicationRecord
calculate_cost(
model: model,
prompt_tokens: estimated_prompt_tokens,
- completion_tokens: estimated_completion_tokens
+ completion_tokens: estimated_completion_tokens,
+ apply_long_context_pricing: false
)
end
end
diff --git a/app/models/provider/openai.rb b/app/models/provider/openai.rb
index 1d3d039f27..43411fad0b 100644
--- a/app/models/provider/openai.rb
+++ b/app/models/provider/openai.rb
@@ -7,8 +7,15 @@ class Provider::Openai < Provider
DEFAULT_MODEL = "gpt-4.1".freeze
DEFAULT_REQUEST_TIMEOUT = 60
MIN_REQUEST_TIMEOUT = 1
- SUPPORTED_MODELS = %w[gpt-4 gpt-5 o1 o3].freeze
- VISION_CAPABLE_MODEL_PREFIXES = %w[gpt-4o gpt-4-turbo gpt-4.1 gpt-5 o1 o3].freeze
+ SUPPORTED_MODELS = %w[gpt-4 gpt-5 gpt-6 o1 o3].freeze
+ VISION_CAPABLE_MODEL_PREFIXES = %w[gpt-4o gpt-4-turbo gpt-4.1 gpt-5 gpt-6 o1 o3].freeze
+ PDF_COMPLETION_LIMIT_MODEL_PREFIXES = %w[gpt-6 o1 o3].freeze
+
+ # Keep the provider's response budget and the PDF request parameter in sync.
+ # @return [Boolean] whether native PDF vision uses max_completion_tokens
+ def self.native_pdf_completion_limit?(model:, custom_provider:)
+ !custom_provider && PDF_COMPLETION_LIMIT_MODEL_PREFIXES.any? { |prefix| model.to_s.start_with?(prefix) }
+ end
# Returns the effective model that would be used by the provider.
# Priority: explicit ENV > Setting > DEFAULT_MODEL. A blank ENV value is
@@ -312,6 +319,11 @@ class Provider::Openai < Provider
VISION_CAPABLE_MODEL_PREFIXES.any? { |prefix| model.start_with?(prefix) }
end
+ # Analyze PDF bytes with the selected model and attribute usage to the family.
+ # @param pdf_content [String] PDF bytes
+ # @param model [String] optional override of the configured model
+ # @param family [Family, nil] usage attribution
+ # @return [Provider::Response] structured result or provider failure
def process_pdf(pdf_content:, model: "", family: nil)
with_provider_response do
effective_model = model.presence || @default_model
@@ -322,6 +334,14 @@ class Provider::Openai < Provider
input: { pdf_size: pdf_content&.bytesize }
)
+ # Reasoning-model completion limits include reasoning; the fallback is a budget reserve.
+ response_limit =
+ if self.class.native_pdf_completion_limit?(model: effective_model, custom_provider: custom_provider?)
+ explicit_max_response_tokens
+ else
+ max_response_tokens
+ end
+
result = PdfProcessor.new(
client,
model: effective_model,
@@ -329,7 +349,7 @@ class Provider::Openai < Provider
custom_provider: custom_provider?,
langfuse_trace: trace,
family: family,
- max_response_tokens: max_response_tokens
+ max_response_tokens: response_limit
).process
upsert_langfuse_trace(trace: trace, output: result.to_h)
diff --git a/app/models/provider/openai/pdf_processor.rb b/app/models/provider/openai/pdf_processor.rb
index 375155817b..6098ab303c 100644
--- a/app/models/provider/openai/pdf_processor.rb
+++ b/app/models/provider/openai/pdf_processor.rb
@@ -105,6 +105,8 @@ class Provider::Openai::PdfProcessor
PdfProcessingResult = Provider::LlmConcept::PdfProcessingResult
+ # Summarize extracted PDF text using the existing uncapped text request.
+ # @return [Provider::LlmConcept::PdfProcessingResult] parsed document summary
def process_with_text_extraction
effective_model = model.presence || Provider::Openai::DEFAULT_MODEL
@@ -158,6 +160,8 @@ class Provider::Openai::PdfProcessor
nil
end
+ # Summarize rendered pages using the endpoint's completion-limit contract.
+ # @return [Provider::LlmConcept::PdfProcessingResult] parsed document summary
def process_with_vision
effective_model = model.presence || Provider::Openai::DEFAULT_MODEL
@@ -187,9 +191,13 @@ class Provider::Openai::PdfProcessor
messages: [
{ role: "system", content: instructions + "\n\nIMPORTANT: Respond with valid JSON only, no markdown or other formatting." },
{ role: "user", content: content }
- ],
- max_tokens: max_response_tokens
+ ]
}
+ if Provider::Openai.native_pdf_completion_limit?(model: effective_model, custom_provider: custom_provider)
+ params[:max_completion_tokens] = max_response_tokens if max_response_tokens
+ else
+ params[:max_tokens] = max_response_tokens
+ end
response = client.chat(parameters: params)
diff --git a/app/views/settings/llm_usages/show.html.erb b/app/views/settings/llm_usages/show.html.erb
index 681aa23413..ea22258798 100644
--- a/app/views/settings/llm_usages/show.html.erb
+++ b/app/views/settings/llm_usages/show.html.erb
@@ -168,7 +168,7 @@
<div class="mt-6">
<%= render DS::Alert.new(
title: t(".cost_estimates_title"),
- message: t(".cost_estimates_description"),
+ message: t(".cost_estimates_description", date: l(LlmUsage::PRICING_VERIFIED_ON)),
variant: :info
) %>
</div>
diff --git a/config/locales/views/settings/ca.yml b/config/locales/views/settings/ca.yml
index fd32b24095..ace1e703c7 100644
--- a/config/locales/views/settings/ca.yml
+++ b/config/locales/views/settings/ca.yml
@@ -119,7 +119,7 @@ ca:
completion: resposta
cost_by_model: Cost per model
cost_by_operation: Cost per operació
- 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_description: 'Els costos s’estimen segons els preus publicats pels proveïdors, verificats per darrera vegada el %{date}. 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/de.yml b/config/locales/views/settings/de.yml
index 879adabf2d..432ca43998 100644
--- a/config/locales/views/settings/de.yml
+++ b/config/locales/views/settings/de.yml
@@ -664,7 +664,7 @@ de:
completion: Antwort
cost_by_model: Kosten nach Modell
cost_by_operation: Kosten nach Vorgang
- cost_estimates_description: Die Kosten sind aus den veröffentlichten Preisen der Anbieter geschätzt, für OpenAI mit Stand Juli 2026. Die tatsächlichen Kosten können abweichen. Die Preise gelten je 1 Million Tokens und unterscheiden sich je Modell. Eigene oder selbst gehostete Modelle zeigen „N/A“ und fließen nicht in die Gesamtkosten ein.
+ cost_estimates_description: Die Kosten werden anhand der veröffentlichten Anbieterpreise geschätzt, zuletzt geprüft am %{date}. Die tatsächlichen Kosten können abweichen. Die Preise gelten je 1 Million Tokens und unterscheiden sich je Modell. Eigene oder selbst gehostete Modelle zeigen „N/A“ und fließen nicht in die Gesamtkosten ein.
cost_estimates_title: Zur Kostenschätzung
end_date: Enddatum
failed: Fehler
diff --git a/config/locales/views/settings/en.yml b/config/locales/views/settings/en.yml
index 828454fd9c..4a6cb4d535 100644
--- a/config/locales/views/settings/en.yml
+++ b/config/locales/views/settings/en.yml
@@ -110,7 +110,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 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."
+ cost_estimates_description: "Costs are estimated from published provider pricing last verified on %{date}. 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:
prompt_field:
provider_label: Provider
diff --git a/config/locales/views/settings/es.yml b/config/locales/views/settings/es.yml
index 041457fff5..0e06b051c1 100644
--- a/config/locales/views/settings/es.yml
+++ b/config/locales/views/settings/es.yml
@@ -67,7 +67,7 @@ es:
failed: Fallida
no_usage_data: No se han encontrado datos de uso para el periodo seleccionado
cost_estimates_title: Acerca de las estimaciones de coste
- cost_estimates_description: Los costes se estiman según las tarifas de OpenAI a fecha de 2025. Los costes reales pueden variar. Las tarifas son por millón de tokens y varían según el modelo. Los modelos personalizados o autoalojados mostrarán "N/D" y no se incluyen en los totales de coste.
+ cost_estimates_description: Los costes se estiman según las tarifas publicadas por los proveedores, verificadas por última vez el %{date}. Los costes reales pueden variar. Las tarifas son por millón de tokens y varían según el modelo. Los modelos personalizados o autoalojados mostrarán "N/D" y no se incluyen en los totales de coste.
ai_prompts:
show:
page_title: Indicaciones de IA
diff --git a/config/locales/views/settings/fr.yml b/config/locales/views/settings/fr.yml
index 233865f38f..b53c783ba3 100644
--- a/config/locales/views/settings/fr.yml
+++ b/config/locales/views/settings/fr.yml
@@ -127,7 +127,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 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_description: "Les coûts sont estimés selon les tarifs publiés par les fournisseurs, vérifiés pour la dernière fois le %{date}. 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 16c9ba68d3..4052040340 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 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."
+ cost_estimates_description: "A költségek a szolgáltatók közzétett árai alapján becsültek, utoljára ellenőrizve: %{date}. 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/it.yml b/config/locales/views/settings/it.yml
index c56455b8ba..d7b4809587 100644
--- a/config/locales/views/settings/it.yml
+++ b/config/locales/views/settings/it.yml
@@ -67,7 +67,7 @@ it:
failed: "Fallita"
no_usage_data: "Nessun dato di utilizzo trovato per il periodo selezionato"
cost_estimates_title: "Informazioni sulle stime dei costi"
- cost_estimates_description: "I costi sono stimati in base ai prezzi di OpenAI del 2025. I costi effettivi possono variare. I prezzi sono per 1 milione di token e variano per modello. I modelli personalizzati o self-hosted mostreranno \"N/A\" e non sono inclusi nei totali dei costi."
+ cost_estimates_description: "I costi sono stimati in base ai prezzi pubblicati dai fornitori, verificati l’ultima volta il %{date}. I costi effettivi possono variare. I prezzi sono per 1 milione di token e variano per modello. I modelli personalizzati o self-hosted mostreranno \"N/A\" e non sono inclusi nei totali dei costi."
ai_prompts:
show:
page_title: Prompt AI
diff --git a/config/locales/views/settings/pl.yml b/config/locales/views/settings/pl.yml
index 0df8b1ddee..9b6452d7cd 100644
--- a/config/locales/views/settings/pl.yml
+++ b/config/locales/views/settings/pl.yml
@@ -176,8 +176,7 @@ pl:
completion: odpowiedź
cost_by_model: Koszt wg modelu
cost_by_operation: Koszt wg operacji
- cost_estimates_description: Koszty są szacowane na podstawie opublikowanych
- cenników dostawców, w tym cennika OpenAI z lipca 2026. Rzeczywiste koszty
+ cost_estimates_description: Koszty są szacowane na podstawie opublikowanych cenników dostawców, ostatnio zweryfikowanych %{date}. Rzeczywiste koszty
mogą się różnić. Ceny podane są za 1 milion tokenów i zależą od modelu.
Modele niestandardowe lub hostowane samodzielnie pokazują "N/D" i nie są
wliczane do sum kosztów.
diff --git a/config/locales/views/settings/pt-PT.yml b/config/locales/views/settings/pt-PT.yml
index b3fb4737b8..c11ba7d469 100644
--- a/config/locales/views/settings/pt-PT.yml
+++ b/config/locales/views/settings/pt-PT.yml
@@ -110,7 +110,7 @@ pt-PT:
failed: "Falhadas"
no_usage_data: "Não foram encontrados dados de utilização para o período selecionado"
cost_estimates_title: "Sobre as Estimativas de Custo"
- cost_estimates_description: "Os custos são estimados com base nos preços publicados dos serviços, incluindo os preços da OpenAI a partir de julho de 2026. Os custos reais podem variar. O preço é por 1 milhão de tokens e varia consoante o modelo. Os modelos personalizados ou autoalojados mostrarão \"N/A\" e não estão incluídos nos totais de custo."
+ cost_estimates_description: "Os custos são estimados com base nos preços publicados dos serviços, verificados pela última vez em %{date}. Os custos reais podem variar. O preço é por 1 milhão de tokens e varia consoante o modelo. Os modelos personalizados ou autoalojados mostrarão \"N/A\" e não estão incluídos nos totais de custo."
ai_prompts:
show:
page_title: Prompts de IA
diff --git a/config/locales/views/settings/ru.yml b/config/locales/views/settings/ru.yml
index 933c544361..2f059ca40c 100644
--- a/config/locales/views/settings/ru.yml
+++ b/config/locales/views/settings/ru.yml
@@ -119,7 +119,7 @@ ru:
completion: ответ
cost_by_model: Стоимость по моделям
cost_by_operation: Стоимость по операциям
- cost_estimates_description: 'Стоимость оценивается на основе опубликованных цен поставщиков, включая цены OpenAI на июль 2026 года. Фактические затраты могут отличаться. Цены указаны за 1 миллион токенов и варьируются в зависимости от модели. Пользовательские или самохостинг-модели будут отображаться как "N/A" и не включаются в общую стоимость.'
+ cost_estimates_description: 'Стоимость оценивается по опубликованным ценам поставщиков, проверенным %{date}. Фактические затраты могут отличаться. Цены указаны за 1 миллион токенов и варьируются в зависимости от модели. Пользовательские или самохостинг-модели будут отображаться как "N/A" и не включаются в общую стоимость.'
cost_estimates_title: Оценка стоимости
end_date: Дата окончания
failed: Неудачно
diff --git a/config/locales/views/settings/tr.yml b/config/locales/views/settings/tr.yml
index 457faca270..00f1bafeb0 100644
--- a/config/locales/views/settings/tr.yml
+++ b/config/locales/views/settings/tr.yml
@@ -117,8 +117,7 @@ tr:
completion: tamamlama
cost_by_model: Modele Göre Maliyet
cost_by_operation: İşleme Göre Maliyet
- cost_estimates_description: Maliyetler, Temmuz 2026 itibarıyla OpenAI fiyatlandırması
- dahil olmak üzere yayınlanan sağlayıcı fiyatlarına göre tahmin edilir. Gerçek
+ cost_estimates_description: Maliyetler, en son %{date} tarihinde doğrulanan yayınlanmış sağlayıcı fiyatlarına göre tahmin edilir. Gerçek
maliyetler farklılık gösterebilir. Fiyatlandırma 1 milyon token başınadır
ve modele göre değişir. Özel veya kendi sunucunuzda barındırılan modeller
"Yok" olarak gösterilir ve maliyet toplamlarına dahil edilmez.
diff --git a/config/locales/views/settings/uk.yml b/config/locales/views/settings/uk.yml
index 9f0d27578a..0bdde570a4 100644
--- a/config/locales/views/settings/uk.yml
+++ b/config/locales/views/settings/uk.yml
@@ -109,7 +109,7 @@ uk:
failed: "Не вдалося"
no_usage_data: "Даних про використання за вибраний період не знайдено"
cost_estimates_title: "Про оцінку вартості"
- cost_estimates_description: "Витрати оцінюються на основі опублікованих цін постачальників, включаючи ціни OpenAI станом на липень 2026 року. Фактичні витрати можуть відрізнятися. Ціни вказані за 1 мільйон токенів і залежать від моделі. Користувацькі або самостійно розміщені моделі показуватимуть \"Н/Д\" і не включатимуться до загальної вартості."
+ cost_estimates_description: "Витрати оцінюються на основі опублікованих цін постачальників, востаннє перевірених %{date}. Фактичні витрати можуть відрізнятися. Ціни вказані за 1 мільйон токенів і залежать від моделі. Користувацькі або самостійно розміщені моделі показуватимуть \"Н/Д\" і не включатимуться до загальної вартості."
ai_prompts:
show:
page_title: Промпти ШІ
diff --git a/config/locales/views/settings/vi.yml b/config/locales/views/settings/vi.yml
index 612751b195..dffb84152e 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 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í."
+ cost_estimates_description: "Chi phí được ước tính theo bảng giá công bố của nhà cung cấp, được xác minh lần cuối vào %{date}. 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 ef5dabeed9..9a2ae29eb4 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: "费用根据各提供商公布的定价估算,包括截至 2026 年 7 月的 OpenAI 定价。实际费用可能不同。定价按每 100 万 token 计算,并随模型而异。自定义或自托管模型将显示为“N/A”,且不计入总费用。"
+ cost_estimates_description: "费用根据各提供商公布的定价估算,最近核实日期为 %{date}。实际费用可能不同。定价按每 100 万 token 计算,并随模型而异。自定义或自托管模型将显示为“N/A”,且不计入总费用。"
ai_prompts:
show:
page_title: AI 提示词
diff --git a/config/locales/views/settings/zh-TW.yml b/config/locales/views/settings/zh-TW.yml
index f6b88a787e..384084606e 100644
--- a/config/locales/views/settings/zh-TW.yml
+++ b/config/locales/views/settings/zh-TW.yml
@@ -110,7 +110,7 @@ zh-TW:
failed: 已失敗
no_usage_data: 所選期間內查無使用資料
cost_estimates_title: 關於費用預估
- cost_estimates_description: 費用是依各供應商公布的價格預估,其中 OpenAI 的價格以 2026 年 7 月為準。實際費用可能有所不同。價格以每 100 萬個 Token 計算,並依模型而異。自訂或自行代管的模型會顯示「N/A」,且不列入費用總計。
+ cost_estimates_description: 費用依各供應商公布的價格預估,最近核實日期為 %{date}。實際費用可能有所不同。價格以每 100 萬個 Token 計算,並依模型而異。自訂或自行代管的模型會顯示「N/A」,且不列入費用總計。
ai_prompts:
show:
page_title: AI 提示詞
diff --git a/docs/hosting/ai.md b/docs/hosting/ai.md
index 959b58bb4f..5d0d056d49 100644
--- a/docs/hosting/ai.md
+++ b/docs/hosting/ai.md
@@ -124,12 +124,27 @@ OPENAI_ACCESS_TOKEN=sk-proj-...
```
**Recommended models:**
+- `gpt-6.1-sol` - Latest Sol model for complex financial analysis; assistant tools require the native Responses API
+- `gpt-6-sol` - Strong reasoning for multi-step financial analysis; use the native OpenAI provider and Responses API for reasoning with function tools
- `gpt-4.1` - Default, best balance of speed and quality
-- `gpt-5` - Latest model, highest quality (more expensive)
+- `gpt-5` - Earlier-generation reasoning model
- `gpt-4o-mini` - Cheaper, good quality
**Pricing:** See [OpenAI Pricing](https://openai.com/api/pricing/)
+GPT-6.1 Sol and GPT-6 Sol use the native Responses API for assistant tools.
+Leave the custom Base URL setting empty when connecting directly to OpenAI.
+GPT-6.1 Sol does not support tool calling in Chat Completions, or the `none`
+and `minimal` reasoning efforts. See the [model documentation](https://developers.openai.com/api/docs/models/gpt-6.1-sol).
+Native GPT-6.1 Sol, GPT-6 Sol,
+`o1`, and `o3` PDF vision requests use `max_completion_tokens`, which includes
+reasoning and visible output, when an output limit is explicitly configured.
+Set `LLM_MAX_RESPONSE_TOKENS` to a positive value to bound each such request;
+the default 512-token context reserve is not sent as a provider limit.
+Text extraction keeps its existing request behavior. Custom endpoints retain
+their existing token parameters. Increase the LLM context budget for cloud
+reasoning models; the default 2048-token context is intended for small local models.
+
### Google Gemini (via OpenRouter)
[OpenRouter](https://openrouter.ai/) provides access to many models including Gemini:
@@ -1034,16 +1049,66 @@ Good test queries that exercise different capabilities:
### Cloud Costs
-Typical costs for OpenAI (as of early 2025):
-
-- **gpt-4.1:** ~$5-15 per 1M input tokens, ~$15-60 per 1M output tokens
-- **gpt-5:** ~2-3x more expensive than gpt-4.1
-- **gpt-4o-mini:** ~$0.15 per 1M input tokens (very cheap)
+**Pricing table last updated and verified: September 29, 2026.** Every model
+listed in [`LlmUsage::PRICING`](../../app/models/llm_usage.rb) was checked against
+official sources. `PRICING_VERIFIED_ON` supplies the verification date shown on
+the LLM usage screen. This is a manual review date, not a claim that providers
+changed every price that day.
+
+Rates are USD per million tokens at the Standard tier. The source coverage is:
+
+| Models in the code | Official pricing source |
+| --- | --- |
+| GPT-6 Sol/6.1 Sol, GPT-5.6, GPT-5.5, GPT-5.4, GPT-5.2, GPT-5.1, GPT-5, GPT-4.1, GPT-4o, o1, o3, o4-mini (including listed variants) | [OpenAI pricing](https://developers.openai.com/api/docs/pricing) |
+| GPT-5.2/5.1 Chat aliases | [GPT-5.2 Chat](https://developers.openai.com/api/docs/models/gpt-5.2-chat-latest), [GPT-5.1 Chat](https://developers.openai.com/api/docs/models/gpt-5.1-chat-latest) |
+| o1-mini | [o1-mini](https://developers.openai.com/api/docs/models/o1-mini) |
+| Gemini 2.5 Pro/Flash | [Google pricing](https://ai.google.dev/gemini-api/docs/pricing) |
+| Claude Opus 4.6/4.7, Sonnet 4.5/4.6, Haiku 4.5 | [Anthropic pricing](https://platform.claude.com/docs/en/about-claude/pricing) |
+
+#### Dated pricing changes
+
+| Model | Input / output | Latest relevant published date found |
+| --- | --- | --- |
+| GPT-6.1 Sol | $2 / $10 | September 29, 2026: launch pricing |
+| GPT-6 Sol | $2 / $10 | September 22, 2026: launch pricing |
+| GPT-5.6 Sol | $4 / $20 | August 21, 2026: price reduction; promotion available at least through November 21, 2026 |
+| GPT-5.6 Terra | $2 / $12 | July 30, 2026: price reduction |
+| GPT-5.6 Luna | $0.20 / $1.20 | July 30, 2026: price reduction |
+| Claude Opus 4.7 | $5 / $25 | April 16, 2026: published launch rate; corrects Sure's erroneous $15 / $75 |
+| Claude Opus 4.6 | $5 / $25 | February 5, 2026: published base launch rate; corrects Sure's erroneous $15 / $75 |
+
+Dates above come from the [OpenAI changelog](https://developers.openai.com/api/docs/changelog)
+and the [Opus 4.7](https://www.anthropic.com/news/claude-opus-4-7) and
+[Opus 4.6](https://www.anthropic.com/news/claude-opus-4-6) announcements.
+For other listed rates, the latest price-change date was **not established**;
+their current prices were verified on September 29. Google's pricing page says
+it was last updated September 24, 2026; that is a page update, not evidence of a
+Gemini 2.5 price change.
+
+#### Context tiers and estimate limits
+
+OpenAI's listed GPT-6 Sol, GPT-6.1 Sol, GPT-5.6, GPT-5.5/Pro and GPT-5.4/Pro
+rates increase above 272,000 input tokens: input doubles and output increases
+by 50% for the entire request. GPT-5.4 mini/nano retain their flat rates.
+Gemini 2.5 Pro changes from $1.25 / $10 to $2.50 / $15 above 200,000 input
+tokens. Gemini 2.5 Flash remains $0.30 / $2.50 for text/image/video input.
+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,
+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.
+Custom endpoints may charge different rates.
+
+For comparison, GPT-4.1 is $2 input / $8 output, GPT-5 is $1.25 / $10,
+and GPT-4o mini is $0.15 / $0.60.
**Typical usage:**
- Chat message: 500-2000 tokens (input) + 100-500 tokens (output)
- Auto-categorization: 1000-3000 tokens per 25 transactions
-- Cost per chat message: $0.01-0.05 for gpt-4.1
+- Cost per chat message: about $0.0018-0.008 for GPT-4.1 at the token counts above
**Optimization tips:**
1. Use `gpt-4o-mini` for categorization
diff --git a/test/controllers/settings/llm_usages_controller_test.rb b/test/controllers/settings/llm_usages_controller_test.rb
index aaab7afcbd..c0a465a4df 100644
--- a/test/controllers/settings/llm_usages_controller_test.rb
+++ b/test/controllers/settings/llm_usages_controller_test.rb
@@ -5,6 +5,7 @@ class Settings::LlmUsagesControllerTest < ActionDispatch::IntegrationTest
sign_in users(:family_admin)
get settings_llm_usage_path
assert_response :success
+ assert_includes response.body, I18n.l(LlmUsage::PRICING_VERIFIED_ON)
end
test "non-admin member cannot view family LLM usage" do
diff --git a/test/models/llm_usage_test.rb b/test/models/llm_usage_test.rb
index cb6a7d3349..84e24ae924 100644
--- a/test/models/llm_usage_test.rb
+++ b/test/models/llm_usage_test.rb
@@ -31,12 +31,60 @@ class LlmUsageTest < ActiveSupport::TestCase
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
+ assert_in_delta 7.25, 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
+ %w[gpt-6-sol gpt-6.1-sol].each do |model|
+ test "calculate_cost estimates #{model} usage at Standard pricing" do
+ cost = LlmUsage.calculate_cost(
+ model: model,
+ prompt_tokens: 100_000,
+ completion_tokens: 10_000
+ )
+
+ assert_in_delta 0.3, cost, 0.0001
+ end
+
+ test "calculate_cost applies #{model} long-context rates to the full request" do
+ cost = LlmUsage.calculate_cost(
+ model: model, prompt_tokens: 1_000_000, completion_tokens: 100_000
+ )
+
+ assert_in_delta 5.5, cost, 0.0001
+ end
+
+ test "#{model} long-context pricing starts strictly above 272000 input tokens" do
+ at_threshold = LlmUsage.calculate_cost(
+ model: model, prompt_tokens: 272_000, completion_tokens: 100_000
+ )
+ above_threshold = LlmUsage.calculate_cost(
+ model: model, prompt_tokens: 272_001, completion_tokens: 100_000
+ )
+
+ assert_in_delta 1.544, at_threshold, 0.000001
+ assert_in_delta 2.588004, above_threshold, 0.000001
+ end
+
+ test "#{model} bulk categorization estimates do not treat aggregate tokens as one long-context request" do
+ cost = LlmUsage.estimate_auto_categorize_cost(
+ model: model, transaction_count: 10_000, category_count: 20
+ )
+
+ assert_in_delta 7.0023, cost, 0.0001
+ end
+ end
+
+ test "large requests for legacy models retain their existing pricing" do
+ cost = LlmUsage.calculate_cost(
+ model: "gpt-4.1", prompt_tokens: 1_000_000, completion_tokens: 100_000
+ )
+
+ assert_in_delta 2.8, cost, 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",
@@ -76,11 +124,60 @@ class LlmUsageTest < ActiveSupport::TestCase
assert_in_delta 4.5, cost, 0.0001
end
- test "calculate_cost uses higher pricing for Opus" do
- cost = LlmUsage.calculate_cost(model: "claude-opus-4-7", prompt_tokens: 1_000_000, completion_tokens: 0)
+ %w[claude-opus-4-6 claude-opus-4-7].each do |model|
+ test "calculate_cost uses corrected input output and cache rates for #{model}" do
+ cost = LlmUsage.calculate_cost(
+ model: model, prompt_tokens: 100_000, completion_tokens: 10_000,
+ cache_creation_tokens: 20_000, cache_read_tokens: 50_000
+ )
+
+ # $0.50 input + $0.25 output + $0.125 cache write + $0.025 cache read.
+ assert_in_delta 0.9, cost, 0.000001
+ end
+ end
+
+ {
+ "gpt-5.6-sol" => [ 6.0, 11.0 ],
+ "gpt-5.6-terra" => [ 3.2, 5.8 ],
+ "gpt-5.6-luna" => [ 0.32, 0.58 ],
+ "gpt-5.5" => [ 8.0, 14.5 ],
+ "gpt-5.5-pro" => [ 48.0, 87.0 ],
+ "gpt-5.4" => [ 4.0, 7.25 ],
+ "gpt-5.4-pro" => [ 48.0, 87.0 ],
+ "gemini-2.5-pro" => [ 2.25, 4.0 ]
+ }.each do |model, (short_cost, long_cost)|
+ test "calculate_cost uses reviewed short and long context rates for #{model}" do
+ assert_in_delta short_cost / 10, LlmUsage.calculate_cost(
+ model: model, prompt_tokens: 100_000, completion_tokens: 10_000
+ ), 0.000001
+ assert_in_delta long_cost, LlmUsage.calculate_cost(
+ model: model, prompt_tokens: 1_000_000, completion_tokens: 100_000
+ ), 0.000001
+ end
+ end
+
+ test "Gemini Pro long-context pricing starts strictly above 200000 input tokens" do
+ assert_in_delta 1.25, LlmUsage.calculate_cost(
+ model: "gemini-2.5-pro", prompt_tokens: 200_000, completion_tokens: 100_000
+ ), 0.000001
+ assert_in_delta 2.000003, LlmUsage.calculate_cost(
+ model: "gemini-2.5-pro", prompt_tokens: 200_001, completion_tokens: 100_000
+ ), 0.000001
+ end
+
+ test "GPT-5.6 long-context pricing starts strictly above 272000 input tokens" do
+ assert_in_delta 3.088, LlmUsage.calculate_cost(
+ model: "gpt-5.6-sol", prompt_tokens: 272_000, completion_tokens: 100_000
+ ), 0.000001
+ assert_in_delta 5.176008, LlmUsage.calculate_cost(
+ model: "gpt-5.6-sol", prompt_tokens: 272_001, completion_tokens: 100_000
+ ), 0.000001
+ end
- # 1M input * $15/MTok = $15.00
- assert_in_delta 15.0, cost, 0.0001
+ test "Gemini bulk categorization estimates retain short-context rates" do
+ assert_in_delta 6.251438, LlmUsage.estimate_auto_categorize_cost(
+ model: "gemini-2.5-pro", transaction_count: 10_000, category_count: 20
+ ), 0.000001
end
test "calculate_cost uses lower pricing for Haiku" do
diff --git a/test/models/provider/openai/pdf_processor_test.rb b/test/models/provider/openai/pdf_processor_test.rb
index 2afa27335a..6ba946cae7 100644
--- a/test/models/provider/openai/pdf_processor_test.rb
+++ b/test/models/provider/openai/pdf_processor_test.rb
@@ -97,6 +97,117 @@ class Provider::Openai::PdfProcessorTest < ActiveSupport::TestCase
assert_equal expected, processor.process
end
+ %w[gpt-6-sol gpt-6.1-sol].each do |model|
+ test "#{model} PDF vision uses the completion token budget" do
+ client = mock
+ client.expects(:chat).with do |request|
+ params = request[:parameters]
+ params[:model] == model &&
+ params[:max_completion_tokens] == 8192 &&
+ !params.key?(:max_tokens)
+ end.returns(
+ "choices" => [ { "message" => { "content" => {
+ document_type: "other", summary: "Synthetic PDF", extracted_data: {}
+ }.to_json } } ],
+ "usage" => { "prompt_tokens" => 10, "completion_tokens" => 20, "total_tokens" => 30 }
+ )
+ processor = Provider::Openai::PdfProcessor.new(
+ client,
+ model: model,
+ pdf_content: @pdf_content,
+ max_response_tokens: 8192,
+ processing_mode: :vision
+ )
+ processor.stubs(:convert_pdf_to_images).returns([ "synthetic-image" ])
+
+ assert_equal "Synthetic PDF", processor.process.summary
+ end
+
+ test "#{model} PDF text extraction preserves the existing uncapped request" do
+ client = mock
+ client.expects(:chat).with do |request|
+ params = request[:parameters]
+ params[:model] == model &&
+ !params.key?(:max_completion_tokens) && !params.key?(:max_tokens)
+ end.returns(
+ "choices" => [ { "message" => { "content" => {
+ document_type: "other", summary: "Synthetic text", extracted_data: {}
+ }.to_json } } ],
+ "usage" => { "prompt_tokens" => 10, "completion_tokens" => 20, "total_tokens" => 30 }
+ )
+ processor = Provider::Openai::PdfProcessor.new(
+ client,
+ model: model,
+ pdf_content: @pdf_content,
+ max_response_tokens: 8192,
+ processing_mode: :text
+ )
+ processor.stubs(:extract_text_from_pdf).returns("Synthetic statement")
+
+ assert_equal "Synthetic text", processor.process.summary
+ end
+
+ test "#{model} PDF vision omits an unconfigured completion limit" do
+ processor = vision_processor(model: model, max_response_tokens: nil)
+ expect_vision_request(processor, model: model) do |params|
+ !params.key?(:max_tokens) && !params.key?(:max_completion_tokens)
+ end
+
+ assert_equal "Synthetic PDF", processor.process.summary
+ end
+ end
+
+ test "native o-series PDF vision uses completion limits when configured" do
+ %w[o1 o3].each do |model|
+ processor = vision_processor(model: model, max_response_tokens: 8192)
+ expect_vision_request(processor, model: model) do |params|
+ params[:max_completion_tokens] == 8192 && !params.key?(:max_tokens)
+ end
+
+ assert_equal "Synthetic PDF", processor.process.summary
+ end
+ end
+
+ test "native o-series PDF vision omits unconfigured completion limits" do
+ %w[o1 o3].each do |model|
+ processor = vision_processor(model: model, max_response_tokens: nil)
+ expect_vision_request(processor, model: model) do |params|
+ !params.key?(:max_tokens) && !params.key?(:max_completion_tokens)
+ end
+
+ assert_equal "Synthetic PDF", processor.process.summary
+ end
+ end
+
+ test "legacy OpenAI PDF vision retains max_tokens" do
+ processor = vision_processor(model: "gpt-4.1", max_response_tokens: 512)
+ expect_vision_request(processor, model: "gpt-4.1") do |params|
+ params[:max_tokens] == 512 && !params.key?(:max_completion_tokens)
+ end
+
+ assert_equal "Synthetic PDF", processor.process.summary
+ end
+
+ %w[gpt-6-sol gpt-6.1-sol].each do |model|
+ test "custom provider PDF vision retains max_tokens even with a #{model} model name" do
+ processor = vision_processor(model: model, max_response_tokens: 512, custom_provider: true)
+ expect_vision_request(processor, model: model) do |params|
+ params[:max_tokens] == 512 && !params.key?(:max_completion_tokens)
+ end
+
+ assert_equal "Synthetic PDF", processor.process.summary
+ end
+ end
+
+ test "custom provider PDF vision retains max_tokens with an o-series model name" do
+ processor = vision_processor(model: "o3", max_response_tokens: 512, custom_provider: true)
+ expect_vision_request(processor, model: "o3") do |params|
+ params[:max_tokens] == 512 && !params.key?(:max_completion_tokens)
+ end
+
+ assert_equal "Synthetic PDF", processor.process.summary
+ end
+
test "convert_pdf_to_images raises a coded error when the pdftoppm binary is missing" do
processor = Provider::Openai::PdfProcessor.new(
mock,
@@ -137,6 +248,35 @@ class Provider::Openai::PdfProcessorTest < ActiveSupport::TestCase
end
private
+ # Build a vision processor with synthetic images and a mocked API client.
+ # @return [Provider::Openai::PdfProcessor] processor under test
+ def vision_processor(model:, max_response_tokens:, custom_provider: false)
+ processor = Provider::Openai::PdfProcessor.new(
+ mock,
+ model: model,
+ pdf_content: @pdf_content,
+ max_response_tokens: max_response_tokens,
+ custom_provider: custom_provider,
+ processing_mode: :vision
+ )
+ processor.stubs(:convert_pdf_to_images).returns([ "synthetic-image" ])
+ processor
+ end
+
+ # Check the emitted API payload and return a synthetic document response.
+ # @yieldparam params [Hash] outbound Chat Completions parameters
+ def expect_vision_request(processor, model:)
+ processor.client.expects(:chat).with do |request|
+ params = request[:parameters]
+ params[:model] == model && yield(params)
+ end.returns(
+ "choices" => [ { "message" => { "content" => {
+ document_type: "other", summary: "Synthetic PDF", extracted_data: {}
+ }.to_json } } ],
+ "usage" => { "prompt_tokens" => 10, "completion_tokens" => 20, "total_tokens" => 30 }
+ )
+ end
+
def build_processor(error, trace)
client = mock
client.expects(:chat).raises(error)
diff --git a/test/models/provider/openai_test.rb b/test/models/provider/openai_test.rb
index 2a28074fc7..3f367d59c5 100644
--- a/test/models/provider/openai_test.rb
+++ b/test/models/provider/openai_test.rb
@@ -8,6 +8,102 @@ class Provider::OpenaiTest < ActiveSupport::TestCase
@subject_model = "gpt-4.1"
end
+ %w[gpt-6-sol gpt-6.1-sol].each do |model|
+ test "builtin assistant resolves #{model} to the native Responses provider" do
+ with_env_overrides(
+ "OPENAI_ACCESS_TOKEN" => "test-openai-token",
+ "OPENAI_URI_BASE" => nil,
+ "OPENAI_MODEL" => model,
+ "OPENAI_SUPPORTS_RESPONSES_ENDPOINT" => nil
+ ) do
+ Setting.stubs(:openai_uri_base).returns(nil)
+ assistant = Assistant::Builtin.for_chat(chats(:two))
+ provider = assistant.get_model_provider(model)
+
+ assert_instance_of Provider::Openai, provider
+ assert provider.supports_responses_endpoint?
+ assert provider.supports_pdf_processing?(model: model)
+ end
+ end
+
+ test "#{model} PDF processing reserves only an explicitly configured output limit" do
+ with_env_overrides("LLM_MAX_RESPONSE_TOKENS" => nil) do
+ Setting.stubs(:llm_max_response_tokens).returns(nil)
+ expect_pdf_response_limit(@openai, model: model, limit: nil)
+ assert @openai.process_pdf(pdf_content: "synthetic PDF", model: model).success?
+ end
+ end
+
+ test "#{model} PDF processing honors an explicit output limit" do
+ with_env_overrides("LLM_MAX_RESPONSE_TOKENS" => "8192") do
+ expect_pdf_response_limit(@openai, model: model, limit: 8192)
+ assert @openai.process_pdf(pdf_content: "synthetic PDF", model: model).success?
+ end
+ end
+ end
+
+ test "GPT-6.1 Sol sends assistant tools through Responses with supported request parameters" do
+ with_env_overrides("OPENAI_SUPPORTS_RESPONSES_ENDPOINT" => nil) do
+ fake_responses = mock
+ fake_client = mock
+ fake_client.stubs(:responses).returns(fake_responses)
+ fake_client.expects(:chat).never
+ @openai.stubs(:client).returns(fake_client)
+
+ fake_responses.expects(:create).with do |parameters:|
+ parameters[:model] == "gpt-6.1-sol" &&
+ parameters[:tools].first[:name] == "get_net_worth" &&
+ !parameters.key?(:reasoning) && !parameters.key?(:reasoning_effort)
+ end.returns(
+ "id" => "resp_sol61", "model" => "gpt-6.1-sol",
+ "output" => [ {
+ "type" => "function_call", "id" => "fc_sol61", "call_id" => "call_sol61",
+ "name" => "get_net_worth", "arguments" => "{}"
+ } ]
+ )
+
+ response = @openai.chat_response(
+ "What is my net worth?", model: "gpt-6.1-sol",
+ functions: [ { name: "get_net_worth", params_schema: { type: "object", properties: {} } } ]
+ )
+
+ assert response.success?
+ assert_equal "get_net_worth", response.data.function_requests.first.function_name
+ end
+ end
+
+ test "native o-series PDF processing reserves only an explicitly configured output limit" do
+ with_env_overrides("LLM_MAX_RESPONSE_TOKENS" => nil) do
+ Setting.stubs(:llm_max_response_tokens).returns(nil)
+ %w[o1 o3].each do |model|
+ expect_pdf_response_limit(@openai, model: model, limit: nil)
+ assert @openai.process_pdf(pdf_content: "synthetic PDF", model: model).success?
+ end
+ end
+
+ with_env_overrides("LLM_MAX_RESPONSE_TOKENS" => "8192") do
+ %w[o1 o3].each do |model|
+ expect_pdf_response_limit(@openai, model: model, limit: 8192)
+ assert @openai.process_pdf(pdf_content: "synthetic PDF", model: model).success?
+ end
+ end
+ end
+
+ test "legacy and custom PDF processing preserve the fallback output limit" do
+ with_env_overrides("LLM_MAX_RESPONSE_TOKENS" => nil) do
+ Setting.stubs(:llm_max_response_tokens).returns(nil)
+ expect_pdf_response_limit(@openai, model: "gpt-4.1", limit: 512)
+ assert @openai.process_pdf(pdf_content: "synthetic PDF", model: "gpt-4.1").success?
+
+ custom = Provider::Openai.new("test-token", uri_base: "https://custom.example/v1", model: "gpt-6-sol")
+ expect_pdf_response_limit(custom, model: "gpt-6-sol", limit: 512)
+ assert custom.process_pdf(pdf_content: "synthetic PDF", model: "gpt-6-sol").success?
+
+ expect_pdf_response_limit(custom, model: "o3", limit: 512)
+ assert custom.process_pdf(pdf_content: "synthetic PDF", model: "o3").success?
+ end
+ end
+
test "effective_model uses Setting when ENV is unset" do
Setting.stubs(:openai_model).returns("llama3")
with_env_overrides("OPENAI_MODEL" => nil) do
@@ -488,7 +584,7 @@ class Provider::OpenaiTest < ActiveSupport::TestCase
end
test "supported_models_description returns model prefixes for standard provider" do
- expected = "models starting with: gpt-4, gpt-5, o1, o3"
+ expected = "models starting with: gpt-4, gpt-5, gpt-6, o1, o3"
assert_equal expected, @subject.supported_models_description
end
@@ -831,4 +927,20 @@ class Provider::OpenaiTest < ActiveSupport::TestCase
tool_call = messages.find { |m| m[:role] == "assistant" }[:tool_calls].first
assert_equal "{}", tool_call.dig(:function, :arguments)
end
+
+ private
+ # Verify the response budget at the provider-to-processor boundary.
+ # @param limit [Integer, nil] expected explicit cap or omitted cap
+ def expect_pdf_response_limit(provider, model:, limit:)
+ result = Provider::LlmConcept::PdfProcessingResult.new(
+ summary: "Synthetic PDF", document_type: "other", extracted_data: {}
+ )
+ processor = mock
+ processor.expects(:process).returns(result)
+ Provider::Openai::PdfProcessor.expects(:new).with do |*args|
+ params = args.last
+ params[:model] == model && params[:max_response_tokens] == limit &&
+ params[:custom_provider] == provider.custom_provider?
+ end.returns(processor)
+ end
end
diff --git a/test/system/chats_test.rb b/test/system/chats_test.rb
index 23aa48aec8..ae30e71422 100644
--- a/test/system/chats_test.rb
+++ b/test/system/chats_test.rb
@@ -66,4 +66,32 @@ class ChatsTest < ApplicationSystemTestCase
assert_text "Can you help with my finances?"
end
end
+
+ %w[gpt-6-sol gpt-6.1-sol].each do |model|
+ test "create chat with an opted-in #{model} model" do
+ with_env_overrides(
+ OPENAI_ACCESS_TOKEN: "test-token",
+ OPENAI_MODEL: model,
+ OPENAI_URI_BASE: nil,
+ ASSISTANT_TYPE: "builtin"
+ ) do
+ Setting.stubs(:openai_uri_base).returns(nil)
+ @user.update!(ai_enabled: true)
+ @user.chats.destroy_all
+
+ visit root_url
+ Chat.any_instance.expects(:ask_assistant_later).once
+
+ within "#chat-form" do
+ fill_in "chat[content]", with: "Help me understand my spending"
+ find("button[type='submit']").click
+ end
+
+ assert_text "Help me understand my spending"
+ chat = @user.chats.reload.first
+ assert_equal model, chat.messages.where(type: "UserMessage").first.ai_model
+ assert_instance_of Assistant::Builtin, Assistant.for_chat(chat)
+ end
+ end
+ end
end