Skip to main content

graphrag_core/generation/
async_mock_llm.rs

1//! Async implementation of MockLLM demonstrating async trait patterns
2//!
3//! This module provides an async version of MockLLM that implements the AsyncLanguageModel trait,
4//! showcasing how to migrate synchronous implementations to async patterns.
5
6use crate::core::traits::{AsyncLanguageModel, GenerationParams, ModelInfo, ModelUsageStats};
7use crate::core::{GraphRAGError, Result};
8use crate::generation::LLMInterface;
9use crate::text::TextProcessor;
10use async_trait::async_trait;
11use std::collections::HashMap;
12use std::sync::atomic::{AtomicU64, Ordering};
13use std::sync::Arc;
14use std::time::{Duration, Instant};
15use tokio::sync::RwLock;
16
17/// Async version of MockLLM that implements AsyncLanguageModel trait
18#[derive(Debug)]
19pub struct AsyncMockLLM {
20    response_templates: Arc<RwLock<HashMap<String, String>>>,
21    text_processor: Arc<TextProcessor>,
22    stats: Arc<AsyncLLMStats>,
23    simulate_delay: Option<Duration>,
24}
25
26/// Statistics tracking for the async LLM
27#[derive(Debug, Default)]
28struct AsyncLLMStats {
29    total_requests: AtomicU64,
30    total_tokens_processed: AtomicU64,
31    total_response_time: Arc<RwLock<Duration>>,
32    error_count: AtomicU64,
33}
34
35impl AsyncMockLLM {
36    /// Create a new async mock LLM
37    pub async fn new() -> Result<Self> {
38        let mut templates = HashMap::new();
39
40        // Default response templates
41        templates.insert(
42            "default".to_string(),
43            "Based on the provided context, here is what I found: {context}".to_string(),
44        );
45        templates.insert(
46            "not_found".to_string(),
47            "I could not find specific information about this in the provided context.".to_string(),
48        );
49        templates.insert(
50            "insufficient_context".to_string(),
51            "The available context is insufficient to provide a complete answer.".to_string(),
52        );
53
54        let text_processor = TextProcessor::new(1000, 100)?;
55
56        Ok(Self {
57            response_templates: Arc::new(RwLock::new(templates)),
58            text_processor: Arc::new(text_processor),
59            stats: Arc::new(AsyncLLMStats::default()),
60            simulate_delay: Some(Duration::from_millis(100)), // Simulate realistic delay
61        })
62    }
63
64    /// Create with custom templates
65    pub async fn with_templates(templates: HashMap<String, String>) -> Result<Self> {
66        let text_processor = TextProcessor::new(1000, 100)?;
67
68        Ok(Self {
69            response_templates: Arc::new(RwLock::new(templates)),
70            text_processor: Arc::new(text_processor),
71            stats: Arc::new(AsyncLLMStats::default()),
72            simulate_delay: Some(Duration::from_millis(100)),
73        })
74    }
75
76    /// Set artificial delay to simulate network latency
77    pub fn set_simulate_delay(&mut self, delay: Option<Duration>) {
78        self.simulate_delay = delay;
79    }
80
81    /// Generate extractive answer from context with improved relevance scoring
82    async fn generate_extractive_answer(&self, context: &str, query: &str) -> Result<String> {
83        // Simulate processing delay
84        if let Some(delay) = self.simulate_delay {
85            tokio::time::sleep(delay).await;
86        }
87
88        let sentences = self.text_processor.extract_sentences(context);
89        if sentences.is_empty() {
90            return Ok("No relevant context found.".to_string());
91        }
92
93        // Enhanced scoring with partial word matching and named entity recognition
94        let query_lower = query.to_lowercase();
95        let query_words: Vec<&str> = query_lower
96            .split_whitespace()
97            .filter(|w| w.len() > 2) // Filter out short words
98            .collect();
99
100        if query_words.is_empty() {
101            return Ok("Query too short or contains no meaningful words.".to_string());
102        }
103
104        let mut sentence_scores: Vec<(usize, f32)> = sentences
105            .iter()
106            .enumerate()
107            .map(|(i, sentence)| {
108                let sentence_lower = sentence.to_lowercase();
109                let mut total_score = 0.0;
110                let mut matches = 0;
111
112                for word in &query_words {
113                    // Exact word match (highest score)
114                    if sentence_lower.contains(word) {
115                        total_score += 2.0;
116                        matches += 1;
117                    }
118                    // Partial match for longer words
119                    else if word.len() > 4 {
120                        for sentence_word in sentence_lower.split_whitespace() {
121                            if sentence_word.contains(word) || word.contains(sentence_word) {
122                                total_score += 1.0;
123                                matches += 1;
124                                break;
125                            }
126                        }
127                    }
128                }
129
130                // Boost score for sentences with multiple matches
131                let coverage_bonus = (matches as f32 / query_words.len() as f32) * 0.5;
132                let final_score = total_score + coverage_bonus;
133
134                (i, final_score)
135            })
136            .collect();
137
138        // Sort by relevance
139        sentence_scores.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
140
141        // Select top sentences with a minimum relevance threshold
142        let mut answer_sentences = Vec::new();
143        for (idx, score) in sentence_scores.iter().take(5) {
144            if *score > 0.5 {
145                // Higher threshold for better quality
146                answer_sentences.push(format!(
147                    "{} (relevance: {:.1})",
148                    sentences[*idx].trim(),
149                    score
150                ));
151            }
152        }
153
154        if answer_sentences.is_empty() {
155            // If no high-quality matches, provide the best available with lower threshold
156            for (idx, score) in sentence_scores.iter().take(2) {
157                if *score > 0.0 {
158                    answer_sentences.push(format!(
159                        "{} (low confidence: {:.1})",
160                        sentences[*idx].trim(),
161                        score
162                    ));
163                }
164            }
165        }
166
167        if answer_sentences.is_empty() {
168            Ok("No directly relevant information found in the context.".to_string())
169        } else {
170            Ok(answer_sentences.join("\n\n"))
171        }
172    }
173
174    /// Generate smart contextual answer
175    async fn generate_smart_answer(&self, context: &str, question: &str) -> Result<String> {
176        // First try extractive approach
177        let extractive_result = self.generate_extractive_answer(context, question).await?;
178
179        // If extractive failed, generate a contextual response
180        if extractive_result.contains("No relevant") || extractive_result.contains("No directly") {
181            return self.generate_contextual_response(context, question).await;
182        }
183
184        Ok(extractive_result)
185    }
186
187    /// Generate contextual response when direct extraction fails
188    async fn generate_contextual_response(&self, context: &str, question: &str) -> Result<String> {
189        let question_lower = question.to_lowercase();
190        let context_lower = context.to_lowercase();
191
192        // Pattern matching for common question types
193        if question_lower.contains("who") && question_lower.contains("friend") {
194            // Look for character names and relationships
195            let names = self.extract_character_names(&context_lower).await;
196            if !names.is_empty() {
197                return Ok(format!("Based on the context, the main characters mentioned include: {}. These appear to be friends and companions in the story.", names.join(", ")));
198            }
199        }
200
201        if question_lower.contains("what")
202            && (question_lower.contains("adventure") || question_lower.contains("happen"))
203        {
204            let events = self.extract_key_events(&context_lower).await;
205            if !events.is_empty() {
206                return Ok(format!(
207                    "The context describes several events: {}",
208                    events.join(", ")
209                ));
210            }
211        }
212
213        if question_lower.contains("where") {
214            let locations = self.extract_locations(&context_lower).await;
215            if !locations.is_empty() {
216                return Ok(format!(
217                    "The story takes place in locations such as: {}",
218                    locations.join(", ")
219                ));
220            }
221        }
222
223        // Fallback: provide a summary of the context
224        let summary = self.generate_summary_async(context, 150).await?;
225        Ok(format!("Based on the available context: {summary}"))
226    }
227
228    /// Generate response for direct questions
229    async fn generate_question_response(&self, question: &str) -> Result<String> {
230        let question_lower = question.to_lowercase();
231
232        // Generic pattern-based responses for common query types
233        if question_lower.contains("friend") || question_lower.contains("relationship") {
234            return Ok("The text describes various character relationships and friendships throughout the narrative.".to_string());
235        }
236
237        if question_lower.contains("main character") || question_lower.contains("protagonist") {
238            return Ok(
239                "The text features several important characters who drive the narrative forward."
240                    .to_string(),
241            );
242        }
243
244        if question_lower.contains("event") || question_lower.contains("scene") {
245            return Ok(
246                "The text contains various significant events and scenes that advance the story."
247                    .to_string(),
248            );
249        }
250
251        Ok(
252            "I need more specific context to provide a detailed answer to this question."
253                .to_string(),
254        )
255    }
256
257    /// Extract capitalized words that might be names from text
258    async fn extract_character_names(&self, text: &str) -> Vec<String> {
259        let mut found_names = Vec::new();
260
261        // Extract capitalized words as potential names
262        for word in text.split_whitespace() {
263            let clean_word = word.trim_matches(|c: char| !c.is_alphabetic());
264            if clean_word.len() > 2
265                && clean_word
266                    .chars()
267                    .next()
268                    .expect("non-empty string")
269                    .is_uppercase()
270                && clean_word.chars().all(|c| c.is_alphabetic())
271            {
272                found_names.push(clean_word.to_lowercase());
273            }
274        }
275
276        found_names
277    }
278
279    /// Extract key events/actions from text
280    async fn extract_key_events(&self, text: &str) -> Vec<String> {
281        let event_keywords = [
282            "adventure",
283            "treasure",
284            "cave",
285            "island",
286            "painting",
287            "school",
288            "church",
289            "graveyard",
290            "river",
291        ];
292        let mut found_events = Vec::new();
293
294        for event in &event_keywords {
295            if text.contains(event) {
296                found_events.push(format!("events involving {event}"));
297            }
298        }
299
300        found_events
301    }
302
303    /// Extract locations from text
304    async fn extract_locations(&self, text: &str) -> Vec<String> {
305        let locations = [
306            "village",
307            "mississippi",
308            "river",
309            "cave",
310            "island",
311            "town",
312            "church",
313            "school",
314            "house",
315        ];
316        let mut found_locations = Vec::new();
317
318        for location in &locations {
319            if text.contains(location) {
320                found_locations.push(location.to_string());
321            }
322        }
323
324        found_locations
325    }
326
327    /// Generate summary asynchronously
328    async fn generate_summary_async(&self, content: &str, max_length: usize) -> Result<String> {
329        let sentences = self.text_processor.extract_sentences(content);
330        if sentences.is_empty() {
331            return Ok(String::new());
332        }
333
334        let mut summary = String::new();
335        for sentence in sentences.iter().take(3) {
336            if summary.len() + sentence.len() > max_length {
337                break;
338            }
339            if !summary.is_empty() {
340                summary.push(' ');
341            }
342            summary.push_str(sentence);
343        }
344
345        Ok(summary)
346    }
347
348    /// Update statistics after a request
349    async fn update_stats(&self, tokens: usize, response_time: Duration, is_error: bool) {
350        self.stats.total_requests.fetch_add(1, Ordering::Relaxed);
351
352        if is_error {
353            self.stats.error_count.fetch_add(1, Ordering::Relaxed);
354        } else {
355            self.stats
356                .total_tokens_processed
357                .fetch_add(tokens as u64, Ordering::Relaxed);
358        }
359
360        let mut total_time = self.stats.total_response_time.write().await;
361        *total_time += response_time;
362    }
363}
364
365#[async_trait]
366impl AsyncLanguageModel for AsyncMockLLM {
367    type Error = GraphRAGError;
368
369    async fn complete(&self, prompt: &str) -> Result<String> {
370        let start_time = Instant::now();
371
372        // Simulate processing delay
373        if let Some(delay) = self.simulate_delay {
374            tokio::time::sleep(delay).await;
375        }
376
377        let result = self.generate_response_internal(prompt).await;
378        let response_time = start_time.elapsed();
379
380        // Estimate tokens (rough approximation)
381        let tokens = prompt.len() / 4;
382        self.update_stats(tokens, response_time, result.is_err())
383            .await;
384
385        result
386    }
387
388    async fn complete_with_params(
389        &self,
390        prompt: &str,
391        _params: GenerationParams,
392    ) -> Result<String> {
393        // For mock LLM, we ignore parameters and just use the basic complete
394        self.complete(prompt).await
395    }
396
397    async fn complete_batch(&self, prompts: &[&str]) -> Result<Vec<String>> {
398        // Process prompts concurrently for better performance
399        let mut handles = Vec::new();
400
401        for prompt in prompts {
402            let prompt_owned = prompt.to_string();
403            let self_clone = self.clone();
404            handles.push(tokio::spawn(async move {
405                self_clone.complete(&prompt_owned).await
406            }));
407        }
408
409        let mut results = Vec::with_capacity(prompts.len());
410        for handle in handles {
411            match handle.await {
412                Ok(result) => results.push(result?),
413                Err(e) => {
414                    return Err(GraphRAGError::Generation {
415                        message: format!("Task join error: {e}"),
416                    })
417                },
418            }
419        }
420
421        Ok(results)
422    }
423
424    async fn is_available(&self) -> bool {
425        true
426    }
427
428    async fn model_info(&self) -> ModelInfo {
429        ModelInfo {
430            name: "AsyncMockLLM".to_string(),
431            version: Some("1.0.0".to_string()),
432            max_context_length: Some(4096),
433            supports_streaming: true,
434        }
435    }
436
437    async fn get_usage_stats(&self) -> Result<ModelUsageStats> {
438        let total_requests = self.stats.total_requests.load(Ordering::Relaxed);
439        let total_tokens = self.stats.total_tokens_processed.load(Ordering::Relaxed);
440        let error_count = self.stats.error_count.load(Ordering::Relaxed);
441        let total_time = *self.stats.total_response_time.read().await;
442
443        let average_response_time_ms = if total_requests > 0 {
444            total_time.as_millis() as f64 / total_requests as f64
445        } else {
446            0.0
447        };
448
449        let error_rate = if total_requests > 0 {
450            error_count as f64 / total_requests as f64
451        } else {
452            0.0
453        };
454
455        Ok(ModelUsageStats {
456            total_requests,
457            total_tokens_processed: total_tokens,
458            average_response_time_ms,
459            error_rate,
460        })
461    }
462
463    async fn estimate_tokens(&self, prompt: &str) -> Result<usize> {
464        // Simple estimation: ~4 characters per token
465        Ok(prompt.len() / 4)
466    }
467}
468
469impl AsyncMockLLM {
470    /// Internal response generation method
471    async fn generate_response_internal(&self, prompt: &str) -> Result<String> {
472        let prompt_lower = prompt.to_lowercase();
473
474        // Handle Q&A format prompts
475        if prompt_lower.contains("context:") && prompt_lower.contains("question:") {
476            if let Some(context_start) = prompt.find("Context:") {
477                let context_section = &prompt[context_start + 8..];
478                if let Some(question_start) = context_section.find("Question:") {
479                    let context = context_section[..question_start].trim();
480                    let question_section = context_section[question_start + 9..].trim();
481
482                    return self.generate_smart_answer(context, question_section).await;
483                }
484            }
485        }
486
487        // Handle direct questions about specific topics
488        if prompt_lower.contains("who")
489            || prompt_lower.contains("what")
490            || prompt_lower.contains("where")
491            || prompt_lower.contains("when")
492            || prompt_lower.contains("how")
493            || prompt_lower.contains("why")
494        {
495            return self.generate_question_response(prompt).await;
496        }
497
498        // Fallback to template
499        let templates = self.response_templates.read().await;
500        Ok(templates
501            .get("default")
502            .unwrap_or(&"I cannot provide a response based on the given prompt.".to_string())
503            .replace("{context}", &prompt[..prompt.len().min(200)]))
504    }
505}
506
507// Implement Clone for AsyncMockLLM
508impl Clone for AsyncMockLLM {
509    fn clone(&self) -> Self {
510        Self {
511            response_templates: Arc::clone(&self.response_templates),
512            text_processor: Arc::clone(&self.text_processor),
513            stats: Arc::clone(&self.stats),
514            simulate_delay: self.simulate_delay,
515        }
516    }
517}
518
519/// Synchronous LLMInterface implementation for backward compatibility
520#[async_trait]
521impl LLMInterface for AsyncMockLLM {
522    fn generate_response(&self, prompt: &str) -> Result<String> {
523        // For sync compatibility, use tokio's block_in_place if we're in a tokio context
524        if tokio::runtime::Handle::try_current().is_ok() {
525            tokio::task::block_in_place(|| {
526                tokio::runtime::Handle::current().block_on(self.complete(prompt))
527            })
528        } else {
529            // If not in async context, create a new runtime
530            let rt = tokio::runtime::Runtime::new().map_err(|e| GraphRAGError::Generation {
531                message: format!("Failed to create async runtime: {e}"),
532            })?;
533            rt.block_on(self.complete(prompt))
534        }
535    }
536
537    fn generate_summary(&self, content: &str, max_length: usize) -> Result<String> {
538        if tokio::runtime::Handle::try_current().is_ok() {
539            tokio::task::block_in_place(|| {
540                tokio::runtime::Handle::current()
541                    .block_on(self.generate_summary_async(content, max_length))
542            })
543        } else {
544            let rt = tokio::runtime::Runtime::new().map_err(|e| GraphRAGError::Generation {
545                message: format!("Failed to create async runtime: {e}"),
546            })?;
547            rt.block_on(self.generate_summary_async(content, max_length))
548        }
549    }
550
551    fn extract_key_points(&self, content: &str, num_points: usize) -> Result<Vec<String>> {
552        let keywords = self
553            .text_processor
554            .extract_keywords(content, num_points * 2);
555        let sentences = self.text_processor.extract_sentences(content);
556
557        let mut key_points = Vec::new();
558        for keyword in keywords.iter().take(num_points) {
559            // Find a sentence containing this keyword
560            if let Some(sentence) = sentences
561                .iter()
562                .find(|s| s.to_lowercase().contains(&keyword.to_lowercase()))
563            {
564                key_points.push(sentence.clone());
565            } else {
566                key_points.push(format!("Key concept: {keyword}"));
567            }
568        }
569
570        Ok(key_points)
571    }
572}
573
574#[cfg(test)]
575mod tests {
576    use super::*;
577
578    #[tokio::test]
579    async fn test_async_completion() {
580        let llm = AsyncMockLLM::new().await.unwrap();
581        let result = llm.complete("Hello, world!").await;
582        assert!(result.is_ok());
583    }
584
585    #[tokio::test]
586    async fn test_async_batch_completion() {
587        let llm = AsyncMockLLM::new().await.unwrap();
588        let prompts = vec!["Hello", "World", "Test"];
589        let results = llm.complete_batch(&prompts).await;
590        assert!(results.is_ok());
591        assert_eq!(results.unwrap().len(), 3);
592    }
593
594    #[tokio::test]
595    async fn test_async_usage_stats() {
596        let llm = AsyncMockLLM::new().await.unwrap();
597
598        // Make some requests
599        let _ = llm.complete("Test prompt 1").await;
600        let _ = llm.complete("Test prompt 2").await;
601
602        let stats = llm.get_usage_stats().await.unwrap();
603        assert_eq!(stats.total_requests, 2);
604        assert!(stats.average_response_time_ms > 0.0);
605    }
606
607    #[tokio::test]
608    async fn test_async_model_availability() {
609        let llm = AsyncMockLLM::new().await.unwrap();
610        let is_available = llm.is_available().await;
611        assert!(is_available);
612    }
613
614    #[tokio::test]
615    async fn test_async_model_info() {
616        let llm = AsyncMockLLM::new().await.unwrap();
617        let info = llm.model_info().await;
618        assert_eq!(info.name, "AsyncMockLLM");
619        assert_eq!(info.version, Some("1.0.0".to_string()));
620        assert!(info.supports_streaming);
621    }
622
623    #[tokio::test]
624    async fn test_token_estimation() {
625        let llm = AsyncMockLLM::new().await.unwrap();
626        let tokens = llm.estimate_tokens("This is a test prompt").await.unwrap();
627        assert!(tokens > 0);
628    }
629}