oxirs-chat 0.2.4

RAG chat API with LLM integration and natural language to SPARQL translation
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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
//! Internationalization (i18n) and Localization Support
//!
//! Provides multi-language support for oxirs-chat with translation management,
//! locale detection, and language-specific formatting.

use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, info};

/// Supported languages
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Language {
    English,
    Japanese,
    Spanish,
    French,
    German,
    Chinese,
    Korean,
    Portuguese,
    Russian,
    Arabic,
}

impl Language {
    /// Get language code (ISO 639-1)
    pub fn code(&self) -> &str {
        match self {
            Language::English => "en",
            Language::Japanese => "ja",
            Language::Spanish => "es",
            Language::French => "fr",
            Language::German => "de",
            Language::Chinese => "zh",
            Language::Korean => "ko",
            Language::Portuguese => "pt",
            Language::Russian => "ru",
            Language::Arabic => "ar",
        }
    }

    /// Parse from language code
    pub fn from_code(code: &str) -> Option<Self> {
        match code.to_lowercase().as_str() {
            "en" => Some(Language::English),
            "ja" => Some(Language::Japanese),
            "es" => Some(Language::Spanish),
            "fr" => Some(Language::French),
            "de" => Some(Language::German),
            "zh" | "zh-cn" | "zh-tw" => Some(Language::Chinese),
            "ko" => Some(Language::Korean),
            "pt" => Some(Language::Portuguese),
            "ru" => Some(Language::Russian),
            "ar" => Some(Language::Arabic),
            _ => None,
        }
    }

    /// Get native name of the language
    pub fn native_name(&self) -> &str {
        match self {
            Language::English => "English",
            Language::Japanese => "日本語",
            Language::Spanish => "Español",
            Language::French => "Français",
            Language::German => "Deutsch",
            Language::Chinese => "中文",
            Language::Korean => "한국어",
            Language::Portuguese => "Português",
            Language::Russian => "Русский",
            Language::Arabic => "العربية",
        }
    }

    /// Check if language is right-to-left
    pub fn is_rtl(&self) -> bool {
        matches!(self, Language::Arabic)
    }
}

/// Translation key type
pub type TranslationKey = &'static str;

/// Translation bundle for a specific language
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TranslationBundle {
    language: Language,
    translations: HashMap<String, String>,
}

impl TranslationBundle {
    /// Create a new translation bundle
    pub fn new(language: Language) -> Self {
        let mut bundle = Self {
            language,
            translations: HashMap::new(),
        };

        // Load default translations
        bundle.load_defaults();
        bundle
    }

    /// Load default translations for common strings
    fn load_defaults(&mut self) {
        match self.language {
            Language::English => self.load_english(),
            Language::Japanese => self.load_japanese(),
            Language::Spanish => self.load_spanish(),
            Language::French => self.load_french(),
            Language::German => self.load_german(),
            Language::Chinese => self.load_chinese(),
            Language::Korean => self.load_korean(),
            Language::Portuguese => self.load_portuguese(),
            Language::Russian => self.load_russian(),
            Language::Arabic => self.load_arabic(),
        }
    }

    fn load_english(&mut self) {
        self.translations.extend([
            ("welcome".to_string(), "Welcome to OxiRS Chat".to_string()),
            (
                "error.not_found".to_string(),
                "Resource not found".to_string(),
            ),
            (
                "error.internal".to_string(),
                "Internal server error".to_string(),
            ),
            ("chat.thinking".to_string(), "Thinking...".to_string()),
            (
                "chat.processing".to_string(),
                "Processing your request".to_string(),
            ),
            (
                "chat.searching".to_string(),
                "Searching knowledge graph".to_string(),
            ),
            (
                "sparql.generating".to_string(),
                "Generating SPARQL query".to_string(),
            ),
            (
                "sparql.executing".to_string(),
                "Executing query".to_string(),
            ),
            (
                "results.found".to_string(),
                "Found {count} results".to_string(),
            ),
            (
                "session.created".to_string(),
                "Session created successfully".to_string(),
            ),
            (
                "session.expired".to_string(),
                "Session has expired".to_string(),
            ),
        ]);
    }

    fn load_japanese(&mut self) {
        self.translations.extend([
            ("welcome".to_string(), "OxiRS Chatへようこそ".to_string()),
            (
                "error.not_found".to_string(),
                "リソースが見つかりません".to_string(),
            ),
            (
                "error.internal".to_string(),
                "内部サーバーエラー".to_string(),
            ),
            ("chat.thinking".to_string(), "考え中...".to_string()),
            (
                "chat.processing".to_string(),
                "リクエストを処理中".to_string(),
            ),
            (
                "chat.searching".to_string(),
                "ナレッジグラフを検索中".to_string(),
            ),
            (
                "sparql.generating".to_string(),
                "SPARQLクエリを生成中".to_string(),
            ),
            ("sparql.executing".to_string(), "クエリを実行中".to_string()),
            (
                "results.found".to_string(),
                "{count}件の結果が見つかりました".to_string(),
            ),
            (
                "session.created".to_string(),
                "セッションが作成されました".to_string(),
            ),
            (
                "session.expired".to_string(),
                "セッションの有効期限が切れました".to_string(),
            ),
        ]);
    }

    fn load_spanish(&mut self) {
        self.translations.extend([
            ("welcome".to_string(), "Bienvenido a OxiRS Chat".to_string()),
            (
                "error.not_found".to_string(),
                "Recurso no encontrado".to_string(),
            ),
            (
                "error.internal".to_string(),
                "Error interno del servidor".to_string(),
            ),
            ("chat.thinking".to_string(), "Pensando...".to_string()),
            (
                "chat.processing".to_string(),
                "Procesando su solicitud".to_string(),
            ),
            (
                "chat.searching".to_string(),
                "Buscando en el grafo de conocimiento".to_string(),
            ),
            (
                "sparql.generating".to_string(),
                "Generando consulta SPARQL".to_string(),
            ),
            (
                "sparql.executing".to_string(),
                "Ejecutando consulta".to_string(),
            ),
            (
                "results.found".to_string(),
                "Se encontraron {count} resultados".to_string(),
            ),
            (
                "session.created".to_string(),
                "Sesión creada exitosamente".to_string(),
            ),
            (
                "session.expired".to_string(),
                "La sesión ha expirado".to_string(),
            ),
        ]);
    }

    fn load_french(&mut self) {
        self.translations.extend([
            (
                "welcome".to_string(),
                "Bienvenue sur OxiRS Chat".to_string(),
            ),
            (
                "error.not_found".to_string(),
                "Ressource non trouvée".to_string(),
            ),
            (
                "error.internal".to_string(),
                "Erreur interne du serveur".to_string(),
            ),
            (
                "chat.thinking".to_string(),
                "Réflexion en cours...".to_string(),
            ),
            (
                "chat.processing".to_string(),
                "Traitement de votre demande".to_string(),
            ),
            (
                "chat.searching".to_string(),
                "Recherche dans le graphe de connaissances".to_string(),
            ),
            (
                "sparql.generating".to_string(),
                "Génération de la requête SPARQL".to_string(),
            ),
            (
                "sparql.executing".to_string(),
                "Exécution de la requête".to_string(),
            ),
            (
                "results.found".to_string(),
                "{count} résultats trouvés".to_string(),
            ),
            (
                "session.created".to_string(),
                "Session créée avec succès".to_string(),
            ),
            (
                "session.expired".to_string(),
                "La session a expiré".to_string(),
            ),
        ]);
    }

    fn load_german(&mut self) {
        self.translations.extend([
            (
                "welcome".to_string(),
                "Willkommen bei OxiRS Chat".to_string(),
            ),
            (
                "error.not_found".to_string(),
                "Ressource nicht gefunden".to_string(),
            ),
            (
                "error.internal".to_string(),
                "Interner Serverfehler".to_string(),
            ),
            ("chat.thinking".to_string(), "Denke nach...".to_string()),
            (
                "chat.processing".to_string(),
                "Bearbeite Ihre Anfrage".to_string(),
            ),
            (
                "chat.searching".to_string(),
                "Durchsuche Wissensgraph".to_string(),
            ),
            (
                "sparql.generating".to_string(),
                "Erstelle SPARQL-Abfrage".to_string(),
            ),
            (
                "sparql.executing".to_string(),
                "Führe Abfrage aus".to_string(),
            ),
            (
                "results.found".to_string(),
                "{count} Ergebnisse gefunden".to_string(),
            ),
            (
                "session.created".to_string(),
                "Sitzung erfolgreich erstellt".to_string(),
            ),
            (
                "session.expired".to_string(),
                "Sitzung ist abgelaufen".to_string(),
            ),
        ]);
    }

    fn load_chinese(&mut self) {
        self.translations.extend([
            ("welcome".to_string(), "欢迎使用 OxiRS Chat".to_string()),
            ("error.not_found".to_string(), "未找到资源".to_string()),
            ("error.internal".to_string(), "内部服务器错误".to_string()),
            ("chat.thinking".to_string(), "思考中...".to_string()),
            (
                "chat.processing".to_string(),
                "正在处理您的请求".to_string(),
            ),
            ("chat.searching".to_string(), "正在搜索知识图谱".to_string()),
            (
                "sparql.generating".to_string(),
                "正在生成 SPARQL 查询".to_string(),
            ),
            ("sparql.executing".to_string(), "正在执行查询".to_string()),
            (
                "results.found".to_string(),
                "找到 {count} 个结果".to_string(),
            ),
            ("session.created".to_string(), "会话创建成功".to_string()),
            ("session.expired".to_string(), "会话已过期".to_string()),
        ]);
    }

    fn load_korean(&mut self) {
        self.translations.extend([
            (
                "welcome".to_string(),
                "OxiRS Chat에 오신 것을 환영합니다".to_string(),
            ),
            (
                "error.not_found".to_string(),
                "리소스를 찾을 수 없습니다".to_string(),
            ),
            ("error.internal".to_string(), "내부 서버 오류".to_string()),
            ("chat.thinking".to_string(), "생각 중...".to_string()),
            ("chat.processing".to_string(), "요청 처리 중".to_string()),
            (
                "chat.searching".to_string(),
                "지식 그래프 검색 중".to_string(),
            ),
            (
                "sparql.generating".to_string(),
                "SPARQL 쿼리 생성 중".to_string(),
            ),
            ("sparql.executing".to_string(), "쿼리 실행 중".to_string()),
            (
                "results.found".to_string(),
                "{count}개의 결과를 찾았습니다".to_string(),
            ),
            (
                "session.created".to_string(),
                "세션이 성공적으로 생성되었습니다".to_string(),
            ),
            (
                "session.expired".to_string(),
                "세션이 만료되었습니다".to_string(),
            ),
        ]);
    }

    fn load_portuguese(&mut self) {
        self.translations.extend([
            ("welcome".to_string(), "Bem-vindo ao OxiRS Chat".to_string()),
            (
                "error.not_found".to_string(),
                "Recurso não encontrado".to_string(),
            ),
            (
                "error.internal".to_string(),
                "Erro interno do servidor".to_string(),
            ),
            ("chat.thinking".to_string(), "Pensando...".to_string()),
            (
                "chat.processing".to_string(),
                "Processando sua solicitação".to_string(),
            ),
            (
                "chat.searching".to_string(),
                "Pesquisando grafo de conhecimento".to_string(),
            ),
            (
                "sparql.generating".to_string(),
                "Gerando consulta SPARQL".to_string(),
            ),
            (
                "sparql.executing".to_string(),
                "Executando consulta".to_string(),
            ),
            (
                "results.found".to_string(),
                "{count} resultados encontrados".to_string(),
            ),
            (
                "session.created".to_string(),
                "Sessão criada com sucesso".to_string(),
            ),
            (
                "session.expired".to_string(),
                "A sessão expirou".to_string(),
            ),
        ]);
    }

    fn load_russian(&mut self) {
        self.translations.extend([
            (
                "welcome".to_string(),
                "Добро пожаловать в OxiRS Chat".to_string(),
            ),
            (
                "error.not_found".to_string(),
                "Ресурс не найден".to_string(),
            ),
            (
                "error.internal".to_string(),
                "Внутренняя ошибка сервера".to_string(),
            ),
            ("chat.thinking".to_string(), "Думаю...".to_string()),
            (
                "chat.processing".to_string(),
                "Обработка вашего запроса".to_string(),
            ),
            (
                "chat.searching".to_string(),
                "Поиск в графе знаний".to_string(),
            ),
            (
                "sparql.generating".to_string(),
                "Генерация SPARQL запроса".to_string(),
            ),
            (
                "sparql.executing".to_string(),
                "Выполнение запроса".to_string(),
            ),
            (
                "results.found".to_string(),
                "Найдено {count} результатов".to_string(),
            ),
            (
                "session.created".to_string(),
                "Сессия успешно создана".to_string(),
            ),
            ("session.expired".to_string(), "Сессия истекла".to_string()),
        ]);
    }

    fn load_arabic(&mut self) {
        self.translations.extend([
            ("welcome".to_string(), "مرحبًا بك في OxiRS Chat".to_string()),
            (
                "error.not_found".to_string(),
                "المورد غير موجود".to_string(),
            ),
            (
                "error.internal".to_string(),
                "خطأ داخلي في الخادم".to_string(),
            ),
            ("chat.thinking".to_string(), "جاري التفكير...".to_string()),
            ("chat.processing".to_string(), "معالجة طلبك".to_string()),
            (
                "chat.searching".to_string(),
                "البحث في الرسم البياني للمعرفة".to_string(),
            ),
            (
                "sparql.generating".to_string(),
                "إنشاء استعلام SPARQL".to_string(),
            ),
            ("sparql.executing".to_string(), "تنفيذ الاستعلام".to_string()),
            (
                "results.found".to_string(),
                "تم العثور على {count} نتيجة".to_string(),
            ),
            (
                "session.created".to_string(),
                "تم إنشاء الجلسة بنجاح".to_string(),
            ),
            (
                "session.expired".to_string(),
                "انتهت صلاحية الجلسة".to_string(),
            ),
        ]);
    }

    /// Get translation for a key
    pub fn get(&self, key: &str) -> Option<&str> {
        self.translations.get(key).map(|s| s.as_str())
    }

    /// Get translation with parameters
    pub fn get_with_params(&self, key: &str, params: &HashMap<&str, &str>) -> Option<String> {
        let template = self.get(key)?;
        let mut result = template.to_string();

        for (param_key, param_value) in params {
            result = result.replace(&format!("{{{}}}", param_key), param_value);
        }

        Some(result)
    }

    /// Add or update a translation
    pub fn set(&mut self, key: String, value: String) {
        self.translations.insert(key, value);
    }
}

/// Internationalization manager
pub struct I18nManager {
    bundles: Arc<RwLock<HashMap<Language, TranslationBundle>>>,
    default_language: Language,
}

impl I18nManager {
    /// Create a new i18n manager
    pub fn new(default_language: Language) -> Self {
        let manager = Self {
            bundles: Arc::new(RwLock::new(HashMap::new())),
            default_language,
        };

        info!(
            "Initialized i18n manager with default language: {:?}",
            default_language
        );
        manager
    }

    /// Load all supported languages lazily (async)
    async fn ensure_bundles_loaded(&self) {
        let bundles = self.bundles.read().await;

        // If bundles are already loaded, return early
        if !bundles.is_empty() {
            return;
        }

        // Drop read lock before acquiring write lock
        drop(bundles);

        let mut bundles = self.bundles.write().await;

        // Double-check after acquiring write lock (another thread might have loaded them)
        if !bundles.is_empty() {
            return;
        }

        let languages = [
            Language::English,
            Language::Japanese,
            Language::Spanish,
            Language::French,
            Language::German,
            Language::Chinese,
            Language::Korean,
            Language::Portuguese,
            Language::Russian,
            Language::Arabic,
        ];

        for lang in &languages {
            bundles.insert(*lang, TranslationBundle::new(*lang));
        }

        info!("Loaded {} language bundles", bundles.len());
    }

    /// Get translation for a key in the specified language
    pub async fn translate(&self, language: Language, key: &str) -> String {
        // Ensure bundles are loaded
        self.ensure_bundles_loaded().await;

        let bundles = self.bundles.read().await;

        // Try requested language first
        if let Some(bundle) = bundles.get(&language) {
            if let Some(translation) = bundle.get(key) {
                return translation.to_string();
            }
        }

        // Fall back to default language
        if let Some(bundle) = bundles.get(&self.default_language) {
            if let Some(translation) = bundle.get(key) {
                debug!("Using fallback translation for key: {}", key);
                return translation.to_string();
            }
        }

        // Return key if no translation found
        debug!("No translation found for key: {}", key);
        key.to_string()
    }

    /// Get translation with parameters
    pub async fn translate_with_params(
        &self,
        language: Language,
        key: &str,
        params: HashMap<&str, &str>,
    ) -> String {
        // Ensure bundles are loaded
        self.ensure_bundles_loaded().await;

        let bundles = self.bundles.read().await;

        // Try requested language first
        if let Some(bundle) = bundles.get(&language) {
            if let Some(translation) = bundle.get_with_params(key, &params) {
                return translation;
            }
        }

        // Fall back to default language
        if let Some(bundle) = bundles.get(&self.default_language) {
            if let Some(translation) = bundle.get_with_params(key, &params) {
                return translation;
            }
        }

        // Return key if no translation found
        key.to_string()
    }

    /// Add custom translation
    pub async fn add_translation(
        &self,
        language: Language,
        key: String,
        value: String,
    ) -> Result<()> {
        let mut bundles = self.bundles.write().await;

        let bundle = bundles
            .entry(language)
            .or_insert_with(|| TranslationBundle::new(language));

        bundle.set(key.clone(), value);

        debug!(
            "Added custom translation for language {:?}: {}",
            language, key
        );
        Ok(())
    }

    /// Detect language from Accept-Language header
    pub fn detect_language(accept_language: &str) -> Language {
        // Parse Accept-Language header (simplified)
        let parts: Vec<&str> = accept_language.split(',').collect();

        for part in parts {
            let lang_code = part
                .split(';')
                .next()
                .unwrap_or("")
                .trim()
                .split('-')
                .next()
                .unwrap_or("");

            if let Some(language) = Language::from_code(lang_code) {
                return language;
            }
        }

        Language::English // Default fallback
    }

    /// Get all supported languages
    pub fn supported_languages() -> Vec<Language> {
        vec![
            Language::English,
            Language::Japanese,
            Language::Spanish,
            Language::French,
            Language::German,
            Language::Chinese,
            Language::Korean,
            Language::Portuguese,
            Language::Russian,
            Language::Arabic,
        ]
    }
}

impl Default for I18nManager {
    fn default() -> Self {
        Self::new(Language::English)
    }
}

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

    #[test]
    fn test_language_code() {
        assert_eq!(Language::English.code(), "en");
        assert_eq!(Language::Japanese.code(), "ja");
        assert_eq!(Language::Spanish.code(), "es");
    }

    #[test]
    fn test_language_from_code() {
        assert_eq!(Language::from_code("en"), Some(Language::English));
        assert_eq!(Language::from_code("ja"), Some(Language::Japanese));
        assert_eq!(Language::from_code("unknown"), None);
    }

    #[test]
    fn test_language_rtl() {
        assert!(!Language::English.is_rtl());
        assert!(Language::Arabic.is_rtl());
    }

    #[tokio::test]
    async fn test_i18n_manager() {
        let manager = I18nManager::new(Language::English);
        let translation = manager.translate(Language::English, "welcome").await;
        assert!(!translation.is_empty());
    }

    #[tokio::test]
    async fn test_translation_with_params() {
        let manager = I18nManager::new(Language::English);
        let mut params = HashMap::new();
        params.insert("count", "42");

        let translation = manager
            .translate_with_params(Language::English, "results.found", params)
            .await;

        assert!(translation.contains("42"));
    }

    #[test]
    fn test_detect_language() {
        assert_eq!(
            I18nManager::detect_language("ja,en-US;q=0.9"),
            Language::Japanese
        );
        assert_eq!(
            I18nManager::detect_language("fr-FR,fr;q=0.9,en;q=0.8"),
            Language::French
        );
        assert_eq!(I18nManager::detect_language("unknown"), Language::English);
    }
}