[2024.11.25]🎯📢LightRAG now supports seamless integration of custom knowledge graphs, empowering users to enhance the system with their own domain expertise.
[2024.11.19]🎯📢A comprehensive guide to LightRAG is now available on LearnOpenCV. Many thanks to the blog author.
The LightRAG Server is designed to provide Web UI and API support. The Web UI facilitates document indexing, knowledge graph exploration, and a simple RAG query interface. LightRAG Server also provide an Ollama compatible interfaces, aiming to emulate LightRAG as an Ollama chat model. This allows AI chat bot, such as Open WebUI, to access LightRAG easily.
Install from PyPI
1
pip install "lightrag-hku[api]"
Installation from Source
1
2
3
# create a Python virtual enviroment if neccesary# Install in editable mode with API supportpip install -e ".[api]"
For more information about LightRAG Server, please refer to LightRAG Server.
importosimportasynciofromlightragimportLightRAG,QueryParamfromlightrag.llm.openaiimportgpt_4o_mini_complete,gpt_4o_complete,openai_embedfromlightrag.kg.shared_storageimportinitialize_pipeline_statusfromlightrag.utilsimportsetup_loggersetup_logger("lightrag",level="INFO")asyncdefinitialize_rag():rag=LightRAG(working_dir="your/path",embedding_func=openai_embed,llm_model_func=gpt_4o_mini_complete)awaitrag.initialize_storages()awaitinitialize_pipeline_status()returnragdefmain():# Initialize RAG instancerag=asyncio.run(initialize_rag())# Insert textrag.insert("Your text")# Perform naive searchmode="naive"# Perform local searchmode="local"# Perform global searchmode="global"# Perform hybrid searchmode="hybrid"# Mix mode Integrates knowledge graph and vector retrieval.mode="mix"rag.query("What are the top themes in this story?",param=QueryParam(mode=mode))if__name__=="__main__":main()
classQueryParam:mode:Literal["local","global","hybrid","naive","mix"]="global""""Specifies the retrieval mode:
- "local": Focuses on context-dependent information.
- "global": Utilizes global knowledge.
- "hybrid": Combines local and global retrieval methods.
- "naive": Performs a basic search without advanced techniques.
- "mix": Integrates knowledge graph and vector retrieval. Mix mode combines knowledge graph and vector search:
- Uses both structured (KG) and unstructured (vector) information
- Provides comprehensive answers by analyzing relationships and context
- Supports image content through HTML img tags
- Allows control over retrieval depth via top_k parameter
"""only_need_context:bool=False"""If True, only returns the retrieved context without generating a response."""response_type:str="Multiple Paragraphs""""Defines the response format. Examples: 'Multiple Paragraphs', 'Single Paragraph', 'Bullet Points'."""top_k:int=60"""Number of top items to retrieve. Represents entities in 'local' mode and relationships in 'global' mode."""max_token_for_text_unit:int=4000"""Maximum number of tokens allowed for each retrieved text chunk."""max_token_for_global_context:int=4000"""Maximum number of tokens allocated for relationship descriptions in global retrieval."""max_token_for_local_context:int=4000"""Maximum number of tokens allocated for entity descriptions in local retrieval."""ids:list[str]|None=None# ONLY SUPPORTED FOR PG VECTOR DBs"""List of ids to filter the RAG."""model_func:Callable[...,object]|None=None"""Optional override for the LLM model function to use for this specific query.
If provided, this will be used instead of the global model function.
This allows using different models for different query modes.
"""...
default value of Top_k can be change by environment variables TOP_K.
LLM and Embedding Injection
LightRAG requires the utilization of LLM and Embedding models to accomplish document indexing and querying tasks. During the initialization phase, it is necessary to inject the invocation methods of the relevant models into LightRAG:
Using Open AI-like APIs
LightRAG also supports Open AI-like chat/embeddings APIs:
If you want to use Hugging Face models, you only need to set LightRAG as follows:
See lightrag_hf_demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Initialize LightRAG with Hugging Face modelrag=LightRAG(working_dir=WORKING_DIR,llm_model_func=hf_model_complete,# Use Hugging Face model for text generationllm_model_name='meta-llama/Llama-3.1-8B-Instruct',# Model name from Hugging Face# Use Hugging Face embedding functionembedding_func=EmbeddingFunc(embedding_dim=384,max_token_size=5000,func=lambdatexts:hf_embed(texts,tokenizer=AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2"),embed_model=AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2"))),)
Using Ollama Models
**Overview**
If you want to use Ollama models, you need to pull model you plan to use and embedding model, for example nomic-embed-text.
Then you only need to set LightRAG as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Initialize LightRAG with Ollama modelrag=LightRAG(working_dir=WORKING_DIR,llm_model_func=ollama_model_complete,# Use Ollama model for text generationllm_model_name='your_model_name',# Your model name# Use Ollama embedding functionembedding_func=EmbeddingFunc(embedding_dim=768,max_token_size=8192,func=lambdatexts:ollama_embed(texts,embed_model="nomic-embed-text")),)
Increasing context size
In order for LightRAG to work context should be at least 32k tokens. By default Ollama models have context size of 8k. You can achieve this using one of two ways:
Increasing the num_ctx parameter in Modelfile
Pull the model:
1
ollama pull qwen2
Display the model file:
1
ollama show --modelfile qwen2 > Modelfile
Edit the Modelfile by adding the following line:
1
PARAMETER num_ctx 32768
Create the modified model:
1
ollama create -f Modelfile qwen2m
Setup num_ctx via Ollama API
Tiy can use llm_model_kwargs param to configure ollama:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
rag=LightRAG(working_dir=WORKING_DIR,llm_model_func=ollama_model_complete,# Use Ollama model for text generationllm_model_name='your_model_name',# Your model namellm_model_kwargs={"options":{"num_ctx":32768}},# Use Ollama embedding functionembedding_func=EmbeddingFunc(embedding_dim=768,max_token_size=8192,func=lambdatexts:ollama_embedding(texts,embed_model="nomic-embed-text")),)
Low RAM GPUs
In order to run this experiment on low RAM GPU you should select small model and tune context window (increasing context increase memory consumption). For example, running this ollama example on repurposed mining GPU with 6Gb of RAM required to set context size to 26k while using gemma2:2b. It was able to find 197 entities and 19 relations on book.txt.
LlamaIndex
LightRAG supports integration with LlamaIndex (llm/llama_index_impl.py):
Integrates with OpenAI and other providers through LlamaIndex
# Using LlamaIndex with direct OpenAI accessimportasynciofromlightragimportLightRAGfromlightrag.llm.llama_index_implimportllama_index_complete_if_cache,llama_index_embedfromllama_index.embeddings.openaiimportOpenAIEmbeddingfromllama_index.llms.openaiimportOpenAIfromlightrag.kg.shared_storageimportinitialize_pipeline_statusfromlightrag.utilsimportsetup_logger# Setup log handler for LightRAGsetup_logger("lightrag",level="INFO")asyncdefinitialize_rag():rag=LightRAG(working_dir="your/path",llm_model_func=llama_index_complete_if_cache,# LlamaIndex-compatible completion functionembedding_func=EmbeddingFunc(# LlamaIndex-compatible embedding functionembedding_dim=1536,max_token_size=8192,func=lambdatexts:llama_index_embed(texts,embed_model=embed_model)),)awaitrag.initialize_storages()awaitinitialize_pipeline_status()returnragdefmain():# Initialize RAG instancerag=asyncio.run(initialize_rag())withopen("./book.txt","r",encoding="utf-8")asf:rag.insert(f.read())# Perform naive searchprint(rag.query("What are the top themes in this story?",param=QueryParam(mode="naive")))# Perform local searchprint(rag.query("What are the top themes in this story?",param=QueryParam(mode="local")))# Perform global searchprint(rag.query("What are the top themes in this story?",param=QueryParam(mode="global")))# Perform hybrid searchprint(rag.query("What are the top themes in this story?",param=QueryParam(mode="hybrid")))if__name__=="__main__":main()
LightRAG provides a TokenTracker tool to monitor and manage token consumption by large language models. This feature is particularly useful for controlling API costs and optimizing performance.
fromlightrag.utilsimportTokenTracker# Create TokenTracker instancetoken_tracker=TokenTracker()# Method 1: Using context manager (Recommended)# Suitable for scenarios requiring automatic token usage trackingwithtoken_tracker:result1=awaitllm_model_func("your question 1")result2=awaitllm_model_func("your question 2")# Method 2: Manually adding token usage records# Suitable for scenarios requiring more granular control over token statisticstoken_tracker.reset()rag.insert()rag.query("your question 1",param=QueryParam(mode="naive"))rag.query("your question 2",param=QueryParam(mode="mix"))# Display total token usage (including insert and query operations)print("Token usage:",token_tracker.get_usage())
Usage Tips
Use context managers for long sessions or batch operations to automatically track all token consumption
For scenarios requiring segmented statistics, use manual mode and call reset() when appropriate
Regular checking of token usage helps detect abnormal consumption early
Actively use this feature during development and testing to optimize production costs
Practical Examples
You can refer to these examples for implementing token tracking:
examples/lightrag_gemini_track_token_demo.py: Token tracking example using Google Gemini model
examples/lightrag_siliconcloud_track_token_demo.py: Token tracking example using SiliconCloud model
These examples demonstrate how to effectively use the TokenTracker feature with different models and scenarios.
Conversation History Support
LightRAG now supports multi-turn dialogue through the conversation history feature. Here’s how to use it:
Usage Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Create conversation historyconversation_history=[{"role":"user","content":"What is the main character's attitude towards Christmas?"},{"role":"assistant","content":"At the beginning of the story, Ebenezer Scrooge has a very negative attitude towards Christmas..."},{"role":"user","content":"How does his attitude change?"}]# Create query parameters with conversation historyquery_param=QueryParam(mode="mix",# or any other mode: "local", "global", "hybrid"conversation_history=conversation_history,# Add the conversation historyhistory_turns=3# Number of recent conversation turns to consider)# Make a query that takes into account the conversation historyresponse=rag.query("What causes this change in his character?",param=query_param)
Custom Prompt Support
LightRAG now supports custom prompts for fine-tuned control over the system’s behavior. Here’s how to use it:
# Create query parametersquery_param=QueryParam(mode="hybrid",# or other mode: "local", "global", "hybrid", "mix" and "naive")# Example 1: Using the default system promptresponse_default=rag.query("What are the primary benefits of renewable energy?",param=query_param)print(response_default)# Example 2: Using a custom promptcustom_prompt="""
You are an expert assistant in environmental science. Provide detailed and structured answers with examples.
---Conversation History---
{history}---Knowledge Base---
{context_data}---Response Rules---
- Target format and length: {response_type}"""response_custom=rag.query("What are the primary benefits of renewable energy?",param=query_param,system_prompt=custom_prompt# Pass the custom prompt)print(response_custom)
Separate Keyword Extraction
We’ve introduced a new function query_with_separate_keyword_extraction to enhance the keyword extraction capabilities. This function separates the keyword extraction process from the user’s prompt, focusing solely on the query to improve the relevance of extracted keywords.
How It Works?
The function operates by dividing the input into two parts:
User Query
Prompt
It then performs keyword extraction exclusively on the user query. This separation ensures that the extraction process is focused and relevant, unaffected by any additional language in the prompt. It also allows the prompt to serve purely for response formatting, maintaining the intent and clarity of the user’s original question.
Usage Example
This example shows how to tailor the function for educational content, focusing on detailed explanations for older students.
1
2
3
4
5
rag.query_with_separate_keyword_extraction(query="Explain the law of gravity",prompt="Provide a detailed explanation suitable for high school students studying physics.",param=QueryParam(mode="hybrid"))
Insert
Basic Insert
1
2
# Basic Insertrag.insert("Text")
Batch Insert
1
2
3
4
5
6
7
8
9
10
11
12
# Basic Batch Insert: Insert multiple texts at oncerag.insert(["TEXT1","TEXT2",...])# Batch Insert with custom batch size configurationrag=LightRAG(working_dir=WORKING_DIR,addon_params={"insert_batch_size":4# Process 4 documents per batch})rag.insert(["TEXT1","TEXT2","TEXT3",...])# Documents will be processed in batches of 4
The insert_batch_size parameter in addon_params controls how many documents are processed in each batch during insertion. This is useful for:
Managing memory usage with large document collections
Optimizing processing speed
Providing better progress tracking
Default value is 10 if not specified
Insert with ID
If you want to provide your own IDs for your documents, number of documents and number of IDs must be the same.
1
2
3
4
5
# Insert single text, and provide ID for itrag.insert("TEXT1",ids=["ID_FOR_TEXT1"])# Insert multiple texts, and provide IDs for themrag.insert(["TEXT1","TEXT2",...],ids=["ID_FOR_TEXT1","ID_FOR_TEXT2"])
Insert using Pipeline
The apipeline_enqueue_documents and apipeline_process_enqueue_documents functions allow you to perform incremental insertion of documents into the graph.
This is useful for scenarios where you want to process documents in the background while still allowing the main thread to continue executing.
And using a routine to process new documents.
1
2
3
4
5
rag=LightRAG(..)awaitrag.apipeline_enqueue_documents(input)# Your routine in loopawaitrag.apipeline_process_enqueue_documents(input)
Insert Multi-file Type Support
The textract supports reading file types such as TXT, DOCX, PPTX, CSV, and PDF.
custom_kg={"chunks":[{"content":"Alice and Bob are collaborating on quantum computing research.","source_id":"doc-1"}],"entities":[{"entity_name":"Alice","entity_type":"person","description":"Alice is a researcher specializing in quantum physics.","source_id":"doc-1"},{"entity_name":"Bob","entity_type":"person","description":"Bob is a mathematician.","source_id":"doc-1"},{"entity_name":"Quantum Computing","entity_type":"technology","description":"Quantum computing utilizes quantum mechanical phenomena for computation.","source_id":"doc-1"}],"relationships":[{"src_id":"Alice","tgt_id":"Bob","description":"Alice and Bob are research partners.","keywords":"collaboration research","weight":1.0,"source_id":"doc-1"},{"src_id":"Alice","tgt_id":"Quantum Computing","description":"Alice conducts research on quantum computing.","keywords":"research expertise","weight":1.0,"source_id":"doc-1"},{"src_id":"Bob","tgt_id":"Quantum Computing","description":"Bob researches quantum computing.","keywords":"research application","weight":1.0,"source_id":"doc-1"}]}rag.insert_custom_kg(custom_kg)
Citation Functionality
By providing file paths, the system ensures that sources can be traced back to their original documents.
1
2
3
4
5
6
# Define documents and their file pathsdocuments=["Document content 1","Document content 2"]file_paths=["path/to/doc1.txt","path/to/doc2.txt"]# Insert documents with file pathsrag.insert(documents,file_paths=file_paths)
Storage
Using Neo4J for Storage
For production level scenarios you will most likely want to leverage an enterprise solution
for KG storage. Running Neo4J in Docker is recommended for seamless local testing.
exportNEO4J_URI="neo4j://localhost:7687"exportNEO4J_USERNAME="neo4j"exportNEO4J_PASSWORD="password"# Setup logger for LightRAGsetup_logger("lightrag",level="INFO")# When you launch the project be sure to override the default KG: NetworkX# by specifying kg="Neo4JStorage".# Note: Default settings use NetworkX# Initialize LightRAG with Neo4J implementation.asyncdefinitialize_rag():rag=LightRAG(working_dir=WORKING_DIR,llm_model_func=gpt_4o_mini_complete,# Use gpt_4o_mini_complete LLM modelgraph_storage="Neo4JStorage",#<-----------override KG default)# Initialize database connectionsawaitrag.initialize_storages()# Initialize pipeline status for document processingawaitinitialize_pipeline_status()returnrag
see test_neo4j.py for a working example.
Using PostgreSQL for Storage
For production level scenarios you will most likely want to leverage an enterprise solution. PostgreSQL can provide a one-stop solution for you as KV store, VectorDB (pgvector) and GraphDB (apache AGE).
PostgreSQL is lightweight,the whole binary distribution including all necessary plugins can be zipped to 40MB: Ref to Windows Release as it is easy to install for Linux/Mac.
load'age';SETsearch_path=ag_catalog,"$user",public;CREATEINDEXCONCURRENTLYentity_p_idxONdickens."Entity"(id);CREATEINDEXCONCURRENTLYvertex_p_idxONdickens."_ag_label_vertex"(id);CREATEINDEXCONCURRENTLYdirected_p_idxONdickens."DIRECTED"(id);CREATEINDEXCONCURRENTLYdirected_eid_idxONdickens."DIRECTED"(end_id);CREATEINDEXCONCURRENTLYdirected_sid_idxONdickens."DIRECTED"(start_id);CREATEINDEXCONCURRENTLYdirected_seid_idxONdickens."DIRECTED"(start_id,end_id);CREATEINDEXCONCURRENTLYedge_p_idxONdickens."_ag_label_edge"(id);CREATEINDEXCONCURRENTLYedge_sid_idxONdickens."_ag_label_edge"(start_id);CREATEINDEXCONCURRENTLYedge_eid_idxONdickens."_ag_label_edge"(end_id);CREATEINDEXCONCURRENTLYedge_seid_idxONdickens."_ag_label_edge"(start_id,end_id);createINDEXCONCURRENTLYvertex_idx_node_idONdickens."_ag_label_vertex"(ag_catalog.agtype_access_operator(properties,'"node_id"'::agtype));createINDEXCONCURRENTLYentity_idx_node_idONdickens."Entity"(ag_catalog.agtype_access_operator(properties,'"node_id"'::agtype));CREATEINDEXCONCURRENTLYentity_node_id_gin_idxONdickens."Entity"usinggin(properties);ALTERTABLEdickens."DIRECTED"CLUSTERONdirected_sid_idx;-- drop if necessary
dropINDEXentity_p_idx;dropINDEXvertex_p_idx;dropINDEXdirected_p_idx;dropINDEXdirected_eid_idx;dropINDEXdirected_sid_idx;dropINDEXdirected_seid_idx;dropINDEXedge_p_idx;dropINDEXedge_sid_idx;dropINDEXedge_eid_idx;dropINDEXedge_seid_idx;dropINDEXvertex_idx_node_id;dropINDEXentity_idx_node_id;dropINDEXentity_node_id_gin_idx;
Known issue of the Apache AGE: The released versions got below issue:
You can Compile the AGE from source code and fix it.
Using Faiss for Storage
Install the required dependencies:
1
pip install faiss-cpu
You can also install faiss-gpu if you have GPU support.
Here we are using sentence-transformers but you can also use OpenAIEmbedding model with 3072 dimensions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
asyncdefembedding_func(texts:list[str])->np.ndarray:model=SentenceTransformer('all-MiniLM-L6-v2')embeddings=model.encode(texts,convert_to_numpy=True)returnembeddings# Initialize LightRAG with the LLM model function and embedding functionrag=LightRAG(working_dir=WORKING_DIR,llm_model_func=llm_model_func,embedding_func=EmbeddingFunc(embedding_dim=384,max_token_size=8192,func=embedding_func,),vector_storage="FaissVectorDBStorage",vector_db_storage_cls_kwargs={"cosine_better_than_threshold":0.3# Your desired threshold})
Delete
1
2
3
4
5
# Delete Entity: Deleting entities by their namesrag.delete_by_entity("Project Gutenberg")# Delete Document: Deleting entities and relationships associated with the document by doc idrag.delete_by_doc_id("doc_id")
Edit Entities and Relations
LightRAG now supports comprehensive knowledge graph management capabilities, allowing you to create, edit, and delete entities and relationships within your knowledge graph.
Create Entities and Relations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Create new entityentity=rag.create_entity("Google",{"description":"Google is a multinational technology company specializing in internet-related services and products.","entity_type":"company"})# Create another entityproduct=rag.create_entity("Gmail",{"description":"Gmail is an email service developed by Google.","entity_type":"product"})# Create relation between entitiesrelation=rag.create_relation("Google","Gmail",{"description":"Google develops and operates Gmail.","keywords":"develops operates service","weight":2.0})
Edit Entities and Relations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Edit an existing entityupdated_entity=rag.edit_entity("Google",{"description":"Google is a subsidiary of Alphabet Inc., founded in 1998.","entity_type":"tech_company"})# Rename an entity (with all its relationships properly migrated)renamed_entity=rag.edit_entity("Gmail",{"entity_name":"Google Mail","description":"Google Mail (formerly Gmail) is an email service."})# Edit a relation between entitiesupdated_relation=rag.edit_relation("Google","Google Mail",{"description":"Google created and maintains Google Mail service.","keywords":"creates maintains email service","weight":3.0})
All operations are available in both synchronous and asynchronous versions. The asynchronous versions have the prefix “a” (e.g., acreate_entity, aedit_relation).
Entity Operations
create_entity: Creates a new entity with specified attributes
edit_entity: Updates an existing entity’s attributes or renames it
Relation Operations
create_relation: Creates a new relation between existing entities
edit_relation: Updates an existing relation’s attributes
These operations maintain data consistency across both the graph database and vector database components, ensuring your knowledge graph remains coherent.
Data Export Functions
Overview
LightRAG allows you to export your knowledge graph data in various formats for analysis, sharing, and backup purposes. The system supports exporting entities, relations, and relationship data.
Export Functions
Basic Usage
1
2
3
4
5
# Basic CSV export (default format)rag.export_data("knowledge_graph.csv")# Specify any formatrag.export_data("output.xlsx",file_format="excel")
Different File Formats supported
1
2
3
4
5
6
7
8
9
10
11
#Export data in CSV formatrag.export_data("graph_data.csv",file_format="csv")# Export data in Excel sheetrag.export_data("graph_data.xlsx",file_format="excel")# Export data in markdown formatrag.export_data("graph_data.md",file_format="md")# Export data in Textrag.export_data("graph_data.txt",file_format="txt")
Additional Options
Include vector embeddings in the export (optional):
# Define custom merge strategy for different fieldsrag.merge_entities(source_entities=["John Smith","Dr. Smith","J. Smith"],target_entity="John Smith",merge_strategy={"description":"concatenate",# Combine all descriptions"entity_type":"keep_first",# Keep the entity type from the first entity"source_id":"join_unique"# Combine all unique source IDs})
With custom target entity data:
1
2
3
4
5
6
7
8
9
# Specify exact values for the merged entityrag.merge_entities(source_entities=["New York","NYC","Big Apple"],target_entity="New York City",target_entity_data={"entity_type":"LOCATION","description":"New York City is the most populous city in the United States.",})
Advanced usage combining both approaches:
1
2
3
4
5
6
7
8
9
10
11
12
# Merge company entities with both strategy and custom datarag.merge_entities(source_entities=["Microsoft Corp","Microsoft Corporation","MSFT"],target_entity="Microsoft",merge_strategy={"description":"concatenate",# Combine all descriptions"source_id":"join_unique"# Combine source IDs},target_entity_data={"entity_type":"ORGANIZATION",})
When merging entities:
All relationships from source entities are redirected to the target entity
Duplicate relationships are intelligently merged
Self-relationships (loops) are prevented
Source entities are removed after merging
Relationship weights and attributes are preserved
Cache
Clear Cache
You can clear the LLM response cache with different modes:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Clear all cacheawaitrag.aclear_cache()# Clear local mode cacheawaitrag.aclear_cache(modes=["local"])# Clear extraction cacheawaitrag.aclear_cache(modes=["default"])# Clear multiple modesawaitrag.aclear_cache(modes=["local","global","hybrid"])# Synchronous versionrag.clear_cache(modes=["local"])
Valid modes are:
"default": Extraction cache
"naive": Naive search cache
"local": Local search cache
"global": Global search cache
"hybrid": Hybrid search cache
"mix": Mix search cache
LightRAG init parameters
Parameters
Parameter
Type
Explanation
Default
working_dir
str
Directory where the cache will be stored
lightrag_cache+timestamp
kv_storage
str
Storage type for documents and text chunks. Supported types: JsonKVStorage,PGKVStorage,RedisKVStorage,MongoKVStorage
JsonKVStorage
vector_storage
str
Storage type for embedding vectors. Supported types: NanoVectorDBStorage,PGVectorStorage,MilvusVectorDBStorage,ChromaVectorDBStorage,FaissVectorDBStorage,MongoVectorDBStorage,QdrantVectorDBStorage
NanoVectorDBStorage
graph_storage
str
Storage type for graph edges and nodes. Supported types: NetworkXStorage,Neo4JStorage,PGGraphStorage,AGEStorage
NetworkXStorage
doc_status_storage
str
Storage type for documents process status. Supported types: JsonDocStatusStorage,PGDocStatusStorage,MongoDocStatusStorage
JsonDocStatusStorage
chunk_token_size
int
Maximum token size per chunk when splitting documents
1200
chunk_overlap_token_size
int
Overlap token size between two chunks when splitting documents
100
tiktoken_model_name
str
Model name for the Tiktoken encoder used to calculate token numbers
gpt-4o-mini
entity_extract_max_gleaning
int
Number of loops in the entity extraction process, appending history messages
Maximum batch size for embedding processes (multiple texts sent per batch)
32
embedding_func_max_async
int
Maximum number of concurrent asynchronous embedding processes
16
llm_model_func
callable
Function for LLM generation
gpt_4o_mini_complete
llm_model_name
str
LLM model name for generation
meta-llama/Llama-3.2-1B-Instruct
llm_model_max_token_size
int
Maximum token size for LLM generation (affects entity relation summaries)
32768(default value changed by env var MAX_TOKENS)
llm_model_max_async
int
Maximum number of concurrent asynchronous LLM processes
4(default value changed by env var MAX_ASYNC)
llm_model_kwargs
dict
Additional parameters for LLM generation
vector_db_storage_cls_kwargs
dict
Additional parameters for vector database, like setting the threshold for nodes and relations retrieval
cosine_better_than_threshold: 0.2(default value changed by env var COSINE_THRESHOLD)
enable_llm_cache
bool
If TRUE, stores LLM results in cache; repeated prompts return cached responses
TRUE
enable_llm_cache_for_entity_extract
bool
If TRUE, stores LLM results in cache for entity extraction; Good for beginners to debug your application
TRUE
addon_params
dict
Additional parameters, e.g., {"example_number": 1, "language": "Simplified Chinese", "entity_types": ["organization", "person", "geo", "event"], "insert_batch_size": 10}: sets example limit, output language, and batch size for document processing
example_number: all examples, language: English, insert_batch_size: 10
convert_response_to_json_func
callable
Not used
convert_response_to_json
embedding_cache_config
dict
Configuration for question-answer caching. Contains three parameters: enabled: Boolean value to enable/disable cache lookup functionality. When enabled, the system will check cached responses before generating new answers. similarity_threshold: Float value (0-1), similarity threshold. When a new question’s similarity with a cached question exceeds this threshold, the cached answer will be returned directly without calling the LLM. use_llm_check: Boolean value to enable/disable LLM similarity verification. When enabled, LLM will be used as a secondary check to verify the similarity between questions before returning cached answers.
The LightRAG Server is designed to provide Web UI and API support. For more information about LightRAG Server, please refer to LightRAG Server.
Graph Visualization
The LightRAG Server offers a comprehensive knowledge graph visualization feature. It supports various gravity layouts, node queries, subgraph filtering, and more. For more information about LightRAG Server, please refer to LightRAG Server.
To evaluate the performance of two RAG systems on high-level queries, LightRAG uses the following prompt, with the specific code available in example/batch_eval.py.
---Role---Youareanexperttaskedwithevaluatingtwoanswerstothesamequestionbasedonthreecriteria:**Comprehensiveness**,**Diversity**,and**Empowerment**.---Goal---Youwillevaluatetwoanswerstothesamequestionbasedonthreecriteria:**Comprehensiveness**,**Diversity**,and**Empowerment**.-**Comprehensiveness**:Howmuchdetaildoestheanswerprovidetocoverallaspectsanddetailsofthequestion?-**Diversity**:Howvariedandrichistheanswerinprovidingdifferentperspectivesandinsightsonthequestion?-**Empowerment**:Howwelldoestheanswerhelpthereaderunderstandandmakeinformedjudgmentsaboutthetopic?Foreachcriterion,choosethebetteranswer(eitherAnswer1orAnswer2)andexplainwhy.Then,selectanoverallwinnerbasedonthesethreecategories.Hereisthequestion:{query}Herearethetwoanswers:**Answer1:**{answer1}**Answer2:**{answer2}Evaluatebothanswersusingthethreecriterialistedaboveandprovidedetailedexplanationsforeachcriterion.OutputyourevaluationinthefollowingJSONformat:{{"Comprehensiveness":{{"Winner":"[Answer 1 or Answer 2]","Explanation":"[Provide explanation here]"}},"Empowerment":{{"Winner":"[Answer 1 or Answer 2]","Explanation":"[Provide explanation here]"}},"Overall Winner":{{"Winner":"[Answer 1 or Answer 2]","Explanation":"[Summarize why this answer is the overall winner based on the three criteria]"}}}}
Overall Performance Table
Agriculture
CS
Legal
Mix
NaiveRAG
LightRAG
NaiveRAG
LightRAG
NaiveRAG
LightRAG
NaiveRAG
LightRAG
Comprehensiveness
32.4%
67.6%
38.4%
61.6%
16.4%
83.6%
38.8%
61.2%
Diversity
23.6%
76.4%
38.0%
62.0%
13.6%
86.4%
32.4%
67.6%
Empowerment
32.4%
67.6%
38.8%
61.2%
16.4%
83.6%
42.8%
57.2%
Overall
32.4%
67.6%
38.8%
61.2%
15.2%
84.8%
40.0%
60.0%
RQ-RAG
LightRAG
RQ-RAG
LightRAG
RQ-RAG
LightRAG
RQ-RAG
LightRAG
Comprehensiveness
31.6%
68.4%
38.8%
61.2%
15.2%
84.8%
39.2%
60.8%
Diversity
29.2%
70.8%
39.2%
60.8%
11.6%
88.4%
30.8%
69.2%
Empowerment
31.6%
68.4%
36.4%
63.6%
15.2%
84.8%
42.4%
57.6%
Overall
32.4%
67.6%
38.0%
62.0%
14.4%
85.6%
40.0%
60.0%
HyDE
LightRAG
HyDE
LightRAG
HyDE
LightRAG
HyDE
LightRAG
Comprehensiveness
26.0%
74.0%
41.6%
58.4%
26.8%
73.2%
40.4%
59.6%
Diversity
24.0%
76.0%
38.8%
61.2%
20.0%
80.0%
32.4%
67.6%
Empowerment
25.2%
74.8%
40.8%
59.2%
26.0%
74.0%
46.0%
54.0%
Overall
24.8%
75.2%
41.6%
58.4%
26.4%
73.6%
42.4%
57.6%
GraphRAG
LightRAG
GraphRAG
LightRAG
GraphRAG
LightRAG
GraphRAG
LightRAG
Comprehensiveness
45.6%
54.4%
48.4%
51.6%
48.4%
51.6%
50.4%
49.6%
Diversity
22.8%
77.2%
40.8%
59.2%
26.4%
73.6%
36.0%
64.0%
Empowerment
41.2%
58.8%
45.2%
54.8%
43.6%
56.4%
50.8%
49.2%
Overall
45.2%
54.8%
48.0%
52.0%
47.2%
52.8%
50.4%
49.6%
Reproduce
All the code can be found in the ./reproduce directory.
Step-0 Extract Unique Contexts
First, we need to extract unique contexts in the datasets.
defextract_unique_contexts(input_directory,output_directory):os.makedirs(output_directory,exist_ok=True)jsonl_files=glob.glob(os.path.join(input_directory,'*.jsonl'))print(f"Found {len(jsonl_files)} JSONL files.")forfile_pathinjsonl_files:filename=os.path.basename(file_path)name,ext=os.path.splitext(filename)output_filename=f"{name}_unique_contexts.json"output_path=os.path.join(output_directory,output_filename)unique_contexts_dict={}print(f"Processing file: {filename}")try:withopen(file_path,'r',encoding='utf-8')asinfile:forline_number,lineinenumerate(infile,start=1):line=line.strip()ifnotline:continuetry:json_obj=json.loads(line)context=json_obj.get('context')ifcontextandcontextnotinunique_contexts_dict:unique_contexts_dict[context]=Noneexceptjson.JSONDecodeErrorase:print(f"JSON decoding error in file {filename} at line {line_number}: {e}")exceptFileNotFoundError:print(f"File not found: {filename}")continueexceptExceptionase:print(f"An error occurred while processing file {filename}: {e}")continueunique_contexts_list=list(unique_contexts_dict.keys())print(f"There are {len(unique_contexts_list)} unique `context` entries in the file {filename}.")try:withopen(output_path,'w',encoding='utf-8')asoutfile:json.dump(unique_contexts_list,outfile,ensure_ascii=False,indent=4)print(f"Unique `context` entries have been saved to: {output_filename}")exceptExceptionase:print(f"An error occurred while saving to the file {output_filename}: {e}")print("All files have been processed.")
Step-1 Insert Contexts
For the extracted contexts, we insert them into the LightRAG system.
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
definsert_text(rag,file_path):withopen(file_path,mode='r')asf:unique_contexts=json.load(f)retries=0max_retries=3whileretries<max_retries:try:rag.insert(unique_contexts)breakexceptExceptionase:retries+=1print(f"Insertion failed, retrying ({retries}/{max_retries}), error: {e}")time.sleep(10)ifretries==max_retries:print("Insertion failed after exceeding the maximum number of retries")
Step-2 Generate Queries
We extract tokens from the first and the second half of each context in the dataset, then combine them as dataset descriptions to generate queries.