Class: Agents::MessageExtractor

Inherits:
Object
  • Object
show all
Defined in:
lib/agents/message_extractor.rb

Overview

Service object responsible for extracting and formatting conversation messages from RubyLLM chat objects into a format suitable for persistence and context restoration.

Handles different message types:

  • User messages: Basic content preservation

  • Assistant messages: Includes agent attribution and tool calls

  • Tool result messages: Links back to original tool calls

Examples:

Extract messages from a chat

messages = MessageExtractor.extract_messages(chat, current_agent)
#=> [
  { role: :user, content: "Hello" },
  { role: :assistant, content: "Hi!", agent_name: "Support", tool_calls: [...] },
  { role: :tool, content: "Result", tool_call_id: "call_123" }
]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(chat, current_agent) ⇒ MessageExtractor

Returns a new instance of MessageExtractor.



44
45
46
47
# File 'lib/agents/message_extractor.rb', line 44

def initialize(chat, current_agent)
  @chat = chat
  @current_agent = current_agent
end

Class Method Details

.content_empty?(content) ⇒ Boolean

Check if content is considered empty (handles both String and Hash content)

Parameters:

  • content (String, Hash, nil)

    The content to check

Returns:

  • (Boolean)

    true if content is empty, false otherwise



24
25
26
27
28
29
30
31
32
33
# File 'lib/agents/message_extractor.rb', line 24

def self.content_empty?(content)
  case content
  when String
    content.strip.empty?
  when Hash
    content.empty?
  else
    content.nil?
  end
end

.extract_messages(chat, current_agent) ⇒ Array<Hash>

Extract messages from a chat object for conversation history persistence

Parameters:

  • chat (Object)

    Chat object that responds to :messages

  • current_agent (Agent)

    The agent currently handling the conversation

Returns:

  • (Array<Hash>)

    Array of message hashes suitable for persistence



40
41
42
# File 'lib/agents/message_extractor.rb', line 40

def self.extract_messages(chat, current_agent)
  new(chat, current_agent).extract
end

Instance Method Details

#extractObject



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/agents/message_extractor.rb', line 49

def extract
  return [] unless @chat.respond_to?(:messages)

  @chat.messages.filter_map do |msg|
    case msg.role
    when :user, :assistant
      extract_user_or_assistant_message(msg)
    when :tool
      extract_tool_message(msg)
    end
  end
end