Class: RubyLLM::SemanticCache::CacheStores::Redis

Inherits:
Base
  • Object
show all
Defined in:
lib/ruby_llm/semantic_cache/cache_stores/redis.rb

Instance Method Summary collapse

Constructor Details

#initialize(config) ⇒ Redis

Returns a new instance of Redis.



10
11
12
13
# File 'lib/ruby_llm/semantic_cache/cache_stores/redis.rb', line 10

def initialize(config)
  super
  setup_client
end

Instance Method Details

#clear!Object



41
42
43
44
45
46
47
48
49
50
# File 'lib/ruby_llm/semantic_cache/cache_stores/redis.rb', line 41

def clear!
  pattern = cache_key("*")
  cursor = "0"

  loop do
    cursor, keys = @client.call("SCAN", cursor, "MATCH", pattern, "COUNT", 100)
    @client.call("DEL", *keys) unless keys.empty?
    break if cursor == "0"
  end
end

#delete(id) ⇒ Object



36
37
38
39
# File 'lib/ruby_llm/semantic_cache/cache_stores/redis.rb', line 36

def delete(id)
  key = cache_key(id)
  @client.call("DEL", key)
end

#empty?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/ruby_llm/semantic_cache/cache_stores/redis.rb', line 52

def empty?
  size.zero?
end

#get(id) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/ruby_llm/semantic_cache/cache_stores/redis.rb', line 15

def get(id)
  key = cache_key(id)
  data = @client.call("GET", key)
  return nil unless data

  JSON.parse(data, symbolize_names: true)
rescue JSON::ParserError
  nil
end

#set(id, data, ttl: nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/ruby_llm/semantic_cache/cache_stores/redis.rb', line 25

def set(id, data, ttl: nil)
  key = cache_key(id)
  json = JSON.generate(data)

  if ttl
    @client.call("SETEX", key, ttl.to_i, json)
  else
    @client.call("SET", key, json)
  end
end

#sizeObject



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/ruby_llm/semantic_cache/cache_stores/redis.rb', line 56

def size
  pattern = cache_key("*")
  stats_key = cache_key("__semantic_cache_stats__")
  count = 0
  cursor = "0"

  loop do
    cursor, keys = @client.call("SCAN", cursor, "MATCH", pattern, "COUNT", 100)
    # Exclude the stats key from the count
    count += keys.reject { |k| k == stats_key }.size
    break if cursor == "0"
  end

  count
end