From bdda6b85ffdb18716b873d596df1572799f6c597 Mon Sep 17 00:00:00 2001 From: Saurabh Sikchi Date: Wed, 26 Nov 2025 19:47:56 +0700 Subject: [PATCH] Fix acts_as_tool_call message: option (#514) --- lib/ruby_llm/active_record/chat_methods.rb | 4 +-- spec/ruby_llm/active_record/acts_as_spec.rb | 28 +++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/lib/ruby_llm/active_record/chat_methods.rb b/lib/ruby_llm/active_record/chat_methods.rb index 41930548c..9c0617108 100644 --- a/lib/ruby_llm/active_record/chat_methods.rb +++ b/lib/ruby_llm/active_record/chat_methods.rb @@ -218,8 +218,8 @@ def cleanup_orphaned_tool_results # rubocop:disable Metrics/PerceivedComplexity if last.tool_call? last.destroy elsif last.tool_result? - tool_call_message = last.parent_tool_call.message - expected_results = tool_call_message.tool_calls.pluck(:id) + tool_call_message = last.parent_tool_call.message_association + expected_results = tool_call_message.tool_calls_association.pluck(:id) actual_results = tool_call_message.tool_results.pluck(:tool_call_id) if expected_results.sort != actual_results.sort diff --git a/spec/ruby_llm/active_record/acts_as_spec.rb b/spec/ruby_llm/active_record/acts_as_spec.rb index a36c00b49..1a80c0d00 100644 --- a/spec/ruby_llm/active_record/acts_as_spec.rb +++ b/spec/ruby_llm/active_record/acts_as_spec.rb @@ -391,6 +391,34 @@ class BotToolCall < ActiveRecord::Base # rubocop:disable Lint/ConstantDefinition bot_chat.with_model('claude-3-5-haiku-20241022') expect(bot_chat.reload.model_id).to eq('claude-3-5-haiku-20241022') end + + it 'cleans up incomplete tool interactions with custom message association name' do + bot_chat = Assistants::BotChat.create!(model: model) + + bot_chat.bot_messages.create!(role: 'user', content: 'Do multiple calculations') + + tool_call_msg = bot_chat.bot_messages.create!(role: 'assistant', content: nil) + tool_call1 = tool_call_msg.bot_tool_calls.create!( + tool_call_id: 'call_custom_1', + name: 'calculator', + arguments: { expression: '2 + 2' }.to_json + ) + tool_call_msg.bot_tool_calls.create!( + tool_call_id: 'call_custom_2', + name: 'calculator', + arguments: { expression: '3 + 3' }.to_json + ) + + bot_chat.bot_messages.create!( + role: 'tool', + content: '4', + parent_tool_call: tool_call1 + ) + + expect do + bot_chat.send(:cleanup_orphaned_tool_results) + end.to change { bot_chat.bot_messages.count }.by(-2) + end end describe 'namespaced chat models with custom foreign keys' do