Class: ActiveHarness::Memory::Adapter::File

Inherits:
Base
  • Object
show all
Defined in:
lib/active_harness/memory/adapter/file.rb

Overview

Persists memory as JSON files on disk.

Each session is stored in one file:

<path>/<session_id>.json                   (no namespace)
<path>/<session_id>/<namespace>.json       (with namespace)

Options:

path             — base directory                  (default: "storage/ai/memory")
filename         — String or Proc(session_id)      (default: "<session_id>.json")
pretty           — format JSON with indentation    (default: false)
compact          — store only q/a keys             (default: false)
encoding         — file encoding                   (default: "UTF-8")
storage_size     — max turns kept in file          (default: 1000)
eviction_percent — % of oldest turns to drop       (default: 10)
on_trim          — Proc called with trimmed turns  (default: nil)

Constant Summary collapse

DEFAULT_PATH =
"storage/ai/memory"
DEFAULT_STORAGE_SIZE =
1000
DEFAULT_TRIM_PERCENT =
10

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ File

Returns a new instance of File.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/active_harness/memory/adapter/file.rb', line 27

def initialize(opts = {})
  @path             = opts.fetch(:path, DEFAULT_PATH)
  @filename_opt     = opts[:filename]
  @pretty           = opts.fetch(:pretty, false)
  @compact          = opts.fetch(:compact, false)
  @encoding         = opts.fetch(:encoding, "UTF-8")
  @storage_size     = opts.fetch(:storage_size, DEFAULT_STORAGE_SIZE)
  @trim_percent = opts.fetch(:eviction_percent, DEFAULT_TRIM_PERCENT)
  @on_trim          = opts[:on_trim]
  @namespace        = opts[:namespace]

  @session_id = nil
  @turns      = []
end

Instance Method Details

#closeObject



57
58
59
# File 'lib/active_harness/memory/adapter/file.rb', line 57

def close
  # File adapter writes immediately on each write, nothing to flush.
end

#deleteObject



61
62
63
64
65
66
67
68
69
70
# File 'lib/active_harness/memory/adapter/file.rb', line 61

def delete
  path = file_path
  ::FileUtils.rm_f(path)
  # remove parent dir only if it's a namespace dir and now empty
  dir = ::File.dirname(path)
  if @namespace && Dir.exist?(dir) && Dir.empty?(dir)
    Dir.rmdir(dir)
  end
  @turns = []
end

#open(session_id) ⇒ Object



42
43
44
45
# File 'lib/active_harness/memory/adapter/file.rb', line 42

def open(session_id)
  @session_id = session_id
  @turns      = load_from_disk
end

#readObject



47
48
49
# File 'lib/active_harness/memory/adapter/file.rb', line 47

def read
  @turns.dup
end

#write(turn) ⇒ Object



51
52
53
54
55
# File 'lib/active_harness/memory/adapter/file.rb', line 51

def write(turn)
  @turns << turn
  trim_if_needed!
  flush!
end