The personal finance app for everyone (by everyone)
Ruby
fix(ai): replay each in-flight tool round as its own message pair (#4133)
Josh Sanders577d32bc4685
diff --git a/app/models/assistant/responder.rb b/app/models/assistant/responder.rbindex 15a0e797f3..b2f72b9211 100644--- a/app/models/assistant/responder.rb+++ b/app/models/assistant/responder.rb@@ -7,6 +7,15 @@ class Assistant::Responder# ASSISTANT_MAX_TOOL_CALL_ITERATIONS (low-resource hosts may want 2).DEFAULT_MAX_TOOL_CALL_ITERATIONS = 8+ # Splits in-flight function results into tool rounds, in order. #respond+ # tags each result with the :round that produced it; providers that rebuild+ # the in-flight history replay one tool-call message plus its results per+ # round, so every follow-up request extends the previous one instead of+ # rewriting it. Results without a :round tag form a single round.+ def self.group_by_round(function_results)+ function_results.chunk_while { |a, b| a[:round] == b[:round] }.to_a+ end+def initialize(message:, instructions:, function_tool_caller:, llm:)@message = message@instructions = instructions@@ -33,7 +42,8 @@ class Assistant::Responderfunction_tool_calls = function_tool_caller.fulfill_requests(response.function_requests)function_results = function_tool_calls.map(&:to_result)- in_flight_function_results.concat(function_results)+ # Tag each result with its round; see .group_by_round.+ in_flight_function_results.concat(function_results.map { |result| result.merge(round: iteration) })emit(:response, {id: response.id,diff --git a/app/models/provider/anthropic/message_formatter.rb b/app/models/provider/anthropic/message_formatter.rbindex 7c697368c1..97c6955ef5 100644--- a/app/models/provider/anthropic/message_formatter.rb+++ b/app/models/provider/anthropic/message_formatter.rb@@ -7,7 +7,7 @@ class Provider::Anthropic::MessageFormatter# the current user message (UserMessage / AssistantMessage)# - function_results: tool-result entries for the in-flight follow-up call# (the responder feeds these back after executing the tool_use blocks- # returned by the previous request)+ # returned by the previous requests, tagging each with its :round)def initialize(prompt:, conversation_history: [], function_results: [])@prompt = prompt@conversation_history = conversation_history@@ -28,12 +28,12 @@ class Provider::Anthropic::MessageFormattermessages << { role: "user", content: @prompt.to_s }- if @function_results.present?- tool_use_blocks = @function_results.map { |fr| tool_use_block_from_result(fr) }- tool_result_blocks = @function_results.map { |fr| tool_result_block(fr) }-- messages << { role: "assistant", content: tool_use_blocks }- messages << { role: "user", content: tool_result_blocks }+ # One assistant tool_use turn plus its user tool_result turn per round, in+ # order, so each follow-up request extends the previous one and prompt+ # caching keeps working.+ Assistant::Responder.group_by_round(@function_results).each do |round_results|+ messages << { role: "assistant", content: round_results.map { |fr| tool_use_block_from_result(fr) } }+ messages << { role: "user", content: round_results.map { |fr| tool_result_block(fr) } }endmessagesdiff --git a/app/models/provider/openai.rb b/app/models/provider/openai.rbindex d4f103e5c2..752825225d 100644--- a/app/models/provider/openai.rb+++ b/app/models/provider/openai.rb@@ -684,11 +684,12 @@ class Provider::Openai < Providerpayload << { role: "user", content: prompt }end- # If there are function results, we need to add the assistant message that made the tool calls- # followed by the tool messages with the results- if function_results.any?+ # For each tool round, add the assistant message that made the tool calls+ # followed by the tool messages with the results, in order, so each+ # follow-up request extends the previous one and prefix caches stay valid.+ Assistant::Responder.group_by_round(function_results).each do |round_results|# Build assistant message with tool_calls- tool_calls = function_results.map do |fn_result|+ tool_calls = round_results.map do |fn_result|# Shared with ToolCall::Function.serialize_arguments so history and# follow-up payloads stay in sync for strict OpenAI-compatible endpoints.arguments_str = ToolCall::Function.serialize_arguments(fn_result[:arguments])@@ -712,7 +713,7 @@ class Provider::Openai < Provider}# Add function results as tool messages- function_results.each do |fn_result|+ round_results.each do |fn_result|# Convert output to JSON string if it's not already a string# OpenAI API requires content to be either a string or array of objects# Handle nil explicitly to avoid serializing to "null"diff --git a/test/models/assistant/responder_test.rb b/test/models/assistant/responder_test.rbindex c3f1d90225..5eb5141c6f 100644--- a/test/models/assistant/responder_test.rb+++ b/test/models/assistant/responder_test.rb@@ -26,6 +26,17 @@ class Assistant::ResponderTest < ActiveSupport::TestCase)end+ test "group_by_round splits consecutive results by round and keeps untagged results together" do+ a = { call_id: "a", round: 1 }+ b = { call_id: "b", round: 2 }+ c = { call_id: "c", round: 2 }++ assert_equal [ [ a ], [ b, c ] ], Assistant::Responder.group_by_round([ a, b, c ])+ assert_equal [ [ { call_id: "x" }, { call_id: "y" } ] ],+ Assistant::Responder.group_by_round([ { call_id: "x" }, { call_id: "y" } ])+ assert_equal [], Assistant::Responder.group_by_round([])+ end+test "default iteration cap is eight rounds" doassert_equal 8, Assistant::Responder::DEFAULT_MAX_TOOL_CALL_ITERATIONSenddiff --git a/test/models/assistant_test.rb b/test/models/assistant_test.rbindex add92aca21..8e828f26f5 100644--- a/test/models/assistant_test.rb+++ b/test/models/assistant_test.rb@@ -213,7 +213,8 @@ class AssistantTest < ActiveSupport::TestCase[ first_tools ],[ second_tools ],[ final_text, final_response ],- expected_function_result_ids: [ [], [ "1" ], [ "1", "2", "3" ] ]+ expected_function_result_ids: [ [], [ "1" ], [ "1", "2", "3" ] ],+ expected_function_result_rounds: [ [], [ 1 ], [ 1, 2, 2 ] ])assert_difference "AssistantMessage.count", 1 do@@ -710,9 +711,10 @@ class AssistantTest < ActiveSupport::TestCase)end- def expect_provider_rounds(*rounds, expected_function_result_ids: nil)+ def expect_provider_rounds(*rounds, expected_function_result_ids: nil, expected_function_result_rounds: nil)queued_rounds = rounds.dupqueued_result_ids = expected_function_result_ids&.dup+ queued_result_rounds = expected_function_result_rounds&.dupresponses = rounds.map do |chunks|response_chunk = chunks.find { |chunk| chunk.type == "response" }provider_success_response(response_chunk.data)@@ -725,6 +727,9 @@ class AssistantTest < ActiveSupport::TestCaseif queued_result_idsassert_equal queued_result_ids.shift, options[:function_results].map { |result| result[:call_id] }end+ if queued_result_rounds+ assert_equal queued_result_rounds.shift, options[:function_results].map { |result| result[:round] }+ endchunks = queued_rounds.shiftchunks.each { |chunk| options[:streamer].call(chunk) }truediff --git a/test/models/provider/anthropic/message_formatter_test.rb b/test/models/provider/anthropic/message_formatter_test.rbindex 88a7d20e92..967a2411dd 100644--- a/test/models/provider/anthropic/message_formatter_test.rb+++ b/test/models/provider/anthropic/message_formatter_test.rb@@ -86,6 +86,31 @@ class Provider::Anthropic::MessageFormatterTest < ActiveSupport::TestCaseassert_includes messages[2][:content].first[:content], "99"end+ test "renders each in-flight tool round as its own tool_use + tool_result pair" do+ round_1 = [+ { call_id: "toolu_a", name: "get_accounts", arguments: "{}", output: { "accounts" => [] }, round: 1 }+ ]+ round_2 = [+ { call_id: "toolu_b", name: "get_categories", arguments: "{}", output: { "categories" => [] }, round: 2 },+ { call_id: "toolu_c", name: "get_tags", arguments: "{}", output: { "tags" => [] }, round: 2 }+ ]++ build = ->(function_results) do+ Provider::Anthropic::MessageFormatter.new(prompt: "hi", function_results: function_results).build+ end+ second_request = build.call(round_1)+ third_request = build.call(round_1 + round_2)++ # Each follow-up request must extend the previous one so prompt caching stays valid.+ assert_equal second_request, third_request.first(second_request.size)++ assert_equal %w[user assistant user assistant user], third_request.map { |m| m[:role] }+ assert_equal [ "toolu_a" ], third_request[1][:content].map { |b| b[:id] }+ assert_equal [ "toolu_a" ], third_request[2][:content].map { |b| b[:tool_use_id] }+ assert_equal [ "toolu_b", "toolu_c" ], third_request[3][:content].map { |b| b[:id] }+ assert_equal [ "toolu_b", "toolu_c" ], third_request[4][:content].map { |b| b[:tool_use_id] }+ end+# Confirms the round-trip flagged in PR #1983 review: an Anthropic tool_use# block returned by the model → ChatFunctionRequest → ToolCall::Function# persisted on the AssistantMessage → MessageFormatter rebuild on the nextdiff --git a/test/models/provider/openai_test.rb b/test/models/provider/openai_test.rbindex ffbf1bb01d..9f44f10830 100644--- a/test/models/provider/openai_test.rb+++ b/test/models/provider/openai_test.rb@@ -981,6 +981,42 @@ class Provider::OpenaiTest < ActiveSupport::TestCaseassert_not_includes tool_call.keys, :extra_contentend+ test "build_generic_messages replays each tool round as its own assistant/tool pair" do+ provider = Provider::Openai.new(+ "test-token",+ uri_base: "https://example.com/v1",+ model: "test-model"+ )++ extra = { "google" => { "thought_signature" => "sig_round_2" } }+ round_1 = [+ { call_id: "call_a", name: "get_accounts", arguments: "{}", output: { "accounts" => [] }, round: 1 }+ ]+ round_2 = [+ { call_id: "call_b", name: "get_categories", arguments: "{}", output: { "categories" => [] }, round: 2 },+ { call_id: "call_c", name: "get_tags", arguments: "{}", output: { "tags" => [] }, extra_content: extra, round: 2 }+ ]++ build = ->(function_results) do+ provider.send(:build_generic_messages, prompt: "hi", instructions: "system", function_results: function_results)+ end+ second_request = build.call(round_1)+ third_request = build.call(round_1 + round_2)++ # Each follow-up request must extend the previous one so prefix caches stay valid.+ assert_equal second_request, third_request.first(second_request.size)++ shape = third_request.map do |message|+ message[:tool_calls] ? message[:tool_calls].map { |call| call[:id] } : message[:tool_call_id] || message[:role]+ end+ assert_equal [ "system", "user", [ "call_a" ], "call_a", [ "call_b", "call_c" ], "call_b", "call_c" ], shape++ round_2_calls = third_request[4][:tool_calls]+ assert_not round_2_calls.first.key?(:extra_content)+ assert_equal extra, round_2_calls.last[:extra_content]+ assert_not_includes third_request.to_json, "\"round\":", "the round tag must not leak into the request"+ end+private# Verify the response budget at the provider-to-processor boundary.# @param limit [Integer, nil] expected explicit cap or omitted cap