Skip to main content

oxirs_chat/rag/
ranking.rs

1//! Result Ranking System
2//!
3//! Advanced ranking algorithms for RAG retrieval results to improve relevance.
4
5use anyhow::Result;
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use tracing::{debug, info};
9
10use super::types::{QueryContext, RetrievalResult};
11
12/// Ranking algorithm type
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
14pub enum RankingAlgorithmType {
15    /// BM25 ranking (Best Match 25)
16    BM25,
17    /// TF-IDF based ranking
18    TFIDF,
19    /// Semantic similarity ranking
20    Semantic,
21    /// Learning to Rank (LTR)
22    LearningToRank,
23    /// Hybrid ranking (combines multiple signals)
24    Hybrid,
25    /// Diversification-based ranking (MMR)
26    MMR,
27    /// PageRank-based ranking
28    PageRank,
29    /// Reciprocal Rank Fusion
30    RRF,
31}
32
33/// Ranking configuration
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct RankingConfig {
36    /// Primary ranking algorithm
37    pub algorithm: RankingAlgorithmType,
38    /// BM25 parameters
39    pub bm25_k1: f32,
40    pub bm25_b: f32,
41    /// Semantic similarity weight (0.0-1.0)
42    pub semantic_weight: f32,
43    /// Keyword match weight (0.0-1.0)
44    pub keyword_weight: f32,
45    /// Recency weight (0.0-1.0)
46    pub recency_weight: f32,
47    /// Popularity weight (0.0-1.0)
48    pub popularity_weight: f32,
49    /// Diversity penalty (0.0-1.0)
50    pub diversity_penalty: f32,
51    /// Enable re-ranking
52    pub enable_reranking: bool,
53    /// Re-ranking top K
54    pub rerank_top_k: usize,
55}
56
57impl Default for RankingConfig {
58    fn default() -> Self {
59        Self {
60            algorithm: RankingAlgorithmType::Hybrid,
61            bm25_k1: 1.5,
62            bm25_b: 0.75,
63            semantic_weight: 0.6,
64            keyword_weight: 0.3,
65            recency_weight: 0.05,
66            popularity_weight: 0.05,
67            diversity_penalty: 0.3,
68            enable_reranking: true,
69            rerank_top_k: 20,
70        }
71    }
72}
73
74/// Ranking features for a result
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct RankingFeatures {
77    /// Semantic similarity score
78    pub semantic_score: f32,
79    /// Keyword match score
80    pub keyword_score: f32,
81    /// BM25 score
82    pub bm25_score: f32,
83    /// TF-IDF score
84    pub tfidf_score: f32,
85    /// Recency score
86    pub recency_score: f32,
87    /// Popularity score
88    pub popularity_score: f32,
89    /// Entity overlap score
90    pub entity_overlap: f32,
91    /// Query-document length ratio
92    pub length_ratio: f32,
93}
94
95/// Result ranker
96pub struct ResultRanker {
97    config: RankingConfig,
98    document_frequencies: HashMap<String, usize>,
99    total_documents: usize,
100}
101
102impl ResultRanker {
103    /// Create a new result ranker
104    pub fn new(config: RankingConfig) -> Self {
105        info!(
106            "Initialized result ranker with {:?} algorithm",
107            config.algorithm
108        );
109
110        Self {
111            config,
112            document_frequencies: HashMap::new(),
113            total_documents: 0,
114        }
115    }
116
117    /// Rank retrieval results
118    pub fn rank(
119        &self,
120        results: &mut [RetrievalResult],
121        query: &str,
122        context: &QueryContext,
123    ) -> Result<()> {
124        debug!("Ranking {} results for query: {}", results.len(), query);
125
126        match self.config.algorithm {
127            RankingAlgorithmType::BM25 => self.rank_bm25(results, query)?,
128            RankingAlgorithmType::TFIDF => self.rank_tfidf(results, query)?,
129            RankingAlgorithmType::Semantic => self.rank_semantic(results)?,
130            RankingAlgorithmType::Hybrid => self.rank_hybrid(results, query, context)?,
131            RankingAlgorithmType::MMR => self.rank_mmr(results, query)?,
132            RankingAlgorithmType::PageRank => self.rank_pagerank(results)?,
133            RankingAlgorithmType::RRF => self.rank_rrf(results)?,
134            RankingAlgorithmType::LearningToRank => self.rank_ltr(results, query, context)?,
135        }
136
137        // Re-ranking if enabled
138        if self.config.enable_reranking {
139            self.rerank_top_k(results, query)?;
140        }
141
142        Ok(())
143    }
144
145    /// BM25 ranking algorithm
146    fn rank_bm25(&self, results: &mut [RetrievalResult], query: &str) -> Result<()> {
147        let query_terms: Vec<&str> = query.split_whitespace().collect();
148        let avg_doc_length = self.calculate_avg_doc_length(results);
149
150        for result in results.iter_mut() {
151            let doc_length = result.document.content.split_whitespace().count();
152            let mut score = 0.0;
153
154            for term in &query_terms {
155                let tf = self.term_frequency(&result.document.content, term);
156                let df = self.document_frequency(term);
157                let idf =
158                    ((self.total_documents as f32 - df as f32 + 0.5) / (df as f32 + 0.5)).ln();
159
160                let numerator = tf * (self.config.bm25_k1 + 1.0);
161                let denominator = tf
162                    + self.config.bm25_k1
163                        * (1.0 - self.config.bm25_b
164                            + self.config.bm25_b * (doc_length as f32 / avg_doc_length));
165
166                score += idf * (numerator / denominator);
167            }
168
169            result.score = score as f64;
170        }
171
172        // Sort with NaN-safe comparison (NaN values go to the end)
173        results.sort_by(|a, b| {
174            b.score
175                .partial_cmp(&a.score)
176                .unwrap_or(std::cmp::Ordering::Equal)
177        });
178        Ok(())
179    }
180
181    /// TF-IDF ranking algorithm
182    fn rank_tfidf(&self, results: &mut [RetrievalResult], query: &str) -> Result<()> {
183        let query_terms: Vec<&str> = query.split_whitespace().collect();
184
185        for result in results.iter_mut() {
186            let mut score = 0.0;
187
188            for term in &query_terms {
189                let tf = self.term_frequency(&result.document.content, term);
190                let df = self.document_frequency(term);
191                let idf = (self.total_documents as f32 / (df as f32 + 1.0)).ln();
192
193                score += tf * idf;
194            }
195
196            result.score = score as f64;
197        }
198
199        results.sort_by(|a, b| {
200            b.score
201                .partial_cmp(&a.score)
202                .unwrap_or(std::cmp::Ordering::Equal)
203        });
204        Ok(())
205    }
206
207    /// Semantic similarity ranking
208    fn rank_semantic(&self, results: &mut [RetrievalResult]) -> Result<()> {
209        // Results already have semantic scores from vector search
210        results.sort_by(|a, b| {
211            b.score
212                .partial_cmp(&a.score)
213                .unwrap_or(std::cmp::Ordering::Equal)
214        });
215        Ok(())
216    }
217
218    /// Hybrid ranking combining multiple signals
219    fn rank_hybrid(
220        &self,
221        results: &mut [RetrievalResult],
222        query: &str,
223        context: &QueryContext,
224    ) -> Result<()> {
225        debug!("Computing hybrid ranking features");
226
227        for result in results.iter_mut() {
228            let features = self.extract_features(result, query, context)?;
229
230            // Combine features with weights
231            let hybrid_score = features.semantic_score * self.config.semantic_weight
232                + features.keyword_score * self.config.keyword_weight
233                + features.recency_score * self.config.recency_weight
234                + features.popularity_score * self.config.popularity_weight;
235
236            result.score = hybrid_score as f64;
237            result
238                .document
239                .metadata
240                .insert("hybrid_score".to_string(), hybrid_score.to_string());
241        }
242
243        results.sort_by(|a, b| {
244            b.score
245                .partial_cmp(&a.score)
246                .unwrap_or(std::cmp::Ordering::Equal)
247        });
248        Ok(())
249    }
250
251    /// Maximal Marginal Relevance (MMR) for diversity
252    fn rank_mmr(&self, results: &mut [RetrievalResult], _query: &str) -> Result<()> {
253        if results.is_empty() {
254            return Ok(());
255        }
256
257        let lambda = 1.0 - self.config.diversity_penalty; // Balance relevance vs diversity
258        let mut selected: Vec<RetrievalResult> = Vec::new();
259        let mut remaining = results.to_vec();
260
261        // Select first result (highest relevance)
262        if let Some(first) = remaining.first() {
263            selected.push(first.clone());
264            remaining.remove(0);
265        }
266
267        // Iteratively select results that maximize MMR
268        while !remaining.is_empty() && selected.len() < results.len() {
269            let mut best_idx = 0;
270            let mut best_mmr = f32::MIN;
271
272            for (idx, result) in remaining.iter().enumerate() {
273                let relevance = result.score as f32;
274
275                // Calculate max similarity to already selected results
276                let max_similarity = selected
277                    .iter()
278                    .map(|s| {
279                        self.calculate_similarity(&result.document.content, &s.document.content)
280                    })
281                    .fold(0.0f32, f32::max);
282
283                let mmr = lambda * relevance - (1.0 - lambda) * max_similarity;
284
285                if mmr > best_mmr {
286                    best_mmr = mmr;
287                    best_idx = idx;
288                }
289            }
290
291            selected.push(remaining.remove(best_idx));
292        }
293
294        // Update original results
295        for (i, sel) in selected.iter().enumerate() {
296            if i < results.len() {
297                results[i] = sel.clone();
298            }
299        }
300        Ok(())
301    }
302
303    /// PageRank-based ranking
304    fn rank_pagerank(&self, results: &mut [RetrievalResult]) -> Result<()> {
305        // Simplified PageRank based on entity connections
306        for result in results.iter_mut() {
307            let entity_count = result
308                .document
309                .content
310                .split_whitespace()
311                .filter(|w| w.starts_with("http://") || w.starts_with("https://"))
312                .count();
313
314            // More connected entities get higher scores
315            result.score *= 1.0 + 0.1 * entity_count as f64;
316        }
317
318        results.sort_by(|a, b| {
319            b.score
320                .partial_cmp(&a.score)
321                .unwrap_or(std::cmp::Ordering::Equal)
322        });
323        Ok(())
324    }
325
326    /// Reciprocal Rank Fusion (RRF)
327    fn rank_rrf(&self, results: &mut [RetrievalResult]) -> Result<()> {
328        let k = 60.0; // RRF parameter
329
330        for (rank, result) in results.iter_mut().enumerate() {
331            result.score = (1.0 / (k + rank as f32 + 1.0)) as f64;
332        }
333
334        results.sort_by(|a, b| {
335            b.score
336                .partial_cmp(&a.score)
337                .unwrap_or(std::cmp::Ordering::Equal)
338        });
339        Ok(())
340    }
341
342    /// Learning to Rank using features
343    fn rank_ltr(
344        &self,
345        results: &mut [RetrievalResult],
346        query: &str,
347        context: &QueryContext,
348    ) -> Result<()> {
349        // Extract features and apply learned model
350        for result in results.iter_mut() {
351            let features = self.extract_features(result, query, context)?;
352
353            // Simple linear model (in production, use trained model)
354            let score = features.semantic_score * 0.4
355                + features.bm25_score * 0.3
356                + features.keyword_score * 0.15
357                + features.entity_overlap * 0.1
358                + features.popularity_score * 0.05;
359
360            result.score = score as f64;
361        }
362
363        results.sort_by(|a, b| {
364            b.score
365                .partial_cmp(&a.score)
366                .unwrap_or(std::cmp::Ordering::Equal)
367        });
368        Ok(())
369    }
370
371    /// Re-rank top K results with expensive features
372    fn rerank_top_k(&self, results: &mut [RetrievalResult], query: &str) -> Result<()> {
373        let top_k = self.config.rerank_top_k.min(results.len());
374
375        debug!("Re-ranking top {} results", top_k);
376
377        for result in results.iter_mut().take(top_k) {
378            // Apply expensive reranking features
379            let enhanced_score = self.compute_enhanced_score(result, query)?;
380            result.score = enhanced_score as f64;
381        }
382
383        // Re-sort after reranking
384        results[..top_k].sort_by(|a, b| {
385            b.score
386                .partial_cmp(&a.score)
387                .unwrap_or(std::cmp::Ordering::Equal)
388        });
389        Ok(())
390    }
391
392    /// Extract ranking features
393    fn extract_features(
394        &self,
395        result: &RetrievalResult,
396        query: &str,
397        _context: &QueryContext,
398    ) -> Result<RankingFeatures> {
399        let doc = &result.document.content;
400
401        Ok(RankingFeatures {
402            semantic_score: result.score as f32,
403            keyword_score: self.keyword_match_score(doc, query),
404            bm25_score: self.compute_bm25_single(doc, query),
405            tfidf_score: self.compute_tfidf_single(doc, query),
406            recency_score: 0.5,    // Would use actual timestamp
407            popularity_score: 0.5, // Would use usage stats
408            entity_overlap: self.entity_overlap_score(doc, query),
409            length_ratio: (query.len() as f32 / doc.len().max(1) as f32).min(1.0),
410        })
411    }
412
413    /// Compute enhanced score for reranking
414    fn compute_enhanced_score(&self, result: &RetrievalResult, query: &str) -> Result<f32> {
415        let doc = &result.document.content;
416
417        // Enhanced features (more expensive to compute)
418        let exact_match_bonus = if doc.to_lowercase().contains(&query.to_lowercase()) {
419            0.2
420        } else {
421            0.0
422        };
423        let position_bonus = 1.0; // Would consider position in document
424        let quality_score = 0.8; // Would use quality metrics
425
426        Ok((result.score as f32) + exact_match_bonus + position_bonus * 0.1 + quality_score * 0.1)
427    }
428
429    // Helper methods
430
431    fn term_frequency(&self, doc: &str, term: &str) -> f32 {
432        let count = doc.to_lowercase().matches(&term.to_lowercase()).count();
433        count as f32
434    }
435
436    fn document_frequency(&self, term: &str) -> usize {
437        self.document_frequencies.get(term).copied().unwrap_or(1)
438    }
439
440    fn calculate_avg_doc_length(&self, results: &[RetrievalResult]) -> f32 {
441        if results.is_empty() {
442            return 100.0;
443        }
444
445        let total: usize = results
446            .iter()
447            .map(|r| r.document.content.split_whitespace().count())
448            .sum();
449
450        total as f32 / results.len() as f32
451    }
452
453    fn keyword_match_score(&self, doc: &str, query: &str) -> f32 {
454        let query_terms: Vec<&str> = query.split_whitespace().collect();
455        let doc_lower = doc.to_lowercase();
456
457        let matches = query_terms
458            .iter()
459            .filter(|term| doc_lower.contains(&term.to_lowercase()))
460            .count();
461
462        matches as f32 / query_terms.len().max(1) as f32
463    }
464
465    fn entity_overlap_score(&self, doc: &str, query: &str) -> f32 {
466        // Count overlap of entities (URIs)
467        let doc_entities: Vec<&str> = doc
468            .split_whitespace()
469            .filter(|w| w.starts_with("http"))
470            .collect();
471
472        let query_entities: Vec<&str> = query
473            .split_whitespace()
474            .filter(|w| w.starts_with("http"))
475            .collect();
476
477        if query_entities.is_empty() {
478            return 0.0;
479        }
480
481        let overlap = query_entities
482            .iter()
483            .filter(|e| doc_entities.contains(e))
484            .count();
485
486        overlap as f32 / query_entities.len() as f32
487    }
488
489    fn compute_bm25_single(&self, doc: &str, query: &str) -> f32 {
490        // Simplified BM25 for a single document
491        let query_terms: Vec<&str> = query.split_whitespace().collect();
492        let mut score = 0.0;
493
494        for term in query_terms {
495            let tf = self.term_frequency(doc, term);
496            score += tf / (tf + self.config.bm25_k1);
497        }
498
499        score
500    }
501
502    fn compute_tfidf_single(&self, doc: &str, query: &str) -> f32 {
503        let query_terms: Vec<&str> = query.split_whitespace().collect();
504        let mut score = 0.0;
505
506        for term in query_terms {
507            let tf = self.term_frequency(doc, term);
508            let idf = 2.0; // Simplified IDF
509            score += tf * idf;
510        }
511
512        score
513    }
514
515    fn calculate_similarity(&self, doc1: &str, doc2: &str) -> f32 {
516        // Jaccard similarity
517        let words1: std::collections::HashSet<_> = doc1.split_whitespace().collect();
518        let words2: std::collections::HashSet<_> = doc2.split_whitespace().collect();
519
520        let intersection = words1.intersection(&words2).count();
521        let union = words1.union(&words2).count();
522
523        if union == 0 {
524            0.0
525        } else {
526            intersection as f32 / union as f32
527        }
528    }
529
530    /// Update document statistics
531    pub fn update_statistics(&mut self, documents: &[String]) {
532        self.total_documents = documents.len();
533        self.document_frequencies.clear();
534
535        for doc in documents {
536            let words: std::collections::HashSet<_> = doc.split_whitespace().collect();
537            for word in words {
538                *self
539                    .document_frequencies
540                    .entry(word.to_string())
541                    .or_insert(0) += 1;
542            }
543        }
544
545        info!("Updated statistics for {} documents", self.total_documents);
546    }
547}
548
549#[cfg(test)]
550mod tests {
551    use super::*;
552    use crate::rag::types::RagDocument;
553
554    fn create_test_result(text: &str, score: f64) -> RetrievalResult {
555        let document = RagDocument::new(
556            uuid::Uuid::new_v4().to_string(),
557            text.to_string(),
558            "test".to_string(),
559        );
560
561        RetrievalResult {
562            document,
563            score,
564            relevance_factors: Vec::new(),
565        }
566    }
567
568    #[test]
569    fn test_bm25_ranking() {
570        let ranker = ResultRanker::new(RankingConfig::default());
571        let mut results = vec![
572            create_test_result("the movie Inception", 0.5),
573            create_test_result("another movie", 0.6),
574            create_test_result("Inception is a great movie", 0.4),
575        ];
576
577        ranker
578            .rank_bm25(&mut results, "Inception movie")
579            .expect("should succeed");
580
581        // Result with "Inception" should rank higher
582        assert!(results[0].document.content.contains("Inception"));
583    }
584
585    #[test]
586    fn test_hybrid_ranking() {
587        let ranker = ResultRanker::new(RankingConfig::default());
588        let mut results = vec![
589            create_test_result("test document one", 0.8),
590            create_test_result("test document two", 0.6),
591        ];
592
593        let context = QueryContext::new("session1".to_string());
594        ranker
595            .rank_hybrid(&mut results, "test document", &context)
596            .expect("should succeed");
597
598        // Should maintain relative ordering based on multiple signals
599        assert!(results[0].score >= results[1].score);
600    }
601
602    #[test]
603    fn test_keyword_match_score() {
604        let ranker = ResultRanker::new(RankingConfig::default());
605
606        let score1 = ranker.keyword_match_score("the movie Inception", "Inception movie");
607        let score2 = ranker.keyword_match_score("another document", "Inception movie");
608
609        assert!(score1 > score2);
610    }
611}