From 1d985d21cdac8ef142f2b7e030314be2af5d3d93 Mon Sep 17 00:00:00 2001 From: Tushar Khatri Date: Sun, 11 Jan 2026 17:09:50 +0530 Subject: [PATCH] Implement pure LightRAG pipeline with complete initialization - Create LightRAGIndexer using LightRAG.ainsert() directly - Create LightRAGRetriever using LightRAG.aquery() with QueryParam - Use sync callbacks (LightRAG requirement) and EmbeddingFunc object - Add 3-step init: create instance, initialize_storages, initialize_pipeline_status - Remove chunker/embedder (LightRAG handles internally) - Update factory.py for distinct pipeline implementations - Fix graph.py imports Performance: llamaindex 3s, lightrag 10-15s, raganything 60s+ All three pipelines now fully decoupled and functional. --- .../rag/components/indexers/__init__.py | 2 + src/services/rag/components/indexers/graph.py | 3 +- .../rag/components/indexers/lightrag.py | 123 ++++++++++++++++ .../rag/components/retrievers/__init__.py | 2 + .../rag/components/retrievers/lightrag.py | 136 ++++++++++++++++++ src/services/rag/factory.py | 6 +- src/services/rag/pipelines/lightrag.py | 35 ++--- 7 files changed, 286 insertions(+), 21 deletions(-) create mode 100644 src/services/rag/components/indexers/lightrag.py create mode 100644 src/services/rag/components/retrievers/lightrag.py diff --git a/src/services/rag/components/indexers/__init__.py b/src/services/rag/components/indexers/__init__.py index 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 BaseIndexer from .graph import GraphIndexer +from .lightrag import LightRAGIndexer from .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.py index 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 True diff --git a/src/services/rag/components/indexers/lightrag.py b/src/services/rag/components/indexers/lightrag.py new file mode 100644 index 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 True diff --git a/src/services/rag/components/retrievers/__init__.py b/src/services/rag/components/retrievers/__init__.py index 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 BaseRetriever from .dense import DenseRetriever from .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.py new file mode 100644 index 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.py index 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.py index 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 LightRAGRetriever from ..pipeline import RAGPipeline def 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 graph Args: 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)) )