zrguo commited on
Commit
3478579
·
unverified ·
2 Parent(s): ce8e264 d381db9

Merge branch 'main' into main

Browse files
examples/graph_visual_with_html.py CHANGED
@@ -11,6 +11,7 @@ net = Network(height="100vh", notebook=True)
11
  # Convert NetworkX graph to Pyvis network
12
  net.from_nx(G)
13
 
 
14
  # Add colors and title to nodes
15
  for node in net.nodes:
16
  node["color"] = "#{:06x}".format(random.randint(0, 0xFFFFFF))
 
11
  # Convert NetworkX graph to Pyvis network
12
  net.from_nx(G)
13
 
14
+
15
  # Add colors and title to nodes
16
  for node in net.nodes:
17
  node["color"] = "#{:06x}".format(random.randint(0, 0xFFFFFF))
examples/lightrag_api_ollama_demo.py ADDED
@@ -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"
lightrag/llm.py CHANGED
@@ -632,7 +632,7 @@ async def jina_embedding(
632
  url = "https://api.jina.ai/v1/embeddings" if not base_url else base_url
633
  headers = {
634
  "Content-Type": "application/json",
635
- "Authorization": f"""Bearer {os.environ["JINA_API_KEY"]}""",
636
  }
637
  data = {
638
  "model": "jina-embeddings-v3",
 
632
  url = "https://api.jina.ai/v1/embeddings" if not base_url else base_url
633
  headers = {
634
  "Content-Type": "application/json",
635
+ "Authorization": f"Bearer {os.environ['JINA_API_KEY']}",
636
  }
637
  data = {
638
  "model": "jina-embeddings-v3",
lightrag/operate.py CHANGED
@@ -222,7 +222,7 @@ async def _merge_edges_then_upsert(
222
  },
223
  )
224
  description = await _handle_entity_relation_summary(
225
- (src_id, tgt_id), description, global_config
226
  )
227
  await knowledge_graph_inst.upsert_edge(
228
  src_id,
@@ -572,7 +572,6 @@ async def kg_query(
572
  mode=query_param.mode,
573
  ),
574
  )
575
-
576
  return response
577
 
578
 
@@ -990,23 +989,37 @@ async def _find_related_text_unit_from_relationships(
990
  for index, unit_list in enumerate(text_units):
991
  for c_id in unit_list:
992
  if c_id not in all_text_units_lookup:
993
- all_text_units_lookup[c_id] = {
994
- "data": await text_chunks_db.get_by_id(c_id),
995
- "order": index,
996
- }
 
 
 
 
 
 
 
997
 
998
- if any([v is None for v in all_text_units_lookup.values()]):
999
- logger.warning("Text chunks are missing, maybe the storage is damaged")
1000
- all_text_units = [
1001
- {"id": k, **v} for k, v in all_text_units_lookup.items() if v is not None
1002
- ]
1003
  all_text_units = sorted(all_text_units, key=lambda x: x["order"])
1004
- all_text_units = truncate_list_by_token_size(
1005
- all_text_units,
 
 
 
 
 
 
 
 
 
 
1006
  key=lambda x: x["data"]["content"],
1007
  max_token_size=query_param.max_token_for_text_unit,
1008
  )
1009
- all_text_units: list[TextChunkSchema] = [t["data"] for t in all_text_units]
 
1010
 
1011
  return all_text_units
1012
 
@@ -1050,24 +1063,43 @@ async def naive_query(
1050
  results = await chunks_vdb.query(query, top_k=query_param.top_k)
1051
  if not len(results):
1052
  return PROMPTS["fail_response"]
 
1053
  chunks_ids = [r["id"] for r in results]
1054
  chunks = await text_chunks_db.get_by_ids(chunks_ids)
1055
 
 
 
 
 
 
 
 
 
 
1056
  maybe_trun_chunks = truncate_list_by_token_size(
1057
- chunks,
1058
  key=lambda x: x["content"],
1059
  max_token_size=query_param.max_token_for_text_unit,
1060
  )
 
 
 
 
 
1061
  logger.info(f"Truncate {len(chunks)} to {len(maybe_trun_chunks)} chunks")
1062
  section = "\n--New Chunk--\n".join([c["content"] for c in maybe_trun_chunks])
 
1063
  if query_param.only_need_context:
1064
  return section
 
1065
  sys_prompt_temp = PROMPTS["naive_rag_response"]
1066
  sys_prompt = sys_prompt_temp.format(
1067
  content_data=section, response_type=query_param.response_type
1068
  )
 
1069
  if query_param.only_need_prompt:
1070
  return sys_prompt
 
1071
  response = await use_model_func(
1072
  query,
1073
  system_prompt=sys_prompt,
 
222
  },
223
  )
224
  description = await _handle_entity_relation_summary(
225
+ f"({src_id}, {tgt_id})", description, global_config
226
  )
227
  await knowledge_graph_inst.upsert_edge(
228
  src_id,
 
572
  mode=query_param.mode,
573
  ),
574
  )
 
575
  return response
576
 
577
 
 
989
  for index, unit_list in enumerate(text_units):
990
  for c_id in unit_list:
991
  if c_id not in all_text_units_lookup:
992
+ chunk_data = await text_chunks_db.get_by_id(c_id)
993
+ # Only store valid data
994
+ if chunk_data is not None and "content" in chunk_data:
995
+ all_text_units_lookup[c_id] = {
996
+ "data": chunk_data,
997
+ "order": index,
998
+ }
999
+
1000
+ if not all_text_units_lookup:
1001
+ logger.warning("No valid text chunks found")
1002
+ return []
1003
 
1004
+ all_text_units = [{"id": k, **v} for k, v in all_text_units_lookup.items()]
 
 
 
 
1005
  all_text_units = sorted(all_text_units, key=lambda x: x["order"])
1006
+
1007
+ # Ensure all text chunks have content
1008
+ valid_text_units = [
1009
+ t for t in all_text_units if t["data"] is not None and "content" in t["data"]
1010
+ ]
1011
+
1012
+ if not valid_text_units:
1013
+ logger.warning("No valid text chunks after filtering")
1014
+ return []
1015
+
1016
+ truncated_text_units = truncate_list_by_token_size(
1017
+ valid_text_units,
1018
  key=lambda x: x["data"]["content"],
1019
  max_token_size=query_param.max_token_for_text_unit,
1020
  )
1021
+
1022
+ all_text_units: list[TextChunkSchema] = [t["data"] for t in truncated_text_units]
1023
 
1024
  return all_text_units
1025
 
 
1063
  results = await chunks_vdb.query(query, top_k=query_param.top_k)
1064
  if not len(results):
1065
  return PROMPTS["fail_response"]
1066
+
1067
  chunks_ids = [r["id"] for r in results]
1068
  chunks = await text_chunks_db.get_by_ids(chunks_ids)
1069
 
1070
+ # Filter out invalid chunks
1071
+ valid_chunks = [
1072
+ chunk for chunk in chunks if chunk is not None and "content" in chunk
1073
+ ]
1074
+
1075
+ if not valid_chunks:
1076
+ logger.warning("No valid chunks found after filtering")
1077
+ return PROMPTS["fail_response"]
1078
+
1079
  maybe_trun_chunks = truncate_list_by_token_size(
1080
+ valid_chunks,
1081
  key=lambda x: x["content"],
1082
  max_token_size=query_param.max_token_for_text_unit,
1083
  )
1084
+
1085
+ if not maybe_trun_chunks:
1086
+ logger.warning("No chunks left after truncation")
1087
+ return PROMPTS["fail_response"]
1088
+
1089
  logger.info(f"Truncate {len(chunks)} to {len(maybe_trun_chunks)} chunks")
1090
  section = "\n--New Chunk--\n".join([c["content"] for c in maybe_trun_chunks])
1091
+
1092
  if query_param.only_need_context:
1093
  return section
1094
+
1095
  sys_prompt_temp = PROMPTS["naive_rag_response"]
1096
  sys_prompt = sys_prompt_temp.format(
1097
  content_data=section, response_type=query_param.response_type
1098
  )
1099
+
1100
  if query_param.only_need_prompt:
1101
  return sys_prompt
1102
+
1103
  response = await use_model_func(
1104
  query,
1105
  system_prompt=sys_prompt,