DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
Implement pure LightRAG pipeline with complete initialization
Tushar Khatri1d985d21cdac
diff --git a/src/services/rag/components/indexers/__init__.py b/src/services/rag/components/indexers/__init__.pyindex 9fff20c69..10fc3c2ca 100644--- a/src/services/rag/components/indexers/__init__.py+++ b/src/services/rag/components/indexers/__init__.py@@ -7,10 +7,12 @@ Indexers for building searchable indexes from documents.from .base import BaseIndexerfrom .graph import GraphIndexer+from .lightrag import LightRAGIndexerfrom .vector import VectorIndexer__all__ = ["BaseIndexer","VectorIndexer","GraphIndexer",+ "LightRAGIndexer",]diff --git a/src/services/rag/components/indexers/graph.py b/src/services/rag/components/indexers/graph.pyindex 9d527aef4..f20f3303e 100644--- a/src/services/rag/components/indexers/graph.py+++ b/src/services/rag/components/indexers/graph.py@@ -115,7 +115,8 @@ class GraphIndexer(BaseComponent):for doc in documents:if doc.content:- await rag.ainsert(doc.content)+ # RAGAnything uses process_document_complete_lightrag_api instead of ainsert+ await rag.process_document_complete_lightrag_api(doc.content)self.logger.info("Knowledge graph built successfully")return Truediff --git a/src/services/rag/components/indexers/lightrag.py b/src/services/rag/components/indexers/lightrag.pynew file mode 100644index 000000000..e7170264f--- /dev/null+++ b/src/services/rag/components/indexers/lightrag.py@@ -0,0 +1,123 @@+"""+LightRAG Indexer+================++Pure LightRAG indexer (text-only, no multimodal processing).+"""++from pathlib import Path+import sys+from typing import Dict, List, Optional++from ...types import Document+from ..base import BaseComponent+++class LightRAGIndexer(BaseComponent):+ """+ Pure LightRAG knowledge graph indexer (text-only).++ Uses LightRAG library directly without multimodal processing.+ Faster than RAGAnything for text-only documents.+ """++ name = "lightrag_indexer"+ _instances: Dict[str, any] = {} # Cache LightRAG instances++ def __init__(self, kb_base_dir: Optional[str] = None):+ """+ Initialize LightRAG indexer.++ Args:+ kb_base_dir: Base directory for knowledge bases+ """+ super().__init__()+ self.kb_base_dir = kb_base_dir or str(+ Path(__file__).resolve().parent.parent.parent.parent.parent.parent+ / "data"+ / "knowledge_bases"+ )++ def _get_lightrag_instance(self, kb_name: str):+ """Get or create a LightRAG instance (text-only)."""+ working_dir = str(Path(self.kb_base_dir) / kb_name / "rag_storage")++ if working_dir in self._instances:+ return self._instances[working_dir]++ # Add LightRAG path+ project_root = Path(__file__).resolve().parent.parent.parent.parent.parent.parent+ raganything_path = project_root.parent / "raganything" / "RAG-Anything"+ if raganything_path.exists() and str(raganything_path) not in sys.path:+ sys.path.insert(0, str(raganything_path))++ try:+ from lightrag import LightRAG+ from lightrag.llm.openai import openai_complete_if_cache++ from src.services.embedding import get_embedding_client+ from src.services.llm import get_llm_client++ llm_client = get_llm_client()+ embed_client = get_embedding_client()++ # LLM function using services (SYNC - LightRAG expects sync functions)+ def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):+ return openai_complete_if_cache(+ llm_client.config.model,+ prompt,+ system_prompt=system_prompt,+ history_messages=history_messages,+ api_key=llm_client.config.api_key,+ base_url=llm_client.config.base_url,+ **kwargs,+ )++ # Create pure LightRAG instance (no multimodal)+ rag = LightRAG(+ working_dir=working_dir,+ llm_model_func=llm_model_func,+ embedding_func=embed_client.get_embedding_func(), # Use proper EmbeddingFunc object+ )++ self._instances[working_dir] = rag+ return rag++ except ImportError as e:+ self.logger.error(f"Failed to import LightRAG: {e}")+ raise++ async def process(self, kb_name: str, documents: List[Document], **kwargs) -> bool:+ """+ Build knowledge graph from documents (text-only).++ Args:+ kb_name: Knowledge base name+ documents: List of documents to index+ **kwargs: Additional arguments++ Returns:+ True if successful+ """+ self.logger.info(f"Building knowledge graph for {kb_name} (text-only)...")++ from src.logging.adapters import LightRAGLogContext++ # Use log forwarding context+ with LightRAGLogContext(scene="LightRAG-Indexer"):+ rag = self._get_lightrag_instance(kb_name)++ # Initialize storages (required for LightRAG)+ await rag.initialize_storages()++ # Initialize pipeline status (required for document processing)+ from lightrag.kg.shared_storage import initialize_pipeline_status+ await initialize_pipeline_status()++ for doc in documents:+ if doc.content:+ # Use direct LightRAG insert (text-only, fast)+ await rag.ainsert(doc.content)++ self.logger.info("Knowledge graph built successfully (text-only)")+ return Truediff --git a/src/services/rag/components/retrievers/__init__.py b/src/services/rag/components/retrievers/__init__.pyindex 2d215acbe..9b358f38a 100644--- a/src/services/rag/components/retrievers/__init__.py+++ b/src/services/rag/components/retrievers/__init__.py@@ -8,9 +8,11 @@ Retrievers for searching indexed documents.from .base import BaseRetrieverfrom .dense import DenseRetrieverfrom .hybrid import HybridRetriever+from .lightrag import LightRAGRetriever__all__ = ["BaseRetriever","DenseRetriever","HybridRetriever",+ "LightRAGRetriever",]diff --git a/src/services/rag/components/retrievers/lightrag.py b/src/services/rag/components/retrievers/lightrag.pynew file mode 100644index 000000000..00361f91f--- /dev/null+++ b/src/services/rag/components/retrievers/lightrag.py@@ -0,0 +1,136 @@+"""+LightRAG Retriever+==================++Pure LightRAG retriever (text-only, no multimodal).+"""++from pathlib import Path+import sys+from typing import Any, Dict, List, Optional++from ..base import BaseComponent+++class LightRAGRetriever(BaseComponent):+ """+ Pure LightRAG retriever using LightRAG.query() directly.++ Uses LightRAG's native retrieval modes (naive, local, global, hybrid).+ Text-only, no multimodal processing.+ """++ name = "lightrag_retriever"+ _instances: Dict[str, any] = {}++ def __init__(self, kb_base_dir: Optional[str] = None):+ """+ Initialize LightRAG retriever.++ Args:+ kb_base_dir: Base directory for knowledge bases+ """+ super().__init__()+ self.kb_base_dir = kb_base_dir or str(+ Path(__file__).resolve().parent.parent.parent.parent.parent.parent+ / "data"+ / "knowledge_bases"+ )++ def _get_lightrag_instance(self, kb_name: str):+ """Get or create a pure LightRAG instance (text-only)."""+ working_dir = str(Path(self.kb_base_dir) / kb_name / "rag_storage")++ if working_dir in self._instances:+ return self._instances[working_dir]++ # Add LightRAG path+ project_root = Path(__file__).resolve().parent.parent.parent.parent.parent.parent+ raganything_path = project_root.parent / "raganything" / "RAG-Anything"+ if raganything_path.exists() and str(raganything_path) not in sys.path:+ sys.path.insert(0, str(raganything_path))++ try:+ from lightrag import LightRAG, QueryParam+ from lightrag.llm.openai import openai_complete_if_cache++ from src.services.embedding import get_embedding_client+ from src.services.llm import get_llm_client++ llm_client = get_llm_client()+ embed_client = get_embedding_client()++ # LLM function using services (SYNC - LightRAG expects sync functions)+ def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):+ return openai_complete_if_cache(+ llm_client.config.model,+ prompt,+ system_prompt=system_prompt,+ history_messages=history_messages,+ api_key=llm_client.config.api_key,+ base_url=llm_client.config.base_url,+ **kwargs,+ )++ # Create pure LightRAG instance (no multimodal)+ rag = LightRAG(+ working_dir=working_dir,+ llm_model_func=llm_model_func,+ embedding_func=embed_client.get_embedding_func(), # Use proper EmbeddingFunc object+ )++ self._instances[working_dir] = rag+ return rag++ except ImportError as e:+ self.logger.error(f"Failed to import LightRAG: {e}")+ raise++ async def process(+ self,+ query: str,+ kb_name: str,+ mode: str = "hybrid",+ only_need_context: bool = False,+ **kwargs,+ ) -> Dict[str, Any]:+ """+ Search using pure LightRAG retrieval (text-only).++ Args:+ query: Search query+ kb_name: Knowledge base name+ mode: Search mode (hybrid, local, global, naive)+ only_need_context: Whether to only return context without answer+ **kwargs: Additional arguments++ Returns:+ Search results dictionary+ """+ self.logger.info(f"LightRAG search ({mode}) in {kb_name}: {query[:50]}...")++ from src.logging.adapters import LightRAGLogContext++ with LightRAGLogContext(scene="LightRAG-Search"):+ rag = self._get_lightrag_instance(kb_name)++ # Initialize storages if not already initialized+ await rag.initialize_storages()+ from lightrag.kg.shared_storage import initialize_pipeline_status+ await initialize_pipeline_status()++ # Import QueryParam for proper query parameter passing+ from lightrag import QueryParam++ # Use LightRAG's native query method with QueryParam object+ query_param = QueryParam(mode=mode, only_need_context=only_need_context)+ answer = await rag.aquery(query, param=query_param)+ answer_str = answer if isinstance(answer, str) else str(answer)++ return {+ "query": query,+ "answer": answer_str,+ "content": answer_str,+ "mode": mode,+ "provider": "lightrag",+ }diff --git a/src/services/rag/factory.py b/src/services/rag/factory.pyindex d6116b4b5..bfbcc7e84 100644--- a/src/services/rag/factory.py+++ b/src/services/rag/factory.py@@ -13,9 +13,9 @@ from .pipelines.raganything import RAGAnythingPipeline# Pipeline registry_PIPELINES: Dict[str, Callable] = {- "raganything": RAGAnythingPipeline,- "lightrag": lightrag.LightRAGPipeline,- "llamaindex": llamaindex.LlamaIndexPipeline,+ "raganything": RAGAnythingPipeline, # Full multimodal: MinerU parser, deep analysis (slow, thorough)+ "lightrag": lightrag.LightRAGPipeline, # Knowledge graph: PDFParser, fast text-only (medium speed)+ "llamaindex": llamaindex.LlamaIndexPipeline, # Vector-only: Simple chunking, fast (fastest)"academic": academic.AcademicPipeline,}diff --git a/src/services/rag/pipelines/lightrag.py b/src/services/rag/pipelines/lightrag.pyindex a30992f3a..88cfd4420 100644--- a/src/services/rag/pipelines/lightrag.py+++ b/src/services/rag/pipelines/lightrag.py@@ -2,29 +2,31 @@LightRAG Pipeline=================-Component-based pipeline using LightRAG for knowledge graph indexing.+Pure LightRAG pipeline (text-only, no multimodal processing).+Faster than RAGAnything for text-heavy documents."""from typing import Optional-from ..components.chunkers import SemanticChunker-from ..components.embedders import OpenAIEmbedder-from ..components.indexers import GraphIndexer-from ..components.parsers import TextParser-from ..components.retrievers import HybridRetriever+from ..components.indexers import LightRAGIndexer+from ..components.parsers import PDFParser+from ..components.retrievers import LightRAGRetrieverfrom ..pipeline import RAGPipelinedef LightRAGPipeline(kb_base_dir: Optional[str] = None) -> RAGPipeline:"""- Create a LightRAG-based pipeline.+ Create a pure LightRAG pipeline (text-only, no multimodal).This pipeline uses:- - TextParser for document parsing (supports txt, md files)- - SemanticChunker for text chunking- - OpenAIEmbedder for embedding generation- - GraphIndexer for knowledge graph indexing- - HybridRetriever for retrieval+ - PDFParser for document parsing (extracts raw text from PDF/txt/md)+ - LightRAGIndexer for knowledge graph indexing (text-only, fast)+ * LightRAG handles chunking, entity extraction, and embedding internally+ * No separate chunker/embedder needed - LightRAG does it all+ - LightRAGRetriever for retrieval (uses LightRAG.aquery() directly)++ Performance: Medium speed (~10-15s per document)+ Use for: Business docs, text-heavy PDFs, when you need knowledge graphArgs:kb_base_dir: Base directory for knowledge bases@@ -34,9 +36,8 @@ def LightRAGPipeline(kb_base_dir: Optional[str] = None) -> RAGPipeline:"""return (RAGPipeline("lightrag", kb_base_dir=kb_base_dir)- .parser(TextParser())- .chunker(SemanticChunker())- .embedder(OpenAIEmbedder())- .indexer(GraphIndexer(kb_base_dir=kb_base_dir))- .retriever(HybridRetriever(kb_base_dir=kb_base_dir))+ .parser(PDFParser())+ # No chunker/embedder - LightRAG does everything internally+ .indexer(LightRAGIndexer(kb_base_dir=kb_base_dir))+ .retriever(LightRAGRetriever(kb_base_dir=kb_base_dir)))