Class: LlmOptimizer::SemanticCache

Inherits:
Object
  • Object
show all
Defined in:
lib/llm_optimizer/semantic_cache.rb

Constant Summary collapse

KEY_NAMESPACE =
"llm_optimizer:cache:"

Instance Method Summary collapse

Constructor Details

#initialize(redis_client, threshold:, ttl:, cache_scope: nil) ⇒ SemanticCache

Returns a new instance of SemanticCache.



10
11
12
13
14
15
# File 'lib/llm_optimizer/semantic_cache.rb', line 10

def initialize(redis_client, threshold:, ttl:, cache_scope: nil)
  @redis       = redis_client
  @threshold   = threshold
  @ttl         = ttl
  @cache_scope = cache_scope
end

Instance Method Details

#cosine_similarity(vec_a, vec_b) ⇒ Object



61
62
63
64
65
66
67
68
# File 'lib/llm_optimizer/semantic_cache.rb', line 61

def cosine_similarity(vec_a, vec_b)
  dot    = vec_a.zip(vec_b).sum { |a, b| a * b }
  mag_a  = Math.sqrt(vec_a.sum { |x| x * x })
  mag_b  = Math.sqrt(vec_b.sum { |x| x * x })
  return 0.0 if mag_a.zero? || mag_b.zero?

  dot / (mag_a * mag_b)
end

#lookup(embedding) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/llm_optimizer/semantic_cache.rb', line 29

def lookup(embedding)
  prefix = KEY_NAMESPACE
  prefix += "#{@cache_scope}:" if @cache_scope
  keys = @redis.keys("#{prefix}*")

  keys.reject! { |k| k.count(":") > 2 } unless @cache_scope

  return nil if keys.empty?

  best_score    = -Float::INFINITY
  best_entry    = nil

  keys.each do |key|
    raw = @redis.get(key)
    next unless raw

    entry = MessagePack.unpack(raw)
    stored_embedding = entry["embedding"].unpack("G*")
    score = cosine_similarity(embedding, stored_embedding)

    if score > best_score
      best_score    = score
      best_entry    = entry
    end
  end

  [best_entry["response"], best_entry["token_info"] || {}] if best_score >= @threshold
rescue ::Redis::BaseError => e
  warn "[llm_optimizer] SemanticCache lookup failed: #{e.message}"
  nil
end

#store(embedding, response, token_info = {}) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/llm_optimizer/semantic_cache.rb', line 17

def store(embedding, response, token_info = {})
  key     = cache_key(embedding)
  payload = MessagePack.pack({
                               "embedding" => embedding.pack("G*"),
                               "response" => response,
                               "token_info" => token_info
                             })
  @redis.set(key, payload, ex: @ttl)
rescue ::Redis::BaseError => e
  warn "[llm_optimizer] SemanticCache store failed: #{e.message}"
end