Class: RubyLLM::Message

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

Overview

A single message in a chat conversation. Can represent user input, AI responses, or tool interactions. Tracks token usage and handles the complexities of tool calls and responses.

Direct Known Subclasses

Chunk

Constant Summary collapse

ROLES =
%i[system user assistant tool].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Message

Returns a new instance of Message.



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/ruby_llm/message.rb', line 12

def initialize(options = {})
  @role = options[:role].to_sym
  @content = options[:content]
  @tool_calls = options[:tool_calls]
  @input_tokens = options[:input_tokens]
  @output_tokens = options[:output_tokens]
  @model_id = options[:model_id]
  @tool_call_id = options[:tool_call_id]

  ensure_valid_role
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



10
11
12
# File 'lib/ruby_llm/message.rb', line 10

def content
  @content
end

#input_tokensObject (readonly)

Returns the value of attribute input_tokens.



10
11
12
# File 'lib/ruby_llm/message.rb', line 10

def input_tokens
  @input_tokens
end

#model_idObject (readonly)

Returns the value of attribute model_id.



10
11
12
# File 'lib/ruby_llm/message.rb', line 10

def model_id
  @model_id
end

#output_tokensObject (readonly)

Returns the value of attribute output_tokens.



10
11
12
# File 'lib/ruby_llm/message.rb', line 10

def output_tokens
  @output_tokens
end

#roleObject (readonly)

Returns the value of attribute role.



10
11
12
# File 'lib/ruby_llm/message.rb', line 10

def role
  @role
end

#tool_call_idObject (readonly)

Returns the value of attribute tool_call_id.



10
11
12
# File 'lib/ruby_llm/message.rb', line 10

def tool_call_id
  @tool_call_id
end

#tool_callsObject (readonly)

Returns the value of attribute tool_calls.



10
11
12
# File 'lib/ruby_llm/message.rb', line 10

def tool_calls
  @tool_calls
end

Instance Method Details

#to_hObject



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/ruby_llm/message.rb', line 36

def to_h
  {
    role: role,
    content: content,
    tool_calls: tool_calls,
    tool_call_id: tool_call_id,
    input_tokens: input_tokens,
    output_tokens: output_tokens,
    model_id: model_id
  }.compact
end

#tool_call?Boolean

Returns:

  • (Boolean)


24
25
26
# File 'lib/ruby_llm/message.rb', line 24

def tool_call?
  !tool_calls.nil? && !tool_calls.empty?
end

#tool_result?Boolean

Returns:

  • (Boolean)


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

def tool_result?
  !tool_call_id.nil? && !tool_call_id.empty?
end

#tool_resultsObject



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

def tool_results
  content if tool_result?
end