Class: Kernai::Message

Inherits:
Object
  • Object
show all
Defined in:
lib/kernai/message.rb

Overview

A message in the conversation. ‘content` is ALWAYS an ordered list of parts (String or Media) — there is no polymorphism to worry about in the rest of the kernel. The constructor normalises scalar inputs so callers can still write `Message.new(role: :user, content: ’hi’)‘.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(role:, content:) ⇒ Message

Returns a new instance of Message.



11
12
13
14
# File 'lib/kernai/message.rb', line 11

def initialize(role:, content:)
  @role = role.to_sym
  @content = Array(content).freeze
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



9
10
11
# File 'lib/kernai/message.rb', line 9

def content
  @content
end

#roleObject (readonly)

Returns the value of attribute role.



9
10
11
# File 'lib/kernai/message.rb', line 9

def role
  @role
end

Instance Method Details

#assistant?Boolean

Returns:

  • (Boolean)


22
# File 'lib/kernai/message.rb', line 22

def assistant? = role == :assistant

#mediaObject



32
33
34
# File 'lib/kernai/message.rb', line 32

def media
  @content.grep(Media)
end

#media?Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/kernai/message.rb', line 36

def media?
  @content.any? { |p| p.is_a?(Media) }
end

#system?Boolean

Returns:

  • (Boolean)


20
# File 'lib/kernai/message.rb', line 20

def system?    = role == :system

#textObject

Joined textual view of the message — concatenates String parts and renders Media parts as a stable placeholder. Used by recorders, the stream parser fallback, and any consumer that doesn’t care about vendor encoding.



28
29
30
# File 'lib/kernai/message.rb', line 28

def text
  @content.map { |p| p.is_a?(Media) ? "[#{p.kind}:#{p.id}]" : p.to_s }.join
end

#to_hObject



16
17
18
# File 'lib/kernai/message.rb', line 16

def to_h
  { role: @role, content: @content }
end

#user?Boolean

Returns:

  • (Boolean)


21
# File 'lib/kernai/message.rb', line 21

def user?      = role == :user