rrag 0.1.0-alpha.2

High-performance Rust framework for Retrieval-Augmented Generation with pluggable components, async-first design, and comprehensive observability
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//! # Query Classifier
//!
//! Intelligent classification of user queries to determine intent and appropriate search strategies.
//! Helps optimize retrieval by understanding what the user is looking for.

use crate::RragResult;
use serde::{Deserialize, Serialize};

/// Query classifier for intent detection
pub struct QueryClassifier {
    /// Intent patterns for classification
    patterns: Vec<IntentPattern>,

    /// Type patterns for classification
    type_patterns: Vec<TypePattern>,
}

/// Query intent categories
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum QueryIntent {
    /// Factual information seeking
    Factual,
    /// Conceptual understanding
    Conceptual,
    /// Procedural how-to questions
    Procedural,
    /// Comparative analysis
    Comparative,
    /// Troubleshooting and problem-solving
    Troubleshooting,
    /// Exploratory research
    Exploratory,
    /// Definitional queries
    Definitional,
    /// Opinion or recommendation seeking
    OpinionSeeking,
}

/// Query type categories
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum QueryType {
    /// Direct question
    Question,
    /// Command or request
    Command,
    /// Keyword search
    Keywords,
    /// Natural language statement
    Statement,
    /// Complex multi-part query
    Complex,
}

/// Result of query classification
#[derive(Debug, Clone)]
pub struct ClassificationResult {
    /// Original query
    pub query: String,

    /// Detected intent
    pub intent: QueryIntent,

    /// Detected query type
    pub query_type: QueryType,

    /// Confidence score (0.0 to 1.0)
    pub confidence: f32,

    /// Additional metadata about the query
    pub metadata: ClassificationMetadata,
}

/// Additional metadata from classification
#[derive(Debug, Clone)]
pub struct ClassificationMetadata {
    /// Key entities detected in the query
    pub entities: Vec<String>,

    /// Domain/topic detected
    pub domain: Option<String>,

    /// Complexity score
    pub complexity: f32,

    /// Whether query requires context
    pub needs_context: bool,

    /// Suggested search strategies
    pub suggested_strategies: Vec<String>,
}

/// Pattern for intent detection
struct IntentPattern {
    /// Intent this pattern detects
    intent: QueryIntent,
    /// Keywords that indicate this intent
    keywords: Vec<String>,
    /// Phrase patterns
    patterns: Vec<String>,
    /// Confidence score
    confidence: f32,
}

/// Pattern for type detection
struct TypePattern {
    /// Query type this pattern detects
    query_type: QueryType,
    /// Indicators for this type
    indicators: Vec<String>,
    /// Confidence score
    confidence: f32,
}

impl QueryClassifier {
    /// Create a new query classifier
    pub fn new() -> Self {
        let patterns = Self::init_intent_patterns();
        let type_patterns = Self::init_type_patterns();

        Self {
            patterns,
            type_patterns,
        }
    }

    /// Classify a query to determine intent and type
    pub async fn classify(&self, query: &str) -> RragResult<ClassificationResult> {
        let query_lower = query.to_lowercase();
        let tokens = self.tokenize(&query_lower);

        // Detect intent
        let (intent, intent_confidence) = self.detect_intent(&query_lower, &tokens);

        // Detect query type
        let (query_type, type_confidence) = self.detect_query_type(&query_lower, &tokens);

        // Extract entities
        let entities = self.extract_entities(&tokens);

        // Detect domain
        let domain = self.detect_domain(&tokens);

        // Calculate complexity
        let complexity = self.calculate_complexity(query, &tokens);

        // Determine if context is needed
        let needs_context = self.needs_context(query, &tokens);

        // Suggest search strategies
        let suggested_strategies = self.suggest_strategies(&intent, &query_type, complexity);

        // Overall confidence is the minimum of intent and type confidence
        let confidence = intent_confidence.min(type_confidence);

        Ok(ClassificationResult {
            query: query.to_string(),
            intent,
            query_type,
            confidence,
            metadata: ClassificationMetadata {
                entities,
                domain,
                complexity,
                needs_context,
                suggested_strategies,
            },
        })
    }

    /// Detect query intent
    fn detect_intent(&self, query: &str, tokens: &[String]) -> (QueryIntent, f32) {
        let mut best_intent = QueryIntent::Factual;
        let mut best_confidence = 0.0;

        for pattern in &self.patterns {
            let mut score = 0.0;
            let mut matches = 0;

            // Check keyword matches
            for keyword in &pattern.keywords {
                if tokens.iter().any(|t| t.contains(keyword)) {
                    score += 1.0;
                    matches += 1;
                }
            }

            // Check phrase patterns
            for phrase in &pattern.patterns {
                if query.contains(phrase) {
                    score += 2.0; // Phrase matches are stronger
                    matches += 1;
                }
            }

            if matches > 0 {
                // Normalize score
                let normalized_score = (score
                    / (pattern.keywords.len() + pattern.patterns.len()) as f32)
                    * pattern.confidence;

                if normalized_score > best_confidence {
                    best_intent = pattern.intent.clone();
                    best_confidence = normalized_score;
                }
            }
        }

        // Default fallback based on simple heuristics
        if best_confidence < 0.3 {
            if query.starts_with("what is") || query.starts_with("define") {
                best_intent = QueryIntent::Definitional;
                best_confidence = 0.6;
            } else if query.starts_with("how to") || query.contains("step") {
                best_intent = QueryIntent::Procedural;
                best_confidence = 0.6;
            } else if query.contains("compare")
                || query.contains("vs")
                || query.contains("difference")
            {
                best_intent = QueryIntent::Comparative;
                best_confidence = 0.6;
            }
        }

        (best_intent, best_confidence)
    }

    /// Detect query type
    fn detect_query_type(&self, query: &str, tokens: &[String]) -> (QueryType, f32) {
        let mut best_type = QueryType::Keywords;
        let mut best_confidence = 0.0;

        for pattern in &self.type_patterns {
            let mut matches = 0;

            for indicator in &pattern.indicators {
                if query.contains(indicator) || tokens.iter().any(|t| t == indicator) {
                    matches += 1;
                }
            }

            if matches > 0 {
                let confidence =
                    (matches as f32 / pattern.indicators.len() as f32) * pattern.confidence;
                if confidence > best_confidence {
                    best_type = pattern.query_type.clone();
                    best_confidence = confidence;
                }
            }
        }

        // Fallback heuristics
        if best_confidence < 0.5 {
            if query.ends_with('?') {
                best_type = QueryType::Question;
                best_confidence = 0.8;
            } else if tokens.len() <= 3 {
                best_type = QueryType::Keywords;
                best_confidence = 0.7;
            } else if tokens.len() > 10 {
                best_type = QueryType::Complex;
                best_confidence = 0.6;
            } else {
                best_type = QueryType::Statement;
                best_confidence = 0.5;
            }
        }

        (best_type, best_confidence)
    }

    /// Extract entities from query tokens
    fn extract_entities(&self, tokens: &[String]) -> Vec<String> {
        let mut entities = Vec::new();

        // Simple entity extraction based on capitalization and known patterns
        for token in tokens {
            // Check if it looks like a proper noun (capitalized)
            if token.chars().next().map_or(false, |c| c.is_uppercase()) {
                entities.push(token.clone());
            }

            // Check for technical terms
            let tech_terms = [
                "api",
                "sql",
                "json",
                "html",
                "css",
                "javascript",
                "python",
                "rust",
                "docker",
            ];
            if tech_terms.contains(&token.to_lowercase().as_str()) {
                entities.push(token.clone());
            }
        }

        entities
    }

    /// Detect query domain
    fn detect_domain(&self, tokens: &[String]) -> Option<String> {
        let domains = [
            (
                "technology",
                vec![
                    "code",
                    "programming",
                    "software",
                    "api",
                    "database",
                    "algorithm",
                    "computer",
                ],
            ),
            (
                "science",
                vec![
                    "research",
                    "study",
                    "experiment",
                    "theory",
                    "analysis",
                    "data",
                    "scientific",
                ],
            ),
            (
                "business",
                vec![
                    "market",
                    "sales",
                    "revenue",
                    "customer",
                    "profit",
                    "strategy",
                    "management",
                ],
            ),
            (
                "health",
                vec![
                    "medical",
                    "health",
                    "disease",
                    "treatment",
                    "doctor",
                    "medicine",
                    "patient",
                ],
            ),
            (
                "education",
                vec![
                    "learn",
                    "study",
                    "school",
                    "university",
                    "course",
                    "education",
                    "teach",
                ],
            ),
        ];

        for (domain, keywords) in &domains {
            let matches = keywords
                .iter()
                .filter(|&&keyword| tokens.iter().any(|t| t.contains(keyword)))
                .count();

            if matches >= 2 || (matches == 1 && tokens.len() <= 5) {
                return Some(domain.to_string());
            }
        }

        None
    }

    /// Calculate query complexity
    fn calculate_complexity(&self, query: &str, tokens: &[String]) -> f32 {
        let mut complexity = 0.0;

        // Length factor
        complexity += (tokens.len() as f32 / 20.0).min(1.0) * 0.3;

        // Question words
        let question_words = ["what", "how", "why", "when", "where", "which", "who"];
        let question_count = question_words
            .iter()
            .filter(|&&word| tokens.iter().any(|t| t == word))
            .count();
        complexity += (question_count as f32 * 0.1).min(0.3);

        // Conjunctions indicating complexity
        let conjunctions = ["and", "or", "but", "however", "also", "additionally"];
        let conjunction_count = conjunctions
            .iter()
            .filter(|&&word| tokens.iter().any(|t| t == word))
            .count();
        complexity += (conjunction_count as f32 * 0.15).min(0.2);

        // Nested questions
        if query.matches('?').count() > 1 {
            complexity += 0.2;
        }

        complexity.min(1.0)
    }

    /// Determine if query needs conversational context
    fn needs_context(&self, _query: &str, tokens: &[String]) -> bool {
        let context_indicators = [
            "this",
            "that",
            "it",
            "they",
            "them",
            "previous",
            "above",
            "following",
        ];
        let pronouns = ["it", "this", "that", "these", "those"];

        // Check for pronouns without clear antecedents
        let has_pronouns = pronouns
            .iter()
            .any(|&pronoun| tokens.contains(&pronoun.to_string()));

        // Check for context indicators
        let has_context_indicators = context_indicators
            .iter()
            .any(|&indicator| tokens.contains(&indicator.to_string()));

        // Very short queries often need context
        let is_very_short = tokens.len() <= 2;

        has_pronouns || has_context_indicators || is_very_short
    }

    /// Suggest search strategies based on classification
    fn suggest_strategies(
        &self,
        intent: &QueryIntent,
        query_type: &QueryType,
        complexity: f32,
    ) -> Vec<String> {
        let mut strategies = Vec::new();

        match intent {
            QueryIntent::Factual => {
                strategies.push("keyword_search".to_string());
                strategies.push("exact_match".to_string());
            }
            QueryIntent::Conceptual => {
                strategies.push("semantic_search".to_string());
                strategies.push("related_documents".to_string());
            }
            QueryIntent::Procedural => {
                strategies.push("step_by_step".to_string());
                strategies.push("tutorial_search".to_string());
            }
            QueryIntent::Comparative => {
                strategies.push("comparative_analysis".to_string());
                strategies.push("side_by_side".to_string());
            }
            QueryIntent::Troubleshooting => {
                strategies.push("problem_solution".to_string());
                strategies.push("diagnostic".to_string());
            }
            QueryIntent::Exploratory => {
                strategies.push("broad_search".to_string());
                strategies.push("topic_exploration".to_string());
            }
            QueryIntent::Definitional => {
                strategies.push("definition_search".to_string());
                strategies.push("glossary_lookup".to_string());
            }
            QueryIntent::OpinionSeeking => {
                strategies.push("review_search".to_string());
                strategies.push("opinion_mining".to_string());
            }
        }

        match query_type {
            QueryType::Complex => {
                strategies.push("query_decomposition".to_string());
                strategies.push("multi_step_search".to_string());
            }
            QueryType::Keywords => {
                strategies.push("keyword_expansion".to_string());
                strategies.push("term_matching".to_string());
            }
            _ => {}
        }

        if complexity > 0.7 {
            strategies.push("complex_reasoning".to_string());
            strategies.push("multi_document_synthesis".to_string());
        }

        strategies
    }

    /// Tokenize query
    fn tokenize(&self, query: &str) -> Vec<String> {
        query
            .split_whitespace()
            .map(|s| s.trim_matches(|c: char| !c.is_alphanumeric()))
            .filter(|s| !s.is_empty())
            .map(|s| s.to_lowercase())
            .collect()
    }

    /// Initialize intent detection patterns
    fn init_intent_patterns() -> Vec<IntentPattern> {
        vec![
            IntentPattern {
                intent: QueryIntent::Definitional,
                keywords: vec![
                    "define".to_string(),
                    "definition".to_string(),
                    "meaning".to_string(),
                ],
                patterns: vec![
                    "what is".to_string(),
                    "what does".to_string(),
                    "define".to_string(),
                ],
                confidence: 0.9,
            },
            IntentPattern {
                intent: QueryIntent::Procedural,
                keywords: vec![
                    "how".to_string(),
                    "step".to_string(),
                    "tutorial".to_string(),
                    "guide".to_string(),
                ],
                patterns: vec![
                    "how to".to_string(),
                    "step by step".to_string(),
                    "how do i".to_string(),
                ],
                confidence: 0.9,
            },
            IntentPattern {
                intent: QueryIntent::Comparative,
                keywords: vec![
                    "compare".to_string(),
                    "difference".to_string(),
                    "better".to_string(),
                    "versus".to_string(),
                ],
                patterns: vec![
                    "vs".to_string(),
                    "compared to".to_string(),
                    "difference between".to_string(),
                ],
                confidence: 0.8,
            },
            IntentPattern {
                intent: QueryIntent::Troubleshooting,
                keywords: vec![
                    "problem".to_string(),
                    "error".to_string(),
                    "fix".to_string(),
                    "issue".to_string(),
                    "broken".to_string(),
                ],
                patterns: vec![
                    "not working".to_string(),
                    "how to fix".to_string(),
                    "troubleshoot".to_string(),
                ],
                confidence: 0.8,
            },
            IntentPattern {
                intent: QueryIntent::Factual,
                keywords: vec![
                    "when".to_string(),
                    "where".to_string(),
                    "who".to_string(),
                    "which".to_string(),
                ],
                patterns: vec![
                    "when did".to_string(),
                    "where is".to_string(),
                    "who created".to_string(),
                ],
                confidence: 0.7,
            },
        ]
    }

    /// Initialize query type patterns
    fn init_type_patterns() -> Vec<TypePattern> {
        vec![
            TypePattern {
                query_type: QueryType::Question,
                indicators: vec![
                    "?".to_string(),
                    "what".to_string(),
                    "how".to_string(),
                    "why".to_string(),
                    "when".to_string(),
                    "where".to_string(),
                ],
                confidence: 0.9,
            },
            TypePattern {
                query_type: QueryType::Command,
                indicators: vec![
                    "show".to_string(),
                    "find".to_string(),
                    "get".to_string(),
                    "list".to_string(),
                    "give".to_string(),
                ],
                confidence: 0.8,
            },
            TypePattern {
                query_type: QueryType::Complex,
                indicators: vec![
                    "and".to_string(),
                    "or".to_string(),
                    "but".to_string(),
                    "however".to_string(),
                    "also".to_string(),
                ],
                confidence: 0.7,
            },
        ]
    }
}

impl Default for QueryClassifier {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_definitional_query() {
        let classifier = QueryClassifier::new();

        let result = classifier
            .classify("What is machine learning?")
            .await
            .unwrap();
        assert_eq!(result.intent, QueryIntent::Definitional);
        assert_eq!(result.query_type, QueryType::Question);
        assert!(result.confidence > 0.5);
    }

    #[tokio::test]
    async fn test_procedural_query() {
        let classifier = QueryClassifier::new();

        let result = classifier
            .classify("How to implement a REST API?")
            .await
            .unwrap();
        assert_eq!(result.intent, QueryIntent::Procedural);
        assert!(result.confidence > 0.5);
    }

    #[tokio::test]
    async fn test_comparative_query() {
        let classifier = QueryClassifier::new();

        let result = classifier
            .classify("Python vs Rust performance comparison")
            .await
            .unwrap();
        assert_eq!(result.intent, QueryIntent::Comparative);
        assert!(result.confidence > 0.5);
    }
}