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
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
# File 'lib/dspy/lm/message.rb', line 106 def self.create() return nil if .nil? # Already a Message? Return as-is return if .is_a?(Message) # Convert to hash if needed if .respond_to?(:to_h) = .to_h end return nil unless .is_a?(Hash) # Normalize keys to symbols normalized = .transform_keys(&:to_sym) create_from_hash(normalized) end |
.create_from_hash(data) ⇒ Object
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 161 162 163 164 |
# File 'lib/dspy/lm/message.rb', line 133 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 StandardError => e DSPy.logger.debug("Failed to create Message: #{e.}") nil end |
.create_many(messages) ⇒ Object
126 127 128 |
# File 'lib/dspy/lm/message.rb', line 126 def self.create_many() .compact.map { |m| create(m) }.compact end |