Class: Soka::Memory

Inherits:
Object
  • Object
show all
Defined in:
lib/soka/memory.rb

Overview

Manages conversation history for agents

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(initial_messages = []) ⇒ Memory

Returns a new instance of Memory.



8
9
10
11
12
13
14
15
# File 'lib/soka/memory.rb', line 8

def initialize(initial_messages = [])
  @messages = []

  # Add initial messages if provided
  return unless initial_messages.is_a?(Array)

  initial_messages.each { |msg| add(**msg) }
end

Instance Attribute Details

#messagesObject (readonly)

Returns the value of attribute messages.



6
7
8
# File 'lib/soka/memory.rb', line 6

def messages
  @messages
end

Instance Method Details

#add(role:, content:) ⇒ Object



17
18
19
20
21
22
23
24
25
26
# File 'lib/soka/memory.rb', line 17

def add(role:, content:)
  validate_role!(role)
  validate_content!(content)

  @messages << {
    role: role.to_s,
    content: content,
    timestamp: Time.now
  }
end

#clearObject



32
33
34
# File 'lib/soka/memory.rb', line 32

def clear
  @messages.clear
end

#empty?Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/soka/memory.rb', line 40

def empty?
  @messages.empty?
end

#inspectObject



58
59
60
# File 'lib/soka/memory.rb', line 58

def inspect
  to_s
end

#lastObject



44
45
46
# File 'lib/soka/memory.rb', line 44

def last
  @messages.last
end

#sizeObject



36
37
38
# File 'lib/soka/memory.rb', line 36

def size
  @messages.size
end

#to_messagesObject



28
29
30
# File 'lib/soka/memory.rb', line 28

def to_messages
  @messages.map { |msg| { role: msg[:role], content: msg[:content] } }
end

#to_sObject



48
49
50
51
52
53
54
55
56
# File 'lib/soka/memory.rb', line 48

def to_s
  return '<Soka::Memory> []' if empty?

  formatted_messages = @messages.map do |msg|
    "  { role: '#{msg[:role]}', content: '#{truncate(msg[:content])}' }"
  end.join(",\n")

  "<Soka::Memory> [\n#{formatted_messages}\n]"
end