Skip to content

Commit f400051

Browse files
committed
Fixed Calling chat.to_llm keeps appending messages to the message array
Closes #145
1 parent c7adb2f commit f400051

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

lib/ruby_llm/active_record/acts_as.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ module ChatMethods
6767

6868
def to_llm
6969
@chat ||= RubyLLM.chat(model: model_id)
70+
@chat.reset_messages!
7071

7172
# Load existing messages into chat
7273
messages.each do |msg|

lib/ruby_llm/chat.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,10 @@ def add_message(message_or_attributes)
110110
message
111111
end
112112

113+
def reset_messages!
114+
@messages.clear
115+
end
116+
113117
private
114118

115119
def handle_tool_calls(response, &)

spec/ruby_llm/active_record/acts_as_spec.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,19 @@ def execute(expression:)
9999
expect(chat.messages.last.output_tokens).to be_positive
100100
end
101101

102+
it 'to_llm returns the correct amount of messages' do # rubocop:disable RSpec/MultipleExpectations,RSpec/ExampleLength
103+
chat = Chat.create!(model_id: 'gpt-4.1-nano')
104+
chat.ask("What's your favorite Ruby feature?")
105+
106+
expect(chat.messages.count).to eq(2)
107+
expect(chat.to_llm.messages.count).to eq(2)
108+
109+
chat.ask('Again?')
110+
111+
expect(chat.messages.count).to eq(4)
112+
expect(chat.to_llm.messages.count).to eq(4)
113+
end
114+
102115
it 'persists tool calls' do # rubocop:disable RSpec/MultipleExpectations
103116
chat = Chat.create!(model_id: 'gpt-4.1-nano')
104117
chat.with_tool(Calculator)

0 commit comments

Comments
 (0)