Home
Login

LightRAG是一个简单快速的检索增强生成框架,支持多种查询模式和知识图谱构建

MITPython 17.7kHKUDS Last Updated: 2025-06-19

LightRAG - 简单快速的检索增强生成框架

项目概述

LightRAG是一个"简单快速的检索增强生成"框架,由香港大学数据科学学院(HKUDS)开发。该项目旨在为开发者提供一套完整的RAG(Retrieval-Augmented Generation)解决方案,支持文档索引、知识图谱构建和智能问答功能。

核心特性

🔍 多种检索模式

LightRAG支持五种不同的检索模式,满足不同场景需求:

  • naive模式: 基础搜索,不使用高级技术
  • local模式: 专注于上下文相关信息的检索
  • global模式: 利用全局知识进行检索
  • hybrid模式: 结合本地和全局检索方法
  • mix模式: 集成知识图谱和向量检索,提供最全面的答案

🎯 知识图谱构建

  • 自动从文档中提取实体和关系
  • 支持知识图谱的可视化展示
  • 提供实体和关系的增删改查功能
  • 支持实体合并和去重

🚀 灵活的模型支持

  • OpenAI模型: 支持GPT-4等OpenAI系列模型
  • Hugging Face模型: 支持本地部署的开源模型
  • Ollama模型: 支持本地运行的量化模型
  • LlamaIndex集成: 通过LlamaIndex支持更多模型提供商

📊 多样化存储后端

  • 向量数据库: 支持Faiss、PGVector等
  • 图数据库: 支持Neo4j、PostgreSQL+Apache AGE
  • 默认存储: 内置NetworkX图存储

安装方式

从PyPI安装

pip install "lightrag-hku[api]"

从源码安装

# 创建Python虚拟环境(如有必要)
# 以可编辑模式安装,包含API支持
pip install -e ".[api]"

基础使用示例

初始化和查询

import os
import asyncio
from lightrag import LightRAG, QueryParam
from lightrag.llm.openai import gpt_4o_mini_complete, openai_embed
from lightrag.kg.shared_storage import initialize_pipeline_status
from lightrag.utils import setup_logger

setup_logger("lightrag", level="INFO")

async def initialize_rag():
    rag = LightRAG(
        working_dir="your/path",
        embedding_func=openai_embed,
        llm_model_func=gpt_4o_mini_complete
    )
    await rag.initialize_storages()
    await initialize_pipeline_status()
    return rag

def main():

    rag = asyncio.run(initialize_rag())
    

    rag.insert("Your text")
    

    result = rag.query(
        "What are the top themes in this story?",
        param=QueryParam(mode="mix")
    )
    print(result)

if __name__ == "__main__":
    main()

高级功能

对话历史支持

# Create conversation history
conversation_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 history
query_param = QueryParam(
    mode="mix",  # or any other mode: "local", "global", "hybrid"
    conversation_history=conversation_history,  # Add the conversation history
    history_turns=3  # Number of recent conversation turns to consider
)

# Make a query that takes into account the conversation history
response = rag.query(
    "What causes this change in his character?",
    param=query_param
)

知识图谱管理

# Create new entity
entity = rag.create_entity("Google", {
    "description": "Google is a multinational technology company specializing in internet-related services and products.",
    "entity_type": "company"
})

# Create another entity
product = rag.create_entity("Gmail", {
    "description": "Gmail is an email service developed by Google.",
    "entity_type": "product"
})

# Create relation between entities
relation = rag.create_relation("Google", "Gmail", {
    "description": "Google develops and operates Gmail.",
    "keywords": "develops operates service",
    "weight": 2.0
})

LightRAG Server

Web UI功能

LightRAG Server提供了完整的Web界面,包括:

  • 文档索引管理
  • 知识图谱可视化
  • 简单的RAG查询界面
  • 支持重力布局、节点查询、子图过滤等功能

API接口

  • 提供RESTful API接口
  • 兼容Ollama API格式
  • 支持AI聊天机器人集成(如Open WebUI)

配置参数

核心参数

  • working_dir: 工作目录路径
  • embedding_func: 嵌入函数
  • llm_model_func: 大语言模型函数
  • vector_storage: 向量存储类型
  • graph_storage: 图存储类型

性能调优参数

  • embedding_batch_size: 嵌入批处理大小(默认32)
  • embedding_func_max_async: 最大并发嵌入进程数(默认16)
  • llm_model_max_async: 最大并发LLM进程数(默认4)
  • enable_llm_cache: 是否启用LLM缓存(默认True)

数据导出和备份

支持多种格式的数据导出:

#Export data in CSV format
rag.export_data("graph_data.csv", file_format="csv")

# Export data in Excel sheet
rag.export_data("graph_data.xlsx", file_format="excel")

# Export data in markdown format
rag.export_data("graph_data.md", file_format="md")

# Export data in Text
rag.export_data("graph_data.txt", file_format="txt")

Token使用跟踪

内置Token消耗监控工具:

from lightrag.utils import TokenTracker

# Create TokenTracker instance
token_tracker = TokenTracker()

# Method 1: Using context manager (Recommended)
# Suitable for scenarios requiring automatic token usage tracking
with token_tracker:
    result1 = await llm_model_func("your question 1")
    result2 = await llm_model_func("your question 2")

# Method 2: Manually adding token usage records
# Suitable for scenarios requiring more granular control over token statistics
token_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())

适用场景

企业知识管理

  • 内部文档检索和问答
  • 知识库构建和维护
  • 技术文档智能助手

学术研究

  • 文献检索和分析
  • 知识图谱构建研究
  • RAG系统性能评估

内容创作

  • 写作辅助和素材检索
  • 多文档内容整合
  • 智能内容推荐

项目优势

  1. 易于集成: 提供简单的Python API和REST API
  2. 高度可定制: 支持多种模型和存储后端
  3. 性能优化: 支持批处理和异步处理
  4. 可视化: 内置知识图谱可视化功能
  5. 企业级: 支持PostgreSQL等企业级数据库

总结

LightRAG是一个功能全面、易于使用的RAG框架,特别适合需要构建智能问答系统和知识管理平台的场景。其灵活的架构设计和丰富的功能特性,使其成为RAG领域的优秀开源解决方案。