Class: Llm::MessageContainer
- Inherits:
-
Object
- Object
- Llm::MessageContainer
- Defined in:
- lib/llm/message_container.rb
Instance Attribute Summary collapse
-
#messages ⇒ Object
readonly
Returns the value of attribute messages.
Instance Method Summary collapse
- #add_default_system_message! ⇒ Object
- #add_raw_message(message) ⇒ Object
- #add_raw_messages(messages) ⇒ Object
- #add_system_message(content) ⇒ Object
- #add_user_message(content) ⇒ Object
-
#initialize ⇒ MessageContainer
constructor
A new instance of MessageContainer.
- #to_capped_messages(token_limit: 28_000) ⇒ Object
- #total_token ⇒ Object
Constructor Details
#initialize ⇒ MessageContainer
Returns a new instance of MessageContainer.
4 5 6 7 8 9 10 |
# File 'lib/llm/message_container.rb', line 4 def initialize @messages = [] @metas = [] @token_encoder = Tiktoken.get_encoding("cl100k_base") self. end |
Instance Attribute Details
#messages ⇒ Object (readonly)
Returns the value of attribute messages.
3 4 5 |
# File 'lib/llm/message_container.rb', line 3 def @messages end |
Instance Method Details
#add_default_system_message! ⇒ Object
58 59 60 |
# File 'lib/llm/message_container.rb', line 58 def self.("Current time is #{Time.now}") end |
#add_raw_message(message) ⇒ Object
22 23 24 25 26 |
# File 'lib/llm/message_container.rb', line 22 def () = .with_indifferent_access @metas << { index: @metas.size, token: @token_encoder.encode([:content].to_s).size, role: [:role] } @messages << end |
#add_raw_messages(messages) ⇒ Object
32 33 34 35 36 |
# File 'lib/llm/message_container.rb', line 32 def () .each do || self.() end end |
#add_system_message(content) ⇒ Object
12 13 14 15 |
# File 'lib/llm/message_container.rb', line 12 def (content) @metas << { index: @metas.size, token: @token_encoder.encode(content.to_s).size, role: :system } @messages << { role: :system, content: } end |
#add_user_message(content) ⇒ Object
17 18 19 20 |
# File 'lib/llm/message_container.rb', line 17 def (content) @metas << { index: @metas.size, token: @token_encoder.encode(content.to_s).size, role: :user } @messages << { role: :user, content: } end |
#to_capped_messages(token_limit: 28_000) ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/llm/message_container.rb', line 38 def (token_limit: 28_000) return @messages if self.total_token <= token_limit # システムメッセージは消さない , = @metas.partition { || [:role] == :system } current_token = .map { || [:token] }.sum filtered_indexes = .map { || [:index] } # 新しいメッセージを優先的に残す .reverse.each do || break if token_limit < current_token + [:token] current_token += [:token] filtered_indexes << [:index] end # システムメッセージが挟み込まれている場合も、並び順を維持すること @messages.select.with_index { |, i| filtered_indexes.include?(i) } end |
#total_token ⇒ Object
28 29 30 |
# File 'lib/llm/message_container.rb', line 28 def total_token @metas.map { || [:token] }.sum end |