Skip to main content

oxirs_chat/
intent_detector.rs

1//! User intent detection for SPARQL chat.
2//!
3//! Classifies natural-language user input into SPARQL query intents (SELECT,
4//! ASK, DESCRIBE, CONSTRUCT), detects entity and property mentions, scores
5//! intent confidence, handles multi-intent inputs, and recognises negation,
6//! aggregation, and temporal modifiers.
7
8use std::collections::HashMap;
9
10// ---------------------------------------------------------------------------
11// Intent types
12// ---------------------------------------------------------------------------
13
14/// SPARQL query type that the user likely intends.
15#[derive(Debug, Clone, PartialEq, Eq, Hash)]
16pub enum QueryIntent {
17    /// The user wants to retrieve bindings (SELECT).
18    Select,
19    /// The user wants a yes/no answer (ASK).
20    Ask,
21    /// The user wants a description of an entity (DESCRIBE).
22    Describe,
23    /// The user wants to build a sub-graph (CONSTRUCT).
24    Construct,
25}
26
27impl QueryIntent {
28    /// Lowercase label for serialisation / display.
29    pub fn as_str(&self) -> &'static str {
30        match self {
31            QueryIntent::Select => "select",
32            QueryIntent::Ask => "ask",
33            QueryIntent::Describe => "describe",
34            QueryIntent::Construct => "construct",
35        }
36    }
37}
38
39/// Aggregation function the user is asking for.
40#[derive(Debug, Clone, PartialEq, Eq, Hash)]
41pub enum AggregationIntent {
42    Count,
43    Sum,
44    Average,
45    Max,
46    Min,
47}
48
49/// Temporal modifier detected in the input.
50#[derive(Debug, Clone, PartialEq, Eq, Hash)]
51pub enum TemporalModifier {
52    Before,
53    After,
54    During,
55    Since,
56}
57
58// ---------------------------------------------------------------------------
59// Detection result
60// ---------------------------------------------------------------------------
61
62/// A scored intent classification.
63#[derive(Debug, Clone)]
64pub struct ScoredIntent {
65    /// The detected query intent.
66    pub intent: QueryIntent,
67    /// Confidence in `[0.0, 1.0]`.
68    pub confidence: f64,
69}
70
71/// Full result of intent detection on a single user message.
72#[derive(Debug, Clone)]
73pub struct IntentDetectionResult {
74    /// Primary intent (highest confidence).
75    pub primary_intent: ScoredIntent,
76    /// All detected intents with their scores.
77    pub all_intents: Vec<ScoredIntent>,
78    /// Entity mentions found in the input.
79    pub entity_mentions: Vec<String>,
80    /// Property mentions found in the input.
81    pub property_mentions: Vec<String>,
82    /// Whether negation was detected.
83    pub negation_detected: bool,
84    /// Aggregation intents detected.
85    pub aggregations: Vec<AggregationIntent>,
86    /// Temporal modifiers detected.
87    pub temporal_modifiers: Vec<TemporalModifier>,
88}
89
90// ---------------------------------------------------------------------------
91// IntentDetector
92// ---------------------------------------------------------------------------
93
94/// Configuration for the intent detector.
95#[derive(Debug, Clone)]
96pub struct IntentDetectorConfig {
97    /// Known entity names / IRIs to look for.
98    pub known_entities: Vec<String>,
99    /// Known property names to look for.
100    pub known_properties: Vec<String>,
101    /// Minimum confidence to report an intent.
102    pub min_confidence: f64,
103}
104
105impl Default for IntentDetectorConfig {
106    fn default() -> Self {
107        Self {
108            known_entities: Vec::new(),
109            known_properties: Vec::new(),
110            min_confidence: 0.1,
111        }
112    }
113}
114
115/// Keyword-based user intent detector for SPARQL chat interfaces.
116pub struct IntentDetector {
117    config: IntentDetectorConfig,
118}
119
120impl IntentDetector {
121    /// Create a new detector with default configuration.
122    pub fn new() -> Self {
123        Self {
124            config: IntentDetectorConfig::default(),
125        }
126    }
127
128    /// Create with a custom configuration.
129    pub fn with_config(config: IntentDetectorConfig) -> Self {
130        Self { config }
131    }
132
133    /// Register an entity name for mention detection.
134    pub fn add_entity(&mut self, entity: impl Into<String>) {
135        self.config.known_entities.push(entity.into());
136    }
137
138    /// Register a property name for mention detection.
139    pub fn add_property(&mut self, property: impl Into<String>) {
140        self.config.known_properties.push(property.into());
141    }
142
143    // ── Detection ────────────────────────────────────────────────────────
144
145    /// Detect intents from a user message.
146    pub fn detect(&self, text: &str) -> IntentDetectionResult {
147        let lower = text.to_lowercase();
148        let words: Vec<&str> = lower.split_whitespace().collect();
149
150        // Score each intent type.
151        let mut scores: HashMap<QueryIntent, f64> = HashMap::new();
152        scores.insert(QueryIntent::Select, self.score_select(&lower, &words));
153        scores.insert(QueryIntent::Ask, self.score_ask(&lower, &words));
154        scores.insert(QueryIntent::Describe, self.score_describe(&lower, &words));
155        scores.insert(QueryIntent::Construct, self.score_construct(&lower, &words));
156
157        // Normalise so max = 1.0 if any signal exists.
158        let max_score = scores.values().copied().fold(0.0f64, f64::max);
159        if max_score > 0.0 {
160            for v in scores.values_mut() {
161                *v /= max_score;
162            }
163        } else {
164            // No signal → default to SELECT with low confidence.
165            scores.insert(QueryIntent::Select, 0.3);
166        }
167
168        // Build sorted intent list.
169        let mut all_intents: Vec<ScoredIntent> = scores
170            .into_iter()
171            .filter(|(_, c)| *c >= self.config.min_confidence)
172            .map(|(intent, confidence)| ScoredIntent { intent, confidence })
173            .collect();
174        all_intents.sort_by(|a, b| {
175            b.confidence
176                .partial_cmp(&a.confidence)
177                .unwrap_or(std::cmp::Ordering::Equal)
178        });
179
180        let primary = all_intents.first().cloned().unwrap_or(ScoredIntent {
181            intent: QueryIntent::Select,
182            confidence: 0.0,
183        });
184
185        let entity_mentions = self.detect_entities(&lower);
186        let property_mentions = self.detect_properties(&lower);
187        let negation_detected = self.detect_negation(&lower);
188        let aggregations = self.detect_aggregations(&lower);
189        let temporal_modifiers = self.detect_temporal(&lower);
190
191        IntentDetectionResult {
192            primary_intent: primary,
193            all_intents,
194            entity_mentions,
195            property_mentions,
196            negation_detected,
197            aggregations,
198            temporal_modifiers,
199        }
200    }
201
202    // ── Intent scorers ───────────────────────────────────────────────────
203
204    /// Score SELECT intent based on wh-words and list-related keywords.
205    fn score_select(&self, text: &str, words: &[&str]) -> f64 {
206        let mut score = 0.0;
207        let select_keywords = [
208            "what", "which", "who", "where", "when", "list", "show", "find", "get", "give", "tell",
209            "retrieve", "fetch", "return",
210        ];
211        for kw in &select_keywords {
212            if words.contains(kw) {
213                score += 1.0;
214            }
215        }
216        // "how many" is also select-ish (with aggregation)
217        if text.contains("how many") || text.contains("how much") {
218            score += 1.0;
219        }
220        score
221    }
222
223    /// Score ASK intent based on yes/no question patterns.
224    fn score_ask(&self, text: &str, words: &[&str]) -> f64 {
225        let mut score = 0.0;
226        let ask_keywords = [
227            "is", "are", "does", "do", "has", "have", "can", "was", "were", "will", "would",
228            "could", "should",
229        ];
230        // The keyword must be the first word to signal a yes/no question.
231        if let Some(&first) = words.first() {
232            if ask_keywords.contains(&first) {
233                score += 2.0;
234            }
235        }
236        if text.contains("is there") || text.contains("does it") {
237            score += 1.0;
238        }
239        if text.ends_with('?') && score > 0.0 {
240            score += 0.5;
241        }
242        score
243    }
244
245    /// Score DESCRIBE intent.
246    fn score_describe(&self, text: &str, words: &[&str]) -> f64 {
247        let mut score = 0.0;
248        let describe_keywords = [
249            "describe",
250            "explain",
251            "detail",
252            "about",
253            "information",
254            "definition",
255            "overview",
256        ];
257        for kw in &describe_keywords {
258            if words.contains(kw) {
259                score += 1.5;
260            }
261        }
262        if text.contains("tell me about") || text.contains("what is") {
263            score += 1.0;
264        }
265        score
266    }
267
268    /// Score CONSTRUCT intent.
269    fn score_construct(&self, _text: &str, words: &[&str]) -> f64 {
270        let mut score = 0.0;
271        let construct_keywords = [
272            "construct",
273            "build",
274            "create",
275            "generate",
276            "produce",
277            "graph",
278            "subgraph",
279            "triples",
280            "rdf",
281        ];
282        for kw in &construct_keywords {
283            if words.contains(kw) {
284                score += 1.5;
285            }
286        }
287        score
288    }
289
290    // ── Entity / property detection ──────────────────────────────────────
291
292    fn detect_entities(&self, text: &str) -> Vec<String> {
293        let mut found = Vec::new();
294
295        // Check known entities (case-insensitive substring match).
296        for entity in &self.config.known_entities {
297            if text.contains(&entity.to_lowercase()) {
298                found.push(entity.clone());
299            }
300        }
301
302        // Also detect IRI-like patterns.
303        for word in text.split_whitespace() {
304            if word.starts_with("http://") || word.starts_with("https://") {
305                let cleaned = word.trim_matches(|c: char| {
306                    !c.is_alphanumeric() && c != ':' && c != '/' && c != '.' && c != '#'
307                });
308                if !found.contains(&cleaned.to_string()) {
309                    found.push(cleaned.to_string());
310                }
311            }
312        }
313
314        found
315    }
316
317    fn detect_properties(&self, text: &str) -> Vec<String> {
318        let mut found = Vec::new();
319        for prop in &self.config.known_properties {
320            if text.contains(&prop.to_lowercase()) {
321                found.push(prop.clone());
322            }
323        }
324        found
325    }
326
327    // ── Negation detection ───────────────────────────────────────────────
328
329    fn detect_negation(&self, text: &str) -> bool {
330        let negation_markers = [
331            "not",
332            "n't",
333            "no",
334            "never",
335            "without",
336            "except",
337            "exclude",
338            "excluding",
339            "neither",
340            "nor",
341        ];
342        let words: Vec<&str> = text.split_whitespace().collect();
343        for marker in &negation_markers {
344            if words.contains(marker) {
345                return true;
346            }
347            // Handle contractions like "doesn't"
348            if text.contains(marker) {
349                return true;
350            }
351        }
352        false
353    }
354
355    // ── Aggregation detection ────────────────────────────────────────────
356
357    fn detect_aggregations(&self, text: &str) -> Vec<AggregationIntent> {
358        let mut agg = Vec::new();
359        if text.contains("count") || text.contains("how many") || text.contains("number of") {
360            agg.push(AggregationIntent::Count);
361        }
362        if text.contains("average") || text.contains("avg") || text.contains("mean") {
363            agg.push(AggregationIntent::Average);
364        }
365        if text.contains(" sum ") || text.contains("total") {
366            agg.push(AggregationIntent::Sum);
367        }
368        if text.contains("maximum")
369            || text.contains(" max ")
370            || text.contains("highest")
371            || text.contains("largest")
372        {
373            agg.push(AggregationIntent::Max);
374        }
375        if text.contains("minimum")
376            || text.contains(" min ")
377            || text.contains("lowest")
378            || text.contains("smallest")
379        {
380            agg.push(AggregationIntent::Min);
381        }
382        agg
383    }
384
385    // ── Temporal detection ───────────────────────────────────────────────
386
387    fn detect_temporal(&self, text: &str) -> Vec<TemporalModifier> {
388        let mut mods = Vec::new();
389        if text.contains("before") || text.contains("prior to") || text.contains("earlier than") {
390            mods.push(TemporalModifier::Before);
391        }
392        if text.contains("after") || text.contains("later than") || text.contains("following") {
393            mods.push(TemporalModifier::After);
394        }
395        if text.contains("during") || text.contains("while") || text.contains("in the period") {
396            mods.push(TemporalModifier::During);
397        }
398        if text.contains("since") || text.contains("from") || text.contains("starting") {
399            mods.push(TemporalModifier::Since);
400        }
401        mods
402    }
403}
404
405impl Default for IntentDetector {
406    fn default() -> Self {
407        Self::new()
408    }
409}
410
411// ---------------------------------------------------------------------------
412// Tests
413// ---------------------------------------------------------------------------
414
415#[cfg(test)]
416mod tests {
417    use super::*;
418
419    fn detector() -> IntentDetector {
420        IntentDetector::new()
421    }
422
423    fn detector_with_entities() -> IntentDetector {
424        let mut d = IntentDetector::new();
425        d.add_entity("Alice");
426        d.add_entity("BRCA1");
427        d.add_property("knows");
428        d.add_property("name");
429        d
430    }
431
432    // ── QueryIntent enum ─────────────────────────────────────────────────
433
434    #[test]
435    fn test_query_intent_as_str_select() {
436        assert_eq!(QueryIntent::Select.as_str(), "select");
437    }
438
439    #[test]
440    fn test_query_intent_as_str_ask() {
441        assert_eq!(QueryIntent::Ask.as_str(), "ask");
442    }
443
444    #[test]
445    fn test_query_intent_as_str_describe() {
446        assert_eq!(QueryIntent::Describe.as_str(), "describe");
447    }
448
449    #[test]
450    fn test_query_intent_as_str_construct() {
451        assert_eq!(QueryIntent::Construct.as_str(), "construct");
452    }
453
454    // ── Default construction ─────────────────────────────────────────────
455
456    #[test]
457    fn test_default_detector() {
458        let d = IntentDetector::default();
459        let r = d.detect("hello");
460        assert!(r.primary_intent.confidence >= 0.0);
461    }
462
463    #[test]
464    fn test_config_default() {
465        let cfg = IntentDetectorConfig::default();
466        assert!(cfg.known_entities.is_empty());
467        assert!(cfg.known_properties.is_empty());
468        assert!((cfg.min_confidence - 0.1).abs() < 1e-10);
469    }
470
471    // ── SELECT intent ────────────────────────────────────────────────────
472
473    #[test]
474    fn test_select_what_query() {
475        let d = detector();
476        let r = d.detect("What are the genes associated with cancer?");
477        assert_eq!(r.primary_intent.intent, QueryIntent::Select);
478    }
479
480    #[test]
481    fn test_select_who_query() {
482        let d = detector();
483        let r = d.detect("Who knows Alice?");
484        assert_eq!(r.primary_intent.intent, QueryIntent::Select);
485    }
486
487    #[test]
488    fn test_select_list_query() {
489        let d = detector();
490        let r = d.detect("List all proteins in the dataset");
491        assert_eq!(r.primary_intent.intent, QueryIntent::Select);
492    }
493
494    #[test]
495    fn test_select_show_query() {
496        let d = detector();
497        let r = d.detect("Show me the results");
498        assert_eq!(r.primary_intent.intent, QueryIntent::Select);
499    }
500
501    // ── ASK intent ───────────────────────────────────────────────────────
502
503    #[test]
504    fn test_ask_is_there() {
505        let d = detector();
506        let r = d.detect("Is there a connection between A and B?");
507        assert_eq!(r.primary_intent.intent, QueryIntent::Ask);
508    }
509
510    #[test]
511    fn test_ask_does() {
512        let d = detector();
513        let r = d.detect("Does Alice know Bob?");
514        assert_eq!(r.primary_intent.intent, QueryIntent::Ask);
515    }
516
517    #[test]
518    fn test_ask_has() {
519        let d = detector();
520        let r = d.detect("Has the experiment been completed?");
521        assert_eq!(r.primary_intent.intent, QueryIntent::Ask);
522    }
523
524    // ── DESCRIBE intent ──────────────────────────────────────────────────
525
526    #[test]
527    fn test_describe_explicit() {
528        let d = detector();
529        let r = d.detect("Describe the protein BRCA1");
530        assert_eq!(r.primary_intent.intent, QueryIntent::Describe);
531    }
532
533    #[test]
534    fn test_describe_tell_me_about() {
535        let d = detector();
536        let r = d.detect("Tell me about breast cancer genes");
537        // "tell" triggers select, "about" triggers describe
538        // "about" with 1.5 weight should win
539        let has_describe = r
540            .all_intents
541            .iter()
542            .any(|i| i.intent == QueryIntent::Describe);
543        assert!(has_describe);
544    }
545
546    #[test]
547    fn test_describe_explain() {
548        let d = detector();
549        let r = d.detect("Explain the relationship between X and Y");
550        assert_eq!(r.primary_intent.intent, QueryIntent::Describe);
551    }
552
553    // ── CONSTRUCT intent ─────────────────────────────────────────────────
554
555    #[test]
556    fn test_construct_explicit() {
557        let d = detector();
558        let r = d.detect("Construct a subgraph of related triples");
559        assert_eq!(r.primary_intent.intent, QueryIntent::Construct);
560    }
561
562    #[test]
563    fn test_construct_build() {
564        let d = detector();
565        let r = d.detect("Build an RDF graph of the results");
566        assert_eq!(r.primary_intent.intent, QueryIntent::Construct);
567    }
568
569    // ── Entity mention detection ─────────────────────────────────────────
570
571    #[test]
572    fn test_entity_mention_known() {
573        let d = detector_with_entities();
574        let r = d.detect("What do we know about alice?");
575        assert!(r.entity_mentions.contains(&"Alice".to_string()));
576    }
577
578    #[test]
579    fn test_entity_mention_iri() {
580        let d = detector();
581        let r = d.detect("Describe http://example.org/entity1 please");
582        assert!(r
583            .entity_mentions
584            .iter()
585            .any(|e| e.contains("http://example.org/entity1")));
586    }
587
588    #[test]
589    fn test_entity_mention_none() {
590        let d = detector_with_entities();
591        let r = d.detect("How many items are there?");
592        assert!(r.entity_mentions.is_empty());
593    }
594
595    // ── Property mention detection ───────────────────────────────────────
596
597    #[test]
598    fn test_property_mention_known() {
599        let d = detector_with_entities();
600        let r = d.detect("What is the name of Alice?");
601        assert!(r.property_mentions.contains(&"name".to_string()));
602    }
603
604    #[test]
605    fn test_property_mention_none() {
606        let d = detector_with_entities();
607        let r = d.detect("Hello world");
608        assert!(r.property_mentions.is_empty());
609    }
610
611    // ── Negation detection ───────────────────────────────────────────────
612
613    #[test]
614    fn test_negation_not() {
615        let d = detector();
616        let r = d.detect("Show items that are not active");
617        assert!(r.negation_detected);
618    }
619
620    #[test]
621    fn test_negation_without() {
622        let d = detector();
623        let r = d.detect("Find proteins without mutations");
624        assert!(r.negation_detected);
625    }
626
627    #[test]
628    fn test_negation_except() {
629        let d = detector();
630        let r = d.detect("All genes except BRCA1");
631        assert!(r.negation_detected);
632    }
633
634    #[test]
635    fn test_no_negation() {
636        let d = detector();
637        let r = d.detect("List all active items");
638        assert!(!r.negation_detected);
639    }
640
641    // ── Aggregation detection ────────────────────────────────────────────
642
643    #[test]
644    fn test_aggregation_count() {
645        let d = detector();
646        let r = d.detect("How many genes are there?");
647        assert!(r.aggregations.contains(&AggregationIntent::Count));
648    }
649
650    #[test]
651    fn test_aggregation_average() {
652        let d = detector();
653        let r = d.detect("What is the average score?");
654        assert!(r.aggregations.contains(&AggregationIntent::Average));
655    }
656
657    #[test]
658    fn test_aggregation_max() {
659        let d = detector();
660        let r = d.detect("What is the maximum value?");
661        assert!(r.aggregations.contains(&AggregationIntent::Max));
662    }
663
664    #[test]
665    fn test_aggregation_min() {
666        let d = detector();
667        let r = d.detect("What is the minimum temperature?");
668        assert!(r.aggregations.contains(&AggregationIntent::Min));
669    }
670
671    #[test]
672    fn test_aggregation_sum() {
673        let d = detector();
674        let r = d.detect("What is the total sum of sales?");
675        assert!(r.aggregations.contains(&AggregationIntent::Sum));
676    }
677
678    #[test]
679    fn test_no_aggregation() {
680        let d = detector();
681        let r = d.detect("Show me the list");
682        assert!(r.aggregations.is_empty());
683    }
684
685    // ── Temporal detection ───────────────────────────────────────────────
686
687    #[test]
688    fn test_temporal_before() {
689        let d = detector();
690        let r = d.detect("Events before 2020");
691        assert!(r.temporal_modifiers.contains(&TemporalModifier::Before));
692    }
693
694    #[test]
695    fn test_temporal_after() {
696        let d = detector();
697        let r = d.detect("Publications after January");
698        assert!(r.temporal_modifiers.contains(&TemporalModifier::After));
699    }
700
701    #[test]
702    fn test_temporal_during() {
703        let d = detector();
704        let r = d.detect("Changes during the experiment");
705        assert!(r.temporal_modifiers.contains(&TemporalModifier::During));
706    }
707
708    #[test]
709    fn test_temporal_since() {
710        let d = detector();
711        let r = d.detect("Active since last year");
712        assert!(r.temporal_modifiers.contains(&TemporalModifier::Since));
713    }
714
715    #[test]
716    fn test_no_temporal() {
717        let d = detector();
718        let r = d.detect("List all items");
719        assert!(r.temporal_modifiers.is_empty());
720    }
721
722    // ── Multi-intent ─────────────────────────────────────────────────────
723
724    #[test]
725    fn test_multi_intent_select_and_count() {
726        let d = detector();
727        let r = d.detect("How many genes are associated with cancer?");
728        // Should have both SELECT (from "how") and aggregation COUNT
729        assert_eq!(r.primary_intent.intent, QueryIntent::Select);
730        assert!(r.aggregations.contains(&AggregationIntent::Count));
731    }
732
733    #[test]
734    fn test_multi_intent_multiple_scored() {
735        let d = detector();
736        let r = d.detect("What is the description of this entity?");
737        // Both SELECT ("what") and DESCRIBE ("description") should score
738        assert!(r.all_intents.len() >= 2);
739    }
740
741    // ── Confidence scoring ───────────────────────────────────────────────
742
743    #[test]
744    fn test_confidence_in_range() {
745        let d = detector();
746        let r = d.detect("What genes are there?");
747        for intent in &r.all_intents {
748            assert!(intent.confidence >= 0.0 && intent.confidence <= 1.0);
749        }
750    }
751
752    #[test]
753    fn test_primary_intent_highest_confidence() {
754        let d = detector();
755        let r = d.detect("Describe the main protein");
756        if r.all_intents.len() > 1 {
757            assert!(r.primary_intent.confidence >= r.all_intents[1].confidence);
758        }
759    }
760
761    // ── Edge cases ───────────────────────────────────────────────────────
762
763    #[test]
764    fn test_empty_input() {
765        let d = detector();
766        let r = d.detect("");
767        // Should still produce a result (low-confidence default)
768        assert!(r.primary_intent.confidence >= 0.0);
769    }
770
771    #[test]
772    fn test_gibberish_input() {
773        let d = detector();
774        let r = d.detect("xyzzy plugh foo bar");
775        // No keywords → default SELECT with low confidence
776        assert!(r.primary_intent.confidence <= 0.5);
777    }
778}