Module: RubyLLM::Mongoid::MessageMethods

Extended by:
ActiveSupport::Concern
Includes:
PayloadHelpers
Defined in:
lib/ruby_llm/mongoid/message_methods.rb

Overview

Mixes into a Mongoid document that represents a persisted chat message. Mirrors RubyLLM::ActiveRecord::MessageMethods but replaces AR-specific introspection with Mongoid equivalents.

Instance Method Summary collapse

Instance Method Details

#cache_read_tokensObject



48
49
50
# File 'lib/ruby_llm/mongoid/message_methods.rb', line 48

def cache_read_tokens
  field_value(:cached_tokens)
end

#cache_write_tokensObject



52
53
54
# File 'lib/ruby_llm/mongoid/message_methods.rb', line 52

def cache_write_tokens
  field_value(:cache_creation_tokens)
end

#costObject



44
45
46
# File 'lib/ruby_llm/mongoid/message_methods.rb', line 44

def cost
  RubyLLM::Cost.new(tokens: tokens, model: model_association)
end

#thinkingObject



27
28
29
30
31
32
# File 'lib/ruby_llm/mongoid/message_methods.rb', line 27

def thinking
  RubyLLM::Thinking.build(
    text: field_value(:thinking_text),
    signature: field_value(:thinking_signature)
  )
end

#to_llmObject



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/ruby_llm/mongoid/message_methods.rb', line 15

def to_llm
  RubyLLM::Message.new(
    role: role.to_sym,
    content: extract_content,
    thinking: thinking,
    tokens: tokens,
    tool_calls: extract_tool_calls,
    tool_call_id: extract_tool_call_id,
    model_id: model_association&.model_id
  )
end

#to_partial_pathObject



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/ruby_llm/mongoid/message_methods.rb', line 56

def to_partial_path
  partial_prefix = self.class.name.underscore.pluralize
  role_partial = if to_llm.tool_call?
                   "tool_calls"
                 elsif role.to_s == "tool"
                   "tool"
                 else
                   role.to_s.presence || "assistant"
                 end
  "#{partial_prefix}/#{role_partial}"
end

#tokensObject



34
35
36
37
38
39
40
41
42
# File 'lib/ruby_llm/mongoid/message_methods.rb', line 34

def tokens
  RubyLLM::Tokens.build(
    input: field_value(:input_tokens),
    output: field_value(:output_tokens),
    cached: field_value(:cached_tokens),
    cache_creation: field_value(:cache_creation_tokens),
    thinking: field_value(:thinking_tokens)
  )
end

#tool_error_messageObject



68
69
70
# File 'lib/ruby_llm/mongoid/message_methods.rb', line 68

def tool_error_message
  payload_error_message(content)
end