oxirag 0.1.1

A four-layer RAG engine with SMT-based logic verification and knowledge graph support
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
//! Entity extraction implementations.

use async_trait::async_trait;
use std::collections::HashSet;

use crate::error::GraphError;
use crate::layer4_graph::traits::EntityExtractor;
use crate::layer4_graph::types::{EntityType, GraphEntity};

/// A mock entity extractor that returns predefined entities for testing.
#[derive(Debug, Default)]
pub struct MockEntityExtractor {
    entities: Vec<GraphEntity>,
}

impl MockEntityExtractor {
    /// Create a new mock extractor with no predefined entities.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a mock extractor with predefined entities.
    #[must_use]
    pub fn with_entities(entities: Vec<GraphEntity>) -> Self {
        Self { entities }
    }

    /// Add a predefined entity.
    pub fn add_entity(&mut self, entity: GraphEntity) {
        self.entities.push(entity);
    }
}

#[async_trait]
impl EntityExtractor for MockEntityExtractor {
    async fn extract_entities(&self, _text: &str) -> Result<Vec<GraphEntity>, GraphError> {
        Ok(self.entities.clone())
    }

    fn supported_entity_types(&self) -> Vec<EntityType> {
        vec![
            EntityType::Person,
            EntityType::Organization,
            EntityType::Location,
            EntityType::Concept,
            EntityType::Technology,
        ]
    }
}

/// A pattern-based entity extractor that uses keywords and simple heuristics.
#[derive(Debug)]
pub struct PatternEntityExtractor {
    /// Keywords associated with person entities.
    person_keywords: HashSet<String>,
    /// Keywords associated with organization entities.
    org_keywords: HashSet<String>,
    /// Keywords associated with location entities.
    location_keywords: HashSet<String>,
    /// Keywords associated with technology entities.
    tech_keywords: HashSet<String>,
    /// Minimum word length to consider as entity.
    min_word_length: usize,
}

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

impl PatternEntityExtractor {
    /// Create a new pattern-based entity extractor with default patterns.
    #[must_use]
    pub fn new() -> Self {
        Self {
            person_keywords: Self::default_person_keywords(),
            org_keywords: Self::default_org_keywords(),
            location_keywords: Self::default_location_keywords(),
            tech_keywords: Self::default_tech_keywords(),
            min_word_length: 2,
        }
    }

    fn default_person_keywords() -> HashSet<String> {
        ["Dr.", "Mr.", "Mrs.", "Ms.", "Prof.", "CEO", "CTO", "CFO"]
            .iter()
            .map(|s| (*s).to_string())
            .collect()
    }

    fn default_org_keywords() -> HashSet<String> {
        [
            "Inc.",
            "Corp.",
            "Ltd.",
            "LLC",
            "Company",
            "Corporation",
            "Foundation",
            "Institute",
            "University",
            "College",
            "Organization",
            "Group",
            "Team",
        ]
        .iter()
        .map(|s| (*s).to_string())
        .collect()
    }

    fn default_location_keywords() -> HashSet<String> {
        [
            "City",
            "State",
            "Country",
            "Street",
            "Avenue",
            "Road",
            "Boulevard",
            "Park",
            "River",
            "Mountain",
            "Lake",
            "Ocean",
            "Sea",
            "Island",
        ]
        .iter()
        .map(|s| (*s).to_string())
        .collect()
    }

    fn default_tech_keywords() -> HashSet<String> {
        [
            "Rust",
            "Python",
            "Java",
            "JavaScript",
            "TypeScript",
            "Go",
            "C++",
            "C#",
            "Ruby",
            "Swift",
            "Kotlin",
            "Scala",
            "PHP",
            "SQL",
            "NoSQL",
            "API",
            "SDK",
            "Framework",
            "Library",
            "Database",
            "Server",
            "Cloud",
            "Docker",
            "Kubernetes",
            "Linux",
            "Windows",
            "macOS",
            "iOS",
            "Android",
            "React",
            "Vue",
            "Angular",
            "Node",
            "Django",
            "Flask",
            "Spring",
            "Rails",
            "AWS",
            "Azure",
            "GCP",
            "ML",
            "AI",
            "LLM",
            "GPU",
            "CPU",
            "RAM",
            "SSD",
            "HTTP",
            "HTTPS",
            "TCP",
            "UDP",
            "REST",
            "GraphQL",
            "gRPC",
            "WebSocket",
            "JSON",
            "XML",
            "YAML",
        ]
        .iter()
        .map(|s| (*s).to_string())
        .collect()
    }

    /// Add custom person keywords.
    pub fn add_person_keywords(&mut self, keywords: impl IntoIterator<Item = impl Into<String>>) {
        for kw in keywords {
            self.person_keywords.insert(kw.into());
        }
    }

    /// Add custom organization keywords.
    pub fn add_org_keywords(&mut self, keywords: impl IntoIterator<Item = impl Into<String>>) {
        for kw in keywords {
            self.org_keywords.insert(kw.into());
        }
    }

    /// Add custom technology keywords.
    pub fn add_tech_keywords(&mut self, keywords: impl IntoIterator<Item = impl Into<String>>) {
        for kw in keywords {
            self.tech_keywords.insert(kw.into());
        }
    }

    /// Set minimum word length for entity consideration.
    pub fn set_min_word_length(&mut self, len: usize) {
        self.min_word_length = len;
    }

    /// Check if a word looks like a capitalized proper noun.
    fn is_capitalized_word(word: &str) -> bool {
        let trimmed = word.trim_matches(|c: char| !c.is_alphanumeric());
        if trimmed.is_empty() {
            return false;
        }
        // Safe: we already checked trimmed.is_empty() above
        trimmed
            .chars()
            .next()
            .is_some_and(|first_char| first_char.is_uppercase() && trimmed.len() > 1)
    }

    /// Determine entity type based on context and keywords.
    fn classify_entity(&self, word: &str, context: &str) -> Option<EntityType> {
        let lower_word = word.to_lowercase();
        let lower_context = context.to_lowercase();

        // Check technology keywords (case-sensitive for most)
        if self.tech_keywords.contains(word) {
            return Some(EntityType::Technology);
        }

        // Check organization context
        for kw in &self.org_keywords {
            if lower_context.contains(&kw.to_lowercase()) {
                return Some(EntityType::Organization);
            }
        }

        // Check location context
        for kw in &self.location_keywords {
            if lower_context.contains(&kw.to_lowercase()) {
                return Some(EntityType::Location);
            }
        }

        // Check person indicators
        for kw in &self.person_keywords {
            if lower_context.contains(&kw.to_lowercase()) {
                return Some(EntityType::Person);
            }
        }

        // Default to Concept for capitalized words
        if Self::is_capitalized_word(word) && !lower_word.is_empty() {
            return Some(EntityType::Concept);
        }

        None
    }

    /// Extract potential entity names from text.
    fn extract_candidate_names(&self, text: &str) -> Vec<(String, String)> {
        let mut candidates = Vec::new();
        let sentences: Vec<&str> = text.split(['.', '!', '?']).collect();

        for sentence in sentences {
            let words: Vec<&str> = sentence.split_whitespace().collect();
            let mut i = 0;

            while i < words.len() {
                let word = words[i];
                let cleaned =
                    word.trim_matches(|c: char| !c.is_alphanumeric() && c != '-' && c != '_');

                if cleaned.len() >= self.min_word_length {
                    // Check for multi-word proper nouns (consecutive capitalized words)
                    if Self::is_capitalized_word(cleaned) {
                        let mut name_parts = vec![cleaned.to_string()];
                        let mut j = i + 1;

                        while j < words.len() {
                            let next_word = words[j];
                            let next_cleaned = next_word.trim_matches(|c: char| {
                                !c.is_alphanumeric() && c != '-' && c != '_'
                            });

                            if Self::is_capitalized_word(next_cleaned) {
                                name_parts.push(next_cleaned.to_string());
                                j += 1;
                            } else {
                                break;
                            }
                        }

                        let full_name = name_parts.join(" ");
                        candidates.push((full_name, sentence.to_string()));
                        i = j;
                        continue;
                    }

                    // Check for technology keywords
                    if self.tech_keywords.contains(cleaned) {
                        candidates.push((cleaned.to_string(), sentence.to_string()));
                    }
                }
                i += 1;
            }
        }

        candidates
    }
}

#[async_trait]
impl EntityExtractor for PatternEntityExtractor {
    async fn extract_entities(&self, text: &str) -> Result<Vec<GraphEntity>, GraphError> {
        let candidates = self.extract_candidate_names(text);
        let mut entities = Vec::new();
        let mut seen_names: HashSet<String> = HashSet::new();

        for (name, context) in candidates {
            let lower_name = name.to_lowercase();
            if seen_names.contains(&lower_name) {
                continue;
            }

            if let Some(entity_type) = self.classify_entity(&name, &context) {
                seen_names.insert(lower_name);
                entities.push(
                    GraphEntity::new(&name, entity_type).with_confidence(0.7), // Pattern-based extraction has moderate confidence
                );
            }
        }

        Ok(entities)
    }

    fn supported_entity_types(&self) -> Vec<EntityType> {
        vec![
            EntityType::Person,
            EntityType::Organization,
            EntityType::Location,
            EntityType::Technology,
            EntityType::Concept,
        ]
    }
}

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

    #[tokio::test]
    async fn test_mock_entity_extractor() {
        let entities = vec![
            GraphEntity::new("Rust", EntityType::Technology),
            GraphEntity::new("Cargo", EntityType::Technology),
        ];
        let extractor = MockEntityExtractor::with_entities(entities);

        let result = extractor.extract_entities("any text").await.unwrap();
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].name, "Rust");
    }

    #[tokio::test]
    async fn test_pattern_extractor_tech_keywords() {
        let extractor = PatternEntityExtractor::new();
        let text = "Rust is a systems programming language. It uses LLVM for compilation.";

        let entities = extractor.extract_entities(text).await.unwrap();

        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"Rust"));
    }

    #[tokio::test]
    async fn test_pattern_extractor_capitalized_words() {
        let extractor = PatternEntityExtractor::new();
        let text = "The Mozilla Foundation created Firefox browser.";

        let entities = extractor.extract_entities(text).await.unwrap();

        let names: Vec<&str> = entities.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"Mozilla Foundation") || names.contains(&"Firefox"));
    }

    #[tokio::test]
    async fn test_pattern_extractor_deduplication() {
        let extractor = PatternEntityExtractor::new();
        let text = "Rust is great. Rust is fast. RUST is memory-safe.";

        let entities = extractor.extract_entities(text).await.unwrap();

        let rust_count = entities
            .iter()
            .filter(|e| e.name.to_lowercase() == "rust")
            .count();
        assert_eq!(rust_count, 1);
    }

    #[test]
    fn test_supported_entity_types() {
        let extractor = PatternEntityExtractor::new();
        let types = extractor.supported_entity_types();

        assert!(types.contains(&EntityType::Person));
        assert!(types.contains(&EntityType::Technology));
        assert!(types.contains(&EntityType::Organization));
    }
}