Skip to main content

oxirs_chat/
external_services.rs

1//! External Services Integration for OxiRS Chat
2//!
3//! This module provides integration with external services including:
4//! - Knowledge base APIs
5//! - Search engines  
6//! - Fact-checking services
7//! - Translation services
8//! - Speech recognition
9//! - Text-to-speech
10
11use anyhow::{anyhow, Result};
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14use std::time::Duration;
15use tracing::warn;
16
17/// Configuration for external services
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct ExternalServicesConfig {
20    pub knowledge_base_apis: Vec<KnowledgeBaseConfig>,
21    pub search_engines: Vec<SearchEngineConfig>,
22    pub fact_checkers: Vec<FactCheckerConfig>,
23    pub translation_services: Vec<TranslationConfig>,
24    pub speech_services: Vec<SpeechConfig>,
25    pub timeout_duration: Duration,
26    pub retry_attempts: usize,
27    pub rate_limit_per_minute: u32,
28}
29
30impl Default for ExternalServicesConfig {
31    fn default() -> Self {
32        Self {
33            knowledge_base_apis: Vec::new(),
34            search_engines: Vec::new(),
35            fact_checkers: Vec::new(),
36            translation_services: Vec::new(),
37            speech_services: Vec::new(),
38            timeout_duration: Duration::from_secs(30),
39            retry_attempts: 3,
40            rate_limit_per_minute: 100,
41        }
42    }
43}
44
45/// Knowledge base API configuration
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct KnowledgeBaseConfig {
48    pub name: String,
49    pub base_url: String,
50    pub api_key: Option<String>,
51    pub headers: HashMap<String, String>,
52    pub enabled: bool,
53    pub priority: u32,
54}
55
56/// Search engine configuration
57#[derive(Debug, Clone, Serialize, Deserialize)]
58pub struct SearchEngineConfig {
59    pub name: String,
60    pub api_url: String,
61    pub api_key: Option<String>,
62    pub search_type: SearchType,
63    pub max_results: usize,
64    pub enabled: bool,
65}
66
67/// Search engine types
68#[derive(Debug, Clone, Serialize, Deserialize)]
69pub enum SearchType {
70    Web,
71    Academic,
72    News,
73    Images,
74    Videos,
75    Knowledge,
76}
77
78/// Fact checker configuration
79#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct FactCheckerConfig {
81    pub name: String,
82    pub api_url: String,
83    pub api_key: Option<String>,
84    pub confidence_threshold: f32,
85    pub enabled: bool,
86}
87
88/// Translation service configuration
89#[derive(Debug, Clone, Serialize, Deserialize)]
90pub struct TranslationConfig {
91    pub name: String,
92    pub api_url: String,
93    pub api_key: Option<String>,
94    pub supported_languages: Vec<String>,
95    pub enabled: bool,
96}
97
98/// Speech service configuration
99#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct SpeechConfig {
101    pub name: String,
102    pub speech_to_text_url: Option<String>,
103    pub text_to_speech_url: Option<String>,
104    pub api_key: Option<String>,
105    pub supported_languages: Vec<String>,
106    pub enabled: bool,
107    pub voice_models: Vec<VoiceModel>,
108    pub real_time_streaming: bool,
109    pub noise_cancellation: bool,
110    pub speech_enhancement: bool,
111    pub speaker_diarization: bool,
112    pub emotion_detection: bool,
113    pub custom_vocabulary: Vec<String>,
114}
115
116/// Voice model configuration for TTS
117#[derive(Debug, Clone, Serialize, Deserialize)]
118pub struct VoiceModel {
119    pub id: String,
120    pub name: String,
121    pub language: String,
122    pub gender: VoiceGender,
123    pub age_range: VoiceAgeRange,
124    pub voice_type: VoiceType,
125    pub sample_rate: u32,
126    pub neural_voice: bool,
127}
128
129/// Voice gender options
130#[derive(Debug, Clone, Serialize, Deserialize)]
131pub enum VoiceGender {
132    Male,
133    Female,
134    Neutral,
135}
136
137/// Voice age range options
138#[derive(Debug, Clone, Serialize, Deserialize)]
139pub enum VoiceAgeRange {
140    Child,
141    Young,
142    Adult,
143    Senior,
144}
145
146/// Voice type characteristics
147#[derive(Debug, Clone, Serialize, Deserialize)]
148pub enum VoiceType {
149    Conversational,
150    News,
151    Narrative,
152    Assistant,
153    Customer,
154    Educational,
155    Emotional,
156}
157
158/// Advanced speech processing options
159#[derive(Debug, Clone, Serialize, Deserialize)]
160pub struct SpeechProcessingOptions {
161    pub enable_punctuation: bool,
162    pub enable_profanity_filter: bool,
163    pub enable_automatic_formatting: bool,
164    pub enable_word_timestamps: bool,
165    pub enable_confidence_scores: bool,
166    pub enable_speaker_identification: bool,
167    pub language_detection_mode: LanguageDetectionMode,
168    pub audio_quality_enhancement: bool,
169}
170
171/// Language detection modes for speech
172#[derive(Debug, Clone, Serialize, Deserialize)]
173pub enum LanguageDetectionMode {
174    None,
175    Automatic,
176    Constrained(Vec<String>),
177}
178
179/// External services integration manager
180pub struct ExternalServicesManager {
181    config: ExternalServicesConfig,
182    client: reqwest::Client,
183    rate_limiter: RateLimiter,
184}
185
186impl ExternalServicesManager {
187    /// Create a new external services manager.
188    ///
189    /// # Errors
190    /// Returns an error if the underlying `reqwest::Client` cannot be built
191    /// (e.g. the platform's TLS backend fails to initialize), rather than
192    /// panicking.
193    pub fn new(config: ExternalServicesConfig) -> Result<Self> {
194        let client = reqwest::Client::builder()
195            .timeout(config.timeout_duration)
196            .build()
197            .map_err(|e| anyhow!("Failed to create HTTP client: {e}"))?;
198
199        Ok(Self {
200            rate_limiter: RateLimiter::new(config.rate_limit_per_minute),
201            config,
202            client,
203        })
204    }
205
206    /// Search knowledge base APIs
207    pub async fn search_knowledge_bases(&self, query: &str) -> Result<Vec<KnowledgeResult>> {
208        let mut results = Vec::new();
209
210        for kb_config in &self.config.knowledge_base_apis {
211            if !kb_config.enabled {
212                continue;
213            }
214
215            self.rate_limiter.check_limit().await?;
216
217            match self.query_knowledge_base(kb_config, query).await {
218                Ok(mut kb_results) => {
219                    results.append(&mut kb_results);
220                }
221                Err(e) => {
222                    warn!("Knowledge base {} failed: {}", kb_config.name, e);
223                }
224            }
225        }
226
227        // Sort by priority and relevance
228        results.sort_by(|a, b| {
229            b.relevance_score
230                .partial_cmp(&a.relevance_score)
231                .unwrap_or(std::cmp::Ordering::Equal)
232        });
233
234        Ok(results)
235    }
236
237    /// Search external search engines
238    pub async fn search_engines(
239        &self,
240        query: &str,
241        search_type: SearchType,
242    ) -> Result<Vec<SearchResult>> {
243        let mut results = Vec::new();
244
245        for engine_config in &self.config.search_engines {
246            if !engine_config.enabled || engine_config.search_type != search_type {
247                continue;
248            }
249
250            self.rate_limiter.check_limit().await?;
251
252            match self.query_search_engine(engine_config, query).await {
253                Ok(mut search_results) => {
254                    results.append(&mut search_results);
255                }
256                Err(e) => {
257                    warn!("Search engine {} failed: {}", engine_config.name, e);
258                }
259            }
260        }
261
262        Ok(results)
263    }
264
265    /// Fact-check a claim
266    pub async fn fact_check(&self, claim: &str) -> Result<Vec<FactCheckResult>> {
267        let mut results = Vec::new();
268
269        for fc_config in &self.config.fact_checkers {
270            if !fc_config.enabled {
271                continue;
272            }
273
274            self.rate_limiter.check_limit().await?;
275
276            match self.check_fact(fc_config, claim).await {
277                Ok(fact_result) => {
278                    if fact_result.confidence >= fc_config.confidence_threshold {
279                        results.push(fact_result);
280                    }
281                }
282                Err(e) => {
283                    warn!("Fact checker {} failed: {}", fc_config.name, e);
284                }
285            }
286        }
287
288        Ok(results)
289    }
290
291    /// Translate text with automatic language detection
292    pub async fn translate(&self, text: &str, target_language: &str) -> Result<TranslationResult> {
293        // First detect the source language
294        let source_language = self.detect_language(text).await?;
295        self.translate_with_source(text, &source_language.language_code, target_language)
296            .await
297    }
298
299    /// Translate text with known source language
300    pub async fn translate_with_source(
301        &self,
302        text: &str,
303        source_language: &str,
304        target_language: &str,
305    ) -> Result<TranslationResult> {
306        for trans_config in &self.config.translation_services {
307            if !trans_config.enabled
308                || !trans_config
309                    .supported_languages
310                    .contains(&target_language.to_string())
311                || !trans_config
312                    .supported_languages
313                    .contains(&source_language.to_string())
314            {
315                continue;
316            }
317
318            self.rate_limiter.check_limit().await?;
319
320            match self
321                .translate_text(trans_config, text, target_language)
322                .await
323            {
324                Ok(result) => return Ok(result),
325                Err(e) => {
326                    warn!("Translation service {} failed: {}", trans_config.name, e);
327                }
328            }
329        }
330
331        Err(anyhow!(
332            "No translation service available for {} -> {}",
333            source_language,
334            target_language
335        ))
336    }
337
338    /// Detect the language of input text
339    pub async fn detect_language(&self, text: &str) -> Result<LanguageDetectionResult> {
340        for trans_config in &self.config.translation_services {
341            if !trans_config.enabled {
342                continue;
343            }
344
345            self.rate_limiter.check_limit().await?;
346
347            // Use specific language detection for this service
348            match self.detect_language_for_service(trans_config, text).await {
349                Ok(result) => return Ok(result),
350                Err(e) => {
351                    warn!(
352                        "Language detection service {} failed: {}",
353                        trans_config.name, e
354                    );
355                }
356            }
357        }
358
359        Err(anyhow!("No language detection service available"))
360    }
361
362    /// Batch translate multiple texts
363    pub async fn batch_translate(
364        &self,
365        texts: &[String],
366        target_language: &str,
367    ) -> Result<Vec<TranslationResult>> {
368        let mut results = Vec::new();
369
370        for text in texts {
371            match self.translate(text, target_language).await {
372                Ok(result) => results.push(result),
373                Err(e) => {
374                    warn!("Failed to translate text '{}': {}", text, e);
375                    // Continue with other texts even if one fails
376                }
377            }
378        }
379
380        Ok(results)
381    }
382
383    /// Get supported language pairs for translation
384    pub fn get_supported_language_pairs(&self) -> Vec<LanguagePair> {
385        let mut pairs = Vec::new();
386
387        for trans_config in &self.config.translation_services {
388            if !trans_config.enabled {
389                continue;
390            }
391
392            // Generate all possible pairs from supported languages
393            for source in &trans_config.supported_languages {
394                for target in &trans_config.supported_languages {
395                    if source != target {
396                        pairs.push(LanguagePair {
397                            source_language: source.clone(),
398                            target_language: target.clone(),
399                            service: trans_config.name.clone(),
400                        });
401                    }
402                }
403            }
404        }
405
406        pairs
407    }
408
409    /// Check if a specific language pair is supported
410    pub fn is_language_pair_supported(&self, source: &str, target: &str) -> bool {
411        for trans_config in &self.config.translation_services {
412            if trans_config.enabled
413                && trans_config
414                    .supported_languages
415                    .contains(&source.to_string())
416                && trans_config
417                    .supported_languages
418                    .contains(&target.to_string())
419            {
420                return true;
421            }
422        }
423        false
424    }
425
426    /// Convert speech to text with advanced processing options
427    pub async fn speech_to_text(&self, audio_data: &[u8], language: &str) -> Result<SpeechResult> {
428        let options = SpeechProcessingOptions {
429            enable_punctuation: true,
430            enable_profanity_filter: false,
431            enable_automatic_formatting: true,
432            enable_word_timestamps: true,
433            enable_confidence_scores: true,
434            enable_speaker_identification: false,
435            language_detection_mode: LanguageDetectionMode::None,
436            audio_quality_enhancement: true,
437        };
438
439        self.speech_to_text_with_options(audio_data, language, &options)
440            .await
441    }
442
443    /// Convert speech to text with custom processing options
444    pub async fn speech_to_text_with_options(
445        &self,
446        audio_data: &[u8],
447        language: &str,
448        _options: &SpeechProcessingOptions,
449    ) -> Result<SpeechResult> {
450        for speech_config in &self.config.speech_services {
451            if !speech_config.enabled
452                || speech_config.speech_to_text_url.is_none()
453                || !speech_config
454                    .supported_languages
455                    .contains(&language.to_string())
456            {
457                continue;
458            }
459
460            self.rate_limiter.check_limit().await?;
461
462            match self
463                .convert_speech_to_text(speech_config, audio_data, language)
464                .await
465            {
466                Ok(result) => return Ok(result),
467                Err(e) => {
468                    warn!(
469                        "Speech-to-text service {} failed: {}",
470                        speech_config.name, e
471                    );
472                }
473            }
474        }
475
476        Err(anyhow!(
477            "No speech-to-text service available for language: {}",
478            language
479        ))
480    }
481
482    /// Real-time streaming speech recognition
483    pub async fn streaming_speech_to_text(
484        &self,
485        audio_stream: tokio::sync::mpsc::Receiver<Vec<u8>>,
486        language: &str,
487        options: &SpeechProcessingOptions,
488    ) -> Result<tokio::sync::mpsc::Receiver<PartialSpeechResult>> {
489        // Find a speech service with real-time streaming support
490        for speech_config in &self.config.speech_services {
491            if !speech_config.enabled
492                || !speech_config.real_time_streaming
493                || speech_config.speech_to_text_url.is_none()
494                || !speech_config
495                    .supported_languages
496                    .contains(&language.to_string())
497            {
498                continue;
499            }
500
501            let url = speech_config
502                .speech_to_text_url
503                .as_ref()
504                .ok_or_else(|| anyhow!("speech_to_text_url missing in config"))?
505                .clone();
506            let api_key = speech_config.api_key.clone();
507            let service_name = speech_config.name.clone();
508            let language_owned = language.to_string();
509            let enable_punctuation = options.enable_punctuation;
510            let http_client = self.client.clone();
511
512            let (tx, rx) = tokio::sync::mpsc::channel::<PartialSpeechResult>(64);
513
514            tokio::spawn(async move {
515                let mut audio_rx = audio_stream;
516                while let Some(chunk) = audio_rx.recv().await {
517                    // Build per-chunk POST request with optional auth
518                    let mut builder = http_client
519                        .post(&url)
520                        .query(&[
521                            ("language", language_owned.as_str()),
522                            (
523                                "punctuation",
524                                if enable_punctuation { "true" } else { "false" },
525                            ),
526                        ])
527                        .body(chunk);
528
529                    if let Some(ref key) = api_key {
530                        builder = builder.header("Authorization", format!("Bearer {key}"));
531                    }
532
533                    match builder.send().await {
534                        Ok(response) => {
535                            match response.json::<serde_json::Value>().await {
536                                Ok(json) => {
537                                    let partial_text = json
538                                        .get("text")
539                                        .or_else(|| json.get("transcript"))
540                                        .and_then(|v| v.as_str())
541                                        .unwrap_or("")
542                                        .to_string();
543                                    let is_final = json
544                                        .get("is_final")
545                                        .and_then(|v| v.as_bool())
546                                        .unwrap_or(false);
547                                    let confidence = json
548                                        .get("confidence")
549                                        .and_then(|v| v.as_f64())
550                                        .unwrap_or(0.0)
551                                        as f32;
552
553                                    let result = PartialSpeechResult {
554                                        service: service_name.clone(),
555                                        partial_text,
556                                        is_final,
557                                        confidence,
558                                        language: language_owned.clone(),
559                                        timestamp: std::time::SystemTime::now(),
560                                    };
561
562                                    if tx.send(result).await.is_err() {
563                                        // Receiver dropped — exit cleanly
564                                        break;
565                                    }
566                                }
567                                Err(e) => {
568                                    tracing::warn!(
569                                        "Failed to parse streaming STT response from {}: {}",
570                                        service_name,
571                                        e
572                                    );
573                                }
574                            }
575                        }
576                        Err(e) => {
577                            tracing::warn!(
578                                "Streaming STT request to {} failed: {}",
579                                service_name,
580                                e
581                            );
582                        }
583                    }
584                }
585            });
586
587            return Ok(rx);
588        }
589
590        Err(anyhow!(
591            "No streaming speech-to-text service available for language: {}",
592            language
593        ))
594    }
595
596    /// Convert text to speech with default voice
597    pub async fn text_to_speech(&self, text: &str, language: &str) -> Result<Vec<u8>> {
598        // Use first available voice model for the language
599        for speech_config in &self.config.speech_services {
600            if let Some(voice_model) = speech_config
601                .voice_models
602                .iter()
603                .find(|v| v.language == language)
604            {
605                return self
606                    .text_to_speech_with_voice(text, language, voice_model)
607                    .await;
608            }
609        }
610
611        // Fallback to basic TTS if no voice models configured
612        self.text_to_speech_basic(text, language).await
613    }
614
615    /// Convert text to speech with specific voice model
616    pub async fn text_to_speech_with_voice(
617        &self,
618        text: &str,
619        _language: &str,
620        voice_model: &VoiceModel,
621    ) -> Result<Vec<u8>> {
622        for speech_config in &self.config.speech_services {
623            if !speech_config.enabled
624                || speech_config.text_to_speech_url.is_none()
625                || !speech_config
626                    .voice_models
627                    .iter()
628                    .any(|v| v.id == voice_model.id)
629            {
630                continue;
631            }
632
633            self.rate_limiter.check_limit().await?;
634
635            match self
636                .convert_text_to_speech(speech_config, text, &voice_model.language)
637                .await
638            {
639                Ok(audio_data) => return Ok(audio_data),
640                Err(e) => {
641                    warn!(
642                        "Text-to-speech service {} failed: {}",
643                        speech_config.name, e
644                    );
645                }
646            }
647        }
648
649        Err(anyhow!(
650            "No text-to-speech service available for voice: {}",
651            voice_model.name
652        ))
653    }
654
655    /// Get available voice models for a language
656    pub fn get_voice_models(&self, language: &str) -> Vec<&VoiceModel> {
657        let mut models = Vec::new();
658        for speech_config in &self.config.speech_services {
659            if speech_config.enabled {
660                models.extend(
661                    speech_config
662                        .voice_models
663                        .iter()
664                        .filter(|v| v.language == language),
665                );
666            }
667        }
668        models
669    }
670
671    /// Get recommended voice model based on preferences
672    pub fn get_recommended_voice(
673        &self,
674        language: &str,
675        gender: Option<VoiceGender>,
676        voice_type: Option<VoiceType>,
677        neural_preferred: bool,
678    ) -> Option<&VoiceModel> {
679        let mut candidates: Vec<&VoiceModel> = self.get_voice_models(language);
680
681        // Filter by gender if specified
682        if let Some(preferred_gender) = gender {
683            candidates.retain(|v| {
684                std::mem::discriminant(&v.gender) == std::mem::discriminant(&preferred_gender)
685            });
686        }
687
688        // Filter by voice type if specified
689        if let Some(preferred_type) = voice_type {
690            candidates.retain(|v| {
691                std::mem::discriminant(&v.voice_type) == std::mem::discriminant(&preferred_type)
692            });
693        }
694
695        // Prefer neural voices if requested
696        if neural_preferred {
697            let neural_voices: Vec<&VoiceModel> = candidates
698                .iter()
699                .filter(|v| v.neural_voice)
700                .copied()
701                .collect();
702            if !neural_voices.is_empty() {
703                candidates = neural_voices;
704            }
705        }
706
707        // Return the first candidate or None if no matches
708        candidates.first().copied()
709    }
710
711    /// Basic text-to-speech fallback method
712    async fn text_to_speech_basic(&self, text: &str, language: &str) -> Result<Vec<u8>> {
713        for speech_config in &self.config.speech_services {
714            if !speech_config.enabled
715                || speech_config.text_to_speech_url.is_none()
716                || !speech_config
717                    .supported_languages
718                    .contains(&language.to_string())
719            {
720                continue;
721            }
722
723            self.rate_limiter.check_limit().await?;
724
725            match self
726                .convert_text_to_speech(speech_config, text, language)
727                .await
728            {
729                Ok(audio_data) => return Ok(audio_data),
730                Err(e) => {
731                    warn!(
732                        "Text-to-speech service {} failed: {}",
733                        speech_config.name, e
734                    );
735                }
736            }
737        }
738
739        Err(anyhow!(
740            "No text-to-speech service available for language: {}",
741            language
742        ))
743    }
744
745    // Private implementation methods
746    async fn query_knowledge_base(
747        &self,
748        config: &KnowledgeBaseConfig,
749        query: &str,
750    ) -> Result<Vec<KnowledgeResult>> {
751        let mut request = self
752            .client
753            .get(format!("{}/search", config.base_url))
754            .query(&[("q", query)]);
755
756        if let Some(api_key) = &config.api_key {
757            request = request.header("Authorization", format!("Bearer {api_key}"));
758        }
759
760        for (key, value) in &config.headers {
761            request = request.header(key, value);
762        }
763
764        let response = request.send().await?;
765        let kb_response: KnowledgeBaseResponse = response.json().await?;
766
767        Ok(kb_response
768            .results
769            .into_iter()
770            .map(|r| KnowledgeResult {
771                source: config.name.clone(),
772                title: r.title,
773                content: r.content,
774                url: r.url,
775                relevance_score: r.score,
776                metadata: r.metadata,
777            })
778            .collect())
779    }
780
781    async fn query_search_engine(
782        &self,
783        config: &SearchEngineConfig,
784        query: &str,
785    ) -> Result<Vec<SearchResult>> {
786        let mut request = self
787            .client
788            .get(&config.api_url)
789            .query(&[("q", query), ("count", &config.max_results.to_string())]);
790
791        if let Some(api_key) = &config.api_key {
792            request = request.header("Authorization", format!("Bearer {api_key}"));
793        }
794
795        let response = request.send().await?;
796        let search_response: SearchEngineResponse = response.json().await?;
797
798        Ok(search_response
799            .results
800            .into_iter()
801            .map(|r| SearchResult {
802                engine: config.name.clone(),
803                title: r.title,
804                description: r.description,
805                url: r.url,
806                score: r.relevance,
807                search_type: config.search_type.clone(),
808            })
809            .collect())
810    }
811
812    async fn check_fact(&self, config: &FactCheckerConfig, claim: &str) -> Result<FactCheckResult> {
813        let mut request = self
814            .client
815            .post(format!("{}/check", config.api_url))
816            .json(&serde_json::json!({"claim": claim}));
817
818        if let Some(api_key) = &config.api_key {
819            request = request.header("Authorization", format!("Bearer {api_key}"));
820        }
821
822        let response = request.send().await?;
823        let fact_response: FactCheckerResponse = response.json().await?;
824
825        Ok(FactCheckResult {
826            checker: config.name.clone(),
827            claim: claim.to_string(),
828            verdict: fact_response.verdict,
829            confidence: fact_response.confidence,
830            explanation: fact_response.explanation,
831            sources: fact_response.sources,
832        })
833    }
834
835    async fn translate_text(
836        &self,
837        config: &TranslationConfig,
838        text: &str,
839        target_language: &str,
840    ) -> Result<TranslationResult> {
841        let mut request = self
842            .client
843            .post(format!("{}/translate", config.api_url))
844            .json(&serde_json::json!({
845                "text": text,
846                "target": target_language
847            }));
848
849        if let Some(api_key) = &config.api_key {
850            request = request.header("Authorization", format!("Bearer {api_key}"));
851        }
852
853        let response = request.send().await?;
854        let trans_response: TranslationResponse = response.json().await?;
855
856        Ok(TranslationResult {
857            service: config.name.clone(),
858            original_text: text.to_string(),
859            translated_text: trans_response.translated_text,
860            source_language: trans_response.detected_language.clone(),
861            target_language: target_language.to_string(),
862            confidence: trans_response.confidence,
863            detected_language: Some(trans_response.detected_language),
864            alternative_translations: Vec::new(),
865            processing_time_ms: 0,
866        })
867    }
868
869    async fn convert_speech_to_text(
870        &self,
871        config: &SpeechConfig,
872        audio_data: &[u8],
873        language: &str,
874    ) -> Result<SpeechResult> {
875        let url = config
876            .speech_to_text_url
877            .as_ref()
878            .expect("speech_to_text_url should be configured");
879
880        let form = reqwest::multipart::Form::new()
881            .part(
882                "audio",
883                reqwest::multipart::Part::bytes(audio_data.to_vec()),
884            )
885            .text("language", language.to_string());
886
887        let mut request = self.client.post(url).multipart(form);
888
889        if let Some(api_key) = &config.api_key {
890            request = request.header("Authorization", format!("Bearer {api_key}"));
891        }
892
893        let response = request.send().await?;
894        let speech_response: SpeechToTextResponse = response.json().await?;
895
896        Ok(SpeechResult {
897            service: config.name.clone(),
898            text: speech_response.text,
899            confidence: speech_response.confidence,
900            language: language.to_string(),
901            word_timestamps: None,
902            speaker_info: None,
903            emotion_analysis: None,
904            processing_time_ms: 0,
905        })
906    }
907
908    async fn detect_language_for_service(
909        &self,
910        config: &TranslationConfig,
911        text: &str,
912    ) -> Result<LanguageDetectionResult> {
913        let mut request = self
914            .client
915            .post(format!("{}/detect", config.api_url))
916            .json(&serde_json::json!({"text": text}));
917
918        if let Some(api_key) = &config.api_key {
919            request = request.header("Authorization", format!("Bearer {api_key}"));
920        }
921
922        let response = request.send().await?;
923        let detection_response: serde_json::Value = response.json().await?;
924
925        Ok(LanguageDetectionResult {
926            service: config.name.clone(),
927            language_code: detection_response["language_code"]
928                .as_str()
929                .unwrap_or("unknown")
930                .to_string(),
931            language_name: detection_response["language_name"]
932                .as_str()
933                .unwrap_or("Unknown")
934                .to_string(),
935            confidence: detection_response["confidence"].as_f64().unwrap_or(0.0) as f32,
936            alternative_languages: Vec::new(),
937            text_sample: text.chars().take(50).collect(),
938        })
939    }
940
941    async fn convert_text_to_speech(
942        &self,
943        config: &SpeechConfig,
944        text: &str,
945        language: &str,
946    ) -> Result<Vec<u8>> {
947        let url = config
948            .text_to_speech_url
949            .as_ref()
950            .expect("text_to_speech_url should be configured");
951
952        let mut request = self.client.post(url).json(&serde_json::json!({
953            "text": text,
954            "language": language
955        }));
956
957        if let Some(api_key) = &config.api_key {
958            request = request.header("Authorization", format!("Bearer {api_key}"));
959        }
960
961        let response = request.send().await?;
962        let audio_data = response.bytes().await?;
963
964        Ok(audio_data.to_vec())
965    }
966}
967
968/// Rate limiter for API calls
969struct RateLimiter {
970    limit_per_minute: u32,
971    calls_made: std::sync::Arc<std::sync::Mutex<u32>>,
972    last_reset: std::sync::Arc<std::sync::Mutex<std::time::Instant>>,
973}
974
975impl RateLimiter {
976    fn new(limit_per_minute: u32) -> Self {
977        Self {
978            limit_per_minute,
979            calls_made: std::sync::Arc::new(std::sync::Mutex::new(0)),
980            last_reset: std::sync::Arc::new(std::sync::Mutex::new(std::time::Instant::now())),
981        }
982    }
983
984    async fn check_limit(&self) -> Result<()> {
985        let now = std::time::Instant::now();
986
987        {
988            let mut last_reset = self.last_reset.lock().expect("lock should not be poisoned");
989            if now.duration_since(*last_reset) >= Duration::from_secs(60) {
990                *last_reset = now;
991                *self.calls_made.lock().expect("lock should not be poisoned") = 0;
992            }
993        }
994
995        let mut calls = self.calls_made.lock().expect("lock should not be poisoned");
996        if *calls >= self.limit_per_minute {
997            return Err(anyhow!("Rate limit exceeded"));
998        }
999
1000        *calls += 1;
1001        Ok(())
1002    }
1003}
1004
1005// Result types
1006#[derive(Debug, Clone, Serialize, Deserialize)]
1007pub struct KnowledgeResult {
1008    pub source: String,
1009    pub title: String,
1010    pub content: String,
1011    pub url: Option<String>,
1012    pub relevance_score: f32,
1013    pub metadata: HashMap<String, String>,
1014}
1015
1016#[derive(Debug, Clone, Serialize, Deserialize)]
1017pub struct SearchResult {
1018    pub engine: String,
1019    pub title: String,
1020    pub description: String,
1021    pub url: String,
1022    pub score: f32,
1023    pub search_type: SearchType,
1024}
1025
1026#[derive(Debug, Clone, Serialize, Deserialize)]
1027pub struct FactCheckResult {
1028    pub checker: String,
1029    pub claim: String,
1030    pub verdict: FactVerdict,
1031    pub confidence: f32,
1032    pub explanation: String,
1033    pub sources: Vec<String>,
1034}
1035
1036#[derive(Debug, Clone, Serialize, Deserialize)]
1037pub enum FactVerdict {
1038    True,
1039    False,
1040    PartiallyTrue,
1041    Misleading,
1042    Unverifiable,
1043    Unknown,
1044}
1045
1046#[derive(Debug, Clone, Serialize, Deserialize)]
1047pub struct TranslationResult {
1048    pub service: String,
1049    pub original_text: String,
1050    pub translated_text: String,
1051    pub source_language: String,
1052    pub target_language: String,
1053    pub confidence: f32,
1054    pub detected_language: Option<String>,
1055    pub alternative_translations: Vec<String>,
1056    pub processing_time_ms: u64,
1057}
1058
1059/// Language detection result
1060#[derive(Debug, Clone, Serialize, Deserialize)]
1061pub struct LanguageDetectionResult {
1062    pub service: String,
1063    pub language_code: String,
1064    pub language_name: String,
1065    pub confidence: f32,
1066    pub alternative_languages: Vec<LanguageCandidate>,
1067    pub text_sample: String,
1068}
1069
1070/// Alternative language candidate from detection
1071#[derive(Debug, Clone, Serialize, Deserialize)]
1072pub struct LanguageCandidate {
1073    pub language_code: String,
1074    pub language_name: String,
1075    pub confidence: f32,
1076}
1077
1078/// Language pair for translation capabilities
1079#[derive(Debug, Clone, Serialize, Deserialize)]
1080pub struct LanguagePair {
1081    pub source_language: String,
1082    pub target_language: String,
1083    pub service: String,
1084}
1085
1086#[derive(Debug, Clone, Serialize, Deserialize)]
1087pub struct SpeechResult {
1088    pub service: String,
1089    pub text: String,
1090    pub confidence: f32,
1091    pub language: String,
1092    pub word_timestamps: Option<Vec<WordTimestamp>>,
1093    pub speaker_info: Option<Vec<SpeakerInfo>>,
1094    pub emotion_analysis: Option<EmotionAnalysis>,
1095    pub processing_time_ms: u64,
1096}
1097
1098/// Enhanced result type for partial speech recognition (streaming)
1099#[derive(Debug, Clone, Serialize, Deserialize)]
1100pub struct PartialSpeechResult {
1101    pub service: String,
1102    pub partial_text: String,
1103    pub is_final: bool,
1104    pub confidence: f32,
1105    pub language: String,
1106    pub timestamp: std::time::SystemTime,
1107}
1108
1109/// Word-level timestamp information
1110#[derive(Debug, Clone, Serialize, Deserialize)]
1111pub struct WordTimestamp {
1112    pub word: String,
1113    pub start_time_ms: u64,
1114    pub end_time_ms: u64,
1115    pub confidence: f32,
1116}
1117
1118/// Speaker identification information
1119#[derive(Debug, Clone, Serialize, Deserialize)]
1120pub struct SpeakerInfo {
1121    pub speaker_id: String,
1122    pub start_time_ms: u64,
1123    pub end_time_ms: u64,
1124    pub confidence: f32,
1125    pub speaker_characteristics: Option<SpeakerCharacteristics>,
1126}
1127
1128/// Speaker voice characteristics
1129#[derive(Debug, Clone, Serialize, Deserialize)]
1130pub struct SpeakerCharacteristics {
1131    pub estimated_gender: Option<VoiceGender>,
1132    pub estimated_age_range: Option<VoiceAgeRange>,
1133    pub voice_energy: f32,
1134    pub speaking_rate: f32,
1135}
1136
1137/// Emotion analysis results
1138#[derive(Debug, Clone, Serialize, Deserialize)]
1139pub struct EmotionAnalysis {
1140    pub primary_emotion: Emotion,
1141    pub emotion_scores: HashMap<Emotion, f32>,
1142    pub valence: f32, // Positive/negative sentiment
1143    pub arousal: f32, // Energy level
1144    pub confidence: f32,
1145}
1146
1147/// Detected emotions
1148#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
1149pub enum Emotion {
1150    Joy,
1151    Sadness,
1152    Anger,
1153    Fear,
1154    Surprise,
1155    Disgust,
1156    Neutral,
1157    Excitement,
1158    Frustration,
1159    Confusion,
1160}
1161
1162// Internal response types for external APIs
1163#[derive(Debug, Deserialize)]
1164struct KnowledgeBaseResponse {
1165    results: Vec<KnowledgeBaseResult>,
1166}
1167
1168#[derive(Debug, Deserialize)]
1169struct KnowledgeBaseResult {
1170    title: String,
1171    content: String,
1172    url: Option<String>,
1173    score: f32,
1174    metadata: HashMap<String, String>,
1175}
1176
1177#[derive(Debug, Deserialize)]
1178struct SearchEngineResponse {
1179    results: Vec<SearchEngineResult>,
1180}
1181
1182#[derive(Debug, Deserialize)]
1183struct SearchEngineResult {
1184    title: String,
1185    description: String,
1186    url: String,
1187    relevance: f32,
1188}
1189
1190#[derive(Debug, Deserialize)]
1191struct FactCheckerResponse {
1192    verdict: FactVerdict,
1193    confidence: f32,
1194    explanation: String,
1195    sources: Vec<String>,
1196}
1197
1198#[derive(Debug, Deserialize)]
1199struct TranslationResponse {
1200    translated_text: String,
1201    detected_language: String,
1202    confidence: f32,
1203}
1204
1205#[derive(Debug, Deserialize)]
1206struct SpeechToTextResponse {
1207    text: String,
1208    confidence: f32,
1209}
1210
1211// Implement PartialEq for SearchType to enable comparison
1212impl PartialEq for SearchType {
1213    fn eq(&self, other: &Self) -> bool {
1214        matches!(
1215            (self, other),
1216            (SearchType::Web, SearchType::Web)
1217                | (SearchType::Academic, SearchType::Academic)
1218                | (SearchType::News, SearchType::News)
1219                | (SearchType::Images, SearchType::Images)
1220                | (SearchType::Videos, SearchType::Videos)
1221                | (SearchType::Knowledge, SearchType::Knowledge)
1222        )
1223    }
1224}
1225
1226#[cfg(test)]
1227mod tests {
1228    use super::*;
1229
1230    fn make_streaming_config(language: &str) -> ExternalServicesConfig {
1231        ExternalServicesConfig {
1232            speech_services: vec![SpeechConfig {
1233                name: "test-stt".to_string(),
1234                speech_to_text_url: Some("http://127.0.0.1:19999/stt".to_string()),
1235                text_to_speech_url: None,
1236                api_key: None,
1237                supported_languages: vec![language.to_string()],
1238                enabled: true,
1239                voice_models: Vec::new(),
1240                real_time_streaming: true,
1241                noise_cancellation: false,
1242                speech_enhancement: false,
1243                speaker_diarization: false,
1244                emotion_detection: false,
1245                custom_vocabulary: Vec::new(),
1246            }],
1247            ..ExternalServicesConfig::default()
1248        }
1249    }
1250
1251    /// streaming_speech_to_text returns Ok(receiver) immediately when a matching config exists.
1252    /// The spawned worker exits cleanly when the audio sender is dropped.
1253    #[tokio::test]
1254    async fn test_streaming_speech_to_text_returns_receiver() {
1255        let config = make_streaming_config("en-US");
1256        let manager = ExternalServicesManager::new(config).expect("should build HTTP client");
1257
1258        let options = SpeechProcessingOptions {
1259            enable_punctuation: false,
1260            enable_profanity_filter: false,
1261            enable_automatic_formatting: false,
1262            enable_word_timestamps: false,
1263            enable_confidence_scores: false,
1264            enable_speaker_identification: false,
1265            language_detection_mode: LanguageDetectionMode::None,
1266            audio_quality_enhancement: false,
1267        };
1268
1269        let (audio_tx, audio_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(8);
1270
1271        let result = manager
1272            .streaming_speech_to_text(audio_rx, "en-US", &options)
1273            .await;
1274
1275        assert!(
1276            result.is_ok(),
1277            "expected Ok(receiver), got {:?}",
1278            result.err()
1279        );
1280
1281        // Drop the audio sender — the spawned worker should exit without hanging
1282        drop(audio_tx);
1283
1284        // Receiver should close once the worker exits (may take a moment since no HTTP)
1285        let mut rx = result.unwrap();
1286        // Give the worker a tick to exit; because the endpoint is unreachable the loop
1287        // will drain then stop — at most we get nothing back and the channel closes.
1288        let _ = tokio::time::timeout(std::time::Duration::from_millis(200), rx.recv()).await;
1289        // Either None (worker exited) or a timeout is acceptable — the point is no panic/hang
1290    }
1291
1292    /// When no matching config is present, the function returns Err with a descriptive message.
1293    #[tokio::test]
1294    async fn test_streaming_speech_to_text_no_matching_service() {
1295        let config = ExternalServicesConfig::default(); // no speech services
1296        let manager = ExternalServicesManager::new(config).expect("should build HTTP client");
1297
1298        let options = SpeechProcessingOptions {
1299            enable_punctuation: false,
1300            enable_profanity_filter: false,
1301            enable_automatic_formatting: false,
1302            enable_word_timestamps: false,
1303            enable_confidence_scores: false,
1304            enable_speaker_identification: false,
1305            language_detection_mode: LanguageDetectionMode::None,
1306            audio_quality_enhancement: false,
1307        };
1308
1309        let (_audio_tx, audio_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(1);
1310
1311        let result = manager
1312            .streaming_speech_to_text(audio_rx, "ja-JP", &options)
1313            .await;
1314
1315        assert!(result.is_err());
1316        let msg = result.unwrap_err().to_string();
1317        assert!(
1318            msg.contains("ja-JP"),
1319            "error should mention language, got: {}",
1320            msg
1321        );
1322        assert!(
1323            !msg.contains("not yet implemented"),
1324            "stub message should be gone, got: {}",
1325            msg
1326        );
1327    }
1328
1329    /// When a config exists but real_time_streaming = false, it should skip that config.
1330    #[tokio::test]
1331    async fn test_streaming_speech_to_text_skips_non_streaming_config() {
1332        let mut config = make_streaming_config("en-US");
1333        // Disable streaming on the only config
1334        config.speech_services[0].real_time_streaming = false;
1335        let manager = ExternalServicesManager::new(config).expect("should build HTTP client");
1336
1337        let options = SpeechProcessingOptions {
1338            enable_punctuation: false,
1339            enable_profanity_filter: false,
1340            enable_automatic_formatting: false,
1341            enable_word_timestamps: false,
1342            enable_confidence_scores: false,
1343            enable_speaker_identification: false,
1344            language_detection_mode: LanguageDetectionMode::None,
1345            audio_quality_enhancement: false,
1346        };
1347
1348        let (_audio_tx, audio_rx) = tokio::sync::mpsc::channel::<Vec<u8>>(1);
1349        let result = manager
1350            .streaming_speech_to_text(audio_rx, "en-US", &options)
1351            .await;
1352
1353        assert!(result.is_err());
1354        assert!(result.unwrap_err().to_string().contains("en-US"));
1355    }
1356}