|
| 1 | +package classification |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + |
| 6 | + candle_binding "github.com/vllm-project/semantic-router/candle-binding" |
| 7 | + "github.com/vllm-project/semantic-router/src/semantic-router/pkg/config" |
| 8 | + "github.com/vllm-project/semantic-router/src/semantic-router/pkg/observability/logging" |
| 9 | +) |
| 10 | + |
| 11 | +// calculateSimilarityBatch is a package-level variable that points to the |
| 12 | +// actual implementation in the candle_binding package. It exists so tests can |
| 13 | +// override it. |
| 14 | +var calculateSimilarityBatch = candle_binding.CalculateSimilarityBatch |
| 15 | + |
| 16 | +// EmbeddingClassifierInitializer initializes KeywordEmbeddingClassifier for embedding based classification |
| 17 | +type EmbeddingClassifierInitializer interface { |
| 18 | + Init(qwen3ModelPath string, gemmaModelPath string, useCPU bool) error |
| 19 | +} |
| 20 | + |
| 21 | +type ExternalModelBasedEmbeddingInitializer struct{} |
| 22 | + |
| 23 | +func (c *ExternalModelBasedEmbeddingInitializer) Init(qwen3ModelPath string, gemmaModelPath string, useCPU bool) error { |
| 24 | + err := candle_binding.InitEmbeddingModels(qwen3ModelPath, gemmaModelPath, useCPU) |
| 25 | + if err != nil { |
| 26 | + return err |
| 27 | + } |
| 28 | + logging.Infof("Initialized KeywordEmbedding classifier with qwen3 model path %q and gemma model path %s", qwen3ModelPath, gemmaModelPath) |
| 29 | + return nil |
| 30 | +} |
| 31 | + |
| 32 | +// createEmbeddingInitializer creates the appropriate keyword embedding initializer based on configuration |
| 33 | +func createEmbeddingInitializer() EmbeddingClassifierInitializer { |
| 34 | + return &ExternalModelBasedEmbeddingInitializer{} |
| 35 | +} |
| 36 | + |
| 37 | +type EmbeddingClassifier struct { |
| 38 | + rules []config.EmbeddingRule |
| 39 | +} |
| 40 | + |
| 41 | +// NewKeywordClassifier creates a new KeywordEmbeddingClassifier. |
| 42 | +func NewEmbeddingClassifier(cfgRules []config.EmbeddingRule) (*EmbeddingClassifier, error) { |
| 43 | + return &EmbeddingClassifier{rules: cfgRules}, nil |
| 44 | +} |
| 45 | + |
| 46 | +// IsKeywordEmbeddingClassifierEnabled checks if Keyword embedding classification rules are properly configured |
| 47 | +func (c *Classifier) IsKeywordEmbeddingClassifierEnabled() bool { |
| 48 | + return len(c.Config.EmbeddingRules) > 0 |
| 49 | +} |
| 50 | + |
| 51 | +// initializeKeywordEmbeddingClassifier initializes the KeywordEmbedding classification model |
| 52 | +func (c *Classifier) initializeKeywordEmbeddingClassifier() error { |
| 53 | + if !c.IsKeywordEmbeddingClassifierEnabled() || c.keywordEmbeddingInitializer == nil { |
| 54 | + return fmt.Errorf("keyword embedding similarity match is not properly configured") |
| 55 | + } |
| 56 | + return c.keywordEmbeddingInitializer.Init(c.Config.InlineModels.Qwen3ModelPath, c.Config.InlineModels.GemmaModelPath, c.Config.InlineModels.EmbeddingModels.UseCPU) |
| 57 | +} |
| 58 | + |
| 59 | +// Classify performs keyword-based embedding similarity classification on the given text. |
| 60 | +func (c *EmbeddingClassifier) Classify(text string) (string, float64, error) { |
| 61 | + var bestScore float32 |
| 62 | + var mostMatchedCategory string |
| 63 | + for _, rule := range c.rules { |
| 64 | + matched, aggregatedScore, err := c.matches(text, rule) // Error handled |
| 65 | + if err != nil { |
| 66 | + return "", 0.0, err // Propagate error |
| 67 | + } |
| 68 | + if matched { |
| 69 | + if len(rule.Keywords) > 0 { |
| 70 | + logging.Infof("Keyword-based embedding similarity classification matched category %q with keywords: %v, confidence score %s", rule.Category, rule.Keywords, aggregatedScore) |
| 71 | + } else { |
| 72 | + logging.Infof("Keyword-based embedding similarity classification do not match category %q with keywords: %v, confidence score %s", rule.Category, rule.Keywords, aggregatedScore) |
| 73 | + } |
| 74 | + if aggregatedScore > bestScore { |
| 75 | + bestScore = aggregatedScore |
| 76 | + mostMatchedCategory = rule.Category |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + return mostMatchedCategory, float64(bestScore), nil |
| 81 | +} |
| 82 | + |
| 83 | +// matches checks if the text matches the given keyword rule. |
| 84 | +func (c *EmbeddingClassifier) matches(text string, rule config.EmbeddingRule) (bool, float32, error) { |
| 85 | + // Validate input |
| 86 | + if text == "" { |
| 87 | + return false, 0.0, fmt.Errorf("keyword-based embedding similarity classification: query must be provided") |
| 88 | + } |
| 89 | + if len(rule.Keywords) == 0 { |
| 90 | + return false, 0.0, fmt.Errorf("keyword-based embedding similarity classification: keywords must be provided") |
| 91 | + } |
| 92 | + // Set defaults |
| 93 | + if rule.Dimension == 0 { |
| 94 | + rule.Dimension = 768 // Default to full dimension |
| 95 | + } |
| 96 | + if rule.Model == "auto" && rule.QualityPriority == 0 && rule.LatencyPriority == 0 { |
| 97 | + rule.QualityPriority = 0.5 |
| 98 | + rule.LatencyPriority = 0.5 |
| 99 | + } |
| 100 | + |
| 101 | + // Validate dimension |
| 102 | + validDimensions := map[int]bool{128: true, 256: true, 512: true, 768: true, 1024: true} |
| 103 | + if !validDimensions[rule.Dimension] { |
| 104 | + return false, 0.0, fmt.Errorf("keyword-based embedding similarity classification: dimension must be one of: 128, 256, 512, 768, 1024 (got %d)", rule.Dimension) |
| 105 | + } |
| 106 | + // Calculate batch similarity |
| 107 | + result, err := calculateSimilarityBatch( |
| 108 | + text, |
| 109 | + rule.Keywords, |
| 110 | + 0, // return scores for all the keywords |
| 111 | + rule.Model, |
| 112 | + rule.Dimension, |
| 113 | + ) |
| 114 | + if err != nil { |
| 115 | + return false, 0.0, fmt.Errorf("keyword-based embedding similarity classification: failed to calculate batch similarity: %w", err) |
| 116 | + } |
| 117 | + // Check for matches based on the aggregation method |
| 118 | + switch rule.AggregationMethodConfiged { |
| 119 | + case config.AggregationMethodMean: |
| 120 | + var aggregatedScore float32 |
| 121 | + for _, match := range result.Matches { |
| 122 | + aggregatedScore += match.Similarity |
| 123 | + } |
| 124 | + aggregatedScore /= float32(len(result.Matches)) |
| 125 | + if aggregatedScore >= rule.SimilarityThreshold { |
| 126 | + return true, aggregatedScore, nil |
| 127 | + } else { |
| 128 | + return false, aggregatedScore, nil |
| 129 | + } |
| 130 | + case config.AggregationMethodMax: |
| 131 | + var aggregatedScore float32 |
| 132 | + for _, match := range result.Matches { |
| 133 | + if match.Similarity > aggregatedScore { |
| 134 | + aggregatedScore = match.Similarity |
| 135 | + } |
| 136 | + } |
| 137 | + if aggregatedScore >= rule.SimilarityThreshold { |
| 138 | + return true, aggregatedScore, nil |
| 139 | + } else { |
| 140 | + return false, aggregatedScore, nil |
| 141 | + } |
| 142 | + case config.AggregationMethodAny: |
| 143 | + for _, match := range result.Matches { |
| 144 | + if match.Similarity >= rule.SimilarityThreshold { |
| 145 | + return true, rule.SimilarityThreshold, nil |
| 146 | + } |
| 147 | + } |
| 148 | + return false, 0.0, nil |
| 149 | + |
| 150 | + } |
| 151 | + return false, 0.0, fmt.Errorf("keyword-based embedding similarity classification: unsupported keyword rule aggregation method: %q", rule.AggregationMethodConfiged) |
| 152 | +} |
0 commit comments