DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Implement LlamaIndex RAG pipeline with dynamic provider selection
Tushar Khatri2de2772d430a
diff --git a/DYNAMIC_RAG_PROVIDER.md b/DYNAMIC_RAG_PROVIDER.mdnew file mode 100644index 000000000..9bf21efe8--- /dev/null+++ b/DYNAMIC_RAG_PROVIDER.md@@ -0,0 +1,135 @@+# Dynamic RAG Provider Selection++## Overview++The knowledge base initialization has been refactored to support dynamic RAG provider selection based on the `RAG_PROVIDER` environment variable.++## Changes Made++### 1. Updated `src/knowledge/initializer.py`++**Previous Behavior:**+- Hardcoded to use `RAGAnything` directly+- Imported `raganything`, `RAGAnythingConfig`, `LightRAGLogContext`, `EmbeddingFunc`+- Manually configured LLM, vision, and embedding functions+- Directly instantiated `RAGAnything` class++**New Behavior:**+- Uses `RAGService` which respects `RAG_PROVIDER` environment variable+- Simplified imports - only imports `RAGService`+- Provider selection is automatic based on environment configuration+- Supports all registered RAG pipelines: `raganything`, `lightrag`, `llamaindex`, `academic`++### 2. Key Code Changes++#### Imports (Lines 26-33)+```python+# Before: Direct RAGAnything imports+from raganything import RAGAnything, RAGAnythingConfig+from lightrag.utils import EmbeddingFunc++# After: RAGService import+from src.services.rag.service import RAGService+```++#### Process Documents Method (Lines 151-235)+```python+# Before: 200+ lines of RAGAnything configuration+config = RAGAnythingConfig(...)+rag = RAGAnything(config=config, llm_model_func=..., ...)+for doc in docs:+ await rag.process_document_complete(...)++# After: Simple RAGService usage+provider = os.getenv("RAG_PROVIDER", "raganything")+rag_service = RAGService(kb_base_dir=str(self.base_dir), provider=provider)+success = await rag_service.initialize(+ kb_name=self.kb_name,+ file_paths=file_paths,+ extract_numbered_items=True+)+```++#### Statistics Display (Lines 405-465)+```python+# Added generic statistics method that works with all providers+async def display_statistics_generic(self):+ # Shows stats for RAGAnything/LightRAG (entities, relations, chunks)+ # Shows stats for LlamaIndex (vector embeddings, dimensions)+ # Displays which provider was used+```++## How It Works++1. **Environment Variable**: Set `RAG_PROVIDER` in `.env` file:+ ```bash+ RAG_PROVIDER=llamaindex # or raganything, lightrag, academic+ ```++2. **Automatic Provider Selection**: `RAGService` reads the environment variable and selects the appropriate pipeline from the factory++3. **Pipeline Execution**: The selected pipeline processes documents according to its implementation:+ - **raganything**: Uses RAG-Anything with MinerU parser, creates graph storage+ - **lightrag**: Uses LightRAG, creates graph-based knowledge base+ - **llamaindex**: Uses LlamaIndex with VectorIndexer and DenseRetriever, creates vector store+ - **academic**: Stub implementation (needs implementation)++4. **Storage Format**: Each provider creates its own storage format:+ - **raganything/lightrag**: `rag_storage/` with JSON files (entities, relations, chunks)+ - **llamaindex**: `vector_store/` with FAISS index and embeddings+ - **Note**: Storage formats are incompatible between providers++## Testing++To test different providers:++1. Set environment variable:+ ```bash+ # In .env file+ RAG_PROVIDER=llamaindex+ ```++2. Create a new knowledge base:+ ```bash+ # Via API or web interface+ # Upload documents to create new KB+ ```++3. Check logs to verify correct provider:+ ```+ [KnowledgeInit] Processing documents with RAG provider: llamaindex+ [RAGService] Initializing KB 'test_kb' with provider 'llamaindex'+ ```++4. Verify storage structure:+ ```bash+ # For LlamaIndex+ ls data/knowledge_bases/test_kb/vector_store/+ # Should see: index.faiss, embeddings.pkl, metadata.json, info.json++ # For RAGAnything/LightRAG+ ls data/knowledge_bases/test_kb/rag_storage/+ # Should see: kv_store_*.json files+ ```++## Benefits++1. **Flexibility**: Switch RAG providers without code changes+2. **Maintainability**: Single point of configuration in environment variables+3. **Extensibility**: Easy to add new RAG providers via factory pattern+4. **Consistency**: All pipelines use the same interface+5. **Testing**: Easy to test different providers for comparison++## Migration Notes++- **Existing KBs**: Continue to work with their original provider+- **New KBs**: Use provider specified in `RAG_PROVIDER` at creation time+- **Provider Changes**: Cannot change provider for existing KB without rebuilding+- **Storage Incompatibility**: Different providers cannot share the same KB storage++## Future Improvements++1. Store provider information in KB metadata to track which provider was used+2. Implement provider migration tool to convert between storage formats+3. Add DocumentAdder support for dynamic provider selection+4. Create unified storage format that all providers can usediff --git a/requirements.txt b/requirements.txtindex 1763b12d0..192a20bf5 100644--- a/requirements.txt+++ b/requirements.txt@@ -48,13 +48,19 @@ raganything>=0.1.0arxiv>=2.0.0# ============================================-# Scientific computing (optional, for code execution)+# Scientific computing (for RAG and code execution)# ============================================-# Uncomment if users need these for code execution feature-# numpy>=1.24.0-# matplotlib>=3.7.0-# scipy>=1.11.0-# pandas>=2.0.0+numpy>=1.24.0+# matplotlib>=3.7.0 # Uncomment if needed for plotting+# scipy>=1.11.0 # Uncomment if needed for scientific computing+# pandas>=2.0.0 # Uncomment if needed for data analysis++# PDF parsing+PyMuPDF>=1.23.0 # For PDF text extraction (fast and reliable)++# Vector search (optional but recommended for llamaindex pipeline)+# faiss-cpu>=1.7.4 # Uncomment for CPU-only FAISS support (faster search)+# faiss-gpu>=1.7.4 # Uncomment if you have GPU and want GPU acceleration# ============================================# Development toolsdiff --git a/src/knowledge/initializer.py b/src/knowledge/initializer.pyindex a84626268..7970151e2 100644--- a/src/knowledge/initializer.py+++ b/src/knowledge/initializer.py@@ -21,22 +21,17 @@ import sysproject_root = Path(__file__).parent.parent.parentsys.path.insert(0, str(project_root))-# Add raganything module path-raganything_path = project_root.parent / "raganything" / "RAG-Anything"-if raganything_path.exists():- sys.path.insert(0, str(raganything_path))from dotenv import load_dotenv-from lightrag.llm.openai import openai_complete_if_cache-from lightrag.utils import EmbeddingFunc-from raganything import RAGAnything, RAGAnythingConfig-from src.services.embedding import get_embedding_client, get_embedding_config+# Import RAGService for dynamic provider selection based on RAG_PROVIDER env var+from src.services.rag.service import RAGService+from src.services.embedding import get_embedding_configfrom src.services.llm import get_llm_configload_dotenv(dotenv_path=".env", override=False)-from src.logging import LightRAGLogContext, get_logger+from src.logging import get_loggerlogger = get_logger("KnowledgeInit")@@ -154,11 +149,13 @@ class KnowledgeBaseInitializer:return copied_filesasync def process_documents(self):- """Process documents using RAG-Anything"""- logger.info("Processing documents with RAG-Anything...")+ """Process documents using RAGService with dynamic provider selection"""+ provider = os.getenv("RAG_PROVIDER", "raganything")+ logger.info(f"Processing documents with RAG provider: {provider}")+self.progress_tracker.update(ProgressStage.PROCESSING_DOCUMENTS,- "Starting to process documents...",+ f"Starting to process documents with {provider} provider...",current=0,total=0,)@@ -183,219 +180,64 @@ class KnowledgeBaseInitializer:total=len(doc_files),)- # Create RAGAnything configuration- config = RAGAnythingConfig(- working_dir=str(self.rag_storage_dir),- parser="mineru",- enable_image_processing=True,- enable_table_processing=True,- enable_equation_processing=True,+ # Initialize RAGService with the selected provider+ rag_service = RAGService(+ kb_base_dir=str(self.base_dir), # Base directory for all KBs (e.g., data/knowledge_bases)+ provider=provider)- # Get LLM configuration from env_config- llm_cfg = get_llm_config()- llm_model = llm_cfg.model- api_key = self.api_key or llm_cfg.api_key- base_url = self.base_url or llm_cfg.base_url-- # Define LLM model function- def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):- return openai_complete_if_cache(- llm_model,- prompt,- system_prompt=system_prompt,- history_messages=history_messages,- api_key=api_key,- base_url=base_url,- **kwargs,- )-- # Define vision model function for image processing- def vision_model_func(- prompt,- system_prompt=None,- history_messages=[],- image_data=None,- messages=None,- **kwargs,- ):- # If messages format is provided, use it directly- if messages:- # Remove 'messages' and other message-related params from kwargs to avoid duplicate parameter- clean_kwargs = {- k: v- for k, v in kwargs.items()- if k not in ["messages", "prompt", "system_prompt", "history_messages"]- }- return openai_complete_if_cache(- llm_model,- prompt="", # Empty prompt when using messages- system_prompt=None,- history_messages=[],- messages=messages,- api_key=api_key,- base_url=base_url,- **clean_kwargs,- )- # Traditional single image format- if image_data:- # Remove message-related params from kwargs to avoid duplicate parameter- clean_kwargs = {- k: v- for k, v in kwargs.items()- if k not in ["messages", "prompt", "system_prompt", "history_messages"]- }- return openai_complete_if_cache(- llm_model,- prompt="", # Empty prompt when using messages- system_prompt=None,- history_messages=[],- messages=[- {"role": "system", "content": system_prompt} if system_prompt else None,- (- {- "role": "user",- "content": [- {"type": "text", "text": prompt},- {- "type": "image_url",- "image_url": {- "url": f"data:image/jpeg;base64,{image_data}"- },- },- ],- }- if image_data- else {"role": "user", "content": prompt}- ),- ],- api_key=api_key,- base_url=base_url,- **clean_kwargs,- )- # Pure text format- return llm_model_func(prompt, system_prompt, history_messages, **kwargs)-- # Define embedding function using unified EmbeddingClient- # Reset client to pick up latest config (including active provider from UI)- from src.services.embedding import reset_embedding_client-- reset_embedding_client()-- embedding_cfg = get_embedding_config() # Reload config- embedding_client = get_embedding_client() # Get fresh client with new config-- logger.info(- f"Using embedding: {embedding_cfg.model} "- f"({embedding_cfg.dim}D, {embedding_cfg.binding})"- )-- # Create async wrapper compatible with LightRAG's expected signature- async def unified_embed_func(texts):- """- Unified embedding function using EmbeddingClient.- Supports multiple providers: OpenAI, Cohere, Jina, Ollama, etc.- """- try:- embeddings = await embedding_client.embed(texts)- return embeddings- except Exception as e:- logger.error(f"Embedding failed: {e}")- raise-- embedding_func = EmbeddingFunc(- embedding_dim=embedding_cfg.dim,- max_token_size=embedding_cfg.max_tokens,- func=unified_embed_func,- )-- # Initialize RAGAnything with log forwarding- with LightRAGLogContext(scene="knowledge_init"):- rag = RAGAnything(- config=config,- llm_model_func=llm_model_func,- vision_model_func=vision_model_func,- embedding_func=embedding_func,- )-- # Ensure LightRAG is initialized- await rag._ensure_lightrag_initialized()+ # Convert Path objects to strings for file paths+ file_paths = [str(doc_file) for doc_file in doc_files]- # Process each document using RAGAnything's process_document_complete- for idx, doc_file in enumerate(doc_files, 1):- logger.info(f"\nProcessing: {doc_file.name}")- self.progress_tracker.update(- ProgressStage.PROCESSING_FILE,- f"Processing: {doc_file.name}",- current=idx,- total=len(doc_files),- file_name=doc_file.name,+ try:+ # Process all documents using the RAGService+ success = await rag_service.initialize(+ kb_name=self.kb_name,+ file_paths=file_paths,+ extract_numbered_items=True # Enable numbered items extraction)- try:- # Use RAGAnything's process_document_complete method- # This method handles document parsing, content extraction, and insertion- logger.info(" → Starting document processing...")- await asyncio.wait_for(- rag.process_document_complete(- file_path=str(doc_file),- output_dir=str(self.content_list_dir),- parse_method="auto",- ),- timeout=600.0, # 10 minute timeout- )- logger.info(f" ✓ Successfully processed: {doc_file.name}")-- # Content list should be automatically saved in output_dir- doc_name = doc_file.stem- content_list_file = self.content_list_dir / f"{doc_name}.json"- if content_list_file.exists():- logger.info(f" ✓ Content list saved: {content_list_file.name}")-- except asyncio.TimeoutError:- error_msg = "Processing timeout (>10 minutes)"- logger.error(f" ✗ Timeout processing {doc_file.name}")- logger.error(" Possible causes: Large PDF, slow embedding API, network issues")+ if success:+ logger.info("✓ Document processing completed!")self.progress_tracker.update(- ProgressStage.ERROR,- f"Timeout processing: {doc_file.name}",- current=idx,+ ProgressStage.PROCESSING_DOCUMENTS,+ "Documents processed successfully",+ current=len(doc_files),total=len(doc_files),- file_name=doc_file.name,- error=error_msg,)- except Exception as e:- error_msg = str(e)- logger.error(f" ✗ Error processing {doc_file.name}: {error_msg}")- import traceback-- logger.error(traceback.format_exc())+ else:+ logger.error("Document processing failed")self.progress_tracker.update(ProgressStage.ERROR,- f"Failed to process file: {doc_file.name}",- current=idx,- total=len(doc_files),- file_name=doc_file.name,- error=error_msg,+ "Document processing failed",+ error="RAG pipeline returned failure")- # Copy extracted images- rag_images_dir = self.rag_storage_dir / "images"- if rag_images_dir.exists():- logger.info(f"\nCopying extracted images to {self.images_dir}")- for img_file in rag_images_dir.glob("*"):- if img_file.is_file():- dest = self.images_dir / img_file.name- shutil.copy2(img_file, dest)- logger.info(" ✓ Copied images")-- logger.info("\n✓ Document processing completed!")+ except asyncio.TimeoutError:+ error_msg = "Processing timeout (>10 minutes)"+ logger.error(f"✗ Timeout processing documents")+ logger.error("Possible causes: Large files, slow embedding API, network issues")+ self.progress_tracker.update(+ ProgressStage.ERROR,+ "Timeout processing documents",+ error=error_msg,+ )+ except Exception as e:+ error_msg = str(e)+ logger.error(f"✗ Error processing documents: {error_msg}")+ import traceback+ logger.error(traceback.format_exc())+ self.progress_tracker.update(+ ProgressStage.ERROR,+ f"Failed to process documents",+ error=error_msg,+ )- # Fix structure: flatten nested content_list directories+ # Fix structure: flatten nested content_list directories (for RAGAnything compatibility)await self.fix_structure()# Display statistics- await self.display_statistics(rag)+ await self.display_statistics_generic()async def fix_structure(self):"""@@ -560,8 +402,12 @@ class KnowledgeBaseInitializer:ProgressStage.ERROR, "Numbered items extraction failed", error=error_msg)- async def display_statistics(self, rag: RAGAnything):- """Display knowledge base statistics"""+ async def display_statistics(self, rag: "RAGAnything"):+ """Display knowledge base statistics (legacy - for RAGAnything)"""+ await self.display_statistics_generic()++ async def display_statistics_generic(self):+ """Display knowledge base statistics (provider-agnostic)"""logger.info("\n" + "=" * 50)logger.info("Knowledge Base Statistics")logger.info("=" * 50)@@ -575,32 +421,44 @@ class KnowledgeBaseInitializer:logger.info(f"Extracted images: {len(image_files)}")logger.info(f"Content lists: {len(content_files)}")- # RAG storage info- if hasattr(rag, "lightrag") and rag.lightrag:- try:- # Try to get entity and relation counts- entities_file = self.rag_storage_dir / "kv_store_full_entities.json"- relations_file = self.rag_storage_dir / "kv_store_full_relations.json"- chunks_file = self.rag_storage_dir / "kv_store_text_chunks.json"-- if entities_file.exists():- with open(entities_file, encoding="utf-8") as f:- entities = json.load(f)- logger.info(f"Knowledge entities: {len(entities)}")-- if relations_file.exists():- with open(relations_file, encoding="utf-8") as f:- relations = json.load(f)- logger.info(f"Knowledge relations: {len(relations)}")-- if chunks_file.exists():- with open(chunks_file, encoding="utf-8") as f:- chunks = json.load(f)- logger.info(f"Text chunks: {len(chunks)}")-- except Exception as e:- logger.warning(f"Could not retrieve statistics: {e!s}")+ # Check for RAG storage (different providers use different formats)+ provider = os.getenv("RAG_PROVIDER", "raganything")++ # RAGAnything/LightRAG format+ entities_file = self.rag_storage_dir / "kv_store_full_entities.json"+ relations_file = self.rag_storage_dir / "kv_store_full_relations.json"+ chunks_file = self.rag_storage_dir / "kv_store_text_chunks.json"++ # LlamaIndex format+ vector_store_dir = self.base_dir / self.kb_name / "vector_store"++ try:+ if entities_file.exists():+ with open(entities_file, encoding="utf-8") as f:+ entities = json.load(f)+ logger.info(f"Knowledge entities: {len(entities)}")++ if relations_file.exists():+ with open(relations_file, encoding="utf-8") as f:+ relations = json.load(f)+ logger.info(f"Knowledge relations: {len(relations)}")++ if chunks_file.exists():+ with open(chunks_file, encoding="utf-8") as f:+ chunks = json.load(f)+ logger.info(f"Text chunks: {len(chunks)}")++ if vector_store_dir.exists():+ metadata_file = vector_store_dir / "metadata.json"+ if metadata_file.exists():+ with open(metadata_file, encoding="utf-8") as f:+ metadata = json.load(f)+ logger.info(f"Vector embeddings: {metadata.get('num_embeddings', 0)}")+ logger.info(f"Embedding dimension: {metadata.get('dimension', 0)}")+ except Exception as e:+ logger.warning(f"Could not retrieve statistics: {e!s}")+ logger.info(f"Provider used: {provider}")logger.info("=" * 50)diff --git a/src/services/rag/components/indexers/vector.py b/src/services/rag/components/indexers/vector.pyindex 4866f1520..38fcac3d8 100644--- a/src/services/rag/components/indexers/vector.py+++ b/src/services/rag/components/indexers/vector.py@@ -2,21 +2,27 @@Vector Indexer==============-Vector-based indexer using dense embeddings.+Vector-based indexer using dense embeddings with FAISS.+Provides fast similarity search for RAG retrieval."""+import json+import picklefrom pathlib import Pathfrom typing import List, Optional+import numpy as np+from ...types import Documentfrom ..base import BaseComponentclass VectorIndexer(BaseComponent):"""- Vector indexer using dense embeddings.+ Vector indexer using FAISS for fast similarity search.- Can use LlamaIndex or other vector stores for indexing.+ Creates and stores vector embeddings for efficient retrieval.+ Falls back to simple cosine similarity if FAISS is not available."""name = "vector_indexer"@@ -34,11 +40,24 @@ class VectorIndexer(BaseComponent):/ "data"/ "knowledge_bases")++ # Try to import FAISS, fallback to simple storage if not available+ self.use_faiss = False+ try:+ import faiss+ self.faiss = faiss+ self.use_faiss = True+ self.logger.info("Using FAISS for vector indexing")+ except ImportError:+ self.logger.warning("FAISS not available, using simple vector storage")async def process(self, kb_name: str, documents: List[Document], **kwargs) -> bool:"""Index documents using vector embeddings.+ Creates FAISS index for fast similarity search or falls back to+ simple JSON storage if FAISS is unavailable.+Args:kb_name: Knowledge base namedocuments: List of documents to index@@ -67,23 +86,56 @@ class VectorIndexer(BaseComponent):kb_dir = Path(self.kb_base_dir) / kb_name / "vector_store"kb_dir.mkdir(parents=True, exist_ok=True)- # Simple JSON-based storage (placeholder for actual vector store)- import json-- index_data = []+ # Convert embeddings to numpy array+ embeddings = np.array([+ chunk.embedding if isinstance(chunk.embedding, list)+ else chunk.embedding.tolist()+ for chunk in all_chunks+ ], dtype=np.float32)++ # Store metadata separately+ metadata = []for i, chunk in enumerate(all_chunks):- index_data.append(- {- "id": i,- "content": chunk.content,- "type": chunk.chunk_type,- "metadata": chunk.metadata,- "embedding": chunk.embedding,- }- )-- with open(kb_dir / "index.json", "w", encoding="utf-8") as f:- json.dump(index_data, f, ensure_ascii=False, indent=2)+ metadata.append({+ "id": i,+ "content": chunk.content,+ "type": chunk.chunk_type,+ "metadata": chunk.metadata,+ })++ # Save metadata+ with open(kb_dir / "metadata.json", "w", encoding="utf-8") as f:+ json.dump(metadata, f, ensure_ascii=False, indent=2)++ if self.use_faiss:+ # Create FAISS index+ dimension = embeddings.shape[1]+ index = self.faiss.IndexFlatL2(dimension) # L2 distance (euclidean)++ # Normalize vectors for cosine similarity+ self.faiss.normalize_L2(embeddings)++ # Add vectors to index+ index.add(embeddings)++ # Save FAISS index+ self.faiss.write_index(index, str(kb_dir / "index.faiss"))+ self.logger.info(f"FAISS index saved with {index.ntotal} vectors")+ else:+ # Simple storage: save embeddings as pickle+ with open(kb_dir / "embeddings.pkl", "wb") as f:+ pickle.dump(embeddings, f)+ self.logger.info(f"Embeddings saved for {len(all_chunks)} chunks")++ # Save index info+ info = {+ "num_chunks": len(all_chunks),+ "num_documents": len(documents),+ "embedding_dim": embeddings.shape[1],+ "use_faiss": self.use_faiss,+ }+ with open(kb_dir / "info.json", "w", encoding="utf-8") as f:+ json.dump(info, f, indent=2)self.logger.info(f"Vector index saved to {kb_dir}")return Truediff --git a/src/services/rag/components/retrievers/dense.py b/src/services/rag/components/retrievers/dense.pyindex d3a426cd5..8597b6d5c 100644--- a/src/services/rag/components/retrievers/dense.py+++ b/src/services/rag/components/retrievers/dense.py@@ -2,13 +2,16 @@Dense Retriever===============-Dense vector-based retriever.+Dense vector-based retriever using FAISS or cosine similarity."""import json+import picklefrom pathlib import Pathfrom typing import Any, Dict, List, Optional+import numpy as np+from ..base import BaseComponent@@ -16,7 +19,8 @@ class DenseRetriever(BaseComponent):"""Dense vector retriever.- Uses embedding similarity for retrieval.+ Uses FAISS for fast similarity search or falls back to+ cosine similarity if FAISS is unavailable."""name = "dense_retriever"@@ -36,80 +40,144 @@ class DenseRetriever(BaseComponent):/ "knowledge_bases")self.top_k = top_k++ # Try to import FAISS+ self.use_faiss = False+ try:+ import faiss+ self.faiss = faiss+ self.use_faiss = True+ except ImportError:+ self.logger.warning("FAISS not available, using simple cosine similarity")async def process(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:"""- Search using dense embeddings.+ Search using dense embeddings with FAISS or cosine similarity.Args:query: Search querykb_name: Knowledge base name- **kwargs: Additional arguments+ **kwargs: Additional arguments (mode, top_k, etc.)Returns:- Search results dictionary+ Search results dictionary with answer and sources"""- self.logger.info(f"Dense search in {kb_name}: {query[:50]}...")+ top_k = kwargs.get("top_k", self.top_k)+ self.logger.info(f"Dense search in {kb_name}: {query[:50]}... (top_k={top_k})")from src.services.embedding import get_embedding_client# Get query embeddingclient = get_embedding_client()- query_embedding = (await client.embed([query]))[0]-+ query_embedding = np.array((await client.embed([query]))[0], dtype=np.float32)+# Load indexkb_dir = Path(self.kb_base_dir) / kb_name / "vector_store"- index_file = kb_dir / "index.json"+ metadata_file = kb_dir / "metadata.json"+ info_file = kb_dir / "info.json"- if not index_file.exists():- self.logger.warning(f"No vector index found at {index_file}")+ if not metadata_file.exists():+ self.logger.warning(f"No vector index found at {kb_dir}")return {"query": query,- "answer": "No documents indexed.",+ "answer": "No documents indexed. Please upload documents first.","content": "","mode": "dense",- "provider": "vector",+ "provider": "llamaindex",+ "results": [],}- with open(index_file, "r", encoding="utf-8") as f:- index_data = json.load(f)-- # Compute similarities- results = []- for item in index_data:- if item.get("embedding"):- similarity = self._cosine_similarity(query_embedding, item["embedding"])- results.append((similarity, item))-- # Sort by similarity- results.sort(key=lambda x: x[0], reverse=True)- top_results = results[: self.top_k]-- # Build response+ # Load metadata and info+ with open(metadata_file, "r", encoding="utf-8") as f:+ metadata = json.load(f)++ with open(info_file, "r", encoding="utf-8") as f:+ info = json.load(f)++ use_faiss = info.get("use_faiss", False)++ if use_faiss and self.use_faiss:+ # Use FAISS for fast search+ index_file = kb_dir / "index.faiss"+ if not index_file.exists():+ self.logger.error(f"FAISS index file not found: {index_file}")+ return self._empty_response(query)++ # Load FAISS index+ index = self.faiss.read_index(str(index_file))++ # Normalize query vector for cosine similarity+ query_vec = query_embedding.reshape(1, -1)+ self.faiss.normalize_L2(query_vec)++ # Search+ distances, indices = index.search(query_vec, min(top_k, len(metadata)))++ # Build results+ results = []+ for dist, idx in zip(distances[0], indices[0]):+ if idx < len(metadata): # Valid index+ score = 1.0 / (1.0 + dist) # Convert distance to similarity score+ results.append((score, metadata[idx]))+ else:+ # Fallback: Load embeddings and use cosine similarity+ embeddings_file = kb_dir / "embeddings.pkl"+ if not embeddings_file.exists():+ self.logger.error(f"Embeddings file not found: {embeddings_file}")+ return self._empty_response(query)++ with open(embeddings_file, "rb") as f:+ embeddings = pickle.load(f)++ # Normalize for cosine similarity+ query_vec = query_embedding / np.linalg.norm(query_embedding)+ doc_vecs = embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True)++ # Compute similarities+ similarities = np.dot(doc_vecs, query_vec)++ # Get top-k results+ top_indices = np.argsort(similarities)[::-1][:top_k]++ results = []+ for idx in top_indices:+ score = float(similarities[idx])+ results.append((score, metadata[idx]))++ # Build response content+ # Format chunks cleanly for LLM context (without score annotations)content_parts = []- for score, item in top_results:- content_parts.append(f"[Score: {score:.3f}] {item['content'][:500]}")-+ sources = []+ for score, item in results:+ content = item.get("content", "").strip()+ if content: # Only include non-empty chunks+ # Add chunk without score prefix for clean LLM input+ content_parts.append(content)+ sources.append({+ "content": content,+ "score": score,+ "metadata": item.get("metadata", {}),+ })++ # Join chunks with clear separationcontent = "\n\n".join(content_parts)return {"query": query,- "answer": content,+ "answer": content, # Return clean context for LLM to use"content": content,"mode": "dense",- "provider": "vector",- "results": [item for _, item in top_results],+ "provider": "llamaindex",+ "results": sources,+ }++ def _empty_response(self, query: str) -> Dict[str, Any]:+ """Return empty response when no results found."""+ return {+ "query": query,+ "answer": "No relevant documents found.",+ "content": "",+ "mode": "dense",+ "provider": "llamaindex",+ "results": [],}-- def _cosine_similarity(self, a: List[float], b: List[float]) -> float:- """Compute cosine similarity between two vectors."""- import math-- dot_product = sum(x * y for x, y in zip(a, b))- norm_a = math.sqrt(sum(x * x for x in a))- norm_b = math.sqrt(sum(x * x for x in b))-- if norm_a == 0 or norm_b == 0:- return 0.0-- return dot_product / (norm_a * norm_b)diff --git a/src/services/rag/pipelines/llamaindex.py b/src/services/rag/pipelines/llamaindex.pyindex 924a00432..305067062 100644--- a/src/services/rag/pipelines/llamaindex.py+++ b/src/services/rag/pipelines/llamaindex.py@@ -10,7 +10,7 @@ from typing import Optionalfrom ..components.chunkers import SemanticChunkerfrom ..components.embedders import OpenAIEmbedderfrom ..components.indexers import VectorIndexer-from ..components.parsers import TextParser+from ..components.parsers import PDFParserfrom ..components.retrievers import DenseRetrieverfrom ..pipeline import RAGPipeline@@ -20,7 +20,7 @@ def LlamaIndexPipeline(kb_base_dir: Optional[str] = None) -> RAGPipeline:Create a LlamaIndex-style pipeline.This pipeline uses:- - TextParser for document parsing (supports txt, md files)+ - PDFParser for document parsing (supports PDF files with PyMuPDF fallback)- SemanticChunker for text chunking- OpenAIEmbedder for embedding generation- VectorIndexer for vector indexing@@ -34,7 +34,7 @@ def LlamaIndexPipeline(kb_base_dir: Optional[str] = None) -> RAGPipeline:"""return (RAGPipeline("llamaindex", kb_base_dir=kb_base_dir)- .parser(TextParser())+ .parser(PDFParser()).chunker(SemanticChunker()).embedder(OpenAIEmbedder()).indexer(VectorIndexer(kb_base_dir=kb_base_dir))diff --git a/web/package-lock.json b/web/package-lock.jsonindex cb6fc0eff..ec3a1a66c 100644--- a/web/package-lock.json+++ b/web/package-lock.json@@ -94,7 +94,6 @@"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@babel/code-frame": "^7.27.1","@babel/generator": "^7.28.5",@@ -1728,7 +1727,6 @@"resolved": "https://registry.npmmirror.com/@types/react/-/react-19.2.7.tgz","integrity": "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==","license": "MIT",- "peer": true,"dependencies": {"csstype": "^3.2.2"}@@ -1801,7 +1799,6 @@"integrity": "sha512-iIACsx8pxRnguSYhHiMn2PvhvfpopO9FXHyn1mG5txZIsAaB6F0KwbFnUQN3KCiG3Jcuad/Cao2FAs1Wp7vAyg==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@typescript-eslint/scope-manager": "8.52.0","@typescript-eslint/types": "8.52.0",@@ -2306,7 +2303,6 @@"resolved": "https://registry.npmmirror.com/acorn/-/acorn-8.15.0.tgz","integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==","license": "MIT",- "peer": true,"bin": {"acorn": "bin/acorn"},@@ -2744,7 +2740,6 @@}],"license": "MIT",- "peer": true,"dependencies": {"baseline-browser-mapping": "^2.9.0","caniuse-lite": "^1.0.30001759",@@ -3149,7 +3144,6 @@"resolved": "https://registry.npmmirror.com/cytoscape/-/cytoscape-3.33.1.tgz","integrity": "sha512-iJc4TwyANnOGR1OmWhsS9ayRS3s+XQ185FmuHObThD+5AeJCakAAbWv8KimMTt08xCCLNgneQwFp+JRJOr9qGQ==","license": "MIT",- "peer": true,"engines": {"node": ">=0.10"}@@ -3550,7 +3544,6 @@"resolved": "https://registry.npmmirror.com/d3-selection/-/d3-selection-3.0.0.tgz","integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==","license": "ISC",- "peer": true,"engines": {"node": ">=12"}@@ -4109,7 +4102,6 @@"integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@eslint-community/eslint-utils": "^4.8.0","@eslint-community/regexpp": "^4.12.1",@@ -4295,7 +4287,6 @@"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@rtsao/scc": "^1.1.0","array-includes": "^3.1.9",@@ -5915,7 +5906,6 @@"integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==","dev": true,"license": "MIT",- "peer": true,"bin": {"jiti": "bin/jiti.js"}@@ -7786,7 +7776,6 @@}],"license": "MIT",- "peer": true,"dependencies": {"nanoid": "^3.3.11","picocolors": "^1.1.1",@@ -8008,7 +7997,6 @@"resolved": "https://registry.npmmirror.com/react/-/react-19.2.3.tgz","integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==","license": "MIT",- "peer": true,"engines": {"node": ">=0.10.0"}@@ -8018,7 +8006,6 @@"resolved": "https://registry.npmmirror.com/react-dom/-/react-dom-19.2.3.tgz","integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==","license": "MIT",- "peer": true,"dependencies": {"scheduler": "^0.27.0"},@@ -9119,7 +9106,6 @@"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">=12"},@@ -9318,7 +9304,6 @@"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==","dev": true,"license": "Apache-2.0",- "peer": true,"bin": {"tsc": "bin/tsc","tsserver": "bin/tsserver"@@ -9845,7 +9830,6 @@"integrity": "sha512-k7Nwx6vuWx1IJ9Bjuf4Zt1PEllcwe7cls3VNzm4CQ1/hgtFUK2bRNG3rvnpPUhFjmqJKAKtjV576KnUkHocg/g==","dev": true,"license": "MIT",- "peer": true,"funding": {"url": "https://github.com/sponsors/colinhacks"}