LightRAG는 홍콩대학교 데이터과학대학(HKUDS)에서 개발한 "간단하고 빠른 검색 증강 생성" 프레임워크입니다. 이 프로젝트는 개발자에게 문서 색인, 지식 그래프 구축 및 지능형 질의응답 기능을 지원하는 완벽한 RAG(Retrieval-Augmented Generation) 솔루션을 제공하는 것을 목표로 합니다.
LightRAG는 다양한 시나리오 요구 사항을 충족하기 위해 다섯 가지의 서로 다른 검색 모드를 지원합니다.
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 인터페이스를 제공합니다.
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")
내장된 토큰 소비 모니터링 도구:
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())
LightRAG는 포괄적인 기능과 사용하기 쉬운 RAG 프레임워크로, 특히 지능형 질의응답 시스템 및 지식 관리 플랫폼을 구축해야 하는 시나리오에 적합합니다. 유연한 아키텍처 설계와 풍부한 기능은 RAG 분야에서 뛰어난 오픈 소스 솔루션으로 만듭니다.