2024-10-15 12:55:05 -07:00
|
|
|
import os
|
|
|
|
import asyncio
|
2025-04-21 00:09:05 +08:00
|
|
|
import inspect
|
|
|
|
import logging
|
|
|
|
import logging.config
|
2024-10-15 12:55:05 -07:00
|
|
|
from lightrag import LightRAG, QueryParam
|
2025-04-21 00:09:05 +08:00
|
|
|
from lightrag.llm.openai import openai_complete_if_cache
|
|
|
|
from lightrag.llm.ollama import ollama_embed
|
|
|
|
from lightrag.utils import EmbeddingFunc, logger, set_verbose_debug
|
2024-10-15 12:55:05 -07:00
|
|
|
import numpy as np
|
2025-03-03 18:33:42 +08:00
|
|
|
from lightrag.kg.shared_storage import initialize_pipeline_status
|
2024-10-15 12:55:05 -07:00
|
|
|
|
|
|
|
WORKING_DIR = "./dickens"
|
2024-10-19 09:43:17 +05:30
|
|
|
|
2025-04-21 00:09:05 +08:00
|
|
|
|
|
|
|
def configure_logging():
|
|
|
|
"""Configure logging for the application"""
|
|
|
|
|
|
|
|
# Reset any existing handlers to ensure clean configuration
|
|
|
|
for logger_name in ["uvicorn", "uvicorn.access", "uvicorn.error", "lightrag"]:
|
|
|
|
logger_instance = logging.getLogger(logger_name)
|
|
|
|
logger_instance.handlers = []
|
|
|
|
logger_instance.filters = []
|
|
|
|
|
|
|
|
# Get log directory path from environment variable or use current directory
|
|
|
|
log_dir = os.getenv("LOG_DIR", os.getcwd())
|
|
|
|
log_file_path = os.path.abspath(
|
|
|
|
os.path.join(log_dir, "lightrag_compatible_demo.log")
|
|
|
|
)
|
|
|
|
|
|
|
|
print(f"\nLightRAG compatible demo log file: {log_file_path}\n")
|
|
|
|
os.makedirs(os.path.dirname(log_dir), exist_ok=True)
|
|
|
|
|
|
|
|
# Get log file max size and backup count from environment variables
|
|
|
|
log_max_bytes = int(os.getenv("LOG_MAX_BYTES", 10485760)) # Default 10MB
|
|
|
|
log_backup_count = int(os.getenv("LOG_BACKUP_COUNT", 5)) # Default 5 backups
|
|
|
|
|
|
|
|
logging.config.dictConfig(
|
|
|
|
{
|
|
|
|
"version": 1,
|
|
|
|
"disable_existing_loggers": False,
|
|
|
|
"formatters": {
|
|
|
|
"default": {
|
|
|
|
"format": "%(levelname)s: %(message)s",
|
|
|
|
},
|
|
|
|
"detailed": {
|
|
|
|
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
"handlers": {
|
|
|
|
"console": {
|
|
|
|
"formatter": "default",
|
|
|
|
"class": "logging.StreamHandler",
|
|
|
|
"stream": "ext://sys.stderr",
|
|
|
|
},
|
|
|
|
"file": {
|
|
|
|
"formatter": "detailed",
|
|
|
|
"class": "logging.handlers.RotatingFileHandler",
|
|
|
|
"filename": log_file_path,
|
|
|
|
"maxBytes": log_max_bytes,
|
|
|
|
"backupCount": log_backup_count,
|
|
|
|
"encoding": "utf-8",
|
|
|
|
},
|
|
|
|
},
|
|
|
|
"loggers": {
|
|
|
|
"lightrag": {
|
|
|
|
"handlers": ["console", "file"],
|
|
|
|
"level": "INFO",
|
|
|
|
"propagate": False,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
# Set the logger level to INFO
|
|
|
|
logger.setLevel(logging.INFO)
|
|
|
|
# Enable verbose debug if needed
|
|
|
|
set_verbose_debug(os.getenv("VERBOSE_DEBUG", "false").lower() == "true")
|
|
|
|
|
|
|
|
|
2024-10-15 12:55:05 -07:00
|
|
|
if not os.path.exists(WORKING_DIR):
|
|
|
|
os.mkdir(WORKING_DIR)
|
|
|
|
|
2024-10-19 09:43:17 +05:30
|
|
|
|
2024-10-15 12:55:05 -07:00
|
|
|
async def llm_model_func(
|
2024-12-05 14:11:43 +08:00
|
|
|
prompt, system_prompt=None, history_messages=[], keyword_extraction=False, **kwargs
|
2024-10-15 12:55:05 -07:00
|
|
|
) -> str:
|
|
|
|
return await openai_complete_if_cache(
|
2025-04-21 00:09:05 +08:00
|
|
|
"deepseek-chat",
|
2024-10-15 12:55:05 -07:00
|
|
|
prompt,
|
|
|
|
system_prompt=system_prompt,
|
|
|
|
history_messages=history_messages,
|
2025-04-21 00:09:05 +08:00
|
|
|
api_key=os.getenv("OPENAI_API_KEY"),
|
|
|
|
base_url="https://api.deepseek.com",
|
2024-10-19 09:43:17 +05:30
|
|
|
**kwargs,
|
2024-10-15 12:55:05 -07:00
|
|
|
)
|
|
|
|
|
2024-10-19 09:43:17 +05:30
|
|
|
|
2024-10-15 12:55:05 -07:00
|
|
|
async def embedding_func(texts: list[str]) -> np.ndarray:
|
2025-04-21 00:09:05 +08:00
|
|
|
return await ollama_embed(
|
|
|
|
texts=texts,
|
|
|
|
embed_model="bge-m3:latest",
|
2025-05-13 00:08:21 +08:00
|
|
|
host="http://localhost:11434",
|
2024-10-15 12:55:05 -07:00
|
|
|
)
|
|
|
|
|
2024-10-19 09:43:17 +05:30
|
|
|
|
2024-10-24 00:58:52 +08:00
|
|
|
async def get_embedding_dim():
|
|
|
|
test_text = ["This is a test sentence."]
|
|
|
|
embedding = await embedding_func(test_text)
|
|
|
|
embedding_dim = embedding.shape[1]
|
|
|
|
return embedding_dim
|
|
|
|
|
|
|
|
|
2024-10-15 12:55:05 -07:00
|
|
|
# function test
|
|
|
|
async def test_funcs():
|
|
|
|
result = await llm_model_func("How are you?")
|
|
|
|
print("llm_model_func: ", result)
|
|
|
|
|
|
|
|
result = await embedding_func(["How are you?"])
|
|
|
|
print("embedding_func: ", result)
|
|
|
|
|
2024-10-19 09:43:17 +05:30
|
|
|
|
2024-10-24 00:58:52 +08:00
|
|
|
# asyncio.run(test_funcs())
|
|
|
|
|
2025-03-03 18:40:03 +08:00
|
|
|
|
2025-04-21 00:09:05 +08:00
|
|
|
async def print_stream(stream):
|
|
|
|
async for chunk in stream:
|
|
|
|
if chunk:
|
|
|
|
print(chunk, end="", flush=True)
|
|
|
|
|
|
|
|
|
2025-03-03 18:33:42 +08:00
|
|
|
async def initialize_rag():
|
|
|
|
embedding_dimension = await get_embedding_dim()
|
|
|
|
print(f"Detected embedding dimension: {embedding_dimension}")
|
|
|
|
|
|
|
|
rag = LightRAG(
|
|
|
|
working_dir=WORKING_DIR,
|
|
|
|
llm_model_func=llm_model_func,
|
|
|
|
embedding_func=EmbeddingFunc(
|
|
|
|
embedding_dim=embedding_dimension,
|
|
|
|
max_token_size=8192,
|
|
|
|
func=embedding_func,
|
|
|
|
),
|
|
|
|
)
|
|
|
|
|
|
|
|
await rag.initialize_storages()
|
|
|
|
await initialize_pipeline_status()
|
2024-10-25 13:32:25 +05:30
|
|
|
|
2025-03-03 18:33:42 +08:00
|
|
|
return rag
|
2025-03-03 18:40:03 +08:00
|
|
|
|
|
|
|
|
2024-10-24 00:58:52 +08:00
|
|
|
async def main():
|
|
|
|
try:
|
2025-03-03 18:33:42 +08:00
|
|
|
# Initialize RAG instance
|
2025-03-04 12:25:07 +08:00
|
|
|
rag = await initialize_rag()
|
2024-10-15 12:55:05 -07:00
|
|
|
|
2024-10-24 00:58:52 +08:00
|
|
|
with open("./book.txt", "r", encoding="utf-8") as f:
|
2024-10-29 23:29:47 +08:00
|
|
|
await rag.ainsert(f.read())
|
2024-10-15 12:55:05 -07:00
|
|
|
|
2024-10-24 00:58:52 +08:00
|
|
|
# Perform naive search
|
2025-04-21 00:09:05 +08:00
|
|
|
print("\n=====================")
|
|
|
|
print("Query mode: naive")
|
|
|
|
print("=====================")
|
|
|
|
resp = await rag.aquery(
|
|
|
|
"What are the top themes in this story?",
|
|
|
|
param=QueryParam(mode="naive", stream=True),
|
2024-10-24 00:58:52 +08:00
|
|
|
)
|
2025-04-21 00:09:05 +08:00
|
|
|
if inspect.isasyncgen(resp):
|
|
|
|
await print_stream(resp)
|
|
|
|
else:
|
|
|
|
print(resp)
|
2024-10-15 12:55:05 -07:00
|
|
|
|
2024-10-24 00:58:52 +08:00
|
|
|
# Perform local search
|
2025-04-21 00:09:05 +08:00
|
|
|
print("\n=====================")
|
|
|
|
print("Query mode: local")
|
|
|
|
print("=====================")
|
|
|
|
resp = await rag.aquery(
|
|
|
|
"What are the top themes in this story?",
|
|
|
|
param=QueryParam(mode="local", stream=True),
|
2024-10-24 00:58:52 +08:00
|
|
|
)
|
2025-04-21 00:09:05 +08:00
|
|
|
if inspect.isasyncgen(resp):
|
|
|
|
await print_stream(resp)
|
|
|
|
else:
|
|
|
|
print(resp)
|
2024-10-15 12:55:05 -07:00
|
|
|
|
2024-10-24 00:58:52 +08:00
|
|
|
# Perform global search
|
2025-04-21 00:09:05 +08:00
|
|
|
print("\n=====================")
|
|
|
|
print("Query mode: global")
|
|
|
|
print("=====================")
|
|
|
|
resp = await rag.aquery(
|
|
|
|
"What are the top themes in this story?",
|
|
|
|
param=QueryParam(mode="global", stream=True),
|
2024-10-24 00:58:52 +08:00
|
|
|
)
|
2025-04-21 00:09:05 +08:00
|
|
|
if inspect.isasyncgen(resp):
|
|
|
|
await print_stream(resp)
|
|
|
|
else:
|
|
|
|
print(resp)
|
2024-10-15 12:55:05 -07:00
|
|
|
|
2024-10-24 00:58:52 +08:00
|
|
|
# Perform hybrid search
|
2025-04-21 00:09:05 +08:00
|
|
|
print("\n=====================")
|
|
|
|
print("Query mode: hybrid")
|
|
|
|
print("=====================")
|
|
|
|
resp = await rag.aquery(
|
|
|
|
"What are the top themes in this story?",
|
|
|
|
param=QueryParam(mode="hybrid", stream=True),
|
2024-10-24 00:58:52 +08:00
|
|
|
)
|
2025-04-21 00:09:05 +08:00
|
|
|
if inspect.isasyncgen(resp):
|
|
|
|
await print_stream(resp)
|
|
|
|
else:
|
|
|
|
print(resp)
|
|
|
|
|
2024-10-24 00:58:52 +08:00
|
|
|
except Exception as e:
|
|
|
|
print(f"An error occurred: {e}")
|
2025-04-21 00:09:05 +08:00
|
|
|
finally:
|
|
|
|
if rag:
|
|
|
|
await rag.finalize_storages()
|
2024-10-15 12:55:05 -07:00
|
|
|
|
2024-10-25 13:32:25 +05:30
|
|
|
|
2024-10-24 00:58:52 +08:00
|
|
|
if __name__ == "__main__":
|
2025-04-21 00:09:05 +08:00
|
|
|
# Configure logging before running the main function
|
|
|
|
configure_logging()
|
2024-10-25 13:32:25 +05:30
|
|
|
asyncio.run(main())
|
2025-04-21 00:09:05 +08:00
|
|
|
print("\nDone!")
|