Class: DSPy::LM::Message

Inherits:
T::Struct
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/dspy/lm/message.rb

Overview

Type-safe representation of chat messages

Defined Under Namespace

Classes: Role

Instance Method Summary collapse

Instance Method Details

#multimodal?Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/dspy/lm/message.rb', line 44

def multimodal?
  content.is_a?(Array)
end

#to_anthropic_formatObject



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/dspy/lm/message.rb', line 73

def to_anthropic_format
  formatted = { role: role.serialize }
  
  if content.is_a?(String)
    formatted[:content] = content
  else
    # Convert multimodal content array to Anthropic format
    formatted[:content] = content.map do |item|
      case item[:type]
      when 'text'
        { type: 'text', text: item[:text] }
      when 'image'
        item[:image].to_anthropic_format
      else
        item
      end
    end
  end
  
  formatted[:name] = name if name
  formatted
end

#to_hObject



25
26
27
28
29
30
31
32
# File 'lib/dspy/lm/message.rb', line 25

def to_h
  base = {
    role: role.serialize,
    content: content
  }
  base[:name] = name if name
  base
end

#to_openai_formatObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/dspy/lm/message.rb', line 49

def to_openai_format
  formatted = { role: role.serialize }
  
  if content.is_a?(String)
    formatted[:content] = content
  else
    # Convert multimodal content array to OpenAI format
    formatted[:content] = content.map do |item|
      case item[:type]
      when 'text'
        { type: 'text', text: item[:text] }
      when 'image'
        item[:image].to_openai_format
      else
        item
      end
    end
  end
  
  formatted[:name] = name if name
  formatted
end

#to_sObject



35
36
37
38
39
40
41
# File 'lib/dspy/lm/message.rb', line 35

def to_s
  if content.is_a?(String)
    name ? "#{role.serialize}(#{name}): #{content}" : "#{role.serialize}: #{content}"
  else
    name ? "#{role.serialize}(#{name}): [multimodal content]" : "#{role.serialize}: [multimodal content]"
  end
end