Module: RubyLLM::SemanticRouter::Utils
- Defined in:
- lib/rubyllm/semantic_router/utils.rb
Overview
Shared utility methods for semantic routing operations
Class Method Summary collapse
-
.cosine_distance(a, b) ⇒ Float
Calculate cosine distance between two vectors Cosine distance = 1 - cosine similarity Returns value in range [0, 2] where 0 = identical, 2 = opposite.
-
.cosine_similarity(a, b) ⇒ Float
Calculate cosine similarity between two vectors Returns value in range [-1, 1] where 1 = identical, -1 = opposite.
-
.truncate_to_max_words(text, max_words) ⇒ String
Truncate text to a maximum number of words.
Class Method Details
.cosine_distance(a, b) ⇒ Float
Calculate cosine distance between two vectors Cosine distance = 1 - cosine similarity Returns value in range [0, 2] where 0 = identical, 2 = opposite
16 17 18 19 20 21 22 23 24 |
# File 'lib/rubyllm/semantic_router/utils.rb', line 16 def cosine_distance(a, b) dot_product = a.zip(b).sum { |x, y| x * y } magnitude_a = Math.sqrt(a.sum { |x| x**2 }) magnitude_b = Math.sqrt(b.sum { |x| x**2 }) return 1.0 if magnitude_a.zero? || magnitude_b.zero? 1.0 - (dot_product / (magnitude_a * magnitude_b)) end |
.cosine_similarity(a, b) ⇒ Float
Calculate cosine similarity between two vectors Returns value in range [-1, 1] where 1 = identical, -1 = opposite
32 33 34 |
# File 'lib/rubyllm/semantic_router/utils.rb', line 32 def cosine_similarity(a, b) 1.0 - cosine_distance(a, b) end |
.truncate_to_max_words(text, max_words) ⇒ String
Truncate text to a maximum number of words
41 42 43 44 45 46 47 48 |
# File 'lib/rubyllm/semantic_router/utils.rb', line 41 def truncate_to_max_words(text, max_words) return text unless max_words words = text.split return text if words.size <= max_words words.first(max_words).join(" ") end |