The personal finance app for everyone (by everyone)
Ruby
Retry Anthropic structured output once after a text-only end_turn response (#4513)
alexcastgonze72bc59e4129
diff --git a/app/models/provider/anthropic/auto_categorizer.rb b/app/models/provider/anthropic/auto_categorizer.rbindex c81e0936b8..1b166d5aba 100644--- a/app/models/provider/anthropic/auto_categorizer.rb+++ b/app/models/provider/anthropic/auto_categorizer.rb@@ -1,5 +1,6 @@class Provider::Anthropic::AutoCategorizerinclude Provider::Anthropic::Concerns::UsageRecorder+ include Provider::Anthropic::Concerns::StructuredOutputTOOL_NAME = "report_categorizations".freeze@@ -21,7 +22,9 @@ class Provider::Anthropic::AutoCategorizeruser_categories: user_categories})- response = client.messages.create(+ response = create_structured_message(+ tool_name: TOOL_NAME,+ operation: "auto_categorize",model: model,max_tokens: max_tokens,system_: Provider::Anthropic.structured_output_system(instructions, model, TOOL_NAME),@@ -135,10 +138,10 @@ class Provider::Anthropic::AutoCategorizerenddef extract_categorizations(response)- tool_use = Array(response.content).find { |block| block_type(block) == :tool_use }+ tool_use = Array(response.content).find { |block| structured_block_type(block) == :tool_use }raise Provider::Anthropic::Error, "Model did not invoke #{TOOL_NAME} (stop_reason: #{response.stop_reason})" unless tool_use- input = block_input(tool_use)+ input = structured_block_input(tool_use)input = JSON.parse(input) if input.is_a?(String)categorizations = input.is_a?(Hash) ? (input["categorizations"] || input[:categorizations]) : nil@@ -164,13 +167,4 @@ class Provider::Anthropic::AutoCategorizermatch = user_categories.find { |c| c[:name].to_s.casecmp(str).zero? }match ? match[:name] : strend-- def block_type(block)- raw = block.respond_to?(:type) ? block.type : block[:type] || block["type"]- raw.to_s.to_sym- end-- def block_input(block)- block.respond_to?(:input) ? block.input : (block[:input] || block["input"])- endenddiff --git a/app/models/provider/anthropic/auto_merchant_detector.rb b/app/models/provider/anthropic/auto_merchant_detector.rbindex ce774145b0..a7a67979eb 100644--- a/app/models/provider/anthropic/auto_merchant_detector.rb+++ b/app/models/provider/anthropic/auto_merchant_detector.rb@@ -1,5 +1,6 @@class Provider::Anthropic::AutoMerchantDetectorinclude Provider::Anthropic::Concerns::UsageRecorder+ include Provider::Anthropic::Concerns::StructuredOutputTOOL_NAME = "report_merchants".freeze@@ -21,7 +22,9 @@ class Provider::Anthropic::AutoMerchantDetectoruser_merchants: user_merchants})- response = client.messages.create(+ response = create_structured_message(+ tool_name: TOOL_NAME,+ operation: "auto_detect_merchants",model: model,max_tokens: max_tokens,system_: Provider::Anthropic.structured_output_system(instructions, model, TOOL_NAME),@@ -137,10 +140,10 @@ class Provider::Anthropic::AutoMerchantDetectorenddef extract_merchants(response)- tool_use = Array(response.content).find { |block| block_type(block) == :tool_use }+ tool_use = Array(response.content).find { |block| structured_block_type(block) == :tool_use }raise Provider::Anthropic::Error, "Model did not invoke #{TOOL_NAME} (stop_reason: #{response.stop_reason})" unless tool_use- input = block_input(tool_use)+ input = structured_block_input(tool_use)input = JSON.parse(input) if input.is_a?(String)merchants = input.is_a?(Hash) ? (input["merchants"] || input[:merchants]) : nil@@ -173,13 +176,4 @@ class Provider::Anthropic::AutoMerchantDetectormatch = user_merchants.find { |m| m[:name].to_s.casecmp(str).zero? }match ? match[:name] : strend-- def block_type(block)- raw = block.respond_to?(:type) ? block.type : block[:type] || block["type"]- raw.to_s.to_sym- end-- def block_input(block)- block.respond_to?(:input) ? block.input : (block[:input] || block["input"])- endenddiff --git a/app/models/provider/anthropic/bank_statement_extractor.rb b/app/models/provider/anthropic/bank_statement_extractor.rbindex 470a9e07d2..df4f521c8f 100644--- a/app/models/provider/anthropic/bank_statement_extractor.rb+++ b/app/models/provider/anthropic/bank_statement_extractor.rb@@ -1,5 +1,6 @@class Provider::Anthropic::BankStatementExtractorinclude Provider::Anthropic::Concerns::UsageRecorder+ include Provider::Anthropic::Concerns::StructuredOutputTOOL_NAME = "report_bank_statement".freeze@@ -28,7 +29,9 @@ class Provider::Anthropic::BankStatementExtractorpdf_size: pdf_content.bytesize})- response = client.messages.create(+ response = create_structured_message(+ tool_name: TOOL_NAME,+ operation: "extract_bank_statement",model: model,max_tokens: max_tokens,system_: Provider::Anthropic.structured_output_system(instructions, model, TOOL_NAME),@@ -147,10 +150,10 @@ class Provider::Anthropic::BankStatementExtractorenddef extract_tool_input(response)- tool_use = Array(response.content).find { |block| block_type(block) == :tool_use }+ tool_use = Array(response.content).find { |block| structured_block_type(block) == :tool_use }raise Provider::Anthropic::Error, "Model did not invoke #{TOOL_NAME} (stop_reason: #{stop_reason(response)})" unless tool_use- input = block_input(tool_use)+ input = structured_block_input(tool_use)input = JSON.parse(input) if input.is_a?(String)inputend@@ -208,13 +211,4 @@ class Provider::Anthropic::BankStatementExtractorreturn amount.to_f if amount.is_a?(Numeric)amount.to_s.gsub(/[^0-9.\-]/, "").to_fend-- def block_type(block)- raw = block.respond_to?(:type) ? block.type : block[:type] || block["type"]- raw.to_s.to_sym- end-- def block_input(block)- block.respond_to?(:input) ? block.input : (block[:input] || block["input"])- endenddiff --git a/app/models/provider/anthropic/bill_setup_suggester.rb b/app/models/provider/anthropic/bill_setup_suggester.rbindex 27c9d5596a..97435533ef 100644--- a/app/models/provider/anthropic/bill_setup_suggester.rb+++ b/app/models/provider/anthropic/bill_setup_suggester.rb@@ -1,5 +1,6 @@class Provider::Anthropic::BillSetupSuggesterinclude Provider::Anthropic::Concerns::UsageRecorder+ include Provider::Anthropic::Concerns::StructuredOutputTOOL_NAME = "report_bill_setup".freeze@@ -22,7 +23,9 @@ class Provider::Anthropic::BillSetupSuggesterconfigure_mode: current_config.present?})- response = client.messages.create(+ response = create_structured_message(+ tool_name: TOOL_NAME,+ operation: "suggest_bill_setup",model: model,max_tokens: max_tokens,system_: Provider::Anthropic.structured_output_system(instructions, model, TOOL_NAME),@@ -127,10 +130,10 @@ class Provider::Anthropic::BillSetupSuggesterenddef extract_input(response)- tool_use = Array(response.content).find { |block| block_type(block) == :tool_use }+ tool_use = Array(response.content).find { |block| structured_block_type(block) == :tool_use }raise Provider::Anthropic::Error, "Model did not invoke #{TOOL_NAME} (stop_reason: #{response.stop_reason})" unless tool_use- input = block_input(tool_use)+ input = structured_block_input(tool_use)input = JSON.parse(input) if input.is_a?(String)input.is_a?(Hash) ? input.stringify_keys : {}end@@ -157,13 +160,4 @@ class Provider::Anthropic::BillSetupSuggesternormalizedend-- def block_type(block)- raw = block.respond_to?(:type) ? block.type : block[:type] || block["type"]- raw.to_s.to_sym- end-- def block_input(block)- block.respond_to?(:input) ? block.input : (block[:input] || block["input"])- endenddiff --git a/app/models/provider/anthropic/concerns/structured_output.rb b/app/models/provider/anthropic/concerns/structured_output.rbnew file mode 100644index 0000000000..e10735815e--- /dev/null+++ b/app/models/provider/anthropic/concerns/structured_output.rb@@ -0,0 +1,55 @@+module Provider::Anthropic::Concerns::StructuredOutput+ extend ActiveSupport::Concern++ private++ # Sends a request that expects its result through a single tool. On the+ # `auto` path (models that reject a forced tool_choice) the model may answer+ # with text only, so one retry asks for the tool again in the prompt. The+ # retry keeps `auto`: those models answer a forced tool with a 400.+ #+ # The first response is billed even though it carried no result, so its+ # usage is recorded here, and so is the retry's when it fails too (the caller+ # raises then); the caller records a successful final response as usual.+ def create_structured_message(tool_name:, operation:, **params)+ response = client.messages.create(**params)+ return response unless retry_for_missing_tool?(response, params[:tool_choice])++ record_usage(model, response.usage, operation: operation, metadata: { attempt: 1, retried: true })+ retry_response = client.messages.create(**params, messages: params[:messages] + tool_retry_messages(response, tool_name))+ if Array(retry_response.content).none? { |block| structured_block_type(block) == :tool_use }+ record_usage(model, retry_response.usage, operation: operation, metadata: { attempt: 2, retried: true })+ end+ retry_response+ end++ def retry_for_missing_tool?(response, tool_choice)+ tool_choice.is_a?(Hash) &&+ tool_choice[:type] == "auto" &&+ response.respond_to?(:stop_reason) &&+ response.stop_reason.to_s == "end_turn" &&+ Array(response.content).none? { |block| structured_block_type(block) == :tool_use }+ end++ def tool_retry_messages(response, tool_name)+ text = Array(response.content).filter_map { |block| structured_block_text(block) }.join("\n").strip+ reminder = { role: "user", content: "You did not call the #{tool_name} tool. Call it now with the result; do not answer with text." }++ text.empty? ? [ reminder ] : [ { role: "assistant", content: text }, reminder ]+ end++ def structured_block_type(block)+ raw = block.respond_to?(:type) ? block.type : block[:type] || block["type"]+ raw.to_s.to_sym+ end++ def structured_block_input(block)+ block.respond_to?(:input) ? block.input : (block[:input] || block["input"])+ end++ def structured_block_text(block)+ return unless structured_block_type(block) == :text++ block.respond_to?(:text) ? block.text.presence : (block[:text] || block["text"]).presence+ end+enddiff --git a/app/models/provider/anthropic/pdf_processor.rb b/app/models/provider/anthropic/pdf_processor.rbindex 865d4355c4..f8e31b1477 100644--- a/app/models/provider/anthropic/pdf_processor.rb+++ b/app/models/provider/anthropic/pdf_processor.rb@@ -1,5 +1,6 @@class Provider::Anthropic::PdfProcessorinclude Provider::Anthropic::Concerns::UsageRecorder+ include Provider::Anthropic::Concerns::StructuredOutputTOOL_NAME = "report_document_analysis".freeze@@ -36,7 +37,9 @@ class Provider::Anthropic::PdfProcessorpdf_size: pdf_content&.bytesize})- response = client.messages.create(+ response = create_structured_message(+ tool_name: TOOL_NAME,+ operation: "process_pdf",model: model,max_tokens: max_tokens,system_: Provider::Anthropic.structured_output_system(instructions, model, TOOL_NAME),@@ -144,10 +147,10 @@ class Provider::Anthropic::PdfProcessorenddef extract_tool_input(response)- tool_use = Array(response.content).find { |block| block_type(block) == :tool_use }+ tool_use = Array(response.content).find { |block| structured_block_type(block) == :tool_use }raise Provider::Anthropic::Error, "Model did not invoke #{TOOL_NAME} (stop_reason: #{response.stop_reason})" unless tool_use- input = block_input(tool_use)+ input = structured_block_input(tool_use)input = JSON.parse(input) if input.is_a?(String)inputend@@ -166,13 +169,4 @@ class Provider::Anthropic::PdfProcessornormalized = doc_type.to_s.strip.downcase.gsub(/\s+/, "_")Import::DOCUMENT_TYPES.include?(normalized) ? normalized : "other"end-- def block_type(block)- raw = block.respond_to?(:type) ? block.type : block[:type] || block["type"]- raw.to_s.to_sym- end-- def block_input(block)- block.respond_to?(:input) ? block.input : (block[:input] || block["input"])- endenddiff --git a/app/models/provider/anthropic/provider_merchant_enhancer.rb b/app/models/provider/anthropic/provider_merchant_enhancer.rbindex dec43f5762..8f4bdabb37 100644--- a/app/models/provider/anthropic/provider_merchant_enhancer.rb+++ b/app/models/provider/anthropic/provider_merchant_enhancer.rb@@ -1,5 +1,6 @@class Provider::Anthropic::ProviderMerchantEnhancerinclude Provider::Anthropic::Concerns::UsageRecorder+ include Provider::Anthropic::Concerns::StructuredOutputTOOL_NAME = "report_enhancements".freeze@@ -19,7 +20,9 @@ class Provider::Anthropic::ProviderMerchantEnhancermerchants: merchants})- response = client.messages.create(+ response = create_structured_message(+ tool_name: TOOL_NAME,+ operation: "enhance_provider_merchants",model: model,max_tokens: max_tokens,system_: Provider::Anthropic.structured_output_system(instructions, model, TOOL_NAME),@@ -107,10 +110,10 @@ class Provider::Anthropic::ProviderMerchantEnhancerenddef extract_enhancements(response)- tool_use = Array(response.content).find { |block| block_type(block) == :tool_use }+ tool_use = Array(response.content).find { |block| structured_block_type(block) == :tool_use }raise Provider::Anthropic::Error, "Model did not invoke #{TOOL_NAME} (stop_reason: #{response.stop_reason})" unless tool_use- input = block_input(tool_use)+ input = structured_block_input(tool_use)input = JSON.parse(input) if input.is_a?(String)enhanced = input.is_a?(Hash) ? (input["merchants"] || input[:merchants]) : nil@@ -133,13 +136,4 @@ class Provider::Anthropic::ProviderMerchantEnhancerreturn nil if str.empty? || str.casecmp("null").zero?strend-- def block_type(block)- raw = block.respond_to?(:type) ? block.type : block[:type] || block["type"]- raw.to_s.to_sym- end-- def block_input(block)- block.respond_to?(:input) ? block.input : (block[:input] || block["input"])- endenddiff --git a/test/models/provider/anthropic/structured_output_retry_test.rb b/test/models/provider/anthropic/structured_output_retry_test.rbnew file mode 100644index 0000000000..c68b66de86--- /dev/null+++ b/test/models/provider/anthropic/structured_output_retry_test.rb@@ -0,0 +1,163 @@+require "test_helper"+require "ostruct"++# The `auto` path (models that reject a forced tool_choice) may get a text-only+# end_turn answer. All six structured-output helpers retry that once.+class Provider::Anthropic::StructuredOutputRetryTest < ActiveSupport::TestCase+ PDF = "%PDF-1.4 fake bytes".b+ AUTO_MODEL = "claude-sonnet-5-5"++ HELPERS = {+ "report_categorizations" => {+ input: { "categorizations" => [ { "transaction_id" => "txn_1", "category_name" => "Fast Food" } ] },+ build: ->(client, family) {+ Provider::Anthropic::AutoCategorizer.new(client, model: AUTO_MODEL, family: family,+ transactions: [ { id: "txn_1", name: "McDonalds", amount: 20 } ], user_categories: [ { id: "c1", name: "Fast Food" } ]).auto_categorize+ },+ check: ->(test, result) { test.assert_equal "Fast Food", result.first.category_name }+ },+ "report_merchants" => {+ input: { "merchants" => [ { "transaction_id" => "txn_1", "business_name" => "Amazon", "business_url" => "amazon.com" } ] },+ build: ->(client, family) {+ Provider::Anthropic::AutoMerchantDetector.new(client, model: AUTO_MODEL, family: family,+ transactions: [ { id: "txn_1", name: "AMZN" } ], user_merchants: []).auto_detect_merchants+ },+ check: ->(test, result) { test.assert_equal "Amazon", result.first.business_name }+ },+ "report_enhancements" => {+ input: { "merchants" => [ { "merchant_id" => "m1", "business_url" => "walmart.com" } ] },+ build: ->(client, family) {+ Provider::Anthropic::ProviderMerchantEnhancer.new(client, model: AUTO_MODEL, family: family,+ merchants: [ { id: "m1", name: "Walmart" } ]).enhance_merchants+ },+ check: ->(test, result) { test.assert_equal "walmart.com", result.first.business_url }+ },+ "report_bill_setup" => {+ input: { "name" => "Netflix", "amount" => 15.49, "frequency" => "monthly", "day_of_month" => 3,+ "category_name" => "Subscriptions", "bill_type" => "subscription", "confidence" => 0.9 },+ build: ->(client, family) {+ Provider::Anthropic::BillSetupSuggester.new(client, model: AUTO_MODEL, family: family,+ charges: [ { date: "2026-08-03", amount: 15.49, name: "NETFLIX.COM" } ], categories: [ "Subscriptions" ]).suggest+ },+ check: ->(test, result) { test.assert_equal "Netflix", result.name }+ },+ "report_document_analysis" => {+ input: { "document_type" => "bank_statement", "summary" => "Statement" },+ build: ->(client, family) {+ Provider::Anthropic::PdfProcessor.new(client, model: AUTO_MODEL, family: family, pdf_content: PDF).process+ },+ check: ->(test, result) { test.assert_equal "Statement", result.summary }+ },+ "report_bank_statement" => {+ input: { "bank_name" => "Bank of Example", "transactions" => [ { "date" => "2026-03-05", "description" => "Coffee", "amount" => -4.5 } ] },+ build: ->(client, family) {+ Provider::Anthropic::BankStatementExtractor.new(client: client, model: AUTO_MODEL, family: family, pdf_content: PDF).extract+ },+ check: ->(test, result) { test.assert_equal 1, result[:transactions].size }+ }+ }.freeze++ setup do+ @family = families(:dylan_family)+ end++ HELPERS.each do |tool_name, helper|+ test "#{tool_name}: retries once after a text-only end_turn and records usage for both calls" do+ requests = []+ client = stub_client(requests, [ text_response("Looks like groceries."), tool_response(tool_name, helper[:input]) ])++ result = nil+ assert_difference -> { @family.llm_usages.count }, 2 do+ result = helper[:build].call(client, @family)+ end++ helper[:check].call(self, result)+ assert_equal 2, requests.size+ assert_equal({ type: "auto", disable_parallel_tool_use: true }, requests.last[:tool_choice])+ retry_messages = requests.last[:messages]+ assert_equal requests.first[:messages], retry_messages.first(requests.first[:messages].size)+ assert_equal [ "assistant", "user" ], retry_messages.last(2).map { |m| m[:role] }+ assert_equal "Looks like groceries.", retry_messages[-2][:content]+ assert_includes retry_messages.last[:content], tool_name+ end++ test "#{tool_name}: raises after a second missing tool call and records both billed attempts" do+ requests = []+ client = stub_client(requests, [ text_response("No."), text_response("Still no.") ])++ err = nil+ # two billed calls plus the zero-token error row the helpers always write+ assert_difference -> { @family.llm_usages.count }, 3 do+ err = assert_raises(Provider::Anthropic::Error) { helper[:build].call(client, @family) }+ end++ assert_match(/did not invoke #{tool_name} \(stop_reason: end_turn\)/, err.message)+ assert_equal 2, requests.size+ end++ test "#{tool_name}: does not retry when the first response has the tool call" do+ requests = []+ client = stub_client(requests, [ tool_response(tool_name, helper[:input]) ])++ assert_difference -> { @family.llm_usages.count }, 1 do+ helper[:build].call(client, @family)+ end++ assert_equal 1, requests.size+ end++ %w[max_tokens refusal].each do |reason|+ test "#{tool_name}: does not retry on #{reason}" do+ requests = []+ client = stub_client(requests, [ text_response("partial", stop_reason: reason) ])++ assert_raises(Provider::Anthropic::Error) { helper[:build].call(client, @family) }+ assert_equal 1, requests.size+ end+ end+ end++ test "does not retry on the forced tool path" do+ requests = []+ client = stub_client(requests, [ text_response("No.") ])++ assert_raises(Provider::Anthropic::Error) do+ Provider::Anthropic::AutoCategorizer.new(client, model: "claude-haiku-4-5", family: @family,+ transactions: [ { id: "txn_1", name: "McDonalds", amount: 20 } ], user_categories: []).auto_categorize+ end++ assert_equal 1, requests.size+ assert_equal "tool", requests.first[:tool_choice][:type]+ end++ test "the retry without any text in the first answer only adds the reminder" do+ requests = []+ response = OpenStruct.new(content: [], stop_reason: :end_turn, usage: OpenStruct.new(input_tokens: 5, output_tokens: 0))+ client = stub_client(requests, [ response, tool_response("report_categorizations", HELPERS["report_categorizations"][:input]) ])++ HELPERS["report_categorizations"][:build].call(client, @family)++ assert_equal [ "user", "user" ], requests.last[:messages].map { |m| m[:role] }+ end++ private+ def stub_client(requests, responses)+ messages = mock+ messages.stubs(:create).with { |params| requests << Marshal.load(Marshal.dump(params)); true }.returns(*responses)+ client = mock+ client.stubs(:messages).returns(messages)+ client+ end++ def text_response(text, stop_reason: "end_turn")+ OpenStruct.new(content: [ OpenStruct.new(type: :text, text: text) ], stop_reason: stop_reason, usage: usage)+ end++ def tool_response(name, input)+ OpenStruct.new(content: [ OpenStruct.new(type: :tool_use, id: "toolu_1", name: name, input: input) ], stop_reason: "tool_use", usage: usage)+ end++ def usage+ OpenStruct.new(input_tokens: 50, output_tokens: 25)+ end+end