Skip to content

Calling chat.to_llm keeps appending messages to the message array #145

@bborn

Description

@bborn

Using the acts_as to_llm adds messages to the chat array on every call (because @chat is memoized).

  it 'persists chat history' do
    chat = Chat.create!(model_id: 'gpt-4.1-nano')
    chat.ask("What's your favorite Ruby feature?")

    expect(chat.messages.count).to eq(2)
    expect(chat.messages.first.role).to eq('user')
    expect(chat.messages.last.role).to eq('assistant')
    expect(chat.messages.last.content).to be_present
    expect(chat.messages.last.input_tokens).to be_positive
    expect(chat.messages.last.output_tokens).to be_positive

    chat.to_llm

    expect(chat.to_llm.messages.count).to eq(2)
  end
  1) RubyLLM::ActiveRecord::ActsAs persists chat history
     Failure/Error: expect(chat.to_llm.messages.count).to eq(2)
     
       expected: 2
            got: 6

It seems like just removing the memoization here would fix it, but I'm not sure if there's a reason it was done that way.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions