Skip to main content

lens_core/semantic/
examples.rs

1//! # Semantic Integration Examples
2//!
3//! This module provides examples of how to integrate the new Rust-based
4//! semantic processing system with the existing search engine.
5
6use crate::search::{SearchEngine, SearchRequest, SearchConfig};
7use super::integration::{SemanticSearchIntegration, SemanticSearchRequest, SearchEngineSemanticExt};
8use super::{SemanticConfig, initialize_semantic_integration};
9use anyhow::Result;
10use tracing::info;
11
12/// Example: Basic semantic search integration
13pub async fn example_basic_semantic_search() -> Result<()> {
14    info!("Running basic semantic search integration example");
15    
16    // 1. Initialize search engine with minimal configuration
17    let search_config = SearchConfig {
18        lsp_routing_rate: 0.0, // Disable LSP for simplicity
19        enable_semantic_search: true,
20        enable_pinned_datasets: false,
21        ..Default::default()
22    };
23    
24    let search_engine = SearchEngine::with_config("./example_index", search_config).await?;
25    
26    // 2. Initialize semantic integration
27    let semantic_config = SemanticConfig::default();
28    let semantic_integration = initialize_semantic_integration(&semantic_config).await?;
29    
30    // 3. Perform semantic search
31    let query = "how to implement binary search algorithm";
32    let semantic_response = search_engine.search_auto_semantic(query, &semantic_integration).await?;
33    
34    info!("Semantic search completed:");
35    info!("- Query: {}", query);
36    info!("- Results found: {}", semantic_response.base_response.results.len());
37    info!("- Semantic enhanced: {}", semantic_response.semantic_enhanced);
38    info!("- Processing time: {}ms", semantic_response.semantic_metrics.total_processing_time_ms);
39    
40    if let Some(classification) = &semantic_response.classification {
41        info!("- Classified as: {:?} (confidence: {:.3})", 
42              classification.intent, classification.confidence);
43    }
44    
45    Ok(())
46}
47
48/// Example: Advanced semantic search with custom configuration
49pub async fn example_advanced_semantic_search() -> Result<()> {
50    info!("Running advanced semantic search integration example");
51    
52    // 1. Initialize search engine
53    let search_engine = SearchEngine::new("./example_index").await?;
54    
55    // 2. Initialize semantic integration with custom config
56    let integration_config = super::integration::SemanticIntegrationConfig {
57        enabled: true,
58        nl_upshift_threshold: 0.6, // Lower threshold for more semantic processing
59        max_processing_time_ms: 200, // More generous time budget
60        enable_conformal_routing: true,
61        fallback_on_error: true,
62        enable_result_caching: true,
63        similarity_threshold: 0.4, // Lower threshold for more inclusive similarity
64    };
65    
66    let semantic_integration = SemanticSearchIntegration::new(integration_config).await?;
67    
68    // 3. Test different query types
69    let test_queries = vec![
70        ("how to optimize search performance", "Natural Language"),
71        ("SearchEngine::search", "Symbol Search"),  
72        ("impl Iterator for", "Structural Search"),
73        ("rust async await patterns", "Mixed Query"),
74    ];
75    
76    for (query, query_type) in test_queries {
77        info!("\n--- Testing {} Query ---", query_type);
78        info!("Query: {}", query);
79        
80        let semantic_request = SemanticSearchRequest {
81            base_request: SearchRequest {
82                query: query.to_string(),
83                max_results: 5,
84                timeout_ms: 500,
85                ..Default::default()
86            },
87            force_semantic: query_type == "Natural Language", // Force semantic for NL queries
88            ..Default::default()
89        };
90        
91        match semantic_integration.process_search(&search_engine, semantic_request).await {
92            Ok(response) => {
93                info!("✅ Results: {}", response.base_response.results.len());
94                info!("✅ Semantic enhanced: {}", response.semantic_enhanced);
95                info!("✅ Processing time: {}ms", response.semantic_metrics.total_processing_time_ms);
96                
97                if let Some(classification) = &response.classification {
98                    info!("✅ Classification: {:?} (confidence: {:.3})", 
99                          classification.intent, classification.confidence);
100                }
101                
102                if let Some(routing) = &response.routing_decision {
103                    info!("✅ Routing: {:?} (expected improvement: {:.3})", 
104                          routing.upshift_type, routing.expected_improvement);
105                }
106            }
107            Err(e) => {
108                info!("❌ Search failed: {}", e);
109            }
110        }
111    }
112    
113    // 4. Display overall integration metrics
114    let metrics = semantic_integration.get_metrics().await;
115    info!("\n--- Integration Metrics ---");
116    info!("Total requests: {}", metrics.total_requests);
117    info!("Successful enhancements: {}", metrics.successful_enhancements);
118    info!("Fallback count: {}", metrics.fallback_count);
119    info!("Average processing time: {:.2}ms", metrics.avg_processing_time_ms);
120    
121    Ok(())
122}
123
124/// Example: Health monitoring and diagnostics
125pub async fn example_health_monitoring() -> Result<()> {
126    info!("Running health monitoring example");
127    
128    // Initialize semantic integration
129    let semantic_config = SemanticConfig::default();
130    let semantic_integration = initialize_semantic_integration(&semantic_config).await?;
131    
132    // Perform health check
133    let health_status = semantic_integration.health_check().await?;
134    
135    info!("=== Semantic System Health Status ===");
136    info!("Overall healthy: {}", health_status.overall_healthy);
137    info!("Encoder healthy: {}", health_status.encoder_healthy);
138    info!("Classifier healthy: {}", health_status.classifier_healthy);
139    info!("Intent router healthy: {}", health_status.intent_router_healthy);
140    info!("Conformal router healthy: {}", health_status.conformal_router_healthy);
141    info!("Last check: {}", health_status.last_check);
142    
143    if !health_status.overall_healthy {
144        info!("⚠️ Some components are unhealthy - check individual status");
145    } else {
146        info!("✅ All semantic components are healthy");
147    }
148    
149    Ok(())
150}
151
152/// Example: Performance benchmarking
153pub async fn example_performance_benchmarking() -> Result<()> {
154    info!("Running performance benchmarking example");
155    
156    let search_engine = SearchEngine::new("./example_index").await?;
157    let semantic_config = SemanticConfig::default();
158    let semantic_integration = initialize_semantic_integration(&semantic_config).await?;
159    
160    // Benchmark semantic vs non-semantic search
161    let test_query = "rust error handling best practices";
162    let iterations = 10;
163    
164    info!("Benchmarking query: '{}'", test_query);
165    info!("Iterations: {}", iterations);
166    
167    // Benchmark non-semantic search
168    let mut non_semantic_times = Vec::new();
169    for _ in 0..iterations {
170        let start = std::time::Instant::now();
171        let _response = search_engine.search(test_query, 10).await?;
172        non_semantic_times.push(start.elapsed().as_millis() as u64);
173    }
174    
175    // Benchmark semantic search
176    let mut semantic_times = Vec::new();
177    for _ in 0..iterations {
178        let start = std::time::Instant::now();
179        let _response = search_engine.search_auto_semantic(test_query, &semantic_integration).await?;
180        semantic_times.push(start.elapsed().as_millis() as u64);
181    }
182    
183    // Calculate statistics
184    let avg_non_semantic = non_semantic_times.iter().sum::<u64>() as f64 / iterations as f64;
185    let avg_semantic = semantic_times.iter().sum::<u64>() as f64 / iterations as f64;
186    
187    let min_non_semantic = *non_semantic_times.iter().min().unwrap();
188    let max_non_semantic = *non_semantic_times.iter().max().unwrap();
189    let min_semantic = *semantic_times.iter().min().unwrap();
190    let max_semantic = *semantic_times.iter().max().unwrap();
191    
192    info!("\n=== Performance Results ===");
193    info!("Non-semantic search:");
194    info!("  Average: {:.2}ms", avg_non_semantic);
195    info!("  Min: {}ms, Max: {}ms", min_non_semantic, max_non_semantic);
196    
197    info!("Semantic search:");
198    info!("  Average: {:.2}ms", avg_semantic);
199    info!("  Min: {}ms, Max: {}ms", min_semantic, max_semantic);
200    
201    let overhead = avg_semantic - avg_non_semantic;
202    let overhead_percentage = (overhead / avg_non_semantic) * 100.0;
203    
204    info!("Semantic overhead: {:.2}ms ({:.1}%)", overhead, overhead_percentage);
205    
206    if overhead_percentage < 50.0 {
207        info!("✅ Semantic processing overhead is acceptable");
208    } else {
209        info!("⚠️ Semantic processing overhead is high - consider optimization");
210    }
211    
212    Ok(())
213}
214
215/// Run all examples
216pub async fn run_all_examples() -> Result<()> {
217    info!("🚀 Running all semantic integration examples");
218    
219    if let Err(e) = example_basic_semantic_search().await {
220        info!("❌ Basic example failed: {}", e);
221    }
222    
223    if let Err(e) = example_advanced_semantic_search().await {
224        info!("❌ Advanced example failed: {}", e);
225    }
226    
227    if let Err(e) = example_health_monitoring().await {
228        info!("❌ Health monitoring example failed: {}", e);
229    }
230    
231    if let Err(e) = example_performance_benchmarking().await {
232        info!("❌ Performance benchmarking example failed: {}", e);
233    }
234    
235    info!("✅ All semantic integration examples completed");
236    Ok(())
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242    
243    #[tokio::test]
244    #[ignore] // Ignore by default since it requires index setup
245    async fn test_basic_semantic_integration() {
246        let result = example_basic_semantic_search().await;
247        assert!(result.is_ok(), "Basic semantic integration example should succeed");
248    }
249    
250    #[tokio::test]
251    async fn test_health_monitoring() {
252        let result = example_health_monitoring().await;
253        assert!(result.is_ok(), "Health monitoring example should succeed");
254    }
255}