LightRAG: Simple and Fast Retrieval-Augmented Generation
repository·main·Indexed 12 days ago
https://github.com/hkuds/lightragA high-performance Retrieval-Augmented Generation (RAG) framework supporting multimodal data, graph databases, and advanced retrieval modes including local, global, hybrid, naive, and mix. It features role-specific LLM configurations (EXTRACT, QUERY, KEYWORDS, VLM), multiple chunking strategies, and integration with storage backends like PostgreSQL, MongoDB, OpenSearch, and Neo4j. Includes a Python SDK and a REST API server.
What's inside LightRAG
- LightRAG is a Simple and Fast Retrieval-Augmented Generation (RAG) framework developed by HKUDS (Hong Kong University Data Science Lab). It is designed to help developers build RAG applications efficiently by combining Large Language Models (LLMs) with external knowledge retrieval to provide accurate, grounded, and up-to-date responses.
Overview of LightRAG features and updates
mainLightRAG is a simple and fast Retrieval-Augmented Generation (RAG) system. Recent major updates include:
- Multimodal Support: Integration with RAG-Anything for parsing text, images, tables, and equations (via MinerU / Docling).
- Storage Backends: Support for OpenSearch, MongoDB, PostgreSQL, and Neo4J.
- Chunking Strategies: Four selectable strategies:
Fix,Recursive,Vector, andParagraph. - LLM Configuration: Role-specific LLM settings for
EXTRACT,QUERY,KEYWORDS, andVLM. - Evaluation & Tracing: Integrated RAGAS for evaluation and Langfuse for tracing.
- Advanced Retrieval: Support for Rerankers and citation functionality for source attribution.
Overview of LightRAG Server and WebUI
mainThe LightRAG Server provides a Web interface and API support.
- Web Interface: Facilitates document indexing, knowledge graph exploration, and simple RAG query interfaces.
- API Support: Provides interfaces compatible with Ollama, allowing LightRAG to be used as an Ollama-compatible chat model. This enables easy integration with AI chatbots like Open WebUI.
Key features include document ingestion, knowledge graph visualization, and RAG-based querying.
Supported Vector Databases in LightRAG
mainLightRAG provides flexible deployment options by supporting a variety of vector database backends. Developers can choose a database based on their specific requirements for scale, performance, and infrastructure complexity.
Supported databases include:
- ChromaDB: Ideal for simple deployment in development environments.
- Neo4j: A graph database that enables graph-based knowledge representation combined with vector search.
- Milvus: Designed for high-performance vector search at scale for large collections.
- Qdrant: Provides fast similarity search with filtering capabilities for production-ready infrastructure.
- MongoDB Atlas Vector Search: Combines document storage with vector search for unified data management.
- Redis: Offers low-latency, in-memory vector search suitable for real-time applications.
- Built-in Nano-VectorDB: A lightweight, built-in option that eliminates external dependencies, making it perfect for small projects and simple deployments.
Key improvements of LightRAG over traditional RAG
mainLightRAG is designed to address common pain points in traditional Retrieval-Augmented Generation (RAG) systems through four primary areas of improvement:
- Simpler API Design: Provides intuitive interfaces that reduce the complex configuration and setup typically required by traditional RAG frameworks.
- Faster Retrieval Performance: Optimizes document retrieval operations to achieve high-quality results with significantly improved query response times.
- Better Vector Database Integration: Offers seamless support for multiple vector database backends, preventing vendor lock-in and allowing flexible storage backend selection.
- Optimized Prompting Strategies: Utilizes refined prompt templates to balance simplicity with high-quality, accurate output, moving beyond the generic prompting used in many traditional systems.
Reference Documentation Overview
mainThe LightRAG documentation is organized into several functional areas:
Deployment and Setup
InteractiveSetup.md: Using themake env-*wizard for.envand Docker Compose generation.DockerDeployment.md: Docker/Docker Compose deployment and GHCR image verification.AppleContainerSetup.md: Running the storage stack (Postgres/Neo4j/Milvus) on Apple Silicon without Docker Desktop.OfflineDeployment.md: Air-gapped installation instructions.MultiSiteDeployment.md: Running isolated instances behind a single reverse proxy.FrontendBuildGuide.md: Building the WebUI using Bun/Node.
Server and API
LightRAG-API-Server.md: Complete guide to startup, configuration, authentication, and REST endpoints.
Document Processing
FileProcessingPipeline.md: Routing rules, engine parameters, and document lifecycle.ParserServiceDeployment.md: Hosting MinerU and docling-serve parsing services.ParagraphSemanticChunking.md: Using theParagraph semantic (P)chunking strategy.LightRAGSidecarFormat.md: The*.parsed/interchange format for multimodal parsers.ThirdPartyParser.md: Developing and registering custom parser engines.ParserDebugCLI.md: Usingpython -m lightrag.parser.clito parse files offline.
Models and Storage
RoleSpecificLLMConfiguration.md: Configuring LLM/VLM per role (EXTRACT,QUERY,KEYWORD,VLM).AsymmetricEmbedding.md: ConfiguringEMBEDDING_ASYMMETRICand model prefixes.MilvusConfigurationGuide.md: Tuning Milvus viavector_db_storage_cls_kwargs.
Overview of File Parsing Engines
mainLightRAG uses different engines to extract content from files. Choosing the right engine depends on your file formats and whether you want to run extraction locally or via external services.
Engine Description Supported Formats (Suffixes) legacyDefault fallback; extracts plain text only. txt,md,pdf,docx,py,js, etc. (wide range)nativeBuilt-in local structured extractor. No external service required. docx,md,textpackmineruExternal MinerU service. High-quality extraction. pdf,docx,pptx,xlsx,png,jpg, etc.doclingExternal Docling service. High-quality extraction. pdf,docx,pptx,xlsx,md,html, etc.Important Notes:
- External Engines: For
mineruanddocling, you must have the service running and configure the correspondingendpointandtokenin your environment. - Custom Formats: If your deployment supports formats outside the baseline (e.g., old Office
.doc), you must declare them usingMINERU_ADDITIONAL_SUFFIXESorDOCLING_ADDITIONAL_SUFFIXESand then route them viaLIGHTRAG_PARSERor filename hints.
- External Engines: For
What is LightRAG?
mainLightRAG is a lightweight knowledge graph (KG) RAG framework designed as an efficient alternative to Microsoft GraphRAG. It uses a dual-layer architecture that manages both Knowledge Graphs and vector embeddings simultaneously, bridging the gap between traditional vector-based RAG and graph-based RAG.
Key advantages include:
- Deep Contextual Understanding: Captures complex semantic dependencies between entities via graph structures, making it ideal for vertical domains like law or finance.
- High Efficiency & Low Cost: Avoids inefficient community reports or multi-hop reasoning, significantly reducing LLM calls and latency during indexing and querying.
- Incremental Updates & Partial Deletion: Supports dynamic data environments by allowing efficient updates and deletions of entities and relationships.
- Multimodal Support: Since v1.5, it integrates images, formulas, and tables into the document processing pipeline and query flow via the knowledge graph.
- Flexible Chunking & Parsing: Supports multiple parsing engines (MinerU, Docling, Native) and four chunking strategies: Fixed-length (F), Recursive character (R), Vector semantic (V), and Paragraph semantic (P).
Overview of LightRAG Storage Types and Implementations
mainLightRAG utilizes four distinct storage types to manage different aspects of the RAG lifecycle. When configuring
LightRAG, you can specify different backend implementations for each type.Storage Type Purpose KV_STORAGE LLM response cache, text chunks, document information VECTOR_STORAGE Entity/relation/chunk embedding vectors GRAPH_STORAGE Entity-relation graph structure DOC_STATUS_STORAGE Document indexing status Supported Implementations
KV_STORAGE
JsonKVStorage(default)PGKVStorage(Postgres)RedisKVStorage(Redis)MongoKVStorage(MongoDB)OpenSearchKVStorage(OpenSearch)
GRAPH_STORAGE
NetworkXStorage(default)Neo4JStorage(Neo4J)PGGraphStorage(PostgreSQL with AGE plugin)PGTableGraphStorage(PostgreSQL, plain tables - no AGE/extensions required)MemgraphStorage(Memgraph)OpenSearchGraphStorage(OpenSearch)
VECTOR_STORAGE
NanoVectorDBStorage(default)PGVectorStorage(Postgres)MilvusVectorDBStorage(Milvus)FaissVectorDBStorage(Faiss)QdrantVectorDBStorage(Qdrant)MongoVectorDBStorage(MongoDB)OpenSearchVectorDBStorage(OpenSearch)
DOC_STATUS_STORAGE
JsonDocStatusStorage(default)PGDocStatusStorage(Postgres)MongoDocStatusStorage(MongoDB)OpenSearchDocStatusStorage(OpenSearch)
Note: LightRAG creates tables within an existing database instance, but it does not create the database instance itself. Connection strings should be configured via environment variables as shown in
env.example.How the parser concurrency model works
mainLightRAG manages parsing workloads using
queue_groups. For every batch, the pipeline creates one queue and one worker group for every uniquequeue_groupidentified in the registry.- Built-in Groups:
native,mineru, anddoclinghave worker counts determined by LightRAG instance fields (e.g.,max_parallel_parse_native). - Third-party Dedicated Groups: If you use a unique
queue_groupname, the worker count is determined by theconcurrencyvalue in theParserSpecthat owns that group. Only one spec per group may declare aconcurrencyvalue; otherwise, batch startup fails. - Sharing the Native Pool: If you set
queue_group="native", your engine shares the built-in pool. In this mode, your spec-levelconcurrencyvalue is ignored (and a warning is logged), as the pool size is controlled by the LightRAG instance'smax_parallel_parse_nativesetting. - Best Practice: External-service engines should use a dedicated
queue_groupso that slow network requests do not block local, lightweight parsing tasks.
- Built-in Groups:
Understand the relationship between process_options and chunk_options
mainLightRAG uses two orthogonal configuration layers to manage document chunking:
process_options: A selector that determines which chunking strategy to use. It uses single-character identifiers:F: Fixed token chunkingR: Recursive character chunkingV: Semantic vector chunkingP: Paragraph semantic chunking
chunk_options: A structured dictionary that determines which parameters are used by the selected strategy.
Data Flow & Lifecycle:
- Initialization:
LightRAG.__init__reads environment variables intoaddon_params["chunker"]. - Enqueuing: When documents are enqueued via
apipeline_enqueue_documents, achunk_optionssnapshot is frozen for each document. If the caller provides specificchunk_options(via SDK), those are persisted; otherwise, they are assembled from the instance'saddon_params. - Processing: The chunker retrieves the corresponding sub-dictionary from the frozen
chunk_optionsbased on theprocess_optionsselector and applies the parameters.
/* Mapping of selector to sub-dictionary */ F -> fixed_token R -> recursive_character V -> semantic_vector P -> paragraph_semanticSelect backend storage types
mainLightRAG requires four types of storage. While default file-persisted in-memory databases are suitable for development, production environments should use robust databases:
KV_STORAGE: LLM response caches, text chunking results, entity-relation extraction results.VECTOR_STORAGE: Vector information for chunks, entities, and relationships.GRAPH_STORAGE: The knowledge graph.DOC_STATUS_STORAGE: The document list.
Production Recommendations:
- Unified Backend: PostgreSQL, MongoDB, or OpenSearch can handle all four types.
- Specialized Backends: Use Milvus or Qdrant for
VECTOR_STORAGE, and Neo4j or Memgraph forGRAPH_STORAGE.