Skip to main content

oxirs_chat/
intent_classifier.rs

1//! # Intent Classifier for SPARQL/RDF Chatbots
2//!
3//! Rule-based intent classification using keyword matching and simple
4//! string pattern matching. Supports the full set of SPARQL/RDF intents
5//! required for a semantic-web chatbot.
6//!
7//! ## Intents
8//!
9//! - **SparqlQuery**: SPARQL SELECT / ASK / CONSTRUCT queries
10//! - **RdfInsert**: Insert triples
11//! - **RdfDelete**: Delete triples
12//! - **SchemaQuestion**: Ontology / schema questions
13//! - **FactLookup**: Entity lookups and listing
14//! - **Navigation**: Browsing the knowledge graph
15//! - **Help**: How-to questions
16//! - **Greeting**: Salutations
17//! - **Farewell**: Goodbyes
18//! - **Unknown**: No rule matched with sufficient confidence
19
20use serde::{Deserialize, Serialize};
21
22// ─────────────────────────────────────────────
23// Intent
24// ─────────────────────────────────────────────
25
26/// Recognised chatbot intent.
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28pub enum Intent {
29    SparqlQuery,
30    RdfInsert,
31    RdfDelete,
32    SchemaQuestion,
33    FactLookup,
34    Navigation,
35    Help,
36    Greeting,
37    Farewell,
38    Unknown,
39}
40
41impl std::fmt::Display for Intent {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        write!(f, "{self:?}")
44    }
45}
46
47// ─────────────────────────────────────────────
48// Rule
49// ─────────────────────────────────────────────
50
51/// A single classification rule for one intent.
52#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct IntentRule {
54    pub intent: Intent,
55    /// Exact lowercase keywords to look for.
56    pub keywords: Vec<String>,
57    /// Literal substrings (case-insensitive) to search for.
58    pub patterns: Vec<String>,
59    /// Score multiplier for this rule.
60    pub weight: f64,
61}
62
63impl IntentRule {
64    fn new(intent: Intent, keywords: &[&str], patterns: &[&str], weight: f64) -> Self {
65        Self {
66            intent,
67            keywords: keywords.iter().map(|s| s.to_string()).collect(),
68            patterns: patterns.iter().map(|s| s.to_string()).collect(),
69            weight,
70        }
71    }
72}
73
74// ─────────────────────────────────────────────
75// Result
76// ─────────────────────────────────────────────
77
78/// Result of classifying a single utterance.
79#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct ClassificationResult {
81    pub intent: Intent,
82    /// Confidence in [0.0, 1.0].
83    pub confidence: f64,
84    /// Keywords that contributed to the match.
85    pub matched_keywords: Vec<String>,
86    /// Patterns that contributed to the match.
87    pub matched_patterns: Vec<String>,
88}
89
90// ─────────────────────────────────────────────
91// Classifier
92// ─────────────────────────────────────────────
93
94/// Rule-based intent classifier.
95#[derive(Debug, Clone)]
96pub struct IntentClassifier {
97    rules: Vec<IntentRule>,
98}
99
100impl Default for IntentClassifier {
101    fn default() -> Self {
102        Self::new()
103    }
104}
105
106impl IntentClassifier {
107    /// Create a new classifier pre-loaded with default rules.
108    pub fn new() -> Self {
109        let rules = vec![
110            IntentRule::new(
111                Intent::SparqlQuery,
112                &[
113                    "select",
114                    "where",
115                    "sparql",
116                    "query",
117                    "ask",
118                    "construct",
119                    "describe",
120                    "prefix",
121                ],
122                &["SELECT * WHERE", "PREFIX ", "ASK {", "CONSTRUCT {"],
123                1.5,
124            ),
125            IntentRule::new(
126                Intent::RdfInsert,
127                &["insert", "add", "create", "triple", "assert"],
128                &["insert data", "add triple", "INSERT DATA"],
129                1.2,
130            ),
131            IntentRule::new(
132                Intent::RdfDelete,
133                &["delete", "remove", "drop", "retract"],
134                &["delete data", "remove triple", "DROP GRAPH"],
135                1.2,
136            ),
137            IntentRule::new(
138                Intent::SchemaQuestion,
139                &[
140                    "schema",
141                    "ontology",
142                    "class",
143                    "property",
144                    "define",
145                    "definition",
146                    "concept",
147                    "subclass",
148                    "domain",
149                    "range",
150                ],
151                &["what is", "what are", "define "],
152                1.0,
153            ),
154            IntentRule::new(
155                Intent::FactLookup,
156                &[
157                    "who", "when", "which", "find", "list", "show", "get", "fetch", "retrieve",
158                ],
159                &["tell me about", "find all", "list all"],
160                1.0,
161            ),
162            IntentRule::new(
163                Intent::Navigation,
164                &[
165                    "navigate", "browse", "explore", "graph", "node", "edge", "traverse", "path",
166                ],
167                &["show graph", "browse to", "navigate to"],
168                0.9,
169            ),
170            IntentRule::new(
171                Intent::Help,
172                &[
173                    "help", "assist", "support", "tutorial", "guide", "manual", "howto",
174                ],
175                &["how to", "how do i", "what can you", "show me how"],
176                2.0,
177            ),
178            IntentRule::new(
179                Intent::Greeting,
180                &[
181                    "hello",
182                    "hi",
183                    "hey",
184                    "greetings",
185                    "howdy",
186                    "morning",
187                    "afternoon",
188                    "evening",
189                ],
190                &["good morning", "good afternoon", "good evening"],
191                0.8,
192            ),
193            IntentRule::new(
194                Intent::Farewell,
195                &[
196                    "bye", "goodbye", "farewell", "ciao", "later", "thanks", "thank",
197                ],
198                &["see you", "take care", "good bye"],
199                1.5,
200            ),
201        ];
202        Self { rules }
203    }
204
205    /// Classify a single utterance.
206    pub fn classify(&self, text: &str) -> ClassificationResult {
207        let normalised = Self::normalize_text(text);
208        let mut best_score = 0.0_f64;
209        let mut best_intent = Intent::Unknown;
210        let mut best_kws: Vec<String> = vec![];
211        let mut best_pats: Vec<String> = vec![];
212
213        for rule in &self.rules {
214            let (score, kws, pats) = self.score_rule(rule, &normalised);
215            if score > best_score {
216                best_score = score;
217                best_intent = rule.intent.clone();
218                best_kws = kws;
219                best_pats = pats;
220            }
221        }
222
223        let confidence = (best_score / 10.0_f64).min(1.0);
224
225        ClassificationResult {
226            intent: best_intent,
227            confidence,
228            matched_keywords: best_kws,
229            matched_patterns: best_pats,
230        }
231    }
232
233    /// Add a custom rule to the classifier.
234    pub fn add_rule(&mut self, rule: IntentRule) {
235        self.rules.push(rule);
236    }
237
238    /// Score a single rule against the normalised text.
239    ///
240    /// Returns `(score, matched_keywords, matched_patterns)`.
241    pub fn score_rule(&self, rule: &IntentRule, text: &str) -> (f64, Vec<String>, Vec<String>) {
242        let mut score = 0.0_f64;
243        let mut matched_kws: Vec<String> = Vec::new();
244        let mut matched_pats: Vec<String> = Vec::new();
245
246        // Keyword matching: each matched keyword contributes 1 point × weight
247        for kw in &rule.keywords {
248            // Use word-boundary-like check: check if kw appears as a token
249            if contains_word(text, kw) {
250                score += rule.weight;
251                matched_kws.push(kw.clone());
252            }
253        }
254
255        // Pattern matching: each matched pattern contributes 2 points × weight
256        for pat in &rule.patterns {
257            if text.contains(pat.to_lowercase().as_str()) {
258                score += rule.weight * 2.0;
259                matched_pats.push(pat.clone());
260            }
261        }
262
263        (score, matched_kws, matched_pats)
264    }
265
266    /// Lowercase and strip punctuation from text.
267    pub fn normalize_text(text: &str) -> String {
268        text.chars()
269            .map(|c| {
270                if c.is_alphanumeric() || c == ' ' || c == '_' {
271                    c.to_ascii_lowercase()
272                } else {
273                    ' '
274                }
275            })
276            .collect::<String>()
277            // Collapse multiple spaces
278            .split_whitespace()
279            .collect::<Vec<_>>()
280            .join(" ")
281    }
282
283    /// Classify a batch of texts.
284    pub fn batch_classify(&self, texts: &[&str]) -> Vec<ClassificationResult> {
285        texts.iter().map(|t| self.classify(t)).collect()
286    }
287
288    /// Return the top-`n` intents by descending score for the given text.
289    pub fn top_n(&self, text: &str, n: usize) -> Vec<(Intent, f64)> {
290        let normalised = Self::normalize_text(text);
291        let mut scores: Vec<(Intent, f64)> = self
292            .rules
293            .iter()
294            .map(|rule| {
295                let (score, _, _) = self.score_rule(rule, &normalised);
296                let confidence = (score / 10.0_f64).min(1.0);
297                (rule.intent.clone(), confidence)
298            })
299            .collect();
300
301        // Sort descending by score
302        scores.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
303        scores.truncate(n);
304        scores
305    }
306}
307
308// ─────────────────────────────────────────────
309// Helpers
310// ─────────────────────────────────────────────
311
312/// Check if `word` appears as a whole token in `text` (space-delimited).
313fn contains_word(text: &str, word: &str) -> bool {
314    text.split_whitespace().any(|t| t == word)
315}
316
317// ─────────────────────────────────────────────
318// Tests
319// ─────────────────────────────────────────────
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324
325    fn clf() -> IntentClassifier {
326        IntentClassifier::new()
327    }
328
329    // ── normalize_text ─────────────────────────────────────────────────
330
331    #[test]
332    fn test_normalize_lowercase() {
333        assert_eq!(
334            IntentClassifier::normalize_text("HELLO World"),
335            "hello world"
336        );
337    }
338
339    #[test]
340    fn test_normalize_strips_punctuation() {
341        let n = IntentClassifier::normalize_text("Hello, world!");
342        assert!(!n.contains(','));
343        assert!(!n.contains('!'));
344    }
345
346    #[test]
347    fn test_normalize_collapses_spaces() {
348        let n = IntentClassifier::normalize_text("foo   bar");
349        assert_eq!(n, "foo bar");
350    }
351
352    #[test]
353    fn test_normalize_empty() {
354        assert_eq!(IntentClassifier::normalize_text(""), "");
355    }
356
357    // ── classify — SparqlQuery ──────────────────────────────────────────
358
359    #[test]
360    fn test_classify_sparql_select() {
361        let result = clf().classify("SELECT * WHERE { ?s ?p ?o }");
362        assert_eq!(result.intent, Intent::SparqlQuery);
363        assert!(result.confidence > 0.0);
364    }
365
366    #[test]
367    fn test_classify_sparql_ask() {
368        let result = clf().classify("ask where the subject is defined");
369        assert_eq!(result.intent, Intent::SparqlQuery);
370    }
371
372    #[test]
373    fn test_classify_sparql_prefix() {
374        let result = clf().classify("Can you run a sparql query for me?");
375        assert_eq!(result.intent, Intent::SparqlQuery);
376    }
377
378    // ── classify — RdfInsert ────────────────────────────────────────────
379
380    #[test]
381    fn test_classify_rdf_insert() {
382        let result = clf().classify("INSERT DATA { <s> <p> <o> }");
383        assert_eq!(result.intent, Intent::RdfInsert);
384    }
385
386    #[test]
387    fn test_classify_add_triple() {
388        let result = clf().classify("add triple <a> <b> <c>");
389        // "add" and "triple" both match RdfInsert keywords
390        assert_eq!(result.intent, Intent::RdfInsert);
391    }
392
393    // ── classify — RdfDelete ────────────────────────────────────────────
394
395    #[test]
396    fn test_classify_rdf_delete() {
397        let result = clf().classify("DELETE DATA { <s> <p> <o> }");
398        assert_eq!(result.intent, Intent::RdfDelete);
399    }
400
401    #[test]
402    fn test_classify_remove_triple() {
403        let result = clf().classify("remove triple <a> <b>");
404        assert_eq!(result.intent, Intent::RdfDelete);
405    }
406
407    // ── classify — SchemaQuestion ───────────────────────────────────────
408
409    #[test]
410    fn test_classify_schema_question_what_is() {
411        let result = clf().classify("what is the ontology for Person class?");
412        assert_eq!(result.intent, Intent::SchemaQuestion);
413    }
414
415    #[test]
416    fn test_classify_schema_class() {
417        let result = clf().classify("define the class hierarchy");
418        assert_eq!(result.intent, Intent::SchemaQuestion);
419    }
420
421    // ── classify — FactLookup ───────────────────────────────────────────
422
423    #[test]
424    fn test_classify_fact_lookup_who() {
425        let result = clf().classify("who created this resource");
426        assert_eq!(result.intent, Intent::FactLookup);
427    }
428
429    #[test]
430    fn test_classify_fact_lookup_find() {
431        let result = clf().classify("find all authors in the graph");
432        assert_eq!(result.intent, Intent::FactLookup);
433    }
434
435    #[test]
436    fn test_classify_fact_lookup_list() {
437        let result = clf().classify("list all available datasets");
438        assert_eq!(result.intent, Intent::FactLookup);
439    }
440
441    // ── classify — Help ──────────────────────────────────────────────────
442
443    #[test]
444    fn test_classify_help() {
445        let result = clf().classify("help me with SPARQL");
446        assert_eq!(result.intent, Intent::Help);
447    }
448
449    #[test]
450    fn test_classify_how_to() {
451        let result = clf().classify("how to write a SPARQL query");
452        assert_eq!(result.intent, Intent::Help);
453    }
454
455    // ── classify — Greeting ─────────────────────────────────────────────
456
457    #[test]
458    fn test_classify_hello() {
459        let result = clf().classify("Hello!");
460        assert_eq!(result.intent, Intent::Greeting);
461    }
462
463    #[test]
464    fn test_classify_good_morning() {
465        let result = clf().classify("Good morning everyone");
466        assert_eq!(result.intent, Intent::Greeting);
467    }
468
469    #[test]
470    fn test_classify_hi() {
471        let result = clf().classify("Hi there");
472        assert_eq!(result.intent, Intent::Greeting);
473    }
474
475    // ── classify — Farewell ─────────────────────────────────────────────
476
477    #[test]
478    fn test_classify_bye() {
479        let result = clf().classify("Bye for now");
480        assert_eq!(result.intent, Intent::Farewell);
481    }
482
483    #[test]
484    fn test_classify_goodbye() {
485        let result = clf().classify("Goodbye see you later");
486        assert_eq!(result.intent, Intent::Farewell);
487    }
488
489    #[test]
490    fn test_classify_thanks() {
491        let result = clf().classify("thanks goodbye");
492        assert_eq!(result.intent, Intent::Farewell);
493    }
494
495    // ── classify — Unknown ──────────────────────────────────────────────
496
497    #[test]
498    fn test_classify_unknown() {
499        let result = clf().classify("xyzzy plugh");
500        assert_eq!(result.intent, Intent::Unknown);
501        assert!((result.confidence).abs() < 1e-9);
502    }
503
504    // ── classify confidence ─────────────────────────────────────────────
505
506    #[test]
507    fn test_classify_confidence_in_range() {
508        let result = clf().classify("SELECT * WHERE { ?s ?p ?o }");
509        assert!(result.confidence >= 0.0 && result.confidence <= 1.0);
510    }
511
512    // ── add_rule ────────────────────────────────────────────────────────
513
514    #[test]
515    fn test_add_custom_rule() {
516        let mut c = clf();
517        c.add_rule(IntentRule::new(Intent::Navigation, &["teleport"], &[], 5.0));
518        let result = c.classify("teleport me to the knowledge graph");
519        assert_eq!(result.intent, Intent::Navigation);
520    }
521
522    // ── matched_keywords ────────────────────────────────────────────────
523
524    #[test]
525    fn test_matched_keywords_non_empty() {
526        let result = clf().classify("select all triples where subject is known");
527        assert!(!result.matched_keywords.is_empty());
528    }
529
530    // ── batch_classify ──────────────────────────────────────────────────
531
532    #[test]
533    fn test_batch_classify_correct_length() {
534        let texts = vec!["hello", "select * where {?s ?p ?o}", "bye"];
535        let results = clf().batch_classify(&texts);
536        assert_eq!(results.len(), 3);
537    }
538
539    #[test]
540    fn test_batch_classify_intents() {
541        let texts = vec!["hello", "SELECT * WHERE { ?s ?p ?o }"];
542        let results = clf().batch_classify(&texts);
543        assert_eq!(results[0].intent, Intent::Greeting);
544        assert_eq!(results[1].intent, Intent::SparqlQuery);
545    }
546
547    // ── top_n ────────────────────────────────────────────────────────────
548
549    #[test]
550    fn test_top_n_correct_length() {
551        let result = clf().top_n("select where sparql", 3);
552        assert!(result.len() <= 3);
553    }
554
555    #[test]
556    fn test_top_n_sorted_descending() {
557        let result = clf().top_n("select all from where construct ask", 5);
558        for w in result.windows(2) {
559            assert!(w[0].1 >= w[1].1, "not sorted: {:?} vs {:?}", w[0], w[1]);
560        }
561    }
562
563    #[test]
564    fn test_top_n_zero() {
565        let result = clf().top_n("hello world", 0);
566        assert!(result.is_empty());
567    }
568
569    // ── score_rule ────────────────────────────────────────────────────────
570
571    #[test]
572    fn test_score_rule_keyword_match() {
573        let c = clf();
574        let rule = IntentRule::new(Intent::Help, &["help"], &[], 1.0);
575        let (score, kws, pats) = c.score_rule(&rule, "help me please");
576        assert!(score > 0.0);
577        assert!(kws.contains(&"help".to_string()));
578        assert!(pats.is_empty());
579    }
580
581    #[test]
582    fn test_score_rule_pattern_match() {
583        let c = clf();
584        let rule = IntentRule::new(Intent::Help, &[], &["how to"], 1.0);
585        let (score, kws, pats) = c.score_rule(&rule, "how to write a query");
586        assert!(score > 0.0);
587        assert!(kws.is_empty());
588        assert!(!pats.is_empty());
589    }
590
591    #[test]
592    fn test_score_rule_no_match() {
593        let c = clf();
594        let rule = IntentRule::new(Intent::Greeting, &["hello"], &[], 1.0);
595        let (score, _, _) = c.score_rule(&rule, "delete the graph");
596        assert!((score).abs() < 1e-9);
597    }
598
599    // ── intent display ────────────────────────────────────────────────────
600
601    #[test]
602    fn test_intent_display() {
603        assert_eq!(format!("{}", Intent::SparqlQuery), "SparqlQuery");
604        assert_eq!(format!("{}", Intent::Unknown), "Unknown");
605    }
606}