diff --git a/src/cli/commands/build.rs b/src/cli/commands/build.rs index 4af0502..cd30114 100644 --- a/src/cli/commands/build.rs +++ b/src/cli/commands/build.rs @@ -1,9 +1,7 @@ use anyhow::{Context, Result}; use console::{Emoji, style}; -use futures::stream::{self, StreamExt}; use indicatif::{HumanDuration, ProgressBar, ProgressStyle}; use std::path::PathBuf; -use std::sync::Arc; use std::time::Instant; use walkdir::WalkDir; @@ -11,8 +9,10 @@ use crate::cli::{LlmProvider, OutputDestination}; use crate::config::Config; use crate::graph::builder::GraphBuilder; use crate::graph::neo4j::Neo4jClient; +use crate::llm::batch_processor::{BatchProcessor, DocumentSelector}; use crate::llm::LlmClient; use crate::parser::DocumentParser; +use crate::parser::ModelContextLimits; static LOOKING_GLASS: Emoji<'_, '_> = Emoji("πŸ” ", ""); static PAPER: Emoji<'_, '_> = Emoji("πŸ“„ ", ""); @@ -60,6 +60,12 @@ pub async fn run( let model = model.or(config.default_model.clone()); let model_display = model.clone().unwrap_or_else(|| "default".to_string()); + // Auto-detect if we should use adaptive processing for local models + let use_adaptive = matches!(provider, LlmProvider::Ollama); + let detected_context = model.as_ref() + .map(|m| ModelContextLimits::get_context_size(m)) + .unwrap_or(4096); + println!( "{}Provider: {}", BRAIN, @@ -67,6 +73,9 @@ pub async fn run( ); println!("{}Model: {}", BRAIN, style(&model_display).cyan()); println!("{}Source: {}", PAPER, style(path.display()).cyan()); + if use_adaptive { + println!("{}Adaptive chunking: {} ({} tokens)", BRAIN, style("enabled").green(), style(detected_context).cyan()); + } if concurrency > 1 { println!("{}Concurrency: {}", BRAIN, style(concurrency).cyan()); } @@ -98,7 +107,7 @@ pub async fn run( // Parse documents let parser = DocumentParser::new(chunk_size, chunk_overlap); - let mut all_chunks = Vec::new(); + let mut doc_contents: Vec<(String, String)> = Vec::new(); // (source, text) let pb = ProgressBar::new(documents.len() as u64); pb.set_style( @@ -113,19 +122,30 @@ pub async fn run( let filename = doc_path.file_name().unwrap_or_default().to_string_lossy(); pb.set_message(format!("{}", style(filename).dim())); let chunks = parser.parse(doc_path)?; - all_chunks.extend(chunks); + // Combine chunks back into full document text for batch processing + let full_text: String = chunks.iter().map(|c| c.text.clone()).collect::>().join("\n\n"); + doc_contents.push((doc_path.to_string_lossy().to_string(), full_text)); pb.inc(1); } pb.finish_and_clear(); + + // Smart document selection for large codebases + let selected_docs = if doc_contents.len() > 100 { + println!("{}Large codebase detected ({} docs). Selecting representative documents...", BRAIN, doc_contents.len()); + DocumentSelector::select_representative_docs(&doc_contents, 5) + } else { + doc_contents + }; + println!( - "{}Parsed {} documents into {} chunks", + "{}Parsed {} documents ({} selected for processing)", CHECK, style(documents.len()).green().bold(), - style(all_chunks.len()).green().bold() + style(selected_docs.len()).green().bold() ); - // Create LLM client (wrapped in Arc for concurrent access) - let llm_client = Arc::new(LlmClient::new(provider, &config, model.as_deref())?); + // Create LLM client + let llm_client = LlmClient::new(provider, &config, model.as_deref())?; // Build knowledge graph println!(); @@ -133,56 +153,37 @@ pub async fn run( let mut builder = GraphBuilder::new(); - let pb = ProgressBar::new(all_chunks.len() as u64); - pb.set_style( - ProgressStyle::default_bar() - .template(&format!("{}{{spinner:.green}} [{{elapsed_precise}}] {{bar:40.magenta/blue}} {{pos}}/{{len}} | {{msg}}", LINK)) - .unwrap() - .progress_chars("━━╸━"), + // Use batch processor for efficient large codebase processing + let batch_size = if use_adaptive { 3 } else { 5 }; // Smaller batches for local models + let mut processor = BatchProcessor::new( + llm_client, + &model_display, + concurrency.max(1), + batch_size, ); - pb.enable_steady_tick(std::time::Duration::from_millis(100)); - let effective_concurrency = concurrency.max(1); - - // Process chunks concurrently - let pb_ref = &pb; - let client_ref = &llm_client; - let results: Vec<(String, Vec)> = - stream::iter(all_chunks.iter().enumerate()) - .map(|(i, chunk)| { - let text = chunk.text.clone(); - let chunk_id = chunk.id.clone(); - let client = Arc::clone(client_ref); - async move { - pb_ref.set_message(format!("chunk {}/{}", i + 1, pb_ref.length().unwrap_or(0))); - let relations = match client.extract_relations(&text).await { - Ok(r) => r, - Err(e) => { - tracing::warn!("LLM extraction failed for chunk {}: {:#}", i + 1, e); - Vec::new() - } - }; - pb_ref.inc(1); - (chunk_id, relations) - } - }) - .buffer_unordered(effective_concurrency) - .collect() - .await; + // Enable progress persistence + let output_json_path = path.with_extension("kg.json"); + processor = processor.with_progress_persistence(&output_json_path); + processor.load_progress().await?; + // Process documents in batches + let relations_result = processor.process_documents(selected_docs).await?; + + // Add all relations to builder let mut total_relations = 0; - for (chunk_id, relations) in results { - total_relations += relations.len(); - builder.add_relations(relations, &chunk_id); + for relation in relations_result { + total_relations += 1; + builder.add_relations(vec![relation], "document"); } - - pb.finish_and_clear(); + let stats = processor.get_stats(); println!( - "{}Extracted {} relations from {} chunks (concurrency: {})", + "{}Extracted {} relations from {} documents (batch size: {}, concurrency: {})", CHECK, style(total_relations).green().bold(), - style(all_chunks.len()).green().bold(), - style(effective_concurrency).cyan(), + style(stats.total_documents).green().bold(), + style(batch_size).cyan(), + style(concurrency.max(1)).cyan(), ); // Calculate contextual proximity diff --git a/src/llm/adaptive_processor.rs b/src/llm/adaptive_processor.rs new file mode 100644 index 0000000..e0d2099 --- /dev/null +++ b/src/llm/adaptive_processor.rs @@ -0,0 +1,295 @@ +use anyhow::{Context, Result}; +use std::sync::Arc; +use tokio::sync::Semaphore; +use tracing::{debug, info, warn}; + +use crate::llm::{LlmClient, Relation}; +use crate::parser::{AdaptiveChunker, Chunk, ModelContextLimits}; + +/// Processor that handles context overflow with automatic retry +pub struct AdaptiveProcessor { + llm_client: Arc, + chunker: AdaptiveChunker, + max_retries: u32, + concurrency: usize, +} + +impl AdaptiveProcessor { + /// Create a new adaptive processor for a specific model + pub fn new(llm_client: LlmClient, model: &str, concurrency: usize) -> Self { + let chunker = ModelContextLimits::create_chunker(model); + + Self { + llm_client: Arc::new(llm_client), + chunker, + max_retries: 3, + concurrency, + } + } + + /// Create with custom chunk size + pub fn with_chunk_size( + llm_client: LlmClient, + target_tokens: usize, + overlap_tokens: usize, + concurrency: usize, + ) -> Self { + Self { + llm_client: Arc::new(llm_client), + chunker: AdaptiveChunker::new(target_tokens, overlap_tokens), + max_retries: 3, + concurrency, + } + } + + /// Process text with automatic overflow handling + pub async fn process(&self, text: &str, source: &str) -> Result> { + let chunks = self.chunker.split(text); + info!("Split text into {} chunks for {}", chunks.len(), source); + + let semaphore = Arc::new(Semaphore::new(self.concurrency)); + let mut tasks = Vec::new(); + + for chunk in chunks { + let permit = semaphore.clone().acquire_owned().await?; + let client = self.llm_client.clone(); + let source = source.to_string(); + + let task = tokio::spawn(async move { + let _permit = permit; // Hold permit until task completes + Self::process_chunk_with_retry(&client, chunk, &source).await + }); + + tasks.push(task); + } + + let mut all_relations = Vec::new(); + let mut errors = Vec::new(); + + for task in tasks { + match task.await { + Ok(Ok(relations)) => all_relations.extend(relations), + Ok(Err(e)) => errors.push(e.to_string()), + Err(e) => errors.push(format!("Task panicked: {}", e)), + } + } + + if !errors.is_empty() && all_relations.is_empty() { + return Err(anyhow::anyhow!( + "All chunks failed. Errors: {}", + errors.join("; ") + )); + } + + if !errors.is_empty() { + warn!("Some chunks failed: {}", errors.join("; ")); + } + + Ok(all_relations) + } + + /// Process a single chunk with retry on overflow + async fn process_chunk_with_retry( + client: &LlmClient, + chunk: Chunk, + source: &str, + ) -> Result> { + let mut current_chunk = chunk; + let mut attempt = 0; + let max_attempts = 3; + + loop { + debug!( + "Processing chunk {} from {} ({} tokens, attempt {})", + current_chunk.chunk_index, + source, + current_chunk.estimated_tokens, + attempt + 1 + ); + + match client.extract_relations(¤t_chunk.text).await { + Ok(relations) => { + return Ok(relations); + } + Err(e) => { + let error_str = e.to_string().to_lowercase(); + + // Check if it's a context overflow error + if Self::is_context_overflow(&error_str) { + attempt += 1; + + if attempt >= max_attempts { + return Err(anyhow::anyhow!( + "Context overflow after {} retries for chunk {} from {}: {}", + max_attempts, + current_chunk.chunk_index, + source, + e + )); + } + + warn!( + "Context overflow for chunk {} from {}, retrying with smaller size (attempt {})", + current_chunk.chunk_index, + source, + attempt + ); + + // Reduce target size by 50% and re-chunk + let new_target = current_chunk.estimated_tokens / 2; + let sub_chunks = AdaptiveChunker::new(new_target, new_target / 10) + .split_with_target(¤t_chunk.text, new_target); + + if sub_chunks.is_empty() { + return Err(anyhow::anyhow!( + "Cannot split chunk {} further", + current_chunk.chunk_index + )); + } + + // Process first sub-chunk (others are discarded on this retry) + if let Some(first_sub) = sub_chunks.first() { + current_chunk = Chunk { + text: first_sub.text.clone(), + estimated_tokens: first_sub.estimated_tokens, + chunk_index: current_chunk.chunk_index, + parent_id: Some(format!( + "{}-retry-{}", + current_chunk.chunk_index, + attempt + )), + }; + } + + // Continue to next attempt + continue; + } + + // Not a context overflow, return the error + return Err(e); + } + } + } + } + + /// Check if error indicates context window overflow + pub fn is_context_overflow(error: &str) -> bool { + let error_lower = error.to_lowercase(); + let overflow_indicators = [ + "context length", + "context window", + "too long", + "token limit", + "max tokens", + "exceeds", + "context size", + "input length", + "too many tokens", + "sequence length", + ]; + + overflow_indicators.iter().any(|indicator| error_lower.contains(indicator)) + } +} + +/// Builder for hierarchical processing +/// +/// Processes chunks, then creates summary nodes to link related chunks +pub struct HierarchicalProcessor { + processor: AdaptiveProcessor, + batch_size: usize, +} + +impl HierarchicalProcessor { + pub fn new(processor: AdaptiveProcessor, batch_size: usize) -> Self { + Self { + processor, + batch_size, + } + } + + /// Process in batches and create hierarchical links + pub async fn process_hierarchical( + &self, + text: &str, + source: &str, + ) -> Result { + let chunks = self.processor.chunker.split(text); + let mut all_relations = Vec::new(); + let mut batch_summaries = Vec::new(); + + // Process in batches + for (batch_idx, batch) in chunks.chunks(self.batch_size).enumerate() { + let batch_text: String = batch + .iter() + .map(|c| c.text.clone()) + .collect::>() + .join("\n\n"); + + let batch_relations = self.processor.process(&batch_text, source).await?; + + // Create a batch summary node + let summary_node = format!("{}_batch_{}", source, batch_idx); + + // Link chunks in this batch to the summary + for chunk in batch { + all_relations.push(Relation { + node_1: summary_node.clone(), + node_1_type: Some("BatchSummary".to_string()), + node_2: format!("{}_chunk_{}", source, chunk.chunk_index), + node_2_type: Some("Chunk".to_string()), + edge: "contains".to_string(), + }); + } + + batch_summaries.push(summary_node); + all_relations.extend(batch_relations); + } + + // Link batches together + for i in 0..batch_summaries.len().saturating_sub(1) { + all_relations.push(Relation { + node_1: batch_summaries[i].clone(), + node_1_type: Some("BatchSummary".to_string()), + node_2: batch_summaries[i + 1].clone(), + node_2_type: Some("BatchSummary".to_string()), + edge: "followed_by".to_string(), + }); + } + + Ok(HierarchicalResult { + relations: all_relations, + batch_count: batch_summaries.len(), + total_chunks: chunks.len(), + }) + } +} + +/// Result from hierarchical processing +#[derive(Debug)] +pub struct HierarchicalResult { + pub relations: Vec, + pub batch_count: usize, + pub total_chunks: usize, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_context_overflow_detection() { + assert!(AdaptiveProcessor::is_context_overflow( + "Error: context length exceeded" + )); + assert!(AdaptiveProcessor::is_context_overflow( + "The input is too long for the model" + )); + assert!(AdaptiveProcessor::is_context_overflow( + "Token limit reached" + )); + assert!(!AdaptiveProcessor::is_context_overflow( + "Network error occurred" + )); + } +} diff --git a/src/llm/batch_processor.rs b/src/llm/batch_processor.rs new file mode 100644 index 0000000..3101f54 --- /dev/null +++ b/src/llm/batch_processor.rs @@ -0,0 +1,444 @@ +use anyhow::Result; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::path::Path; +use tokio::fs; +use tracing::{debug, info, warn}; + +use crate::llm::{LlmClient, Relation}; +use crate::parser::{AdaptiveChunker, Chunk, ModelContextLimits}; + +/// Batch processor for efficient large codebase processing +/// +/// Optimizations: +/// 1. Batches multiple small chunks into single LLM calls +/// 2. Persists progress for resume capability +/// 3. Skips already-processed documents +/// 4. Deduplicates similar content +pub struct BatchProcessor { + llm_client: LlmClient, + chunker: AdaptiveChunker, + concurrency: usize, + batch_size: usize, // Number of chunks per LLM call + progress_file: Option, + processed_hashes: HashMap, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct ProcessedDoc { + hash: String, + chunks_processed: usize, + relations_count: usize, + timestamp: String, +} + +impl BatchProcessor { + /// Create a new batch processor + /// + /// # Arguments + /// * `llm_client` - The LLM client to use + /// * `model` - Model name for context window detection + /// * `concurrency` - Number of concurrent batch operations + /// * `batch_size` - Number of chunks to process per LLM call (default: 5) + pub fn new( + llm_client: LlmClient, + model: &str, + concurrency: usize, + batch_size: usize, + ) -> Self { + let chunker = ModelContextLimits::create_chunker(model); + + Self { + llm_client, + chunker, + concurrency, + batch_size: batch_size.max(1), + progress_file: None, + processed_hashes: HashMap::new(), + } + } + + /// Enable progress persistence for resume capability + pub fn with_progress_persistence(mut self, output_path: &Path) -> Self { + let progress_file = output_path + .parent() + .map(|p| p.join(".rknowledge_progress.json")) + .and_then(|p| p.to_str().map(String::from)); + + self.progress_file = progress_file; + self + } + + /// Load previous progress if exists + pub async fn load_progress(&mut self) -> Result<()> { + if let Some(ref path) = self.progress_file { + if Path::new(path).exists() { + let content = fs::read_to_string(path).await?; + self.processed_hashes = serde_json::from_str(&content)?; + info!("Loaded progress: {} documents already processed", self.processed_hashes.len()); + } + } + Ok(()) + } + + /// Save progress to disk + async fn save_progress(&self) -> Result<()> { + if let Some(ref path) = self.progress_file { + let content = serde_json::to_string_pretty(&self.processed_hashes)?; + fs::write(path, content).await?; + } + Ok(()) + } + + /// Calculate simple hash for content deduplication + fn calculate_hash(text: &str) -> String { + use std::collections::hash_map::DefaultHasher; + use std::hash::{Hash, Hasher}; + + let mut hasher = DefaultHasher::new(); + text.hash(&mut hasher); + format!("{:x}", hasher.finish()) + } + + /// Check if document was already processed + fn is_already_processed(&self, source: &str, hash: &str) -> bool { + if let Some(doc) = self.processed_hashes.get(source) { + return doc.hash == hash; + } + false + } + + /// Process multiple documents efficiently + pub async fn process_documents( + &mut self, + documents: Vec<(String, String)>, // (source, text) pairs + ) -> Result> { + let mut all_relations = Vec::new(); + let mut total_chunks = 0; + let mut skipped_docs = 0; + let mut processed_docs = 0; + + let total_docs = documents.len(); + info!("Processing {} documents with batch size {}", total_docs, self.batch_size); + + for (source, text) in documents { + let hash = Self::calculate_hash(&text); + + // Skip if already processed + if self.is_already_processed(&source, &hash) { + debug!("Skipping already processed document: {}", source); + skipped_docs += 1; + continue; + } + + // Split into chunks + let chunks = self.chunker.split(&text); + let chunk_count = chunks.len(); + total_chunks += chunk_count; + + info!("Processing {} ({} chunks)", source, chunk_count); + + // Process chunks in batches + let doc_relations = self.process_chunks_in_batches(&chunks, &source).await?; + let relation_count = doc_relations.len(); + all_relations.extend(doc_relations); + + // Mark as processed + self.processed_hashes.insert(source, ProcessedDoc { + hash, + chunks_processed: chunk_count, + relations_count: relation_count, + timestamp: std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs() + .to_string(), + }); + + processed_docs += 1; + + // Save progress periodically + if processed_docs % 10 == 0 { + self.save_progress().await?; + info!("Progress saved: {}/{} documents", processed_docs, total_docs); + } + } + + // Final save + self.save_progress().await?; + + info!( + "Processing complete: {} processed, {} skipped, {} total chunks, {} relations", + processed_docs, skipped_docs, total_chunks, all_relations.len() + ); + + Ok(all_relations) + } + + /// Process chunks in batches (multiple chunks per LLM call) + async fn process_chunks_in_batches( + &self, + chunks: &[Chunk], + source: &str, + ) -> Result> { + let mut all_relations = Vec::new(); + + // Group chunks into batches + let batches: Vec> = chunks + .chunks(self.batch_size) + .map(|c| c.iter().collect()) + .collect(); + + info!("Processing {} chunks in {} batches", chunks.len(), batches.len()); + + for (batch_idx, batch) in batches.iter().enumerate() { + debug!("Processing batch {}/{} ({} chunks)", batch_idx + 1, batches.len(), batch.len()); + + // Combine chunks for batch processing + let batch_text = self.format_batch_for_processing(batch, source, batch_idx); + + // Process with retry logic + match self.process_batch_with_retry(&batch_text, source, batch_idx).await { + Ok(relations) => { + all_relations.extend(relations); + } + Err(e) => { + warn!("Batch {} failed: {}. Falling back to individual chunk processing", batch_idx, e); + // Fallback: process chunks individually + for chunk in batch.iter() { + match self.process_single_chunk(chunk, source).await { + Ok(relations) => all_relations.extend(relations), + Err(e) => warn!("Failed to process chunk {}: {}", chunk.chunk_index, e), + } + } + } + } + } + + Ok(all_relations) + } + + /// Format multiple chunks for batch LLM processing + fn format_batch_for_processing(&self, chunks: &[&Chunk], source: &str, batch_idx: usize) -> String { + let mut result = format!("Document: {} (Batch {})", source, batch_idx); + result.push_str("\n===CHUNK_SEPARATOR===\n"); + + for (i, chunk) in chunks.iter().enumerate() { + result.push_str(&format!("\n---CHUNK_{}---\n", i)); + result.push_str(&chunk.text); + } + + result.push_str("\n===END_DOCUMENT===\n"); + result + } + + /// Process a batch with automatic retry and splitting + async fn process_batch_with_retry( + &self, + batch_text: &str, + source: &str, + batch_idx: usize, + ) -> Result> { + let mut attempt = 0; + let max_attempts = 2; + + loop { + match self.llm_client.extract_relations(batch_text).await { + Ok(relations) => { + debug!("Batch {} processed successfully: {} relations", batch_idx, relations.len()); + return Ok(relations); + } + Err(e) => { + let error_str = e.to_string().to_lowercase(); + + if Self::is_context_overflow(&error_str) && attempt < max_attempts { + attempt += 1; + warn!("Context overflow for batch {}, retrying with smaller content (attempt {})", + batch_idx, attempt); + // Return error to trigger fallback to individual processing + return Err(anyhow::anyhow!("Context overflow, needs fallback")); + } + + return Err(e); + } + } + } + } + + /// Process a single chunk (fallback method) + async fn process_single_chunk(&self, chunk: &Chunk, _source: &str) -> Result> { + debug!("Processing single chunk {}", chunk.chunk_index); + self.llm_client.extract_relations(&chunk.text).await + } + + /// Check if error indicates context window overflow + fn is_context_overflow(error: &str) -> bool { + let error_lower = error.to_lowercase(); + let overflow_indicators = [ + "context length", + "context window", + "too long", + "token limit", + "max tokens", + "exceeds", + "context size", + "input length", + "too many tokens", + "sequence length", + ]; + + overflow_indicators.iter().any(|indicator| error_lower.contains(indicator)) + } + + /// Get processing statistics + pub fn get_stats(&self) -> ProcessingStats { + ProcessingStats { + total_documents: self.processed_hashes.len(), + total_relations: self.processed_hashes.values().map(|d| d.relations_count).sum(), + total_chunks: self.processed_hashes.values().map(|d| d.chunks_processed).sum(), + } + } +} + +/// Processing statistics +#[derive(Debug)] +pub struct ProcessingStats { + pub total_documents: usize, + pub total_relations: usize, + pub total_chunks: usize, +} + +/// Smart document selector to avoid processing duplicates/similar docs +pub struct DocumentSelector; + +impl DocumentSelector { + /// Select representative documents from a large codebase + /// + /// Strategy: + /// 1. Prioritize "index" files (README, TOC, SKILL) + /// 2. Limit files per directory (avoiding duplication) + /// 3. Skip auto-generated files + /// 4. Prioritize recent/modified files + pub fn select_representative_docs( + all_docs: &[(String, String)], + max_per_dir: usize, + ) -> Vec<(String, String)> { + let mut selected = Vec::new(); + let mut dir_counts: HashMap = HashMap::new(); + + // Sort to prioritize important files + let mut sorted_docs = all_docs.to_vec(); + sorted_docs.sort_by(|(path_a, _), (path_b, _)| { + let score_a = Self::document_priority(path_a); + let score_b = Self::document_priority(path_b); + score_b.cmp(&score_a) // Higher score first + }); + + for (source, text) in sorted_docs { + // Get directory + let dir = Path::new(&source) + .parent() + .and_then(|p| p.to_str()) + .unwrap_or("") + .to_string(); + + // Check if we should skip + if Self::should_skip(&source, &text) { + continue; + } + + // Check directory limit + let count = dir_counts.entry(dir.clone()).or_insert(0); + if *count >= max_per_dir { + continue; + } + + *count += 1; + selected.push((source, text)); + } + + info!("Selected {} representative documents from {}", selected.len(), all_docs.len()); + selected + } + + /// Calculate document priority (higher = more important) + fn document_priority(path: &str) -> i32 { + let lower = path.to_lowercase(); + let mut score = 0; + + // High priority files + if lower.contains("readme") || lower.contains("skill") || lower.contains("toc") { + score += 100; + } + if lower.contains("overview") || lower.contains("getting-started") { + score += 50; + } + if lower.contains("example") || lower.contains("guide") { + score += 30; + } + + // Penalize generated files + if lower.contains("generated") || lower.contains("auto") { + score -= 50; + } + + // Prefer smaller, focused files + if lower.ends_with(".md") { + score += 10; + } + + score + } + + /// Check if document should be skipped + fn should_skip(source: &str, text: &str) -> bool { + let lower = source.to_lowercase(); + + // Skip generated files + if lower.contains("generated") + || lower.contains("auto-generated") + || lower.contains("broken-links") + || lower.contains("source-reference-map") { + return true; + } + + // Skip very small files + if text.len() < 100 { + return true; + } + + // Skip JSON data files + if lower.ends_with(".json") { + return true; + } + + false + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_context_overflow_detection() { + assert!(BatchProcessor::is_context_overflow("Error: context length exceeded")); + assert!(BatchProcessor::is_context_overflow("Token limit reached")); + assert!(!BatchProcessor::is_context_overflow("Network error occurred")); + } + + #[test] + fn test_document_priority() { + assert!(DocumentSelector::document_priority("README.md") > + DocumentSelector::document_priority("generated-file.md")); + assert!(DocumentSelector::document_priority("SKILL.md") > + DocumentSelector::document_priority("random.md")); + } + + #[test] + fn test_should_skip() { + assert!(DocumentSelector::should_skip("broken-links.json", "{}")); + assert!(DocumentSelector::should_skip("generated.md", "content")); + assert!(!DocumentSelector::should_skip("readme.md", "# Title\n\nThis is a long content that should not be skipped because it has more than one hundred characters to pass the minimum length check.")); + } +} diff --git a/src/llm/mod.rs b/src/llm/mod.rs index 697ba17..84b48e8 100644 --- a/src/llm/mod.rs +++ b/src/llm/mod.rs @@ -1,3 +1,5 @@ +pub mod adaptive_processor; +pub mod batch_processor; mod anthropic; mod google; mod ollama; diff --git a/src/llm/ollama.rs b/src/llm/ollama.rs index 940a113..29568b7 100644 --- a/src/llm/ollama.rs +++ b/src/llm/ollama.rs @@ -2,6 +2,7 @@ use anyhow::{Context, Result}; use async_trait::async_trait; use reqwest::Client; use serde::{Deserialize, Serialize}; +use std::time::Duration; use super::parsing::parse_relations_json; use super::prompts::{GRAPH_EXTRACTION_SYSTEM_PROMPT, graph_extraction_user_prompt}; @@ -14,54 +15,92 @@ pub struct OllamaProvider { } #[derive(Serialize)] -struct OllamaRequest { +struct OllamaChatRequest { model: String, - prompt: String, - system: String, + messages: Vec, stream: bool, options: OllamaOptions, } +#[derive(Serialize)] +struct Message { + role: String, + content: String, +} + #[derive(Serialize)] struct OllamaOptions { temperature: f32, - num_predict: i32, + #[serde(skip_serializing_if = "Option::is_none")] + num_predict: Option, + #[serde(skip_serializing_if = "Option::is_none")] + top_p: Option, + #[serde(skip_serializing_if = "Option::is_none")] + top_k: Option, } #[derive(Deserialize)] -struct OllamaResponse { - response: String, +struct OllamaChatResponse { + message: ResponseMessage, +} + +#[derive(Deserialize)] +struct ResponseMessage { + content: String, } impl OllamaProvider { pub fn new(base_url: &str, model: &str) -> Self { + // Create client with optimized settings for local models + let client = Client::builder() + .timeout(Duration::from_secs(300)) // 5 min timeout for slow local models + .connect_timeout(Duration::from_secs(10)) + .pool_idle_timeout(Duration::from_secs(90)) + .pool_max_idle_per_host(10) // Reuse connections for parallel requests + .build() + .unwrap_or_else(|_| Client::new()); + Self { - client: Client::new(), + client, base_url: base_url.trim_end_matches('/').to_string(), model: model.to_string(), } } async fn complete(&self, system: &str, user_message: &str) -> Result { - let request = OllamaRequest { + let request = OllamaChatRequest { model: self.model.clone(), - prompt: user_message.to_string(), - system: system.to_string(), + messages: vec![ + Message { + role: "system".to_string(), + content: system.to_string(), + }, + Message { + role: "user".to_string(), + content: user_message.to_string(), + }, + ], stream: false, options: OllamaOptions { - temperature: 0.0, - num_predict: 4096, + // Small temperature for more focused output while avoiding repetition + temperature: 0.1, + // Let model decide when to stop (no forced token limit) + num_predict: None, + // Nucleus sampling for better quality + top_p: Some(0.9), + // Reduce vocabulary for faster sampling + top_k: Some(40), }, }; let response = self .client - .post(format!("{}/api/generate", self.base_url)) + .post(format!("{}/api/chat", self.base_url)) .header("Content-Type", "application/json") .json(&request) .send() .await - .context("Failed to send request to Ollama API. Is Ollama running?")?; + .context("Failed to send request to Ollama API. Is Ollama running? (try: ollama serve)")?; if !response.status().is_success() { let status = response.status(); @@ -69,12 +108,12 @@ impl OllamaProvider { anyhow::bail!("Ollama API error ({}): {}", status, error_text); } - let response: OllamaResponse = response + let response: OllamaChatResponse = response .json() .await .context("Failed to parse Ollama response")?; - Ok(response.response) + Ok(response.message.content) } } diff --git a/src/parser/adaptive_chunker.rs b/src/parser/adaptive_chunker.rs new file mode 100644 index 0000000..0457c10 --- /dev/null +++ b/src/parser/adaptive_chunker.rs @@ -0,0 +1,366 @@ +/// Token estimation for context-aware chunking +/// +/// Rough approximation: 1 token β‰ˆ 4 characters for English text +/// This is a simple estimation - for production, use tiktoken or similar +pub fn estimate_tokens(text: &str) -> usize { + // Simple character-based estimation: ~4 chars per token + // This is conservative but works for most English text + (text.len() as f32 / 4.0).ceil() as usize +} + +/// Adaptive chunker that adjusts size based on available context +pub struct AdaptiveChunker { + target_tokens: usize, + overlap_tokens: usize, + separators: Vec<&'static str>, + max_retries: u32, +} + +impl AdaptiveChunker { + /// Create a new adaptive chunker + /// + /// # Arguments + /// * `target_tokens` - Target token count per chunk (e.g., 1000 for 4K context models) + /// * `overlap_tokens` - Overlap between chunks to maintain context + pub fn new(target_tokens: usize, overlap_tokens: usize) -> Self { + Self { + target_tokens, + overlap_tokens, + separators: vec!["\n\n", "\n", ". ", "! ", "? ", "; ", ", ", " ", ""], + max_retries: 3, + } + } + + /// Create a chunker optimized for a specific model context size + /// + /// Reserves space for: + /// - System prompt (~200 tokens) + /// - User prompt + text + /// - Response buffer (~500 tokens) + pub fn for_context_window(context_size: usize) -> Self { + let reserved = 700; // System prompt + response buffer + let safe_target = (context_size.saturating_sub(reserved)) / 2; + let overlap = safe_target / 10; + + Self::new(safe_target, overlap) + } + + /// Split text into token-aware chunks + pub fn split(&self, text: &str) -> Vec { + let text = text.trim(); + if text.is_empty() { + return vec![]; + } + + let estimated_tokens = estimate_tokens(text); + if estimated_tokens <= self.target_tokens { + return vec![Chunk { + text: text.to_string(), + estimated_tokens, + chunk_index: 0, + parent_id: None, + }]; + } + + self.recursive_split(text, 0, 0, None) + } + + /// Split with a specific target (used for retry with smaller size) + pub fn split_with_target(&self, text: &str, target_tokens: usize) -> Vec { + let mut temp = Self::new(target_tokens, target_tokens / 10); + temp.max_retries = self.max_retries; + temp.split(text) + } + + fn recursive_split( + &self, + text: &str, + separator_idx: usize, + chunk_index: usize, + parent_id: Option, + ) -> Vec { + if separator_idx >= self.separators.len() { + return self.split_by_tokens(text, chunk_index, parent_id); + } + + let separator = self.separators[separator_idx]; + let splits: Vec<&str> = if separator.is_empty() { + text.chars().map(|c| &text[..c.len_utf8()]).collect() + } else { + text.split(separator).collect() + }; + + let mut chunks = Vec::new(); + let mut current_chunk = String::new(); + let mut current_tokens = 0; + let mut idx = chunk_index; + + for (i, split) in splits.iter().enumerate() { + let split_with_sep = if i < splits.len() - 1 && !separator.is_empty() { + format!("{}{}", split, separator) + } else { + split.to_string() + }; + + let split_tokens = estimate_tokens(&split_with_sep); + + if current_tokens + split_tokens > self.target_tokens { + if !current_chunk.is_empty() { + let chunk_tokens = estimate_tokens(¤t_chunk); + + // If still too big, recurse with next separator + if chunk_tokens > self.target_tokens { + chunks.extend(self.recursive_split( + ¤t_chunk, + separator_idx + 1, + idx, + parent_id.clone(), + )); + } else { + chunks.push(Chunk { + text: current_chunk.trim().to_string(), + estimated_tokens: chunk_tokens, + chunk_index: idx, + parent_id: parent_id.clone(), + }); + idx += 1; + } + } + + // Start new chunk with overlap + let overlap_text = if !chunks.is_empty() && self.overlap_tokens > 0 { + self.get_overlap_text(&chunks.last().unwrap().text) + } else { + String::new() + }; + + current_chunk = format!("{}{}", overlap_text, split_with_sep); + current_tokens = estimate_tokens(¤t_chunk); + } else { + current_chunk.push_str(&split_with_sep); + current_tokens += split_tokens; + } + } + + // Don't forget the last chunk + if !current_chunk.is_empty() { + let trimmed = current_chunk.trim().to_string(); + if !trimmed.is_empty() { + let chunk_tokens = estimate_tokens(&trimmed); + + if chunk_tokens > self.target_tokens { + chunks.extend(self.recursive_split( + &trimmed, + separator_idx + 1, + idx, + parent_id, + )); + } else { + chunks.push(Chunk { + text: trimmed, + estimated_tokens: chunk_tokens, + chunk_index: idx, + parent_id, + }); + } + } + } + + chunks + } + + fn split_by_tokens( + &self, + text: &str, + chunk_index: usize, + parent_id: Option, + ) -> Vec { + let words: Vec<&str> = text.split_whitespace().collect(); + let mut chunks = Vec::new(); + let mut current_words = Vec::new(); + let mut current_tokens = 0; + let mut idx = chunk_index; + + for word in words { + let word_tokens = (word.len() as f32 * 0.5) as usize + 1; + + if current_tokens + word_tokens > self.target_tokens { + if !current_words.is_empty() { + let text = current_words.join(" "); + chunks.push(Chunk { + text: text.clone(), + estimated_tokens: estimate_tokens(&text), + chunk_index: idx, + parent_id: parent_id.clone(), + }); + idx += 1; + } + + // Overlap: keep last N words + let overlap_words = if self.overlap_tokens > 0 { + let overlap_count = (self.overlap_tokens / 2).max(5).min(current_words.len()); + current_words.split_off(current_words.len() - overlap_count) + } else { + vec![] + }; + + current_words = overlap_words; + current_words.push(word); + current_tokens = current_words + .iter() + .map(|w| (w.len() as f32 * 0.5) as usize + 1) + .sum(); + } else { + current_words.push(word); + current_tokens += word_tokens; + } + } + + // Last chunk + if !current_words.is_empty() { + let text = current_words.join(" "); + chunks.push(Chunk { + text, + estimated_tokens: current_tokens, + chunk_index: idx, + parent_id, + }); + } + + chunks + } + + fn get_overlap_text(&self, text: &str) -> String { + let words: Vec<&str> = text.split_whitespace().collect(); + let overlap_word_count = (self.overlap_tokens / 2).max(5).min(words.len()); + + words[words.len().saturating_sub(overlap_word_count)..].join(" ") + " " + } +} + +/// A chunk with metadata +#[derive(Debug, Clone)] +pub struct Chunk { + pub text: String, + pub estimated_tokens: usize, + pub chunk_index: usize, + pub parent_id: Option, +} + +/// Model context limits database +pub struct ModelContextLimits; + +impl ModelContextLimits { + /// Get context window size for known models + pub fn get_context_size(model: &str) -> usize { + let model_lower = model.to_lowercase(); + + match model_lower.as_str() { + // Small local models (Ollama) + m if m.contains("llama3.2") || m.contains("llama-3.2") => 8192, + m if m.contains("phi3:mini") || m.contains("phi-3-mini") => 4096, + m if m.contains("mistral") => 32768, + m if m.contains("qwen2.5:3b") => 8192, + m if m.contains("qwen2.5:7b") => 32768, + m if m.contains("gemma2:2b") => 4096, + m if m.contains("gemma2:9b") => 8192, + + // Larger local models + m if m.contains("llama3.3") || m.contains("llama-3.3") => 128000, + m if m.contains("qwen2.5:72b") => 32768, + + // Cloud models + m if m.contains("claude-3-opus") => 200000, + m if m.contains("claude-3-sonnet") => 200000, + m if m.contains("claude-3-haiku") => 200000, + m if m.contains("gpt-4") => 8192, + m if m.contains("gpt-4o") => 128000, + m if m.contains("gpt-3.5") => 16385, + m if m.contains("gemini") => 1048576, + + // Default for unknown models (conservative) + _ => 4096, + } + } + + /// Create an adaptive chunker for a specific model + pub fn create_chunker(model: &str) -> AdaptiveChunker { + let context_size = Self::get_context_size(model); + AdaptiveChunker::for_context_window(context_size) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_token_estimation() { + let text = "This is a simple test sentence with eight words."; + let tokens = estimate_tokens(text); + // 48 chars / 4 = ~12 tokens + assert!( + tokens >= 10 && tokens <= 15, + "Expected ~12 tokens, got {}", + tokens + ); + } + + #[test] + fn test_adaptive_chunking() { + let chunker = AdaptiveChunker::new(100, 20); + let text = "This is a test. ".repeat(100); + let chunks = chunker.split(&text); + + assert!(!chunks.is_empty()); + for chunk in &chunks { + assert!(chunk.estimated_tokens <= 150); // Some flexibility + } + } + + #[test] + fn test_context_window_chunker() { + let chunker = AdaptiveChunker::for_context_window(4096); + // Create enough text to definitely require multiple chunks + // "Word " = 5 chars, ~1.25 tokens each. + // 8000 repetitions = 40000 chars = ~10000 tokens + let text = "Word ".repeat(8000); + let chunks = chunker.split(&text); + + // Should create multiple chunks for very large text + assert!( + chunks.len() > 1, + "Expected multiple chunks, got {}", + chunks.len() + ); + + // Each chunk should be reasonable size (under ~1700 tokens for 4K context) + for chunk in &chunks { + assert!( + chunk.estimated_tokens <= 2000, + "Chunk too large: {} tokens", + chunk.estimated_tokens + ); + } + } + + #[test] + fn test_model_context_limits() { + assert_eq!(ModelContextLimits::get_context_size("mistral"), 32768); + assert_eq!(ModelContextLimits::get_context_size("llama3.2"), 8192); + assert_eq!(ModelContextLimits::get_context_size("phi3:mini"), 4096); + assert_eq!(ModelContextLimits::get_context_size("unknown-model"), 4096); + } + + #[test] + fn test_chunk_overlap() { + let chunker = AdaptiveChunker::new(50, 10); + let text = "First sentence here. Second sentence follows. Third ends. Fourth comes after."; + let chunks = chunker.split(text); + + if chunks.len() >= 2 { + // Check that overlap is maintained + assert!(chunks[0].chunk_index < chunks[1].chunk_index); + } + } +} diff --git a/src/parser/mod.rs b/src/parser/mod.rs index aac7983..c7fa748 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -1,3 +1,4 @@ +mod adaptive_chunker; mod chunker; mod html; mod markdown; @@ -9,6 +10,7 @@ use serde::{Deserialize, Serialize}; use std::path::Path; use uuid::Uuid; +pub use adaptive_chunker::{AdaptiveChunker, Chunk, ModelContextLimits}; pub use chunker::TextChunker; /// A document chunk with metadata