Class: Looped::State

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/looped/state.rb

Constant Summary collapse

DEFAULT_STORAGE_DIR =
T.let(File.expand_path('~/.looped'), String)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(storage_dir: nil) ⇒ State

Returns a new instance of State.



17
18
19
20
21
22
23
24
# File 'lib/looped/state.rb', line 17

def initialize(storage_dir: nil)
  @storage_dir = T.let(
    storage_dir || ENV['LOOPED_STORAGE_DIR'] || DEFAULT_STORAGE_DIR,
    String
  )
  FileUtils.mkdir_p(@storage_dir)
  FileUtils.mkdir_p(File.join(@storage_dir, 'history'))
end

Instance Attribute Details

#storage_dirObject (readonly)

Returns the value of attribute storage_dir.



14
15
16
# File 'lib/looped/state.rb', line 14

def storage_dir
  @storage_dir
end

Instance Method Details

#append_training_result(result) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/looped/state.rb', line 57

def append_training_result(result)
  buffer = load_training_buffer_raw
  buffer << {
    task: result.task,
    solution: result.solution,
    score: result.score,
    feedback: result.feedback,
    timestamp: result.timestamp
  }
  File.write(training_buffer_path, JSON.pretty_generate(buffer))
end

#consume_training_bufferObject



75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/looped/state.rb', line 75

def consume_training_buffer
  buffer = peek_training_buffer
  return [] if buffer.empty?

  # Archive to history
  archive_path = File.join(@storage_dir, 'history', "#{Time.now.to_i}.json")
  File.write(archive_path, JSON.pretty_generate(load_training_buffer_raw))

  # Clear buffer
  File.write(training_buffer_path, '[]')

  buffer
end

#load_instructionsObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/looped/state.rb', line 27

def load_instructions
  path = instructions_path
  return nil unless File.exist?(path)

  data = JSON.parse(File.read(path), symbolize_names: true)
  instructions_data = data[:instructions] || {}

  Types::Instructions.new(
    thought_generator: instructions_data[:thought_generator],
    observation_processor: instructions_data[:observation_processor],
    score: data[:score]&.to_f || 0.0,
    generation: data[:generation]&.to_i || 0,
    updated_at: data[:updated_at] || Time.now.utc.iso8601
  )
rescue JSON::ParserError
  nil
end

#peek_training_bufferObject



70
71
72
# File 'lib/looped/state.rb', line 70

def peek_training_buffer
  load_training_buffer_raw.map { |data| deserialize_training_result(data) }
end

#save_instructions(instructions:, score:, generation:) ⇒ Object



46
47
48
49
50
51
52
53
54
# File 'lib/looped/state.rb', line 46

def save_instructions(instructions:, score:, generation:)
  data = {
    instructions: instructions,
    score: score,
    generation: generation,
    updated_at: Time.now.utc.iso8601
  }
  File.write(instructions_path, JSON.pretty_generate(data))
end