Skip to content

Conversation

xiaohui-zhangxh
Copy link

Refactor: Extract populate_messages method for customizable message loading

Extract message population logic into a separate method to enable custom message filtering in subclasses.

Type of change

  • Refactor

Description

This refactor extracts the message population logic into a dedicated populate_messages method, allowing subclasses to override message loading behavior. This enables features like agent-based message filtering without modifying the core chat functionality.

Changes

  • Extract message population logic to populate_messages method
  • Enable custom message filtering through method overriding
  • Maintain backward compatibility - no breaking changes

Example Usage

With this refactor, you can implement custom message loading logic:

class Chat
  acts_as_chat

  def with_agent(agent)
    @agent_instruction = messages_association.create!(
      role: :system, 
      agent: agent, 
      content: agent.system_prompt
    )
    with_temperature(agent.temperature)
  end

  def without_agent
    @agent_instruction = nil
    self
  end

  private

  def populate_messages
    @chat.reset_messages!
    messages_association.each do |msg|
      # Skip non-agent system messages when agent is active
      next if @agent_instruction && msg.role == "system" && msg.id != @agent_instruction.id
      
      # Skip agent system messages when no agent is active
      next if @agent_instruction.nil? && msg.agent_id.present?

      @chat.add_message(msg.to_llm)
    end
  end
end

Demo

# Create a gaming expert agent
agent = Agent.create(
  name: "Gaming Expert", 
  system_prompt: "You are a veteran gamer with extensive knowledge of video games. You only discuss gaming-related topics and politely decline non-gaming questions.", 
  temperature: 0.9
)

chat = Chat.last

# With agent - declines non-gaming questions
chat.with_agent(agent).ask("What movies do you recommend?")
# => "I'm here to discuss gaming topics. Is there anything about video games you'd like to talk about?"

# Without agent - answers all questions normally  
chat.without_agent.ask("What is the capital of California?")
# => "The capital of California is Sacramento."

Quality Assurance

  • ✅ No breaking changes
  • ✅ Existing functionality preserved
  • ✅ New customization capability added
  • ✅ Backward compatible

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant