Module: DSPy::LM::MessageFactory

Extended by:
T::Sig
Defined in:
lib/dspy/lm/message.rb

Overview

Factory for creating Message objects from various formats

Class Method Summary collapse

Class Method Details

.create(message_data) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/dspy/lm/message.rb', line 102

def self.create(message_data)
  return nil if message_data.nil?
  
  # Already a Message? Return as-is
  return message_data if message_data.is_a?(Message)
  
  # Convert to hash if needed
  if message_data.respond_to?(:to_h)
    message_data = message_data.to_h
  end
  
  return nil unless message_data.is_a?(Hash)
  
  # Normalize keys to symbols
  normalized = message_data.transform_keys(&:to_sym)
  
  create_from_hash(normalized)
end

.create_from_hash(data) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/dspy/lm/message.rb', line 129

def self.create_from_hash(data)
  role_str = data[:role]&.to_s
  content = data[:content]
  
  return nil if role_str.nil? || content.nil?
  
  # Handle both string and array content
  formatted_content = if content.is_a?(Array)
    content
  else
    content.to_s
  end
  
  # Convert string role to enum
  role = case role_str
         when 'system' then Message::Role::System
         when 'user' then Message::Role::User
         when 'assistant' then Message::Role::Assistant
         else
           DSPy.logger.debug("Unknown message role: #{role_str}")
           return nil
         end
  
  Message.new(
    role: role,
    content: formatted_content,
    name: data[:name]&.to_s
  )
rescue => e
  DSPy.logger.debug("Failed to create Message: #{e.message}")
  nil
end

.create_many(messages) ⇒ Object



122
123
124
# File 'lib/dspy/lm/message.rb', line 122

def self.create_many(messages)
  messages.compact.map { |m| create(m) }.compact
end