The personal finance app for everyone (by everyone)
Ruby
feat(ai): support Gemini 3 models and preserve tool call thought signatures
Teju Nareddy3a391a35abb4
diff --git a/app/models/llm_usage.rb b/app/models/llm_usage.rbindex f4ff5a713e..8954262990 100644--- a/app/models/llm_usage.rb+++ b/app/models/llm_usage.rb@@ -12,7 +12,7 @@ class LlmUsage < ApplicationRecord# 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+ PRICING_VERIFIED_ON = Date.new(2026, 10, 4).freeze# Standard USD pricing per 1M tokens, excluding regional and service-tier modifiers.# Source: https://developers.openai.com/api/docs/pricing@@ -91,6 +91,25 @@ class LlmUsage < ApplicationRecord},# Source: https://ai.google.dev/gemini-api/docs/pricing"google" => {+ # Gemini 3 models+ # Flash series promotion through 2026-12-31: $0.75 / $3.75 ($1.50 / $7.50 starting 2027)+ "gemini-3.8-flash" => { prompt: 0.75, completion: 3.75 },+ "gemini-3.7-flash" => { prompt: 0.75, completion: 3.75 },+ "gemini-3.6-flash" => { prompt: 0.75, completion: 3.75 },+ "gemini-3.5-flash" => { prompt: 1.50, completion: 9.00 },+ "gemini-3.5-flash-lite" => { prompt: 0.30, completion: 2.50 },+ "gemini-3.1-flash-lite" => { prompt: 0.25, completion: 1.50 },+ "gemini-3.1-pro" => {+ prompt: 2.00, completion: 12.00,+ long_context: { threshold: 200_000, prompt: 4.00, completion: 18.00 }+ },+ "gemini-3.1-pro-preview" => {+ prompt: 2.00, completion: 12.00,+ long_context: { threshold: 200_000, prompt: 4.00, completion: 18.00 }+ },+ "gemini-3-flash" => { prompt: 0.50, completion: 3.00 },+ "gemini-3-flash-preview" => { prompt: 0.50, completion: 3.00 },+ # Gemini 2.5 models"gemini-2.5-pro" => {prompt: 1.25, completion: 10.00,long_context: { threshold: 200_000, prompt: 2.50, completion: 15.00 }@@ -179,6 +198,7 @@ class LlmUsage < ApplicationRecord# correct even when we can't compute a per-token rate (custom endpoints# bill via their own provider, not Anthropic directly).return "anthropic" if model.start_with?("anthropic.", "anthropic/")+ return "google" if model.start_with?("gemini-", "google/")# Check each provider to see if they have pricing for this modelPRICING.each do |provider_name, provider_pricing|diff --git a/app/models/provider/llm_concept.rb b/app/models/provider/llm_concept.rbindex 1caad8174f..82ec7acb81 100644--- a/app/models/provider/llm_concept.rb+++ b/app/models/provider/llm_concept.rb@@ -44,7 +44,11 @@ module Provider::LlmConceptChatMessage = Data.define(:id, :output_text)ChatStreamChunk = Data.define(:type, :data, :usage)ChatResponse = Data.define(:id, :model, :messages, :function_requests)- ChatFunctionRequest = Data.define(:id, :call_id, :function_name, :function_args)+ ChatFunctionRequest = Data.define(:id, :call_id, :function_name, :function_args, :extra_content) do+ def initialize(id:, call_id:, function_name:, function_args:, extra_content: nil)+ super+ end+ enddef chat_response(prompt,diff --git a/app/models/provider/openai.rb b/app/models/provider/openai.rbindex 43411fad0b..d4f103e5c2 100644--- a/app/models/provider/openai.rb+++ b/app/models/provider/openai.rb@@ -693,7 +693,7 @@ class Provider::Openai < Provider# follow-up payloads stay in sync for strict OpenAI-compatible endpoints.arguments_str = ToolCall::Function.serialize_arguments(fn_result[:arguments])- {+ call = {id: fn_result[:call_id],type: "function",function: {@@ -701,6 +701,8 @@ class Provider::Openai < Providerarguments: arguments_str}}+ call[:extra_content] = fn_result[:extra_content] if fn_result[:extra_content].present?+ callendpayload << {diff --git a/app/models/provider/openai/generic_chat_parser.rb b/app/models/provider/openai/generic_chat_parser.rbindex 45057af004..da8a9afd65 100644--- a/app/models/provider/openai/generic_chat_parser.rb+++ b/app/models/provider/openai/generic_chat_parser.rb@@ -53,7 +53,8 @@ class Provider::Openai::GenericChatParserid: tool_call.dig("id"),call_id: tool_call.dig("id"),function_name: tool_call.dig("function", "name"),- function_args: tool_call.dig("function", "arguments")+ function_args: tool_call.dig("function", "arguments"),+ extra_content: tool_call.dig("extra_content"))endenddiff --git a/app/models/tool_call/function.rb b/app/models/tool_call/function.rbindex 844adf7f75..756bdc8d7c 100644--- a/app/models/tool_call/function.rb+++ b/app/models/tool_call/function.rb@@ -2,6 +2,8 @@ class ToolCall::Function < ToolCallvalidates :function_name, :function_result, presence: truevalidates :function_arguments, presence: true, allow_blank: true+ attr_accessor :extra_content+class << self# Translates an "LLM Concept" provider's FunctionRequest into a ToolCall::Functiondef from_function_request(function_request, result)@@ -11,7 +13,9 @@ class ToolCall::Function < ToolCallfunction_name: function_request.function_name,function_arguments: function_request.function_args,function_result: result- )+ ).tap do |call|+ call.extra_content = function_request.extra_content if function_request.respond_to?(:extra_content)+ endend# Serializes tool-call arguments to the JSON-encoded string OpenAI requires.@@ -29,7 +33,8 @@ class ToolCall::Function < ToolCallcall_id: provider_call_id,name: function_name,arguments: function_arguments,- output: function_result+ output: function_result,+ extra_content: extra_content}end@@ -38,7 +43,7 @@ class ToolCall::Function < ToolCall# OpenAI-compatible endpoints reject an object payload with a 400.arguments = self.class.serialize_arguments(function_arguments)- {+ call = {id: provider_call_id,type: "function",function: {@@ -46,5 +51,7 @@ class ToolCall::Function < ToolCallarguments: arguments}}+ call[:extra_content] = extra_content if extra_content.present?+ callendenddiff --git a/config/locales/views/admin/system_health/en.yml b/config/locales/views/admin/system_health/en.ymlindex 1d8e8792f7..e6d318e26a 100644--- a/config/locales/views/admin/system_health/en.yml+++ b/config/locales/views/admin/system_health/en.yml@@ -158,7 +158,7 @@ en:message: Sure could not verify both the configured endpoint and model. The failure was recorded in Settings → Debug logs and Rails.logger.llm_model_not_available:title: The configured AI model is not available- message: The endpoint answered, but it did not list or serve the configured model. Pick an active model for the selected provider, then run the checks again. For Gemini through an OpenAI-compatible translation layer, use a currently supported model such as gemini-2.5-flash.+ message: The endpoint answered, but it did not list or serve the configured model. Pick an active model for the selected provider, then run the checks again. For Gemini through an OpenAI-compatible translation layer, use a currently supported model such as gemini-3.8-flash.pdf_text_extraction_failed:title: The synthetic PDF text-extraction check failedmessage: Sure could not complete the text-first path that extracts embedded PDF text locally and sends it to the configured model. No customer data was sent. The failure was recorded in Settings → Debug logs and Rails.logger.diff --git a/docs/hosting/ai.md b/docs/hosting/ai.mdindex 5d0d056d49..9e428f1aea 100644--- a/docs/hosting/ai.md+++ b/docs/hosting/ai.md@@ -145,14 +145,36 @@ Text extraction keeps its existing request behavior. Custom endpoints retaintheir existing token parameters. Increase the LLM context budget for cloudreasoning models; the default 2048-token context is intended for small local models.-### Google Gemini (via OpenRouter)+### Google Gemini++You can connect to Google Gemini either directly via Google AI Studio's OpenAI-compatible endpoint or via OpenRouter.++**Recommended Gemini models:**++- `gemini-3.8-flash` - Best all-around choice; fast, strong reasoning, and reliable tool calling for chat and finance tools+- `gemini-3.5-flash-lite` - Ultra-low cost and fast; ideal for background categorization and merchant detection+- `gemini-3.1-pro` - Best for complex financial analysis, portfolio queries, and multi-year trends+- `gemini-2.5-flash` - Previous-generation budget model; fast and dependable fallback+- `gemini-2.5-pro` - Previous-generation model for complex financial analysis++#### Direct via Google AI Studio++[Google AI Studio](https://aistudio.google.com/) provides direct API access to Gemini models with a free tier and an OpenAI-compatible endpoint:++```bash+OPENAI_ACCESS_TOKEN=your-google-ai-studio-api-key+OPENAI_URI_BASE=https://generativelanguage.googleapis.com/v1beta/openai+OPENAI_MODEL=gemini-3.8-flash+```++#### Via OpenRouter[OpenRouter](https://openrouter.ai/) provides access to many models including Gemini:```bashOPENAI_ACCESS_TOKEN=your-openrouter-api-keyOPENAI_URI_BASE=https://openrouter.ai/api/v1-OPENAI_MODEL=google/gemini-2.0-flash-exp+OPENAI_MODEL=google/gemini-3.8-flash```**Why OpenRouter?**@@ -161,10 +183,6 @@ OPENAI_MODEL=google/gemini-2.0-flash-exp- Automatic fallbacks- Usage tracking-**Recommended Gemini models via OpenRouter:**-- `google/gemini-2.5-flash` - Fast and capable-- `google/gemini-2.5-pro` - High quality, good for complex queries-### Anthropic Claude (via OpenRouter)```bash@@ -1049,7 +1067,7 @@ Good test queries that exercise different capabilities:### Cloud Costs-**Pricing table last updated and verified: September 29, 2026.** Every model+**Pricing table last updated and verified: October 4, 2026.** Every modellisted in [`LlmUsage::PRICING`](../../app/models/llm_usage.rb) was checked againstofficial sources. `PRICING_VERIFIED_ON` supplies the verification date shown onthe LLM usage screen. This is a manual review date, not a claim that providers@@ -1062,7 +1080,7 @@ Rates are USD per million tokens at the Standard tier. The source coverage is:| 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) |+| Gemini 3.8/3.7/3.6/3.5 Flash, 3.5/3.1 Flash-Lite, 3.1 Pro, 3 Flash, 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@@ -1081,9 +1099,8 @@ Dates above come from the [OpenAI changelog](https://developers.openai.com/api/dand 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.+their current prices were verified on October 4. Google's pricing page lists+launch promotional pricing for Gemini 3.8, 3.7, and 3.6 Flash through December 31, 2026.#### Context tiers and estimate limits@@ -1091,7 +1108,12 @@ OpenAI's listed GPT-6 Sol, GPT-6.1 Sol, GPT-5.6, GPT-5.5/Pro and GPT-5.4/Prorates increase above 272,000 input tokens: input doubles and output increasesby 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.+tokens. Gemini 3.1 Pro (and 3.1 Pro Preview) changes from $2.00 / $12.00 to+$4.00 / $18.00 above 200,000 input tokens. Gemini 3.8 Flash, 3.7 Flash, and+3.6 Flash are $0.75 / $3.75 through 2026 ($1.50 / $7.50 starting 2027).+Gemini 3.5 Flash is $1.50 / $9.00, Gemini 3.5 Flash-Lite is $0.30 / $2.50,+Gemini 3.1 Flash-Lite is $0.25 / $1.50, Gemini 3 Flash is $0.50 / $3.00,+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 categorizationdiff --git a/test/models/llm_usage_test.rb b/test/models/llm_usage_test.rbindex 84e24ae924..b5f631d188 100644--- a/test/models/llm_usage_test.rb+++ b/test/models/llm_usage_test.rb@@ -12,6 +12,14 @@ class LlmUsageTest < ActiveSupport::TestCaseassert_equal "openai", LlmUsage.infer_provider("gpt-5")end+ test "infer_provider returns google for gemini and google/ models" do+ assert_equal "google", LlmUsage.infer_provider("gemini-3.8-flash")+ assert_equal "google", LlmUsage.infer_provider("gemini-3.1-pro")+ assert_equal "google", LlmUsage.infer_provider("gemini-2.5-flash")+ assert_equal "google", LlmUsage.infer_provider("gemini-unknown-model")+ assert_equal "google", LlmUsage.infer_provider("google/gemini-2.5-flash")+ end+test "infer_provider attributes Bedrock and Vertex prefixed IDs to anthropic" doassert_equal "anthropic", LlmUsage.infer_provider("anthropic.claude-sonnet-4-5-20250929-v1:0")assert_equal "anthropic", LlmUsage.infer_provider("anthropic.claude-opus-4-20250514-v1:0")@@ -144,7 +152,8 @@ class LlmUsageTest < ActiveSupport::TestCase"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 ]+ "gemini-2.5-pro" => [ 2.25, 4.0 ],+ "gemini-3.1-pro" => [ 3.2, 5.8 ]}.each do |model, (short_cost, long_cost)|test "calculate_cost uses reviewed short and long context rates for #{model}" doassert_in_delta short_cost / 10, LlmUsage.calculate_cost(@@ -156,7 +165,7 @@ class LlmUsageTest < ActiveSupport::TestCaseendend- test "Gemini Pro long-context pricing starts strictly above 200000 input tokens" do+ test "Gemini 2.5 Pro long-context pricing starts strictly above 200000 input tokens" doassert_in_delta 1.25, LlmUsage.calculate_cost(model: "gemini-2.5-pro", prompt_tokens: 200_000, completion_tokens: 100_000), 0.000001@@ -165,6 +174,15 @@ class LlmUsageTest < ActiveSupport::TestCase), 0.000001end+ test "Gemini 3.1 Pro long-context pricing starts strictly above 200000 input tokens" do+ assert_in_delta 1.60, LlmUsage.calculate_cost(+ model: "gemini-3.1-pro", prompt_tokens: 200_000, completion_tokens: 100_000+ ), 0.000001+ assert_in_delta 2.600004, LlmUsage.calculate_cost(+ model: "gemini-3.1-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" doassert_in_delta 3.088, LlmUsage.calculate_cost(model: "gpt-5.6-sol", prompt_tokens: 272_000, completion_tokens: 100_000@@ -180,6 +198,30 @@ class LlmUsageTest < ActiveSupport::TestCase), 0.000001end+ test "calculate_cost returns Google pricing for Gemini 3 models" do+ # gemini-3.8-flash, 3.7-flash, 3.6-flash: $0.75 prompt / $3.75 completion per 1M tokens+ %w[gemini-3.8-flash gemini-3.7-flash gemini-3.6-flash].each do |model|+ cost = LlmUsage.calculate_cost(model: model, prompt_tokens: 1_000_000, completion_tokens: 100_000)+ assert_in_delta 1.125, cost, 0.0001+ end++ # gemini-3.5-flash: $1.50 prompt / $9.00 completion per 1M tokens+ cost_35_flash = LlmUsage.calculate_cost(model: "gemini-3.5-flash", prompt_tokens: 1_000_000, completion_tokens: 100_000)+ assert_in_delta 2.40, cost_35_flash, 0.0001++ # gemini-3.5-flash-lite: $0.30 prompt / $2.50 completion per 1M tokens+ cost_35_lite = LlmUsage.calculate_cost(model: "gemini-3.5-flash-lite", prompt_tokens: 1_000_000, completion_tokens: 100_000)+ assert_in_delta 0.55, cost_35_lite, 0.0001++ # gemini-3.1-flash-lite: $0.25 prompt / $1.50 completion per 1M tokens+ cost_31_lite = LlmUsage.calculate_cost(model: "gemini-3.1-flash-lite", prompt_tokens: 1_000_000, completion_tokens: 100_000)+ assert_in_delta 0.40, cost_31_lite, 0.0001++ # gemini-3-flash: $0.50 prompt / $3.00 completion per 1M tokens+ cost_3_flash = LlmUsage.calculate_cost(model: "gemini-3-flash", prompt_tokens: 1_000_000, completion_tokens: 100_000)+ assert_in_delta 0.80, cost_3_flash, 0.0001+ end+test "calculate_cost uses lower pricing for Haiku" docost = LlmUsage.calculate_cost(model: "claude-haiku-4-5", prompt_tokens: 1_000_000, completion_tokens: 1_000_000)diff --git a/test/models/provider/openai/generic_chat_parser_test.rb b/test/models/provider/openai/generic_chat_parser_test.rbnew file mode 100644index 0000000000..6a8f1158ab--- /dev/null+++ b/test/models/provider/openai/generic_chat_parser_test.rb@@ -0,0 +1,79 @@+# frozen_string_literal: true++require "test_helper"++class Provider::Openai::GenericChatParserTest < ActiveSupport::TestCase+ test "parses regular function calls without extra_content" do+ raw_response = {+ "id" => "chatcmpl-123",+ "model" => "gpt-4.1",+ "choices" => [+ {+ "message" => {+ "role" => "assistant",+ "content" => nil,+ "tool_calls" => [+ {+ "id" => "call_abc123",+ "type" => "function",+ "function" => {+ "name" => "get_accounts",+ "arguments" => "{}"+ }+ }+ ]+ }+ }+ ]+ }++ parsed = Provider::Openai::GenericChatParser.new(raw_response).parsed++ assert_equal "chatcmpl-123", parsed.id+ assert_equal "gpt-4.1", parsed.model+ assert_empty parsed.messages+ assert_equal 1, parsed.function_requests.size++ request = parsed.function_requests.first+ assert_equal "call_abc123", request.id+ assert_equal "call_abc123", request.call_id+ assert_equal "get_accounts", request.function_name+ assert_equal "{}", request.function_args+ assert_nil request.extra_content+ end++ test "parses function calls with extra_content including thought_signature" do+ extra = { "google" => { "thought_signature" => "sig_encrypted_token_123" } }+ raw_response = {+ "id" => "chatcmpl-gemini-123",+ "model" => "gemini-3.8-flash",+ "choices" => [+ {+ "message" => {+ "role" => "assistant",+ "content" => nil,+ "tool_calls" => [+ {+ "id" => "call_gemini_456",+ "type" => "function",+ "function" => {+ "name" => "get_holdings",+ "arguments" => '{"account_id":"acc_1"}'+ },+ "extra_content" => extra+ }+ ]+ }+ }+ ]+ }++ parsed = Provider::Openai::GenericChatParser.new(raw_response).parsed++ assert_equal 1, parsed.function_requests.size+ request = parsed.function_requests.first+ assert_equal "call_gemini_456", request.call_id+ assert_equal "get_holdings", request.function_name+ assert_equal extra, request.extra_content+ end+enddiff --git a/test/models/provider/openai_test.rb b/test/models/provider/openai_test.rbindex 3f367d59c5..ffbf1bb01d 100644--- a/test/models/provider/openai_test.rb+++ b/test/models/provider/openai_test.rb@@ -928,6 +928,59 @@ class Provider::OpenaiTest < ActiveSupport::TestCaseassert_equal "{}", tool_call.dig(:function, :arguments)end+ test "build_generic_messages preserves extra_content on assistant tool_calls when present" do+ provider = Provider::Openai.new(+ "test-token",+ uri_base: "https://generativelanguage.googleapis.com/v1beta/openai",+ model: "gemini-3.8-flash"+ )++ extra = { "google" => { "thought_signature" => "sig_encrypted_token_123" } }+ messages = provider.send(+ :build_generic_messages,+ prompt: "hi",+ function_results: [+ {+ call_id: "call_1",+ name: "get_net_worth",+ arguments: "{}",+ output: { "amount" => 10000 },+ extra_content: extra+ }+ ]+ )++ assistant_message = messages.find { |m| m[:role] == "assistant" }+ tool_call = assistant_message[:tool_calls].first+ assert_equal extra, tool_call[:extra_content]+ end++ test "build_generic_messages omits extra_content on assistant tool_calls when nil" do+ provider = Provider::Openai.new(+ "test-token",+ uri_base: "https://example.com/v1",+ model: "test-model"+ )++ messages = provider.send(+ :build_generic_messages,+ prompt: "hi",+ function_results: [+ {+ call_id: "call_1",+ name: "get_net_worth",+ arguments: "{}",+ output: { "amount" => 10000 },+ extra_content: nil+ }+ ]+ )++ assistant_message = messages.find { |m| m[:role] == "assistant" }+ tool_call = assistant_message[:tool_calls].first+ assert_not_includes tool_call.keys, :extra_content+ end+private# Verify the response budget at the provider-to-processor boundary.# @param limit [Integer, nil] expected explicit cap or omitted capdiff --git a/test/models/tool_call/function_test.rb b/test/models/tool_call/function_test.rbindex e54f26bbb3..692a1c26ee 100644--- a/test/models/tool_call/function_test.rb+++ b/test/models/tool_call/function_test.rb@@ -53,4 +53,34 @@ class ToolCall::FunctionTest < ActiveSupport::TestCaseassert_equal({ "currency" => "USD" }, tool_call.to_result[:arguments])end++ test "from_function_request preserves extra_content and includes it in to_result and to_tool_call" do+ extra = { "google" => { "thought_signature" => "sig_123" } }+ request = Provider::LlmConcept::ChatFunctionRequest.new(+ id: "resp_1",+ call_id: "call_1",+ function_name: "get_net_worth",+ function_args: '{"currency":"USD"}',+ extra_content: extra+ )++ tool_call = ToolCall::Function.from_function_request(request, { "amount" => 10000 })++ assert_equal extra, tool_call.extra_content+ assert_equal extra, tool_call.to_result[:extra_content]+ assert_equal extra, tool_call.to_tool_call[:extra_content]+ end++ test "to_tool_call omits extra_content when not set" do+ tool_call = ToolCall::Function.new(+ provider_id: "resp_1",+ provider_call_id: "call_1",+ function_name: "get_net_worth",+ function_arguments: '{"currency":"USD"}',+ function_result: { "amount" => 10000 }+ )++ assert_nil tool_call.extra_content+ assert_not_includes tool_call.to_tool_call.keys, :extra_content+ endend