manx_cli/rag/
llm.rs

1//! Multi-provider LLM integration for answer synthesis
2//!
3//! Supports OpenAI GPT, Anthropic Claude, Groq, OpenRouter, HuggingFace, and custom endpoints
4//! with automatic failover and comprehensive error handling.
5
6use anyhow::{anyhow, Result};
7use serde::{Deserialize, Serialize};
8
9use crate::rag::RagSearchResult;
10
11/// Configuration for LLM integration supporting multiple providers
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct LlmConfig {
14    pub openai_api_key: Option<String>,
15    pub anthropic_api_key: Option<String>,
16    pub groq_api_key: Option<String>,
17    pub openrouter_api_key: Option<String>,
18    pub huggingface_api_key: Option<String>,
19    pub custom_endpoint: Option<String>,
20    pub preferred_provider: LlmProvider,
21    pub fallback_providers: Vec<LlmProvider>,
22    pub timeout_seconds: u64,
23    pub max_tokens: u32,
24    pub temperature: f32,
25    pub model_name: Option<String>,
26    pub streaming: bool,
27}
28
29impl Default for LlmConfig {
30    fn default() -> Self {
31        Self {
32            openai_api_key: None,
33            anthropic_api_key: None,
34            groq_api_key: None,
35            openrouter_api_key: None,
36            huggingface_api_key: None,
37            custom_endpoint: None,
38            preferred_provider: LlmProvider::Auto,
39            fallback_providers: vec![
40                LlmProvider::OpenAI,
41                LlmProvider::Anthropic,
42                LlmProvider::Groq,
43                LlmProvider::OpenRouter,
44            ],
45            timeout_seconds: 30,
46            max_tokens: 1000,
47            temperature: 0.1,
48            model_name: None,
49            streaming: false,
50        }
51    }
52}
53
54/// Available LLM providers
55#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
56pub enum LlmProvider {
57    Auto,
58    OpenAI,
59    Anthropic,
60    Groq,
61    OpenRouter,
62    HuggingFace,
63    Custom,
64}
65
66/// LLM response with comprehensive metadata
67#[derive(Debug, Clone, Serialize, Deserialize)]
68pub struct LlmResponse {
69    pub answer: String,
70    pub sources_used: Vec<String>,
71    pub confidence: Option<f32>,
72    pub provider_used: LlmProvider,
73    pub model_used: String,
74    pub tokens_used: Option<u32>,
75    pub response_time_ms: u64,
76    pub finish_reason: Option<String>,
77    pub citations: Vec<Citation>,
78}
79
80/// Citation information linking to source documents
81#[derive(Debug, Clone, Serialize, Deserialize)]
82pub struct Citation {
83    pub source_id: String,
84    pub source_title: String,
85    pub source_url: Option<String>,
86    pub relevance_score: f32,
87    pub excerpt: String,
88}
89
90/// Multi-provider LLM client with automatic failover
91#[derive(Clone)]
92pub struct LlmClient {
93    pub(crate) config: LlmConfig,
94    pub(crate) http_client: reqwest::Client,
95}
96
97impl LlmClient {
98    /// Create a new LLM client with configuration
99    pub fn new(config: LlmConfig) -> Result<Self> {
100        let http_client = reqwest::Client::builder()
101            .timeout(std::time::Duration::from_secs(config.timeout_seconds))
102            .build()?;
103
104        Ok(Self {
105            config,
106            http_client,
107        })
108    }
109
110    /// Check if any LLM provider is available
111    pub fn is_available(&self) -> bool {
112        self.has_openai_key()
113            || self.has_anthropic_key()
114            || self.has_groq_key()
115            || self.has_openrouter_key()
116            || self.has_huggingface_key()
117            || self.config.custom_endpoint.is_some()
118    }
119
120    /// Check availability of specific providers
121    pub fn has_openai_key(&self) -> bool {
122        self.config
123            .openai_api_key
124            .as_ref()
125            .is_some_and(|key| !key.is_empty())
126    }
127
128    pub fn has_anthropic_key(&self) -> bool {
129        self.config
130            .anthropic_api_key
131            .as_ref()
132            .is_some_and(|key| !key.is_empty())
133    }
134
135    pub fn has_groq_key(&self) -> bool {
136        self.config
137            .groq_api_key
138            .as_ref()
139            .is_some_and(|key| !key.is_empty())
140    }
141
142    pub fn has_openrouter_key(&self) -> bool {
143        self.config
144            .openrouter_api_key
145            .as_ref()
146            .is_some_and(|key| !key.is_empty())
147    }
148
149    pub fn has_huggingface_key(&self) -> bool {
150        self.config
151            .huggingface_api_key
152            .as_ref()
153            .is_some_and(|key| !key.is_empty())
154    }
155
156    /// Get the best available provider based on configuration and API key availability
157    pub fn get_best_provider(&self) -> Option<LlmProvider> {
158        if self.config.preferred_provider != LlmProvider::Auto {
159            // Check if preferred provider is available
160            if self.is_provider_available(&self.config.preferred_provider) {
161                return Some(self.config.preferred_provider.clone());
162            }
163        }
164
165        // Try fallback providers in order
166        for provider in &self.config.fallback_providers {
167            if self.is_provider_available(provider) {
168                return Some(provider.clone());
169            }
170        }
171
172        None
173    }
174
175    /// Check if a specific provider is available
176    pub fn is_provider_available(&self, provider: &LlmProvider) -> bool {
177        match provider {
178            LlmProvider::OpenAI => self.has_openai_key(),
179            LlmProvider::Anthropic => self.has_anthropic_key(),
180            LlmProvider::Groq => self.has_groq_key(),
181            LlmProvider::OpenRouter => self.has_openrouter_key(),
182            LlmProvider::HuggingFace => self.has_huggingface_key(),
183            LlmProvider::Custom => self.config.custom_endpoint.is_some(),
184            LlmProvider::Auto => false, // Auto is not a real provider
185        }
186    }
187
188    /// Synthesize an answer from search results using the best available provider
189    pub async fn synthesize_answer(
190        &self,
191        query: &str,
192        results: &[RagSearchResult],
193    ) -> Result<LlmResponse> {
194        let provider = self
195            .get_best_provider()
196            .ok_or_else(|| anyhow!("No LLM provider available"))?;
197
198        let start_time = std::time::Instant::now();
199
200        let response = match provider {
201            LlmProvider::OpenAI => self.synthesize_with_openai(query, results).await,
202            LlmProvider::Anthropic => self.synthesize_with_anthropic(query, results).await,
203            LlmProvider::Groq => self.synthesize_with_groq(query, results).await,
204            LlmProvider::OpenRouter => self.synthesize_with_openrouter(query, results).await,
205            LlmProvider::HuggingFace => self.synthesize_with_huggingface(query, results).await,
206            LlmProvider::Custom => self.synthesize_with_custom(query, results).await,
207            LlmProvider::Auto => unreachable!(),
208        };
209
210        // If primary provider fails, try fallback providers
211        match response {
212            Ok(mut resp) => {
213                resp.response_time_ms = start_time.elapsed().as_millis() as u64;
214                Ok(resp)
215            }
216            Err(e) => {
217                log::warn!("Primary provider {:?} failed: {}", provider, e);
218                self.try_fallback_providers(query, results, &provider).await
219            }
220        }
221    }
222
223    /// Try fallback providers if primary fails
224    async fn try_fallback_providers(
225        &self,
226        query: &str,
227        results: &[RagSearchResult],
228        failed_provider: &LlmProvider,
229    ) -> Result<LlmResponse> {
230        for provider in &self.config.fallback_providers {
231            if provider != failed_provider && self.is_provider_available(provider) {
232                log::info!("Trying fallback provider: {:?}", provider);
233
234                let start_time = std::time::Instant::now();
235                let response = match provider {
236                    LlmProvider::OpenAI => self.synthesize_with_openai(query, results).await,
237                    LlmProvider::Anthropic => self.synthesize_with_anthropic(query, results).await,
238                    LlmProvider::Groq => self.synthesize_with_groq(query, results).await,
239                    LlmProvider::OpenRouter => {
240                        self.synthesize_with_openrouter(query, results).await
241                    }
242                    LlmProvider::HuggingFace => {
243                        self.synthesize_with_huggingface(query, results).await
244                    }
245                    LlmProvider::Custom => self.synthesize_with_custom(query, results).await,
246                    LlmProvider::Auto => continue,
247                };
248
249                if let Ok(mut resp) = response {
250                    resp.response_time_ms = start_time.elapsed().as_millis() as u64;
251                    return Ok(resp);
252                }
253            }
254        }
255
256        Err(anyhow!("All LLM providers failed"))
257    }
258
259    /// Get the appropriate model name for a provider
260    fn get_model_name(&self, provider: &LlmProvider) -> String {
261        if let Some(model) = &self.config.model_name {
262            return model.clone();
263        }
264
265        match provider {
266            LlmProvider::OpenAI => "gpt-4o-mini".to_string(),
267            LlmProvider::Anthropic => "claude-3-haiku-20240307".to_string(),
268            LlmProvider::Groq => "llama-3.1-8b-instant".to_string(),
269            LlmProvider::OpenRouter => "openai/gpt-3.5-turbo".to_string(),
270            LlmProvider::HuggingFace => "microsoft/DialoGPT-medium".to_string(),
271            LlmProvider::Custom => "custom-model".to_string(),
272            LlmProvider::Auto => "auto".to_string(),
273        }
274    }
275
276    /// Create concise system prompt focused on clean, scannable output
277    fn create_system_prompt(&self) -> String {
278        r#"You are a concise technical documentation assistant. Provide clear, scannable answers based ONLY on the provided search results.
279
280RESPONSE FORMAT:
2811. **Quick Answer** (1-2 sentences max)
2822. **Key Points** (bullet points, max 4 items)  
2833. **Code Example** (if available - keep it short and practical)
284
285RULES:
286- Be extremely concise and scannable
287- Use bullet points and short paragraphs
288- Only include essential information
289- Cite sources as [Source N] 
290- Never add information not in the sources
291- Focus on what developers need to know immediately
292
293STYLE:
294- Write for busy developers who want quick answers
295- Use clear, simple language
296- Keep code examples minimal but complete
297- Prioritize readability over completeness"#.to_string()
298    }
299
300    /// Create user prompt with query and search results
301    fn create_user_prompt(&self, query: &str, results: &[RagSearchResult]) -> String {
302        let mut prompt = format!("Question: {}\n\nSearch Results:\n\n", query);
303
304        for (i, result) in results.iter().enumerate() {
305            prompt.push_str(&format!(
306                "[Source {}] {}\nURL: {}\nContent: {}\n\n",
307                i + 1,
308                result.title.as_ref().unwrap_or(&"Untitled".to_string()),
309                result.source_path.to_string_lossy(),
310                result.content.chars().take(1000).collect::<String>()
311            ));
312        }
313
314        prompt.push_str("\nPlease provide a comprehensive answer based on these search results.");
315        prompt
316    }
317
318    /// Extract the actual answer from responses that may contain thinking content (instance)
319    fn extract_final_answer(&self, response_text: &str) -> String {
320        Self::extract_final_answer_text(response_text)
321    }
322
323    /// Extract the actual answer from responses that may contain thinking content (static)
324    pub(crate) fn extract_final_answer_text(response_text: &str) -> String {
325        // Handle models with thinking capabilities - check for both <thinking> and <think> tags
326        if response_text.contains("<thinking>") && response_text.contains("</thinking>") {
327            // Find the end of the thinking section
328            if let Some(thinking_end) = response_text.find("</thinking>") {
329                let after_thinking = &response_text[thinking_end + "</thinking>".len()..];
330                return after_thinking.trim().to_string();
331            }
332        }
333
334        // Handle models that use <think> tags instead of <thinking>
335        if response_text.contains("<think>") && response_text.contains("</think>") {
336            // Find the end of the think section
337            if let Some(think_end) = response_text.find("</think>") {
338                let after_think = &response_text[think_end + "</think>".len()..];
339                return after_think.trim().to_string();
340            }
341        }
342
343        // Handle models that might use other thinking patterns
344        // Some models use patterns like "Let me think about this..." followed by the actual answer
345        if response_text.starts_with("Let me think") || response_text.starts_with("I need to think")
346        {
347            // Look for common transition phrases that indicate the start of the actual answer
348            let transition_phrases = [
349                "Here's my answer:",
350                "My answer is:",
351                "To answer your question:",
352                "Based on the search results:",
353                "The answer is:",
354                "\n\n**", // Common formatting transition
355                "\n\nQuick Answer:",
356                "\n\n##", // Markdown heading transition
357            ];
358
359            for phrase in &transition_phrases {
360                if let Some(pos) = response_text.find(phrase) {
361                    let answer_start = if phrase.starts_with('\n') {
362                        pos + 2 // Skip the newlines
363                    } else {
364                        pos + phrase.len()
365                    };
366                    return response_text[answer_start..].trim().to_string();
367                }
368            }
369        }
370
371        // For other models or no thinking pattern detected, return the full response
372        response_text.to_string()
373    }
374
375    /// Extract citations from LLM response
376    fn extract_citations(&self, response_text: &str, results: &[RagSearchResult]) -> Vec<Citation> {
377        let mut citations = Vec::new();
378
379        // Simple citation extraction - look for [Source N] patterns
380        for (i, result) in results.iter().enumerate() {
381            let source_ref = format!("[Source {}]", i + 1);
382            if response_text.contains(&source_ref) {
383                citations.push(Citation {
384                    source_id: result.id.clone(),
385                    source_title: result
386                        .title
387                        .clone()
388                        .unwrap_or_else(|| "Untitled".to_string()),
389                    source_url: Some(result.source_path.to_string_lossy().to_string()),
390                    relevance_score: result.score,
391                    excerpt: result.content.chars().take(200).collect(),
392                });
393            }
394        }
395
396        citations
397    }
398
399    /// OpenAI GPT integration with streaming support
400    async fn synthesize_with_openai(
401        &self,
402        query: &str,
403        results: &[RagSearchResult],
404    ) -> Result<LlmResponse> {
405        let api_key = self
406            .config
407            .openai_api_key
408            .as_ref()
409            .ok_or_else(|| anyhow!("OpenAI API key not configured"))?;
410
411        let model = self.get_model_name(&LlmProvider::OpenAI);
412        let system_prompt = self.create_system_prompt();
413        let user_prompt = self.create_user_prompt(query, results);
414
415        let payload = serde_json::json!({
416            "model": model,
417            "messages": [
418                {
419                    "role": "system",
420                    "content": system_prompt
421                },
422                {
423                    "role": "user",
424                    "content": user_prompt
425                }
426            ],
427            "max_tokens": self.config.max_tokens,
428            "temperature": self.config.temperature,
429            "stream": self.config.streaming
430        });
431
432        let response = self
433            .http_client
434            .post("https://api.openai.com/v1/chat/completions")
435            .header("Authorization", format!("Bearer {}", api_key))
436            .header("Content-Type", "application/json")
437            .json(&payload)
438            .send()
439            .await?;
440
441        if !response.status().is_success() {
442            let error_text = response.text().await?;
443            return Err(anyhow!("OpenAI API error: {}", error_text));
444        }
445
446        let response_json: serde_json::Value = response.json().await?;
447
448        let raw_answer = response_json["choices"][0]["message"]["content"]
449            .as_str()
450            .ok_or_else(|| anyhow!("Invalid OpenAI response format"))?;
451        let answer = self.extract_final_answer(raw_answer);
452
453        let usage = &response_json["usage"];
454        let tokens_used = usage["total_tokens"].as_u64().map(|t| t as u32);
455        let finish_reason = response_json["choices"][0]["finish_reason"]
456            .as_str()
457            .map(|s| s.to_string());
458
459        let citations = self.extract_citations(&answer, results);
460
461        Ok(LlmResponse {
462            answer,
463            sources_used: results.iter().map(|r| r.id.clone()).collect(),
464            confidence: Some(0.9), // OpenAI typically high confidence
465            provider_used: LlmProvider::OpenAI,
466            model_used: model,
467            tokens_used,
468            response_time_ms: 0, // Will be set by caller
469            finish_reason,
470            citations,
471        })
472    }
473
474    /// Anthropic Claude integration with function calling support
475    async fn synthesize_with_anthropic(
476        &self,
477        query: &str,
478        results: &[RagSearchResult],
479    ) -> Result<LlmResponse> {
480        let api_key = self
481            .config
482            .anthropic_api_key
483            .as_ref()
484            .ok_or_else(|| anyhow!("Anthropic API key not configured"))?;
485
486        let model = self.get_model_name(&LlmProvider::Anthropic);
487        let system_prompt = self.create_system_prompt();
488        let user_prompt = self.create_user_prompt(query, results);
489
490        let payload = serde_json::json!({
491            "model": model,
492            "max_tokens": self.config.max_tokens,
493            "temperature": self.config.temperature,
494            "system": system_prompt,
495            "messages": [
496                {
497                    "role": "user",
498                    "content": user_prompt
499                }
500            ]
501        });
502
503        let response = self
504            .http_client
505            .post("https://api.anthropic.com/v1/messages")
506            .header("x-api-key", api_key)
507            .header("content-type", "application/json")
508            .header("anthropic-version", "2023-06-01")
509            .json(&payload)
510            .send()
511            .await?;
512
513        if !response.status().is_success() {
514            let error_text = response.text().await?;
515            return Err(anyhow!("Anthropic API error: {}", error_text));
516        }
517
518        let response_json: serde_json::Value = response.json().await?;
519
520        let raw_answer = response_json["content"][0]["text"]
521            .as_str()
522            .ok_or_else(|| anyhow!("Invalid Anthropic response format"))?;
523        let answer = self.extract_final_answer(raw_answer);
524
525        let usage = &response_json["usage"];
526        let tokens_used = usage["output_tokens"].as_u64().map(|t| t as u32);
527        let finish_reason = response_json["stop_reason"].as_str().map(|s| s.to_string());
528
529        let citations = self.extract_citations(&answer, results);
530
531        Ok(LlmResponse {
532            answer,
533            sources_used: results.iter().map(|r| r.id.clone()).collect(),
534            confidence: Some(0.85), // Claude typically good confidence
535            provider_used: LlmProvider::Anthropic,
536            model_used: model,
537            tokens_used,
538            response_time_ms: 0,
539            finish_reason,
540            citations,
541        })
542    }
543
544    /// Groq fast inference integration for ultra-fast responses
545    async fn synthesize_with_groq(
546        &self,
547        query: &str,
548        results: &[RagSearchResult],
549    ) -> Result<LlmResponse> {
550        let api_key = self
551            .config
552            .groq_api_key
553            .as_ref()
554            .ok_or_else(|| anyhow!("Groq API key not configured"))?;
555
556        let model = self.get_model_name(&LlmProvider::Groq);
557        let system_prompt = self.create_system_prompt();
558        let user_prompt = self.create_user_prompt(query, results);
559
560        let payload = serde_json::json!({
561            "model": model,
562            "messages": [
563                {
564                    "role": "system",
565                    "content": system_prompt
566                },
567                {
568                    "role": "user",
569                    "content": user_prompt
570                }
571            ],
572            "max_tokens": self.config.max_tokens,
573            "temperature": self.config.temperature,
574            "stream": false
575        });
576
577        let response = self
578            .http_client
579            .post("https://api.groq.com/openai/v1/chat/completions")
580            .header("Authorization", format!("Bearer {}", api_key))
581            .header("Content-Type", "application/json")
582            .json(&payload)
583            .send()
584            .await?;
585
586        if !response.status().is_success() {
587            let status = response.status();
588            let error_text = response.text().await?;
589            log::error!(
590                "Groq API error - Status: {}, Response: {}",
591                status,
592                error_text
593            );
594            return Err(anyhow!("Groq API error ({}): {}", status, error_text));
595        }
596
597        let response_json: serde_json::Value = response.json().await?;
598
599        let raw_answer = response_json["choices"][0]["message"]["content"]
600            .as_str()
601            .ok_or_else(|| anyhow!("Invalid Groq response format"))?;
602        let answer = self.extract_final_answer(raw_answer);
603
604        let usage = &response_json["usage"];
605        let tokens_used = usage["total_tokens"].as_u64().map(|t| t as u32);
606        let finish_reason = response_json["choices"][0]["finish_reason"]
607            .as_str()
608            .map(|s| s.to_string());
609
610        let citations = self.extract_citations(&answer, results);
611
612        Ok(LlmResponse {
613            answer,
614            sources_used: results.iter().map(|r| r.id.clone()).collect(),
615            confidence: Some(0.8), // Groq usually good quality
616            provider_used: LlmProvider::Groq,
617            model_used: model,
618            tokens_used,
619            response_time_ms: 0,
620            finish_reason,
621            citations,
622        })
623    }
624
625    /// OpenRouter multi-model gateway for access to multiple providers
626    async fn synthesize_with_openrouter(
627        &self,
628        query: &str,
629        results: &[RagSearchResult],
630    ) -> Result<LlmResponse> {
631        let api_key = self
632            .config
633            .openrouter_api_key
634            .as_ref()
635            .ok_or_else(|| anyhow!("OpenRouter API key not configured"))?;
636
637        let model = self.get_model_name(&LlmProvider::OpenRouter);
638        let system_prompt = self.create_system_prompt();
639        let user_prompt = self.create_user_prompt(query, results);
640
641        let payload = serde_json::json!({
642            "model": model,
643            "messages": [
644                {
645                    "role": "system",
646                    "content": system_prompt
647                },
648                {
649                    "role": "user",
650                    "content": user_prompt
651                }
652            ],
653            "max_tokens": self.config.max_tokens,
654            "temperature": self.config.temperature,
655            "stream": self.config.streaming
656        });
657
658        let response = self
659            .http_client
660            .post("https://openrouter.ai/api/v1/chat/completions")
661            .header("Authorization", format!("Bearer {}", api_key))
662            .header("Content-Type", "application/json")
663            .header("HTTP-Referer", "https://github.com/neur0map/manx")
664            .header("X-Title", "Manx Documentation Finder")
665            .json(&payload)
666            .send()
667            .await?;
668
669        if !response.status().is_success() {
670            let error_text = response.text().await?;
671            return Err(anyhow!("OpenRouter API error: {}", error_text));
672        }
673
674        let response_json: serde_json::Value = response.json().await?;
675
676        let raw_answer = response_json["choices"][0]["message"]["content"]
677            .as_str()
678            .ok_or_else(|| anyhow!("Invalid OpenRouter response format"))?;
679        let answer = self.extract_final_answer(raw_answer);
680
681        let usage = &response_json["usage"];
682        let tokens_used = usage["total_tokens"].as_u64().map(|t| t as u32);
683        let finish_reason = response_json["choices"][0]["finish_reason"]
684            .as_str()
685            .map(|s| s.to_string());
686
687        let citations = self.extract_citations(&answer, results);
688
689        Ok(LlmResponse {
690            answer,
691            sources_used: results.iter().map(|r| r.id.clone()).collect(),
692            confidence: Some(0.82), // Varies by underlying model
693            provider_used: LlmProvider::OpenRouter,
694            model_used: model,
695            tokens_used,
696            response_time_ms: 0,
697            finish_reason,
698            citations,
699        })
700    }
701
702    /// HuggingFace Router API for open-source models
703    async fn synthesize_with_huggingface(
704        &self,
705        query: &str,
706        results: &[RagSearchResult],
707    ) -> Result<LlmResponse> {
708        let api_key = self
709            .config
710            .huggingface_api_key
711            .as_ref()
712            .ok_or_else(|| anyhow!("HuggingFace API key not configured"))?;
713
714        let model = self.get_model_name(&LlmProvider::HuggingFace);
715        let system_prompt = self.create_system_prompt();
716        let user_prompt = self.create_user_prompt(query, results);
717
718        // Use OpenAI-compatible chat completions format
719        let payload = serde_json::json!({
720            "model": model,
721            "messages": [
722                {"role": "system", "content": system_prompt},
723                {"role": "user", "content": user_prompt}
724            ],
725            "max_tokens": self.config.max_tokens,
726            "temperature": self.config.temperature
727        });
728
729        let response = self
730            .http_client
731            .post("https://router.huggingface.co/v1/chat/completions")
732            .header("Authorization", format!("Bearer {}", api_key))
733            .header("Content-Type", "application/json")
734            .json(&payload)
735            .send()
736            .await?;
737
738        if !response.status().is_success() {
739            let error_text = response.text().await?;
740            return Err(anyhow!("HuggingFace API error: {}", error_text));
741        }
742
743        let response_json: serde_json::Value = response.json().await?;
744
745        let raw_answer = if let Some(choices) = response_json["choices"].as_array() {
746            if let Some(first_choice) = choices.first() {
747                if let Some(message) = first_choice["message"].as_object() {
748                    message["content"].as_str().unwrap_or("")
749                } else {
750                    return Err(anyhow!(
751                        "Invalid HuggingFace response format: missing message"
752                    ));
753                }
754            } else {
755                return Err(anyhow!(
756                    "Invalid HuggingFace response format: empty choices"
757                ));
758            }
759        } else {
760            return Err(anyhow!(
761                "Invalid HuggingFace response format: missing choices"
762            ));
763        };
764
765        let answer = self.extract_final_answer(raw_answer);
766
767        let citations = self.extract_citations(&answer, results);
768
769        Ok(LlmResponse {
770            answer,
771            sources_used: results.iter().map(|r| r.id.clone()).collect(),
772            confidence: Some(0.75), // Open source models vary
773            provider_used: LlmProvider::HuggingFace,
774            model_used: model,
775            tokens_used: response_json["usage"]["total_tokens"]
776                .as_u64()
777                .map(|t| t as u32),
778            response_time_ms: 0,
779            finish_reason: response_json["choices"][0]["finish_reason"]
780                .as_str()
781                .map(|s| s.to_string()),
782            citations,
783        })
784    }
785
786    /// Custom endpoint integration for self-hosted models
787    async fn synthesize_with_custom(
788        &self,
789        query: &str,
790        results: &[RagSearchResult],
791    ) -> Result<LlmResponse> {
792        let endpoint = self
793            .config
794            .custom_endpoint
795            .as_ref()
796            .ok_or_else(|| anyhow!("Custom endpoint not configured"))?;
797
798        let model = self.get_model_name(&LlmProvider::Custom);
799        let system_prompt = self.create_system_prompt();
800        let user_prompt = self.create_user_prompt(query, results);
801
802        // Use OpenAI-compatible format for custom endpoints
803        let payload = serde_json::json!({
804            "model": model,
805            "messages": [
806                {
807                    "role": "system",
808                    "content": system_prompt
809                },
810                {
811                    "role": "user",
812                    "content": user_prompt
813                }
814            ],
815            "max_tokens": self.config.max_tokens,
816            "temperature": self.config.temperature,
817            "stream": self.config.streaming
818        });
819
820        let response = self
821            .http_client
822            .post(format!("{}/v1/chat/completions", endpoint))
823            .header("Content-Type", "application/json")
824            .json(&payload)
825            .send()
826            .await?;
827
828        if !response.status().is_success() {
829            let error_text = response.text().await?;
830            return Err(anyhow!("Custom endpoint error: {}", error_text));
831        }
832
833        let response_json: serde_json::Value = response.json().await?;
834
835        let raw_answer = response_json["choices"][0]["message"]["content"]
836            .as_str()
837            .ok_or_else(|| anyhow!("Invalid custom endpoint response format"))?;
838        let answer = self.extract_final_answer(raw_answer);
839
840        let usage = &response_json["usage"];
841        let tokens_used = usage
842            .get("total_tokens")
843            .and_then(|t| t.as_u64())
844            .map(|t| t as u32);
845        let finish_reason = response_json["choices"][0]
846            .get("finish_reason")
847            .and_then(|r| r.as_str())
848            .map(|s| s.to_string());
849
850        let citations = self.extract_citations(&answer, results);
851
852        Ok(LlmResponse {
853            answer,
854            sources_used: results.iter().map(|r| r.id.clone()).collect(),
855            confidence: Some(0.8), // Assume reasonable confidence for custom
856            provider_used: LlmProvider::Custom,
857            model_used: model,
858            tokens_used,
859            response_time_ms: 0,
860            finish_reason,
861            citations,
862        })
863    }
864}
865
866#[cfg(test)]
867mod tests {
868    use super::*;
869
870    #[test]
871    fn test_extract_final_answer_with_thinking_tags() {
872        let response_with_thinking = r#"<thinking>
873Let me analyze this query about Rust error handling.
874
875The user is asking about Result types and how to handle errors properly.
876I should explain the basics of Result<T, E> and common patterns.
877</thinking>
878
879**Quick Answer**
880Rust uses `Result<T, E>` for error handling, where `T` is the success type and `E` is the error type.
881
882**Key Points**
883- Use `?` operator for error propagation
884- `unwrap()` panics on error, avoid in production
885- `expect()` provides custom panic message
886- Pattern match with `match` for comprehensive handling"#;
887
888        let extracted = LlmClient::extract_final_answer_text(response_with_thinking);
889
890        assert!(!extracted.contains("<thinking>"));
891        assert!(!extracted.contains("</thinking>"));
892        assert!(extracted.contains("**Quick Answer**"));
893        assert!(extracted.contains("Result<T, E>"));
894    }
895
896    #[test]
897    fn test_extract_final_answer_with_think_tags() {
898        let response_with_think = r#"<think>
899This question is about JavaScript async/await patterns.
900
901The user wants to understand how to handle asynchronous operations.
902I should provide clear examples and best practices.
903</think>
904
905**Quick Answer**
906Use `async/await` for handling asynchronous operations in JavaScript.
907
908**Key Points**
909- `async` functions return Promises
910- `await` pauses execution until Promise resolves
911- Use try/catch for error handling
912- Avoid callback hell with Promise chains"#;
913
914        let extracted = LlmClient::extract_final_answer_text(response_with_think);
915
916        assert!(!extracted.contains("<think>"));
917        assert!(!extracted.contains("</think>"));
918        assert!(extracted.contains("**Quick Answer**"));
919        assert!(extracted.contains("async/await"));
920    }
921
922    #[test]
923    fn test_extract_final_answer_without_thinking() {
924        let normal_response = r#"**Quick Answer**
925This is a normal response without thinking tags.
926
927**Key Points**
928- Point 1
929- Point 2"#;
930
931        let extracted = LlmClient::extract_final_answer_text(normal_response);
932
933        assert_eq!(extracted, normal_response);
934    }
935
936    #[test]
937    fn test_extract_final_answer_with_thinking_prefix() {
938        let response_with_prefix = r#"Let me think about this question carefully...
939
940I need to consider the different aspects of the query.
941
942Based on the search results:
943
944**Quick Answer**
945Here is the actual answer after thinking.
946
947**Key Points**
948- Important point 1
949- Important point 2"#;
950
951        let extracted = LlmClient::extract_final_answer_text(response_with_prefix);
952
953        assert!(!extracted.contains("Let me think"));
954        assert!(extracted.contains("**Quick Answer**"));
955        assert!(extracted.contains("Here is the actual answer"));
956    }
957}