Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Send tool_choice auto to Claude models that reject a forced tool (#4178)

alexcastgonzf0277fe73f82
diff --git a/app/models/provider/anthropic.rb b/app/models/provider/anthropic.rb
index d827d97385..b52073cac7 100644
--- a/app/models/provider/anthropic.rb
+++ b/app/models/provider/anthropic.rb
@@ -11,6 +11,36 @@ class Provider::Anthropic < Provider
# All Claude 3.5+ and 4.x models accept native document content blocks.
VISION_CAPABLE_MODEL_PREFIXES = %w[claude].freeze
+ # Claude 3.x, 4.x and Haiku 5.5 accept a forced `tool_choice`. Anything else
+ # gets `auto` (Opus 5.5, Sonnet 5.5, Fable 5.1 and Mythos 5.1 reject a forced
+ # one), so a model released after this line still works. Matches anywhere in
+ # the ID to cover Bedrock (`anthropic.claude-sonnet-4-5-…-v1:0`) and Vertex
+ # (`claude-sonnet-4-5@…`) IDs.
+ FORCED_TOOL_CHOICE_MODELS = /claude-(?:3|(?:opus|sonnet|haiku)-4|haiku-5[-.]5)(?!\d)/
+
+ def self.forced_tool_choice_supported?(model)
+ model.to_s.match?(FORCED_TOOL_CHOICE_MODELS)
+ end
+
+ # The tool_choice for a helper that returns its result through a single tool.
+ # Models that can't be forced get `auto`, paired with structured_output_system.
+ def self.structured_output_tool_choice(model, tool_name)
+ if forced_tool_choice_supported?(model)
+ { type: "tool", name: tool_name, disable_parallel_tool_use: true }
+ else
+ { type: "auto", disable_parallel_tool_use: true }
+ end
+ end
+
+ # The system prompt for a helper that returns its result through a single tool.
+ # With `auto`, a family's prompt override may not mention the tool, so a fixed
+ # instruction to call it is appended.
+ def self.structured_output_system(instructions, model, tool_name)
+ return instructions if forced_tool_choice_supported?(model)
+
+ "#{instructions}\n\nReturn the result by calling the #{tool_name} tool. Do not answer with text."
+ end
+
def self.effective_model
# Use ENV[].presence rather than ENV.fetch(KEY, default) so the Setting
# lookup is only performed when the ENV var is actually absent — otherwise
diff --git a/app/models/provider/anthropic/auto_categorizer.rb b/app/models/provider/anthropic/auto_categorizer.rb
index abc7ead34e..ccf9a1aa81 100644
--- a/app/models/provider/anthropic/auto_categorizer.rb
+++ b/app/models/provider/anthropic/auto_categorizer.rb
@@ -24,10 +24,10 @@ class Provider::Anthropic::AutoCategorizer
response = client.messages.create(
model: model,
max_tokens: max_tokens,
- system_: instructions,
+ system_: Provider::Anthropic.structured_output_system(instructions, model, TOOL_NAME),
messages: [ { role: "user", content: user_message } ],
tools: [ output_tool ],
- tool_choice: { type: "tool", name: TOOL_NAME, disable_parallel_tool_use: true }
+ tool_choice: Provider::Anthropic.structured_output_tool_choice(model, TOOL_NAME)
)
categorizations = extract_categorizations(response)
@@ -136,7 +136,7 @@ class Provider::Anthropic::AutoCategorizer
def extract_categorizations(response)
tool_use = Array(response.content).find { |block| block_type(block) == :tool_use }
- raise Provider::Anthropic::Error, "Model did not invoke #{TOOL_NAME}" unless 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 = JSON.parse(input) if input.is_a?(String)
diff --git a/app/models/provider/anthropic/auto_merchant_detector.rb b/app/models/provider/anthropic/auto_merchant_detector.rb
index 9674c18aeb..c958a3ef32 100644
--- a/app/models/provider/anthropic/auto_merchant_detector.rb
+++ b/app/models/provider/anthropic/auto_merchant_detector.rb
@@ -24,10 +24,10 @@ class Provider::Anthropic::AutoMerchantDetector
response = client.messages.create(
model: model,
max_tokens: max_tokens,
- system_: instructions,
+ system_: Provider::Anthropic.structured_output_system(instructions, model, TOOL_NAME),
messages: [ { role: "user", content: user_message } ],
tools: [ output_tool ],
- tool_choice: { type: "tool", name: TOOL_NAME, disable_parallel_tool_use: true }
+ tool_choice: Provider::Anthropic.structured_output_tool_choice(model, TOOL_NAME)
)
merchants_data = extract_merchants(response)
@@ -138,7 +138,7 @@ class Provider::Anthropic::AutoMerchantDetector
def extract_merchants(response)
tool_use = Array(response.content).find { |block| block_type(block) == :tool_use }
- raise Provider::Anthropic::Error, "Model did not invoke #{TOOL_NAME}" unless 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 = JSON.parse(input) if input.is_a?(String)
diff --git a/app/models/provider/anthropic/bank_statement_extractor.rb b/app/models/provider/anthropic/bank_statement_extractor.rb
index e91d44b47b..acc62a92d4 100644
--- a/app/models/provider/anthropic/bank_statement_extractor.rb
+++ b/app/models/provider/anthropic/bank_statement_extractor.rb
@@ -31,10 +31,10 @@ class Provider::Anthropic::BankStatementExtractor
response = client.messages.create(
model: model,
max_tokens: max_tokens,
- system_: instructions,
+ system_: Provider::Anthropic.structured_output_system(instructions, model, TOOL_NAME),
messages: [ { role: "user", content: user_content } ],
tools: [ output_tool ],
- tool_choice: { type: "tool", name: TOOL_NAME, disable_parallel_tool_use: true }
+ tool_choice: Provider::Anthropic.structured_output_tool_choice(model, TOOL_NAME)
)
parsed = extract_tool_input(response)
@@ -148,7 +148,7 @@ class Provider::Anthropic::BankStatementExtractor
def extract_tool_input(response)
tool_use = Array(response.content).find { |block| block_type(block) == :tool_use }
- raise Provider::Anthropic::Error, "Model did not invoke #{TOOL_NAME}" unless 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 = JSON.parse(input) if input.is_a?(String)
diff --git a/app/models/provider/anthropic/bill_setup_suggester.rb b/app/models/provider/anthropic/bill_setup_suggester.rb
index 801f09429f..b5ce43f38d 100644
--- a/app/models/provider/anthropic/bill_setup_suggester.rb
+++ b/app/models/provider/anthropic/bill_setup_suggester.rb
@@ -25,10 +25,10 @@ class Provider::Anthropic::BillSetupSuggester
response = client.messages.create(
model: model,
max_tokens: max_tokens,
- system_: instructions,
+ system_: Provider::Anthropic.structured_output_system(instructions, model, TOOL_NAME),
messages: [ { role: "user", content: user_message } ],
tools: [ output_tool ],
- tool_choice: { type: "tool", name: TOOL_NAME, disable_parallel_tool_use: true }
+ tool_choice: Provider::Anthropic.structured_output_tool_choice(model, TOOL_NAME)
)
result = build_suggestion(extract_input(response))
@@ -128,7 +128,7 @@ class Provider::Anthropic::BillSetupSuggester
def extract_input(response)
tool_use = Array(response.content).find { |block| block_type(block) == :tool_use }
- raise Provider::Anthropic::Error, "Model did not invoke #{TOOL_NAME}" unless 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 = JSON.parse(input) if input.is_a?(String)
diff --git a/app/models/provider/anthropic/pdf_processor.rb b/app/models/provider/anthropic/pdf_processor.rb
index b19d920266..aaceb71891 100644
--- a/app/models/provider/anthropic/pdf_processor.rb
+++ b/app/models/provider/anthropic/pdf_processor.rb
@@ -39,10 +39,10 @@ class Provider::Anthropic::PdfProcessor
response = client.messages.create(
model: model,
max_tokens: max_tokens,
- system_: instructions,
+ system_: Provider::Anthropic.structured_output_system(instructions, model, TOOL_NAME),
messages: [ { role: "user", content: user_content } ],
tools: [ output_tool ],
- tool_choice: { type: "tool", name: TOOL_NAME, disable_parallel_tool_use: true }
+ tool_choice: Provider::Anthropic.structured_output_tool_choice(model, TOOL_NAME)
)
parsed = extract_tool_input(response)
@@ -145,7 +145,7 @@ class Provider::Anthropic::PdfProcessor
def extract_tool_input(response)
tool_use = Array(response.content).find { |block| block_type(block) == :tool_use }
- raise Provider::Anthropic::Error, "Model did not invoke #{TOOL_NAME}" unless 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 = JSON.parse(input) if input.is_a?(String)
diff --git a/app/models/provider/anthropic/provider_merchant_enhancer.rb b/app/models/provider/anthropic/provider_merchant_enhancer.rb
index 1a74604ed5..4ee94740a1 100644
--- a/app/models/provider/anthropic/provider_merchant_enhancer.rb
+++ b/app/models/provider/anthropic/provider_merchant_enhancer.rb
@@ -22,10 +22,10 @@ class Provider::Anthropic::ProviderMerchantEnhancer
response = client.messages.create(
model: model,
max_tokens: max_tokens,
- system_: instructions,
+ system_: Provider::Anthropic.structured_output_system(instructions, model, TOOL_NAME),
messages: [ { role: "user", content: user_message } ],
tools: [ output_tool ],
- tool_choice: { type: "tool", name: TOOL_NAME, disable_parallel_tool_use: true }
+ tool_choice: Provider::Anthropic.structured_output_tool_choice(model, TOOL_NAME)
)
enhanced = extract_enhancements(response)
@@ -108,7 +108,7 @@ class Provider::Anthropic::ProviderMerchantEnhancer
def extract_enhancements(response)
tool_use = Array(response.content).find { |block| block_type(block) == :tool_use }
- raise Provider::Anthropic::Error, "Model did not invoke #{TOOL_NAME}" unless 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 = JSON.parse(input) if input.is_a?(String)
diff --git a/docs/hosting/ai.md b/docs/hosting/ai.md
index 4ab4608e56..3491f90e21 100644
--- a/docs/hosting/ai.md
+++ b/docs/hosting/ai.md
@@ -188,7 +188,7 @@ Or in the UI: **Settings** → **Self-Hosting** → **AI Provider** → **Anthro
|----------|---------|--------------|
| `LLM_PROVIDER` | `openai` | `anthropic` selects this provider. If the selected provider has no key, Sure uses the other one. While a custom OpenAI-compatible provider is configured (`OPENAI_URI_BASE` with an access token and model), chat still goes to it, so remove those settings when switching. |
| `ANTHROPIC_API_KEY` | — | API key. `ANTHROPIC_ACCESS_TOKEN` also works and wins if both are set. |
-| `ANTHROPIC_MODEL` | `claude-sonnet-4-6` | Model for chat and all background jobs. Must start with `claude` unless a base URL is set. Claude Opus 5.5, Sonnet 5.5 and Fable 5.1 work for chat only until [#4125](https://github.com/we-promise/sure/issues/4125) is fixed. |
+| `ANTHROPIC_MODEL` | `claude-sonnet-4-6` | Model for chat and all background jobs. Must start with `claude` unless a base URL is set. |
| `ANTHROPIC_MAX_TOKENS` | `4096` | Reply limit, sent with every request (the Messages API requires one). |
| `ANTHROPIC_REQUEST_TIMEOUT` | `600` | HTTP timeout per call, in seconds. |
| `ANTHROPIC_BASE_URL` | `https://api.anthropic.com` | Anthropic-compatible endpoint. Requires `ANTHROPIC_MODEL`. |
@@ -199,7 +199,7 @@ How it differs from the OpenAI-compatible provider:
- **Every provider:** below `4096`, the chat's system prompt lists accounts and categories only as counts, and the model fetches them with tools.
- **OpenAI-compatible:** it is also the budget, with `LLM_MAX_RESPONSE_TOKENS` and `LLM_SYSTEM_PROMPT_RESERVE`, for splitting auto-categorization and merchant batches, and for trimming chat history on Chat Completions endpoints (`LLM_MAX_HISTORY_TOKENS`). The native OpenAI Responses API keeps history on OpenAI's side, so nothing is trimmed there.
- **Native Anthropic:** only the system-prompt check applies. History is sent whole, batches aren't split, and `LLM_MAX_RESPONSE_TOKENS`, `LLM_MAX_HISTORY_TOKENS` and `LLM_SYSTEM_PROMPT_RESERVE` are ignored. Set `LLM_CONTEXT_WINDOW` by env (e.g. `200000`) so the prompt lists accounts and categories; its UI field is in the OpenAI panel.
-- **The reply limit is always sent.** A reply that needs more than `ANTHROPIC_MAX_TOKENS` is cut off. Only bank statement extraction detects this (it logs a warning). Raise the limit if long answers or batch results come back incomplete.
+- **The reply limit is always sent.** A reply that needs more than `ANTHROPIC_MAX_TOKENS` is cut off, and on Claude 5 models the model's thinking counts toward it. Only bank statement extraction detects this (it logs a warning). Raise the limit if long answers or batch results come back incomplete.
- **Batch size.** Auto-categorization, merchant detection and merchant enhancement send `LLM_MAX_ITEMS_PER_CALL` items per request (default `25`), with no splitting to fit the context window. Raise `ANTHROPIC_MAX_TOKENS` along with it, or replies are cut off (see [Where AI jobs run](#where-ai-jobs-run-sidekiq-lanes)).
- **Its own timeout.** `ANTHROPIC_REQUEST_TIMEOUT` replaces `OPENAI_REQUEST_TIMEOUT`. `AI_RESPONSE_TIMEOUT` still covers the whole chat turn. `OPENAI_EXTRA_HEADERS`, `LLM_JSON_MODE` and `OPENAI_SUPPORTS_*` don't apply.
diff --git a/test/models/provider/anthropic/auto_categorizer_test.rb b/test/models/provider/anthropic/auto_categorizer_test.rb
index 647bc76215..5da3f3cb9d 100644
--- a/test/models/provider/anthropic/auto_categorizer_test.rb
+++ b/test/models/provider/anthropic/auto_categorizer_test.rb
@@ -49,6 +49,29 @@ class Provider::Anthropic::AutoCategorizerTest < ActiveSupport::TestCase
assert_equal "Subscriptions", result.find { |r| r.transaction_id == "txn_2" }.category_name
end
+ test "sends tool_choice auto to a model that rejects a forced tool" do
+ fake_response = build_response(content: [
+ tool_use_block(
+ id: "toolu_3",
+ name: "report_categorizations",
+ input: { "categorizations" => [ { "transaction_id" => "txn_1", "category_name" => "Fast Food" } ] }
+ )
+ ])
+ client = stub_client(fake_response, expect_request: ->(params) {
+ assert_equal({ type: "auto", disable_parallel_tool_use: true }, params[:tool_choice])
+ assert_includes params[:system_], "calling the report_categorizations tool"
+ })
+
+ result = Provider::Anthropic::AutoCategorizer.new(
+ client,
+ model: "claude-sonnet-5-5",
+ transactions: @transactions,
+ user_categories: @user_categories
+ ).auto_categorize
+
+ assert_equal "Fast Food", result.find { |r| r.transaction_id == "txn_1" }.category_name
+ end
+
test "normalizes null category names to nil" do
fake_response = build_response(content: [
tool_use_block(
diff --git a/test/models/provider/anthropic/auto_merchant_detector_test.rb b/test/models/provider/anthropic/auto_merchant_detector_test.rb
index c9af1db6df..58d65b3e97 100644
--- a/test/models/provider/anthropic/auto_merchant_detector_test.rb
+++ b/test/models/provider/anthropic/auto_merchant_detector_test.rb
@@ -85,6 +85,29 @@ class Provider::Anthropic::AutoMerchantDetectorTest < ActiveSupport::TestCase
assert_match(/did not invoke report_merchants/i, err.message)
end
+ test "sends tool_choice auto to a model that rejects a forced tool" do
+ fake_response = build_response(content: [
+ tool_use_block(
+ id: "toolu_3",
+ name: "report_merchants",
+ input: { "merchants" => [ { "transaction_id" => "txn_1", "business_name" => "Amazon", "business_url" => "amazon.com" } ] }
+ )
+ ])
+ client = stub_client(fake_response, expect_request: ->(params) {
+ assert_equal({ type: "auto", disable_parallel_tool_use: true }, params[:tool_choice])
+ assert_includes params[:system_], "calling the report_merchants tool"
+ })
+
+ result = Provider::Anthropic::AutoMerchantDetector.new(
+ client,
+ model: "claude-sonnet-5-5",
+ transactions: @transactions,
+ user_merchants: @user_merchants
+ ).auto_detect_merchants
+
+ assert_equal "Amazon", result.find { |r| r.transaction_id == "txn_1" }.business_name
+ end
+
private
def stub_client(response, expect_request: nil)
messages = mock
diff --git a/test/models/provider/anthropic/bank_statement_extractor_test.rb b/test/models/provider/anthropic/bank_statement_extractor_test.rb
index 2032462219..3a75c4fb0c 100644
--- a/test/models/provider/anthropic/bank_statement_extractor_test.rb
+++ b/test/models/provider/anthropic/bank_statement_extractor_test.rb
@@ -117,6 +117,36 @@ class Provider::Anthropic::BankStatementExtractorTest < ActiveSupport::TestCase
assert_equal true, result[:truncated]
end
+ test "sends tool_choice auto to a model that rejects a forced tool" do
+ fake_response = build_response(content: [
+ tool_use_block(
+ id: "toolu_4",
+ name: "report_bank_statement",
+ input: {
+ "bank_name" => "Bank of Example",
+ "transactions" => [ { "date" => "2026-03-05", "description" => "Coffee", "amount" => -4.5 } ]
+ }
+ )
+ ])
+ messages = mock
+ messages.expects(:create).with do |params|
+ assert_equal({ type: "auto", disable_parallel_tool_use: true }, params[:tool_choice])
+ assert_includes params[:system_], "calling the report_bank_statement tool"
+ true
+ end.returns(fake_response)
+ client = mock
+ client.stubs(:messages).returns(messages)
+
+ result = Provider::Anthropic::BankStatementExtractor.new(
+ client: client,
+ model: "claude-sonnet-5-5",
+ pdf_content: @pdf_content
+ ).extract
+
+ assert_equal "Bank of Example", result[:bank_name]
+ assert_equal "Coffee", result[:transactions].first[:name]
+ end
+
private
def stub_client(response)
messages = mock
diff --git a/test/models/provider/anthropic/bill_setup_suggester_test.rb b/test/models/provider/anthropic/bill_setup_suggester_test.rb
new file mode 100644
index 0000000000..2fbed5616f
--- /dev/null
+++ b/test/models/provider/anthropic/bill_setup_suggester_test.rb
@@ -0,0 +1,107 @@
+require "test_helper"
+require "ostruct"
+
+class Provider::Anthropic::BillSetupSuggesterTest < ActiveSupport::TestCase
+ setup do
+ @charges = [
+ { date: "2026-08-03", amount: 15.49, name: "NETFLIX.COM" },
+ { date: "2026-09-03", amount: 15.49, name: "NETFLIX.COM" }
+ ]
+ @categories = [ "Subscriptions", "Utilities" ]
+ end
+
+ test "issues a forced tool call and maps the suggestion" do
+ client = stub_client(build_response(content: [ suggestion_block ]), expect_request: ->(params) {
+ assert_equal "claude-haiku-4-5", params[:model]
+ assert_equal({ type: "tool", name: "report_bill_setup", disable_parallel_tool_use: true }, params[:tool_choice])
+ assert_equal "report_bill_setup", params[:tools].first[:name]
+ assert_not_includes params[:system_], "Do not answer with text."
+ })
+
+ result = suggester(client, model: "claude-haiku-4-5").suggest
+
+ assert_suggestion result
+ end
+
+ test "sends tool_choice auto to a model that rejects a forced tool" do
+ client = stub_client(build_response(content: [ suggestion_block ]), expect_request: ->(params) {
+ assert_equal({ type: "auto", disable_parallel_tool_use: true }, params[:tool_choice])
+ assert_includes params[:system_], "calling the report_bill_setup tool"
+ })
+
+ result = suggester(client, model: "claude-sonnet-5-5").suggest
+
+ assert_suggestion result
+ end
+
+ test "raises with the stop reason when the model returns no tool_use" do
+ response = build_response(content: [ OpenStruct.new(type: :text, text: "Looks monthly.") ])
+ response.stop_reason = :end_turn
+
+ err = assert_raises(Provider::Anthropic::Error) do
+ suggester(stub_client(response), model: "claude-sonnet-5-5").suggest
+ end
+
+ assert_match(/did not invoke report_bill_setup \(stop_reason: end_turn\)/, err.message)
+ end
+
+ private
+ def suggester(client, model:)
+ Provider::Anthropic::BillSetupSuggester.new(client, model: model, charges: @charges, categories: @categories)
+ end
+
+ def assert_suggestion(result)
+ assert_equal "Netflix", result.name
+ assert_equal 15.49, result.amount
+ assert_equal "monthly", result.frequency
+ assert_equal 3, result.day_of_month
+ assert_equal "Subscriptions", result.category_name
+ assert_equal "subscription", result.bill_type
+ assert_nil result.autopay
+ end
+
+ def suggestion_block
+ OpenStruct.new(
+ type: :tool_use,
+ id: "toolu_1",
+ name: "report_bill_setup",
+ input: {
+ "name" => "Netflix",
+ "amount" => 15.49,
+ "frequency" => "monthly",
+ "day_of_month" => 3,
+ "weekday" => nil,
+ "month_of_year" => nil,
+ "category_name" => "Subscriptions",
+ "bill_type" => "subscription",
+ "autopay" => nil,
+ "confidence" => 0.9,
+ "rationale" => "Same charge on the 3rd of each month."
+ }
+ )
+ end
+
+ def stub_client(response, expect_request: nil)
+ messages = mock
+ if expect_request
+ messages.expects(:create).with do |params|
+ expect_request.call(params)
+ true
+ end.returns(response)
+ else
+ messages.stubs(:create).returns(response)
+ end
+ client = mock
+ client.stubs(:messages).returns(messages)
+ client
+ end
+
+ def build_response(content:)
+ OpenStruct.new(
+ id: "msg_test",
+ model: "claude-haiku-4-5",
+ content: content,
+ usage: OpenStruct.new(input_tokens: 120, output_tokens: 60)
+ )
+ end
+end
diff --git a/test/models/provider/anthropic/pdf_processor_test.rb b/test/models/provider/anthropic/pdf_processor_test.rb
index 2b807d1795..2be3e32eee 100644
--- a/test/models/provider/anthropic/pdf_processor_test.rb
+++ b/test/models/provider/anthropic/pdf_processor_test.rb
@@ -166,6 +166,28 @@ class Provider::Anthropic::PdfProcessorTest < ActiveSupport::TestCase
assert_match(/detail unavailable/i, captured_output[:error_detail])
end
+ test "sends tool_choice auto to a model that rejects a forced tool" do
+ fake_response = build_response(content: [
+ tool_use_block(
+ id: "toolu_4",
+ name: "report_document_analysis",
+ input: { "document_type" => "bank_statement", "summary" => "Statement.", "extracted_data" => {} }
+ )
+ ])
+ captured = nil
+ client = stub_client(fake_response) { |params| captured = params }
+
+ result = Provider::Anthropic::PdfProcessor.new(
+ client,
+ model: "claude-sonnet-5-5",
+ pdf_content: @pdf_content
+ ).process
+
+ assert_equal({ type: "auto", disable_parallel_tool_use: true }, captured[:tool_choice])
+ assert_includes captured[:system_], "calling the report_document_analysis tool"
+ assert_equal "bank_statement", result.document_type
+ end
+
private
def stub_failing_client(error)
messages = mock
diff --git a/test/models/provider/anthropic/provider_merchant_enhancer_test.rb b/test/models/provider/anthropic/provider_merchant_enhancer_test.rb
index 89ef088d46..1572f96db5 100644
--- a/test/models/provider/anthropic/provider_merchant_enhancer_test.rb
+++ b/test/models/provider/anthropic/provider_merchant_enhancer_test.rb
@@ -51,6 +51,28 @@ class Provider::Anthropic::ProviderMerchantEnhancerTest < ActiveSupport::TestCas
assert_match(/did not invoke report_enhancements/i, err.message)
end
+ test "sends tool_choice auto to a model that rejects a forced tool" do
+ fake_response = build_response(content: [
+ tool_use_block(
+ id: "toolu_3",
+ name: "report_enhancements",
+ input: { "merchants" => [ { "merchant_id" => "m1", "business_url" => "walmart.com" } ] }
+ )
+ ])
+ client = stub_client(fake_response, expect_request: ->(params) {
+ assert_equal({ type: "auto", disable_parallel_tool_use: true }, params[:tool_choice])
+ assert_includes params[:system_], "calling the report_enhancements tool"
+ })
+
+ result = Provider::Anthropic::ProviderMerchantEnhancer.new(
+ client,
+ model: "claude-sonnet-5-5",
+ merchants: @merchants
+ ).enhance_merchants
+
+ assert_equal "walmart.com", result.find { |r| r.merchant_id == "m1" }.business_url
+ end
+
private
def stub_client(response, expect_request: nil)
messages = mock
diff --git a/test/models/provider/anthropic_test.rb b/test/models/provider/anthropic_test.rb
index 26d8945660..26898026ad 100644
--- a/test/models/provider/anthropic_test.rb
+++ b/test/models/provider/anthropic_test.rb
@@ -25,6 +25,41 @@ class Provider::AnthropicTest < ActiveSupport::TestCase
assert_equal "Custom Anthropic-compatible (https://bedrock.example.com/anthropic)", custom.provider_name
end
+ test "structured_output_tool_choice forces the tool on models that accept it" do
+ %w[
+ claude-sonnet-4-6 claude-haiku-4-5 claude-haiku-5-5 claude-opus-4-8 claude-3-7-sonnet-20250219
+ claude-sonnet-4-20250514 anthropic.claude-sonnet-4-5-20250929-v1:0 claude-sonnet-4-5@20250929
+ anthropic/claude-sonnet-4.5 anthropic/claude-haiku-5.5
+ ].each do |model|
+ assert_equal(
+ { type: "tool", name: "report", disable_parallel_tool_use: true },
+ Provider::Anthropic.structured_output_tool_choice(model, "report"),
+ model
+ )
+ end
+ end
+
+ test "structured_output_tool_choice sends auto to every other model" do
+ %w[
+ claude-opus-5-5 claude-sonnet-5-5 claude-fable-5-1 claude-mythos-5-1 claude-opus-5 claude-opus-5-6
+ claude-opus-6 claude-haiku-5-6 claude-haiku-6 us.anthropic.claude-sonnet-5-5-v1:0
+ ].each do |model|
+ assert_equal(
+ { type: "auto", disable_parallel_tool_use: true },
+ Provider::Anthropic.structured_output_tool_choice(model, "report"),
+ model
+ )
+ end
+ end
+
+ test "structured_output_system adds a tool instruction only where tool_choice is auto" do
+ assert_equal "Custom prompt", Provider::Anthropic.structured_output_system("Custom prompt", "claude-sonnet-4-6", "report")
+
+ system = Provider::Anthropic.structured_output_system("Custom prompt", "claude-sonnet-5-5", "report")
+ assert system.start_with?("Custom prompt\n\n")
+ assert_includes system, "calling the report tool"
+ end
+
test "supports_model? returns true for claude prefix" do
assert @subject.supports_model?("claude-sonnet-4-6")
assert @subject.supports_model?("claude-opus-4-7")