The personal finance app for everyone (by everyone)
Ruby
fix(ai): retry without strict JSON when Auto mode can't parse the response (#3602)
Arnav Joshif6e126c08a69
diff --git a/app/models/provider/openai.rb b/app/models/provider/openai.rbindex 71e759304f..0c7211ceb4 100644--- a/app/models/provider/openai.rb+++ b/app/models/provider/openai.rb@@ -5,6 +5,11 @@ class Provider::Openai < Provider# Subclass so errors caught in this provider are raised as Provider::Openai::ErrorError = Class.new(Provider::Error)+ # Raised when a successful HTTP response can't be parsed into the expected+ # structure; used by Auto JSON mode to decide whether to retry without+ # response_format.+ ResponseFormatError = Class.new(Error)+DEFAULT_MODEL = "gpt-4.1".freezeDEFAULT_REQUEST_TIMEOUT = 60MIN_REQUEST_TIMEOUT = 1diff --git a/app/models/provider/openai/auto_categorizer.rb b/app/models/provider/openai/auto_categorizer.rbindex 6c181ddb8e..2e317cebe2 100644--- a/app/models/provider/openai/auto_categorizer.rb+++ b/app/models/provider/openai/auto_categorizer.rb@@ -6,6 +6,10 @@ class Provider::Openai::AutoCategorizer# This is a heuristic to detect when strict JSON mode is breaking the model's ability to reasonAUTO_MODE_NULL_THRESHOLD = 0.5+ # Key aliases accepted from models that don't follow the schema's field names+ TRANSACTION_ID_KEYS = %w[transaction_id id txn_id].freeze+ CATEGORY_NAME_KEYS = %w[category_name category name].freeze+attr_reader :client, :model, :transactions, :user_categories, :custom_provider, :langfuse_trace, :family, :json_modedef initialize(client, model: "", transactions: [], user_categories: [], custom_provider: false, langfuse_trace: nil, family: nil, json_mode: nil)@@ -134,8 +138,10 @@ class Provider::Openai::AutoCategorizerendrescue Faraday::BadRequestError => e# If strict mode fails (HTTP 400), fall back to none mode- # This handles providers that don't support json_schema response format- if json_mode == JSON_MODE_STRICT || json_mode == JSON_MODE_AUTO+ # This handles providers that don't support json_schema response format.+ # Auto mode performs its own strict-attempt fallback; a BadRequestError+ # reaching this rescue while in auto mode came from a none-mode retry.+ if json_mode == JSON_MODE_STRICTRails.logger.warn("Strict JSON mode failed, falling back to none mode: #{e.message}")auto_categorize_with_mode(JSON_MODE_NONE)else@@ -153,7 +159,18 @@ class Provider::Openai::AutoCategorizer# The heuristic is simple: if >50% of results are null or missing, the model likely# needs the freedom to reason in its output (which strict mode prevents).def auto_categorize_with_auto_mode- result = auto_categorize_with_mode(JSON_MODE_STRICT)+ result = begin+ auto_categorize_with_mode(JSON_MODE_STRICT)+ rescue Provider::Openai::ResponseFormatError => e+ Rails.logger.warn("Auto mode: strict JSON response could not be parsed (#{e.message}), retrying with none mode")+ return auto_categorize_with_mode(JSON_MODE_NONE)+ rescue Faraday::BadRequestError => e+ # Handle the provider-rejects-strict-schema fallback inside auto mode so+ # a failure of the none-mode retry propagates instead of re-entering+ # the outer BadRequestError rescue and firing a second fallback.+ Rails.logger.warn("Auto mode: strict JSON mode rejected by provider (#{e.message}), retrying with none mode")+ return auto_categorize_with_mode(JSON_MODE_NONE)+ endnull_count = result.count { |r| r.category_name.nil? || r.category_name == "null" }missing_count = transactions.size - result.size@@ -313,22 +330,39 @@ class Provider::Openai::AutoCategorizerraw = response.dig("choices", 0, "message", "content")parsed = parse_json_flexibly(raw)- # Handle different response formats from various LLMs- categorizations = parsed.dig("categorizations") ||- parsed.dig("results") ||- (parsed.is_a?(Array) ? parsed : nil)+ # Handle different response formats from various LLMs. parsed can be any+ # JSON value; only Hash (with a known key) and bare Array are usable.+ categorizations = if parsed.is_a?(Hash)+ parsed.dig("categorizations") || parsed.dig("results")+ else+ parsed+ end++ unless categorizations.is_a?(Array) && categorizations.all? { |c| c.is_a?(Hash) }+ raise Provider::Openai::ResponseFormatError, "Could not find categorizations in response"+ end- raise Provider::Openai::Error, "Could not find categorizations in response" if categorizations.nil?+ # Drop items with no transaction id: they can't be correlated to a+ # transaction, and left in they'd surface as nil-field rows that hide a+ # malformed batch from the auto-mode retry heuristic. A missing category+ # field is fine (models in none/json_object mode often omit nulls) and+ # is treated as "no category" downstream.+ categorizations.select! { |cat| field_value(cat, TRANSACTION_ID_KEYS).present? }# Normalize field names (some LLMs use different naming)categorizations.map do |cat|{- "transaction_id" => cat["transaction_id"] || cat["id"] || cat["txn_id"],- "category_name" => cat["category_name"] || cat["category"] || cat["name"]+ "transaction_id" => field_value(cat, TRANSACTION_ID_KEYS),+ "category_name" => field_value(cat, CATEGORY_NAME_KEYS)}endend+ # First truthy value among the accepted key aliases (same semantics as `a || b || c`)+ def field_value(item, keys)+ item.values_at(*keys).find(&:itself)+ end+# Flexible JSON parsing that handles common LLM output issuesdef parse_json_flexibly(raw)return {} if raw.blank?@@ -391,7 +425,7 @@ class Provider::Openai::AutoCategorizerendend- raise Provider::Openai::Error, "Could not parse JSON from response: #{raw.truncate(200)}"+ raise Provider::Openai::ResponseFormatError, "Could not parse JSON from response: #{raw.truncate(200)}"end# Strip thinking model tags (<think>...</think>) from responsediff --git a/app/models/provider/openai/auto_merchant_detector.rb b/app/models/provider/openai/auto_merchant_detector.rbindex 5e4b850953..69630bd1dd 100644--- a/app/models/provider/openai/auto_merchant_detector.rb+++ b/app/models/provider/openai/auto_merchant_detector.rb@@ -5,6 +5,11 @@ class Provider::Openai::AutoMerchantDetector# Threshold for auto mode: if more than this percentage returns null, retry with none modeAUTO_MODE_NULL_THRESHOLD = 0.5+ # Key aliases accepted from models that don't follow the schema's field names+ TRANSACTION_ID_KEYS = %w[transaction_id id txn_id].freeze+ BUSINESS_NAME_KEYS = %w[business_name name merchant_name merchant].freeze+ BUSINESS_URL_KEYS = %w[business_url url website].freeze+attr_reader :client, :model, :transactions, :user_merchants, :custom_provider, :langfuse_trace, :family, :json_modedef initialize(client, model: "", transactions:, user_merchants:, custom_provider: false, langfuse_trace: nil, family: nil, json_mode: nil)@@ -146,8 +151,10 @@ class Provider::Openai::AutoMerchantDetectorendrescue Faraday::BadRequestError => e# If strict mode fails (HTTP 400), fall back to none mode- # This handles providers that don't support json_schema response format- if json_mode == JSON_MODE_STRICT || json_mode == JSON_MODE_AUTO+ # This handles providers that don't support json_schema response format.+ # Auto mode performs its own strict-attempt fallback; a BadRequestError+ # reaching this rescue while in auto mode came from a none-mode retry.+ if json_mode == JSON_MODE_STRICTRails.logger.warn("Strict JSON mode failed, falling back to none mode: #{e.message}")auto_detect_merchants_with_mode(JSON_MODE_NONE)else@@ -157,13 +164,26 @@ class Provider::Openai::AutoMerchantDetector# Auto mode: try strict first, fall back to none if too many nulls or missing resultsdef auto_detect_merchants_with_auto_mode- result = auto_detect_merchants_with_mode(JSON_MODE_STRICT)+ result = begin+ auto_detect_merchants_with_mode(JSON_MODE_STRICT)+ rescue Provider::Openai::ResponseFormatError => e+ Rails.logger.warn("Auto mode: strict JSON response could not be parsed (#{e.message}), retrying with none mode")+ return auto_detect_merchants_with_mode(JSON_MODE_NONE)+ rescue Faraday::BadRequestError => e+ # Handle the provider-rejects-strict-schema fallback inside auto mode so+ # a failure of the none-mode retry propagates instead of re-entering+ # the outer BadRequestError rescue and firing a second fallback.+ Rails.logger.warn("Auto mode: strict JSON mode rejected by provider (#{e.message}), retrying with none mode")+ return auto_detect_merchants_with_mode(JSON_MODE_NONE)+ end# Check if too many nulls OR missing results were returned# Models that can't reason in strict mode often:# 1. Return null for everything, OR# 2. Simply omit transactions they can't detect (returning fewer results than input)- null_count = result.count { |r| r.business_name.nil? || r.business_name == "null" }+ # A detection is only usable downstream with both a name and a URL, so an+ # item missing either counts as a failure for the retry heuristic.+ null_count = result.count { |r| r.business_name.blank? || r.business_url.blank? }missing_count = transactions.size - result.sizefailed_count = null_count + missing_countfailed_ratio = transactions.size > 0 ? failed_count.to_f / transactions.size : 0.0@@ -270,23 +290,40 @@ class Provider::Openai::AutoMerchantDetectorraw = response.dig("choices", 0, "message", "content")parsed = parse_json_flexibly(raw)- # Handle different response formats from various LLMs- merchants = parsed.dig("merchants") ||- parsed.dig("results") ||- (parsed.is_a?(Array) ? parsed : nil)+ # Handle different response formats from various LLMs. parsed can be any+ # JSON value; only Hash (with a known key) and bare Array are usable.+ merchants = if parsed.is_a?(Hash)+ parsed.dig("merchants") || parsed.dig("results")+ else+ parsed+ end++ unless merchants.is_a?(Array) && merchants.all? { |m| m.is_a?(Hash) }+ raise Provider::Openai::ResponseFormatError, "Could not find merchants in response"+ end- raise Provider::Openai::Error, "Could not find merchants in response" if merchants.nil?+ # Drop items with no transaction id: they can't be correlated to a+ # transaction, and left in they'd surface as nil-field rows that hide a+ # malformed batch from the auto-mode retry heuristic. Missing name/url+ # fields are fine (models in none/json_object mode often omit nulls) and+ # are treated as "unknown" downstream.+ merchants.select! { |m| field_value(m, TRANSACTION_ID_KEYS).present? }# Normalize field names (some LLMs use different naming)merchants.map do |m|{- "transaction_id" => m["transaction_id"] || m["id"] || m["txn_id"],- "business_name" => m["business_name"] || m["name"] || m["merchant_name"] || m["merchant"],- "business_url" => m["business_url"] || m["url"] || m["website"]+ "transaction_id" => field_value(m, TRANSACTION_ID_KEYS),+ "business_name" => field_value(m, BUSINESS_NAME_KEYS),+ "business_url" => field_value(m, BUSINESS_URL_KEYS)}endend+ # First truthy value among the accepted key aliases (same semantics as `a || b || c`)+ def field_value(item, keys)+ item.values_at(*keys).find(&:itself)+ end+# Flexible JSON parsing that handles common LLM output issuesdef parse_json_flexibly(raw)return {} if raw.blank?@@ -347,7 +384,7 @@ class Provider::Openai::AutoMerchantDetectorendend- raise Provider::Openai::Error, "Could not parse JSON from response: #{raw.truncate(200)}"+ raise Provider::Openai::ResponseFormatError, "Could not parse JSON from response: #{raw.truncate(200)}"end# Strip thinking model tags (<think>...</think>) from responsediff --git a/test/models/provider/openai/auto_categorizer_test.rb b/test/models/provider/openai/auto_categorizer_test.rbnew file mode 100644index 0000000000..439ff76077--- /dev/null+++ b/test/models/provider/openai/auto_categorizer_test.rb@@ -0,0 +1,183 @@+require "test_helper"++class Provider::Openai::AutoCategorizerTest < ActiveSupport::TestCase+ setup do+ @client = mock+ @transactions = [+ { id: "1", name: "McDonalds", amount: 20, classification: "expense" }+ ]+ @user_categories = [+ { id: "cat1", name: "Food", is_subcategory: false, parent_id: nil, classification: "expense" }+ ]+ end++ test "auto mode retries without response_format when strict JSON cannot be parsed" do+ call_params = []+ @client.expects(:chat).twice+ .with { |args| call_params << args[:parameters]; true }+ .returns(+ chat_response('{"categorizations":[{"transaction_id":"1","category_name":"Food"'),+ chat_response('{"categorizations":[{"transaction_id":"1","category_name":"Food"}]}')+ )++ result = categorizer(json_mode: "auto").auto_categorize++ assert_equal 1, result.size+ assert_equal "Food", result.first.category_name+ assert call_params.first[:response_format].present?, "strict attempt should send response_format"+ assert_nil call_params.second[:response_format], "retry should omit response_format"+ end++ test "auto mode retries when strict response parses but has the wrong shape" do+ @client.expects(:chat).twice+ .returns(+ chat_response('{"foo": []}'),+ chat_response('{"categorizations":[{"transaction_id":"1","category_name":"Food"}]}')+ )++ result = categorizer(json_mode: "auto").auto_categorize++ assert_equal "Food", result.first.category_name+ end++ test "auto mode accepts a top-level JSON array in a single call" do+ @client.expects(:chat).once+ .returns(chat_response('[{"transaction_id":"1","category_name":"Food"}]'))++ result = categorizer(json_mode: "auto").auto_categorize++ assert_equal "Food", result.first.category_name+ end++ test "auto mode retries when strict response is a JSON scalar" do+ @client.expects(:chat).twice+ .returns(+ chat_response("null"),+ chat_response('{"categorizations":[{"transaction_id":"1","category_name":"Food"}]}')+ )++ result = categorizer(json_mode: "auto").auto_categorize++ assert_equal "Food", result.first.category_name+ end++ test "auto mode retries when a recognized key holds a non-array value" do+ @client.expects(:chat).twice+ .returns(+ chat_response('{"categorizations": 5}'),+ chat_response('{"categorizations":[{"transaction_id":"1","category_name":"Food"}]}')+ )++ result = categorizer(json_mode: "auto").auto_categorize++ assert_equal "Food", result.first.category_name+ end++ test "auto mode does not fire a second fallback when the none-mode retry returns HTTP 400" do+ @client.expects(:chat).twice+ .returns(chat_response('{"categorizations":[{"transaction_id":"1"'))+ .then+ .raises(Faraday::BadRequestError.new("400"))++ assert_raises Faraday::BadRequestError do+ categorizer(json_mode: "auto").auto_categorize+ end+ end++ test "auto mode makes a single call when strict returns categorizations for all transactions" do+ @client.expects(:chat).once+ .returns(chat_response('{"categorizations":[{"transaction_id":"1","category_name":"Food"}]}'))++ result = categorizer(json_mode: "auto").auto_categorize++ assert_equal 1, result.size+ assert_equal "Food", result.first.category_name+ end++ test "strict mode raises ResponseFormatError on unparseable JSON without retrying" do+ @client.expects(:chat).once+ .returns(chat_response('{"categorizations":[{"transaction_id":"1"'))++ assert_raises Provider::Openai::ResponseFormatError do+ categorizer(json_mode: "strict").auto_categorize+ end+ end++ test "auto mode propagates network errors from the strict attempt" do+ @client.expects(:chat).once.raises(Faraday::TimeoutError.new("timeout"))++ assert_raises Faraday::TimeoutError do+ categorizer(json_mode: "auto").auto_categorize+ end+ end++ test "auto mode retries when every strict response item is malformed" do+ @client.expects(:chat).twice+ .returns(+ chat_response('{"categorizations":[{}]}'),+ chat_response('{"categorizations":[{"transaction_id":"1","category_name":"Food"}]}')+ )++ result = categorizer(json_mode: "auto").auto_categorize++ assert_equal "Food", result.first.category_name+ end++ test "auto mode drops malformed items below the retry threshold instead of returning nil fields" do+ @transactions.concat([+ { id: "2", name: "Shell", amount: 50, classification: "expense" },+ { id: "3", name: "Netflix", amount: 15, classification: "expense" },+ { id: "4", name: "Spotify", amount: 10, classification: "expense" }+ ])++ @client.expects(:chat).once+ .returns(chat_response(<<~JSON.squish))+ {"categorizations":[+ {"category_name":"Food"},+ {"transaction_id":"2"},+ {"transaction_id":"3","category_name":"Food"},+ {"transaction_id":"4","category_name":"Food"}+ ]}+ JSON++ result = categorizer(json_mode: "auto").auto_categorize++ assert_equal %w[2 3 4], result.map(&:transaction_id), "only the id-less item should be dropped"+ assert_nil result.first.category_name, "an omitted category field should be kept as nil, not dropped"+ end++ test "auto mode still falls back to none mode on HTTP 400" do+ call_params = []+ @client.expects(:chat).twice+ .with { |args| call_params << args[:parameters]; true }+ .raises(Faraday::BadRequestError.new("400"))+ .then+ .returns(chat_response('{"categorizations":[{"transaction_id":"1","category_name":"Food"}]}'))++ result = categorizer(json_mode: "auto").auto_categorize++ assert_equal "Food", result.first.category_name+ assert call_params.first[:response_format].present?+ assert_nil call_params.second[:response_format]+ end++ private++ def categorizer(json_mode:)+ Provider::Openai::AutoCategorizer.new(+ @client,+ model: "test-model",+ transactions: @transactions,+ user_categories: @user_categories,+ custom_provider: true,+ json_mode: json_mode+ )+ end++ def chat_response(content)+ {+ "choices" => [ { "message" => { "content" => content } } ],+ "usage" => { "total_tokens" => 1 }+ }+ end+enddiff --git a/test/models/provider/openai/auto_merchant_detector_test.rb b/test/models/provider/openai/auto_merchant_detector_test.rbnew file mode 100644index 0000000000..edfcef9904--- /dev/null+++ b/test/models/provider/openai/auto_merchant_detector_test.rb@@ -0,0 +1,175 @@+require "test_helper"++class Provider::Openai::AutoMerchantDetectorTest < ActiveSupport::TestCase+ setup do+ @client = mock+ @transactions = [+ { id: "1", name: "AMAZON.COM*1A2B3C", amount: 20, classification: "expense" }+ ]+ @user_merchants = [ { name: "Amazon" } ]+ end++ test "auto mode retries without response_format when strict JSON cannot be parsed" do+ call_params = []+ @client.expects(:chat).twice+ .with { |args| call_params << args[:parameters]; true }+ .returns(+ chat_response('{"merchants":[{"transaction_id":"1","business_name":"Ama'),+ chat_response('{"merchants":[{"transaction_id":"1","business_name":"Amazon","business_url":"amazon.com"}]}')+ )++ result = detector(json_mode: "auto").auto_detect_merchants++ assert_equal 1, result.size+ assert_equal "Amazon", result.first.business_name+ assert_equal "amazon.com", result.first.business_url+ assert call_params.first[:response_format].present?, "strict attempt should send response_format"+ assert_nil call_params.second[:response_format], "retry should omit response_format"+ end++ test "auto mode retries when strict response parses but has the wrong shape" do+ @client.expects(:chat).twice+ .returns(+ chat_response('{"foo": []}'),+ chat_response('{"merchants":[{"transaction_id":"1","business_name":"Amazon","business_url":"amazon.com"}]}')+ )++ result = detector(json_mode: "auto").auto_detect_merchants++ assert_equal "Amazon", result.first.business_name+ end++ test "auto mode accepts a top-level JSON array in a single call" do+ @client.expects(:chat).once+ .returns(chat_response('[{"transaction_id":"1","business_name":"Amazon","business_url":"amazon.com"}]'))++ result = detector(json_mode: "auto").auto_detect_merchants++ assert_equal "Amazon", result.first.business_name+ end++ test "auto mode retries when strict response is a JSON scalar" do+ @client.expects(:chat).twice+ .returns(+ chat_response("null"),+ chat_response('{"merchants":[{"transaction_id":"1","business_name":"Amazon","business_url":"amazon.com"}]}')+ )++ result = detector(json_mode: "auto").auto_detect_merchants++ assert_equal "Amazon", result.first.business_name+ end++ test "auto mode retries when every strict response item is malformed" do+ @client.expects(:chat).twice+ .returns(+ chat_response('{"merchants":[{}]}'),+ chat_response('{"merchants":[{"transaction_id":"1","business_name":"Amazon","business_url":"amazon.com"}]}')+ )++ result = detector(json_mode: "auto").auto_detect_merchants++ assert_equal "Amazon", result.first.business_name+ end++ test "auto mode drops malformed items below the retry threshold instead of returning nil fields" do+ @transactions.concat([+ { id: "2", name: "SHELL OIL", amount: 50, classification: "expense" },+ { id: "3", name: "NETFLIX", amount: 15, classification: "expense" },+ { id: "4", name: "SPOTIFY", amount: 10, classification: "expense" }+ ])++ @client.expects(:chat).once+ .returns(chat_response(<<~JSON.squish))+ {"merchants":[+ {"business_name":"Shell","business_url":"shell.com"},+ {"transaction_id":"1","business_name":"Amazon"},+ {"transaction_id":"3","business_name":"Netflix","business_url":"netflix.com"},+ {"transaction_id":"4","business_name":"Spotify","business_url":"spotify.com"}+ ]}+ JSON++ result = detector(json_mode: "auto").auto_detect_merchants++ assert_equal %w[1 3 4], result.map(&:transaction_id), "only the id-less item should be dropped"+ assert_equal "Amazon", result.first.business_name, "an omitted url field must not drop the merchant name"+ assert_nil result.first.business_url+ end++ test "auto mode retries when strict results lack a usable business_url" do+ @client.expects(:chat).twice+ .returns(+ chat_response('{"merchants":[{"transaction_id":"1","business_name":"Amazon"}]}'),+ chat_response('{"merchants":[{"transaction_id":"1","business_name":"Amazon","business_url":"amazon.com"}]}')+ )++ result = detector(json_mode: "auto").auto_detect_merchants++ assert_equal "amazon.com", result.first.business_url+ end++ test "auto mode still falls back to none mode on HTTP 400" do+ call_params = []+ @client.expects(:chat).twice+ .with { |args| call_params << args[:parameters]; true }+ .raises(Faraday::BadRequestError.new("400"))+ .then+ .returns(chat_response('{"merchants":[{"transaction_id":"1","business_name":"Amazon","business_url":"amazon.com"}]}'))++ result = detector(json_mode: "auto").auto_detect_merchants++ assert_equal "Amazon", result.first.business_name+ assert call_params.first[:response_format].present?+ assert_nil call_params.second[:response_format]+ end++ test "auto mode does not fire a second fallback when the none-mode retry returns HTTP 400" do+ @client.expects(:chat).twice+ .returns(chat_response('{"merchants":[{"transaction_id":"1"'))+ .then+ .raises(Faraday::BadRequestError.new("400"))++ assert_raises Faraday::BadRequestError do+ detector(json_mode: "auto").auto_detect_merchants+ end+ end++ test "auto mode makes a single call when strict returns merchants for all transactions" do+ @client.expects(:chat).once+ .returns(chat_response('{"merchants":[{"transaction_id":"1","business_name":"Amazon","business_url":"amazon.com"}]}'))++ result = detector(json_mode: "auto").auto_detect_merchants++ assert_equal 1, result.size+ assert_equal "Amazon", result.first.business_name+ end++ test "strict mode raises ResponseFormatError on unparseable JSON without retrying" do+ @client.expects(:chat).once+ .returns(chat_response('{"merchants":[{"transaction_id":"1"'))++ assert_raises Provider::Openai::ResponseFormatError do+ detector(json_mode: "strict").auto_detect_merchants+ end+ end++ private++ def detector(json_mode:)+ Provider::Openai::AutoMerchantDetector.new(+ @client,+ model: "test-model",+ transactions: @transactions,+ user_merchants: @user_merchants,+ custom_provider: true,+ json_mode: json_mode+ )+ end++ def chat_response(content)+ {+ "choices" => [ { "message" => { "content" => content } } ],+ "usage" => { "total_tokens" => 1 }+ }+ end+end