Class: RubyLLM::SemanticRouter::Strategies::Semantic

Inherits:
Base
  • Object
show all
Defined in:
lib/rubyllm/semantic_router/strategies/semantic.rb

Overview

Semantic routing strategy using embeddings and kNN search

This strategy:

  1. Generates an embedding for the user’s message

  2. Finds the nearest routing examples using cosine similarity

  3. Routes to the agent associated with the best match

  4. Falls back if confidence is below threshold

Defined Under Namespace

Classes: CustomSearchMatch, InMemoryMatch

Instance Method Summary collapse

Instance Method Details

#route(message, agents:, examples:, current_agent:, config:, find_examples: nil, precomputed_embedding: nil) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
60
61
62
63
64
65
66
67
# File 'lib/rubyllm/semantic_router/strategies/semantic.rb', line 14

def route(message, agents:, examples:, current_agent:, config:, find_examples: nil, precomputed_embedding: nil)
  # If custom find_examples provided, use it
  # Otherwise, check if we have examples to search
  has_search = find_examples.respond_to?(:call) ||
               (examples && !examples_empty?(examples))

  unless has_search
    return apply_fallback(
      config: config,
      current_agent: current_agent,
      default_agent: config.default_agent
    )
  end

  # Use precomputed embedding if provided (for batch operations), otherwise generate
  embedding = precomputed_embedding || generate_embedding(message, config.embedding_model, max_words: config.max_words)

  # Find nearest neighbors using custom search or built-in
  matches = if find_examples.respond_to?(:call)
    find_with_custom_search(find_examples, embedding, config.k_neighbors)
  else
    find_nearest_neighbors(examples, embedding, config)
  end

  # No matches found
  if matches.empty?
    return apply_fallback(
      config: config,
      current_agent: current_agent,
      default_agent: config.default_agent
    )
  end

  # Get best match and calculate confidence
  best_match = matches.first
  confidence = calculate_confidence(best_match)

  # Check threshold
  if confidence < config.similarity_threshold
    return apply_fallback(
      config: config,
      current_agent: current_agent,
      default_agent: config.default_agent
    )
  end

  # Return semantic match decision
  RoutingDecision.new(
    agent: extract_agent_name(best_match),
    confidence: confidence,
    matched_example: extract_example_text(best_match),
    reason: :semantic_match
  )
end