Skip to content

Commit e7ac7da

Browse files
authored
Merge branch 'HKUDS:main' into main
2 parents 9724b59 + 725284e commit e7ac7da

8 files changed

Lines changed: 284 additions & 18 deletions

File tree

examples/graph_visual_with_html.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
# Convert NetworkX graph to Pyvis network
1212
net.from_nx(G)
1313

14+
1415
# Add colors and title to nodes
1516
for node in net.nodes:
1617
node["color"] = "#{:06x}".format(random.randint(0, 0xFFFFFF))
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
from fastapi import FastAPI, HTTPException, File, UploadFile
2+
from pydantic import BaseModel
3+
import os
4+
from lightrag import LightRAG, QueryParam
5+
from lightrag.llm import ollama_embedding, ollama_model_complete
6+
from lightrag.utils import EmbeddingFunc
7+
from typing import Optional
8+
import asyncio
9+
import nest_asyncio
10+
import aiofiles
11+
12+
# Apply nest_asyncio to solve event loop issues
13+
nest_asyncio.apply()
14+
15+
DEFAULT_RAG_DIR = "index_default"
16+
app = FastAPI(title="LightRAG API", description="API for RAG operations")
17+
18+
DEFAULT_INPUT_FILE = "book.txt"
19+
INPUT_FILE = os.environ.get("INPUT_FILE", f"{DEFAULT_INPUT_FILE}")
20+
print(f"INPUT_FILE: {INPUT_FILE}")
21+
22+
# Configure working directory
23+
WORKING_DIR = os.environ.get("RAG_DIR", f"{DEFAULT_RAG_DIR}")
24+
print(f"WORKING_DIR: {WORKING_DIR}")
25+
26+
27+
if not os.path.exists(WORKING_DIR):
28+
os.mkdir(WORKING_DIR)
29+
30+
31+
rag = LightRAG(
32+
working_dir=WORKING_DIR,
33+
llm_model_func=ollama_model_complete,
34+
llm_model_name="gemma2:9b",
35+
llm_model_max_async=4,
36+
llm_model_max_token_size=8192,
37+
llm_model_kwargs={"host": "http://localhost:11434", "options": {"num_ctx": 8192}},
38+
embedding_func=EmbeddingFunc(
39+
embedding_dim=768,
40+
max_token_size=8192,
41+
func=lambda texts: ollama_embedding(
42+
texts, embed_model="nomic-embed-text", host="http://localhost:11434"
43+
),
44+
),
45+
)
46+
47+
48+
# Data models
49+
class QueryRequest(BaseModel):
50+
query: str
51+
mode: str = "hybrid"
52+
only_need_context: bool = False
53+
54+
55+
class InsertRequest(BaseModel):
56+
text: str
57+
58+
59+
class Response(BaseModel):
60+
status: str
61+
data: Optional[str] = None
62+
message: Optional[str] = None
63+
64+
65+
# API routes
66+
@app.post("/query", response_model=Response)
67+
async def query_endpoint(request: QueryRequest):
68+
try:
69+
loop = asyncio.get_event_loop()
70+
result = await loop.run_in_executor(
71+
None,
72+
lambda: rag.query(
73+
request.query,
74+
param=QueryParam(
75+
mode=request.mode, only_need_context=request.only_need_context
76+
),
77+
),
78+
)
79+
return Response(status="success", data=result)
80+
except Exception as e:
81+
raise HTTPException(status_code=500, detail=str(e))
82+
83+
84+
# insert by text
85+
@app.post("/insert", response_model=Response)
86+
async def insert_endpoint(request: InsertRequest):
87+
try:
88+
loop = asyncio.get_event_loop()
89+
await loop.run_in_executor(None, lambda: rag.insert(request.text))
90+
return Response(status="success", message="Text inserted successfully")
91+
except Exception as e:
92+
raise HTTPException(status_code=500, detail=str(e))
93+
94+
95+
# insert by file in payload
96+
@app.post("/insert_file", response_model=Response)
97+
async def insert_file(file: UploadFile = File(...)):
98+
try:
99+
file_content = await file.read()
100+
# Read file content
101+
try:
102+
content = file_content.decode("utf-8")
103+
except UnicodeDecodeError:
104+
# If UTF-8 decoding fails, try other encodings
105+
content = file_content.decode("gbk")
106+
# Insert file content
107+
loop = asyncio.get_event_loop()
108+
await loop.run_in_executor(None, lambda: rag.insert(content))
109+
110+
return Response(
111+
status="success",
112+
message=f"File content from {file.filename} inserted successfully",
113+
)
114+
except Exception as e:
115+
raise HTTPException(status_code=500, detail=str(e))
116+
117+
118+
# insert by local default file
119+
@app.post("/insert_default_file", response_model=Response)
120+
@app.get("/insert_default_file", response_model=Response)
121+
async def insert_default_file():
122+
try:
123+
# Read file content from book.txt
124+
async with aiofiles.open(INPUT_FILE, "r", encoding="utf-8") as file:
125+
content = await file.read()
126+
print(f"read input file {INPUT_FILE} successfully")
127+
# Insert file content
128+
loop = asyncio.get_event_loop()
129+
await loop.run_in_executor(None, lambda: rag.insert(content))
130+
131+
return Response(
132+
status="success",
133+
message=f"File content from {INPUT_FILE} inserted successfully",
134+
)
135+
except Exception as e:
136+
raise HTTPException(status_code=500, detail=str(e))
137+
138+
139+
@app.get("/health")
140+
async def health_check():
141+
return {"status": "healthy"}
142+
143+
144+
if __name__ == "__main__":
145+
import uvicorn
146+
147+
uvicorn.run(app, host="0.0.0.0", port=8020)
148+
149+
# Usage example
150+
# To run the server, use the following command in your terminal:
151+
# python lightrag_api_openai_compatible_demo.py
152+
153+
# Example requests:
154+
# 1. Query:
155+
# curl -X POST "http://127.0.0.1:8020/query" -H "Content-Type: application/json" -d '{"query": "your query here", "mode": "hybrid"}'
156+
157+
# 2. Insert text:
158+
# curl -X POST "http://127.0.0.1:8020/insert" -H "Content-Type: application/json" -d '{"text": "your text here"}'
159+
160+
# 3. Insert file:
161+
# curl -X POST "http://127.0.0.1:8020/insert_file" -H "Content-Type: application/json" -d '{"file_path": "path/to/your/file.txt"}'
162+
163+
# 4. Health check:
164+
# curl -X GET "http://127.0.0.1:8020/health"
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import os
2+
import inspect
3+
from lightrag import LightRAG
4+
from lightrag.llm import openai_complete, openai_embedding
5+
from lightrag.utils import EmbeddingFunc
6+
from lightrag.lightrag import always_get_an_event_loop
7+
from lightrag import QueryParam
8+
9+
# WorkingDir
10+
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
11+
WORKING_DIR = os.path.join(ROOT_DIR, "dickens")
12+
if not os.path.exists(WORKING_DIR):
13+
os.mkdir(WORKING_DIR)
14+
print(f"WorkingDir: {WORKING_DIR}")
15+
16+
api_key = "empty"
17+
rag = LightRAG(
18+
working_dir=WORKING_DIR,
19+
llm_model_func=openai_complete,
20+
llm_model_name="qwen2.5-14b-instruct@4bit",
21+
llm_model_max_async=4,
22+
llm_model_max_token_size=32768,
23+
llm_model_kwargs={"base_url": "http://127.0.0.1:1234/v1", "api_key": api_key},
24+
embedding_func=EmbeddingFunc(
25+
embedding_dim=1024,
26+
max_token_size=8192,
27+
func=lambda texts: openai_embedding(
28+
texts=texts,
29+
model="text-embedding-bge-m3",
30+
base_url="http://127.0.0.1:1234/v1",
31+
api_key=api_key,
32+
),
33+
),
34+
)
35+
36+
with open("./book.txt", "r", encoding="utf-8") as f:
37+
rag.insert(f.read())
38+
39+
resp = rag.query(
40+
"What are the top themes in this story?",
41+
param=QueryParam(mode="hybrid", stream=True),
42+
)
43+
44+
45+
async def print_stream(stream):
46+
async for chunk in stream:
47+
if chunk:
48+
print(chunk, end="", flush=True)
49+
50+
51+
loop = always_get_an_event_loop()
52+
if inspect.isasyncgen(resp):
53+
loop.run_until_complete(print_stream(resp))
54+
else:
55+
print(resp)

lightrag/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from .lightrag import LightRAG as LightRAG, QueryParam as QueryParam
22

3-
__version__ = "1.0.4"
3+
__version__ = "1.0.5"
44
__author__ = "Zirui Guo"
55
__url__ = "https://github.com/HKUDS/LightRAG"

lightrag/lightrag.py

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,21 +40,37 @@
4040
NetworkXStorage,
4141
)
4242

43-
from .kg.neo4j_impl import Neo4JStorage
44-
45-
from .kg.oracle_impl import OracleKVStorage, OracleGraphStorage, OracleVectorDBStorage
46-
47-
from .kg.milvus_impl import MilvusVectorDBStorge
48-
49-
from .kg.mongo_impl import MongoKVStorage
50-
5143
# future KG integrations
5244

5345
# from .kg.ArangoDB_impl import (
5446
# GraphStorage as ArangoDBStorage
5547
# )
5648

5749

50+
def lazy_external_import(module_name: str, class_name: str):
51+
"""Lazily import an external module and return a class from it."""
52+
53+
def import_class():
54+
import importlib
55+
56+
# Import the module using importlib
57+
module = importlib.import_module(module_name)
58+
59+
# Get the class from the module
60+
return getattr(module, class_name)
61+
62+
# Return the import_class function itself, not its result
63+
return import_class
64+
65+
66+
Neo4JStorage = lazy_external_import(".kg.neo4j_impl", "Neo4JStorage")
67+
OracleKVStorage = lazy_external_import(".kg.oracle_impl", "OracleKVStorage")
68+
OracleGraphStorage = lazy_external_import(".kg.oracle_impl", "OracleGraphStorage")
69+
OracleVectorDBStorage = lazy_external_import(".kg.oracle_impl", "OracleVectorDBStorage")
70+
MilvusVectorDBStorge = lazy_external_import(".kg.milvus_impl", "MilvusVectorDBStorge")
71+
MongoKVStorage = lazy_external_import(".kg.mongo_impl", "MongoKVStorage")
72+
73+
5874
def always_get_an_event_loop() -> asyncio.AbstractEventLoop:
5975
"""
6076
Ensure that there is always an event loop available.
@@ -68,7 +84,7 @@ def always_get_an_event_loop() -> asyncio.AbstractEventLoop:
6884
try:
6985
# Try to get the current event loop
7086
current_loop = asyncio.get_event_loop()
71-
if current_loop._closed:
87+
if current_loop.is_closed():
7288
raise RuntimeError("Event loop is closed.")
7389
return current_loop
7490

lightrag/llm.py

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,11 +76,24 @@ async def openai_complete_if_cache(
7676
response = await openai_async_client.chat.completions.create(
7777
model=model, messages=messages, **kwargs
7878
)
79-
content = response.choices[0].message.content
80-
if r"\u" in content:
81-
content = content.encode("utf-8").decode("unicode_escape")
8279

83-
return content
80+
if hasattr(response, "__aiter__"):
81+
82+
async def inner():
83+
async for chunk in response:
84+
content = chunk.choices[0].delta.content
85+
if content is None:
86+
continue
87+
if r"\u" in content:
88+
content = content.encode("utf-8").decode("unicode_escape")
89+
yield content
90+
91+
return inner()
92+
else:
93+
content = response.choices[0].message.content
94+
if r"\u" in content:
95+
content = content.encode("utf-8").decode("unicode_escape")
96+
return content
8497

8598

8699
@retry(
@@ -306,7 +319,7 @@ async def ollama_model_if_cache(
306319

307320
response = await ollama_client.chat(model=model, messages=messages, **kwargs)
308321
if stream:
309-
""" cannot cache stream response """
322+
"""cannot cache stream response"""
310323

311324
async def inner():
312325
async for chunk in response:
@@ -447,6 +460,22 @@ class GPTKeywordExtractionFormat(BaseModel):
447460
low_level_keywords: List[str]
448461

449462

463+
async def openai_complete(
464+
prompt, system_prompt=None, history_messages=[], keyword_extraction=False, **kwargs
465+
) -> Union[str, AsyncIterator[str]]:
466+
keyword_extraction = kwargs.pop("keyword_extraction", None)
467+
if keyword_extraction:
468+
kwargs["response_format"] = "json"
469+
model_name = kwargs["hashing_kv"].global_config["llm_model_name"]
470+
return await openai_complete_if_cache(
471+
model_name,
472+
prompt,
473+
system_prompt=system_prompt,
474+
history_messages=history_messages,
475+
**kwargs,
476+
)
477+
478+
450479
async def gpt_4o_complete(
451480
prompt, system_prompt=None, history_messages=[], keyword_extraction=False, **kwargs
452481
) -> str:
@@ -890,6 +919,8 @@ async def llm_model_func(
890919
self, prompt, system_prompt=None, history_messages=[], **kwargs
891920
) -> str:
892921
kwargs.pop("model", None) # stop from overwriting the custom model name
922+
kwargs.pop("keyword_extraction", None)
923+
kwargs.pop("mode", None)
893924
next_model = self._next_model()
894925
args = dict(
895926
prompt=prompt,

lightrag/operate.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ async def _merge_edges_then_upsert(
222222
},
223223
)
224224
description = await _handle_entity_relation_summary(
225-
(src_id, tgt_id), description, global_config
225+
f"({src_id}, {tgt_id})", description, global_config
226226
)
227227
await knowledge_graph_inst.upsert_edge(
228228
src_id,
@@ -572,7 +572,6 @@ async def kg_query(
572572
mode=query_param.mode,
573573
),
574574
)
575-
576575
return response
577576

578577

lightrag/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -488,7 +488,7 @@ class CacheData:
488488

489489

490490
async def save_to_cache(hashing_kv, cache_data: CacheData):
491-
if hashing_kv is None:
491+
if hashing_kv is None or hasattr(cache_data.content, "__aiter__"):
492492
return
493493

494494
mode_cache = await hashing_kv.get_by_id(cache_data.mode) or {}

0 commit comments

Comments
 (0)