LarFii commited on
Commit
5c22708
·
1 Parent(s): 356b4e1
Files changed (6) hide show
  1. lightrag/__init__.py +1 -1
  2. lightrag/base.py +116 -0
  3. lightrag/prompt.py +256 -0
  4. lightrag/storage.py +246 -0
  5. lightrag/utils.py +165 -0
  6. setup.py +1 -1
lightrag/__init__.py CHANGED
@@ -1,5 +1,5 @@
1
  from .lightrag import LightRAG, QueryParam
2
 
3
- __version__ = "0.0.1"
4
  __author__ = "Zirui Guo"
5
  __url__ = "https://github.com/HKUDS/GraphEdit"
 
1
  from .lightrag import LightRAG, QueryParam
2
 
3
+ __version__ = "0.0.2"
4
  __author__ = "Zirui Guo"
5
  __url__ = "https://github.com/HKUDS/GraphEdit"
lightrag/base.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass, field
2
+ from typing import TypedDict, Union, Literal, Generic, TypeVar
3
+
4
+ import numpy as np
5
+
6
+ from .utils import EmbeddingFunc
7
+
8
+ TextChunkSchema = TypedDict(
9
+ "TextChunkSchema",
10
+ {"tokens": int, "content": str, "full_doc_id": str, "chunk_order_index": int},
11
+ )
12
+
13
+ T = TypeVar("T")
14
+
15
+ @dataclass
16
+ class QueryParam:
17
+ mode: Literal["local", "global", "hybird", "naive"] = "global"
18
+ only_need_context: bool = False
19
+ response_type: str = "Multiple Paragraphs"
20
+ top_k: int = 60
21
+ max_token_for_text_unit: int = 4000
22
+ max_token_for_global_context: int = 4000
23
+ max_token_for_local_context: int = 4000
24
+
25
+
26
+ @dataclass
27
+ class StorageNameSpace:
28
+ namespace: str
29
+ global_config: dict
30
+
31
+ async def index_done_callback(self):
32
+ """commit the storage operations after indexing"""
33
+ pass
34
+
35
+ async def query_done_callback(self):
36
+ """commit the storage operations after querying"""
37
+ pass
38
+
39
+ @dataclass
40
+ class BaseVectorStorage(StorageNameSpace):
41
+ embedding_func: EmbeddingFunc
42
+ meta_fields: set = field(default_factory=set)
43
+
44
+ async def query(self, query: str, top_k: int) -> list[dict]:
45
+ raise NotImplementedError
46
+
47
+ async def upsert(self, data: dict[str, dict]):
48
+ """Use 'content' field from value for embedding, use key as id.
49
+ If embedding_func is None, use 'embedding' field from value
50
+ """
51
+ raise NotImplementedError
52
+
53
+ @dataclass
54
+ class BaseKVStorage(Generic[T], StorageNameSpace):
55
+ async def all_keys(self) -> list[str]:
56
+ raise NotImplementedError
57
+
58
+ async def get_by_id(self, id: str) -> Union[T, None]:
59
+ raise NotImplementedError
60
+
61
+ async def get_by_ids(
62
+ self, ids: list[str], fields: Union[set[str], None] = None
63
+ ) -> list[Union[T, None]]:
64
+ raise NotImplementedError
65
+
66
+ async def filter_keys(self, data: list[str]) -> set[str]:
67
+ """return un-exist keys"""
68
+ raise NotImplementedError
69
+
70
+ async def upsert(self, data: dict[str, T]):
71
+ raise NotImplementedError
72
+
73
+ async def drop(self):
74
+ raise NotImplementedError
75
+
76
+
77
+ @dataclass
78
+ class BaseGraphStorage(StorageNameSpace):
79
+ async def has_node(self, node_id: str) -> bool:
80
+ raise NotImplementedError
81
+
82
+ async def has_edge(self, source_node_id: str, target_node_id: str) -> bool:
83
+ raise NotImplementedError
84
+
85
+ async def node_degree(self, node_id: str) -> int:
86
+ raise NotImplementedError
87
+
88
+ async def edge_degree(self, src_id: str, tgt_id: str) -> int:
89
+ raise NotImplementedError
90
+
91
+ async def get_node(self, node_id: str) -> Union[dict, None]:
92
+ raise NotImplementedError
93
+
94
+ async def get_edge(
95
+ self, source_node_id: str, target_node_id: str
96
+ ) -> Union[dict, None]:
97
+ raise NotImplementedError
98
+
99
+ async def get_node_edges(
100
+ self, source_node_id: str
101
+ ) -> Union[list[tuple[str, str]], None]:
102
+ raise NotImplementedError
103
+
104
+ async def upsert_node(self, node_id: str, node_data: dict[str, str]):
105
+ raise NotImplementedError
106
+
107
+ async def upsert_edge(
108
+ self, source_node_id: str, target_node_id: str, edge_data: dict[str, str]
109
+ ):
110
+ raise NotImplementedError
111
+
112
+ async def clustering(self, algorithm: str):
113
+ raise NotImplementedError
114
+
115
+ async def embed_nodes(self, algorithm: str) -> tuple[np.ndarray, list[str]]:
116
+ raise NotImplementedError("Node embedding is not used in lightrag.")
lightrag/prompt.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GRAPH_FIELD_SEP = "<SEP>"
2
+
3
+ PROMPTS = {}
4
+
5
+ PROMPTS["DEFAULT_TUPLE_DELIMITER"] = "<|>"
6
+ PROMPTS["DEFAULT_RECORD_DELIMITER"] = "##"
7
+ PROMPTS["DEFAULT_COMPLETION_DELIMITER"] = "<|COMPLETE|>"
8
+ PROMPTS["process_tickers"] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
9
+
10
+ PROMPTS["DEFAULT_ENTITY_TYPES"] = ["organization", "person", "geo", "event"]
11
+
12
+ PROMPTS[
13
+ "entity_extraction"
14
+ ] = """-Goal-
15
+ Given a text document that is potentially relevant to this activity and a list of entity types, identify all entities of those types from the text and all relationships among the identified entities.
16
+
17
+ -Steps-
18
+ 1. Identify all entities. For each identified entity, extract the following information:
19
+ - entity_name: Name of the entity, capitalized
20
+ - entity_type: One of the following types: [{entity_types}]
21
+ - entity_description: Comprehensive description of the entity's attributes and activities
22
+ Format each entity as ("entity"{tuple_delimiter}<entity_name>{tuple_delimiter}<entity_type>{tuple_delimiter}<entity_description>
23
+
24
+ 2. From the entities identified in step 1, identify all pairs of (source_entity, target_entity) that are *clearly related* to each other.
25
+ For each pair of related entities, extract the following information:
26
+ - source_entity: name of the source entity, as identified in step 1
27
+ - target_entity: name of the target entity, as identified in step 1
28
+ - relationship_description: explanation as to why you think the source entity and the target entity are related to each other
29
+ - relationship_strength: a numeric score indicating strength of the relationship between the source entity and target entity
30
+ - relationship_keywords: one or more high-level key words that summarize the overarching nature of the relationship, focusing on concepts or themes rather than specific details
31
+ Format each relationship as ("relationship"{tuple_delimiter}<source_entity>{tuple_delimiter}<target_entity>{tuple_delimiter}<relationship_description>{tuple_delimiter}<relationship_keywords>{tuple_delimiter}<relationship_strength>)
32
+
33
+ 3. Identify high-level key words that summarize the main concepts, themes, or topics of the entire text. These should capture the overarching ideas present in the document.
34
+ Format the content-level key words as ("content_keywords"{tuple_delimiter}<high_level_keywords>)
35
+
36
+ 4. Return output in English as a single list of all the entities and relationships identified in steps 1 and 2. Use **{record_delimiter}** as the list delimiter.
37
+
38
+ 5. When finished, output {completion_delimiter}
39
+
40
+ ######################
41
+ -Examples-
42
+ ######################
43
+ Example 1:
44
+
45
+ Entity_types: [person, technology, mission, organization, location]
46
+ Text:
47
+ while Alex clenched his jaw, the buzz of frustration dull against the backdrop of Taylor's authoritarian certainty. It was this competitive undercurrent that kept him alert, the sense that his and Jordan's shared commitment to discovery was an unspoken rebellion against Cruz's narrowing vision of control and order.
48
+
49
+ Then Taylor did something unexpected. They paused beside Jordan and, for a moment, observed the device with something akin to reverence. “If this tech can be understood..." Taylor said, their voice quieter, "It could change the game for us. For all of us.”
50
+
51
+ The underlying dismissal earlier seemed to falter, replaced by a glimpse of reluctant respect for the gravity of what lay in their hands. Jordan looked up, and for a fleeting heartbeat, their eyes locked with Taylor's, a wordless clash of wills softening into an uneasy truce.
52
+
53
+ It was a small transformation, barely perceptible, but one that Alex noted with an inward nod. They had all been brought here by different paths
54
+ ################
55
+ Output:
56
+ ("entity"{tuple_delimiter}"Alex"{tuple_delimiter}"person"{tuple_delimiter}"Alex is a character who experiences frustration and is observant of the dynamics among other characters."){record_delimiter}
57
+ ("entity"{tuple_delimiter}"Taylor"{tuple_delimiter}"person"{tuple_delimiter}"Taylor is portrayed with authoritarian certainty and shows a moment of reverence towards a device, indicating a change in perspective."){record_delimiter}
58
+ ("entity"{tuple_delimiter}"Jordan"{tuple_delimiter}"person"{tuple_delimiter}"Jordan shares a commitment to discovery and has a significant interaction with Taylor regarding a device."){record_delimiter}
59
+ ("entity"{tuple_delimiter}"Cruz"{tuple_delimiter}"person"{tuple_delimiter}"Cruz is associated with a vision of control and order, influencing the dynamics among other characters."){record_delimiter}
60
+ ("entity"{tuple_delimiter}"The Device"{tuple_delimiter}"technology"{tuple_delimiter}"The Device is central to the story, with potential game-changing implications, and is revered by Taylor."){record_delimiter}
61
+ ("relationship"{tuple_delimiter}"Alex"{tuple_delimiter}"Taylor"{tuple_delimiter}"Alex is affected by Taylor's authoritarian certainty and observes changes in Taylor's attitude towards the device."{tuple_delimiter}"power dynamics, perspective shift"{tuple_delimiter}7){record_delimiter}
62
+ ("relationship"{tuple_delimiter}"Alex"{tuple_delimiter}"Jordan"{tuple_delimiter}"Alex and Jordan share a commitment to discovery, which contrasts with Cruz's vision."{tuple_delimiter}"shared goals, rebellion"{tuple_delimiter}6){record_delimiter}
63
+ ("relationship"{tuple_delimiter}"Taylor"{tuple_delimiter}"Jordan"{tuple_delimiter}"Taylor and Jordan interact directly regarding the device, leading to a moment of mutual respect and an uneasy truce."{tuple_delimiter}"conflict resolution, mutual respect"{tuple_delimiter}8){record_delimiter}
64
+ ("relationship"{tuple_delimiter}"Jordan"{tuple_delimiter}"Cruz"{tuple_delimiter}"Jordan's commitment to discovery is in rebellion against Cruz's vision of control and order."{tuple_delimiter}"ideological conflict, rebellion"{tuple_delimiter}5){record_delimiter}
65
+ ("relationship"{tuple_delimiter}"Taylor"{tuple_delimiter}"The Device"{tuple_delimiter}"Taylor shows reverence towards the device, indicating its importance and potential impact."{tuple_delimiter}"reverence, technological significance"{tuple_delimiter}9){record_delimiter}
66
+ ("content_keywords"{tuple_delimiter}"power dynamics, ideological conflict, discovery, rebellion"){completion_delimiter}
67
+ #############################
68
+ Example 2:
69
+
70
+ Entity_types: [person, technology, mission, organization, location]
71
+ Text:
72
+ They were no longer mere operatives; they had become guardians of a threshold, keepers of a message from a realm beyond stars and stripes. This elevation in their mission could not be shackled by regulations and established protocols—it demanded a new perspective, a new resolve.
73
+
74
+ Tension threaded through the dialogue of beeps and static as communications with Washington buzzed in the background. The team stood, a portentous air enveloping them. It was clear that the decisions they made in the ensuing hours could redefine humanity's place in the cosmos or condemn them to ignorance and potential peril.
75
+
76
+ Their connection to the stars solidified, the group moved to address the crystallizing warning, shifting from passive recipients to active participants. Mercer's latter instincts gained precedence— the team's mandate had evolved, no longer solely to observe and report but to interact and prepare. A metamorphosis had begun, and Operation: Dulce hummed with the newfound frequency of their daring, a tone set not by the earthly
77
+ #############
78
+ Output:
79
+ ("entity"{tuple_delimiter}"Washington"{tuple_delimiter}"location"{tuple_delimiter}"Washington is a location where communications are being received, indicating its importance in the decision-making process."){record_delimiter}
80
+ ("entity"{tuple_delimiter}"Operation: Dulce"{tuple_delimiter}"mission"{tuple_delimiter}"Operation: Dulce is described as a mission that has evolved to interact and prepare, indicating a significant shift in objectives and activities."){record_delimiter}
81
+ ("entity"{tuple_delimiter}"The team"{tuple_delimiter}"organization"{tuple_delimiter}"The team is portrayed as a group of individuals who have transitioned from passive observers to active participants in a mission, showing a dynamic change in their role."){record_delimiter}
82
+ ("relationship"{tuple_delimiter}"The team"{tuple_delimiter}"Washington"{tuple_delimiter}"The team receives communications from Washington, which influences their decision-making process."{tuple_delimiter}"decision-making, external influence"{tuple_delimiter}7){record_delimiter}
83
+ ("relationship"{tuple_delimiter}"The team"{tuple_delimiter}"Operation: Dulce"{tuple_delimiter}"The team is directly involved in Operation: Dulce, executing its evolved objectives and activities."{tuple_delimiter}"mission evolution, active participation"{tuple_delimiter}9){completion_delimiter}
84
+ ("content_keywords"{tuple_delimiter}"mission evolution, decision-making, active participation, cosmic significance"){completion_delimiter}
85
+ #############################
86
+ Example 3:
87
+
88
+ Entity_types: [person, role, technology, organization, event, location, concept]
89
+ Text:
90
+ their voice slicing through the buzz of activity. "Control may be an illusion when facing an intelligence that literally writes its own rules," they stated stoically, casting a watchful eye over the flurry of data.
91
+
92
+ "It's like it's learning to communicate," offered Sam Rivera from a nearby interface, their youthful energy boding a mix of awe and anxiety. "This gives talking to strangers' a whole new meaning."
93
+
94
+ Alex surveyed his team—each face a study in concentration, determination, and not a small measure of trepidation. "This might well be our first contact," he acknowledged, "And we need to be ready for whatever answers back."
95
+
96
+ Together, they stood on the edge of the unknown, forging humanity's response to a message from the heavens. The ensuing silence was palpable—a collective introspection about their role in this grand cosmic play, one that could rewrite human history.
97
+
98
+ The encrypted dialogue continued to unfold, its intricate patterns showing an almost uncanny anticipation
99
+ #############
100
+ Output:
101
+ ("entity"{tuple_delimiter}"Sam Rivera"{tuple_delimiter}"person"{tuple_delimiter}"Sam Rivera is a member of a team working on communicating with an unknown intelligence, showing a mix of awe and anxiety."){record_delimiter}
102
+ ("entity"{tuple_delimiter}"Alex"{tuple_delimiter}"person"{tuple_delimiter}"Alex is the leader of a team attempting first contact with an unknown intelligence, acknowledging the significance of their task."){record_delimiter}
103
+ ("entity"{tuple_delimiter}"Control"{tuple_delimiter}"concept"{tuple_delimiter}"Control refers to the ability to manage or govern, which is challenged by an intelligence that writes its own rules."){record_delimiter}
104
+ ("entity"{tuple_delimiter}"Intelligence"{tuple_delimiter}"concept"{tuple_delimiter}"Intelligence here refers to an unknown entity capable of writing its own rules and learning to communicate."){record_delimiter}
105
+ ("entity"{tuple_delimiter}"First Contact"{tuple_delimiter}"event"{tuple_delimiter}"First Contact is the potential initial communication between humanity and an unknown intelligence."){record_delimiter}
106
+ ("entity"{tuple_delimiter}"Humanity's Response"{tuple_delimiter}"event"{tuple_delimiter}"Humanity's Response is the collective action taken by Alex's team in response to a message from an unknown intelligence."){record_delimiter}
107
+ ("relationship"{tuple_delimiter}"Sam Rivera"{tuple_delimiter}"Intelligence"{tuple_delimiter}"Sam Rivera is directly involved in the process of learning to communicate with the unknown intelligence."{tuple_delimiter}"communication, learning process"{tuple_delimiter}9){record_delimiter}
108
+ ("relationship"{tuple_delimiter}"Alex"{tuple_delimiter}"First Contact"{tuple_delimiter}"Alex leads the team that might be making the First Contact with the unknown intelligence."{tuple_delimiter}"leadership, exploration"{tuple_delimiter}10){record_delimiter}
109
+ ("relationship"{tuple_delimiter}"Alex"{tuple_delimiter}"Humanity's Response"{tuple_delimiter}"Alex and his team are the key figures in Humanity's Response to the unknown intelligence."{tuple_delimiter}"collective action, cosmic significance"{tuple_delimiter}8){record_delimiter}
110
+ ("relationship"{tuple_delimiter}"Control"{tuple_delimiter}"Intelligence"{tuple_delimiter}"The concept of Control is challenged by the Intelligence that writes its own rules."{tuple_delimiter}"power dynamics, autonomy"{tuple_delimiter}7){record_delimiter}
111
+ ("content_keywords"{tuple_delimiter}"first contact, control, communication, cosmic significance"){completion_delimiter}
112
+ #############################
113
+ -Real Data-
114
+ ######################
115
+ Entity_types: {entity_types}
116
+ Text: {input_text}
117
+ ######################
118
+ Output:
119
+ """
120
+
121
+ PROMPTS[
122
+ "summarize_entity_descriptions"
123
+ ] = """You are a helpful assistant responsible for generating a comprehensive summary of the data provided below.
124
+ Given one or two entities, and a list of descriptions, all related to the same entity or group of entities.
125
+ Please concatenate all of these into a single, comprehensive description. Make sure to include information collected from all the descriptions.
126
+ If the provided descriptions are contradictory, please resolve the contradictions and provide a single, coherent summary.
127
+ Make sure it is written in third person, and include the entity names so we the have full context.
128
+
129
+ #######
130
+ -Data-
131
+ Entities: {entity_name}
132
+ Description List: {description_list}
133
+ #######
134
+ Output:
135
+ """
136
+
137
+ PROMPTS[
138
+ "entiti_continue_extraction"
139
+ ] = """MANY entities were missed in the last extraction. Add them below using the same format:
140
+ """
141
+
142
+ PROMPTS[
143
+ "entiti_if_loop_extraction"
144
+ ] = """It appears some entities may have still been missed. Answer YES | NO if there are still entities that need to be added.
145
+ """
146
+
147
+ PROMPTS["fail_response"] = "Sorry, I'm not able to provide an answer to that question."
148
+
149
+ PROMPTS[
150
+ "rag_response"
151
+ ] = """---Role---
152
+
153
+ You are a helpful assistant responding to questions about data in the tables provided.
154
+
155
+
156
+ ---Goal---
157
+
158
+ Generate a response of the target length and format that responds to the user's question, summarizing all information in the input data tables appropriate for the response length and format, and incorporating any relevant general knowledge.
159
+ If you don't know the answer, just say so. Do not make anything up.
160
+ Do not include information where the supporting evidence for it is not provided.
161
+
162
+ ---Target response length and format---
163
+
164
+ {response_type}
165
+
166
+
167
+ ---Data tables---
168
+
169
+ {context_data}
170
+
171
+
172
+ ---Goal---
173
+
174
+ Generate a response of the target length and format that responds to the user's question, summarizing all information in the input data tables appropriate for the response length and format, and incorporating any relevant general knowledge.
175
+
176
+ If you don't know the answer, just say so. Do not make anything up.
177
+
178
+ Do not include information where the supporting evidence for it is not provided.
179
+
180
+
181
+ ---Target response length and format---
182
+
183
+ {response_type}
184
+
185
+ Add sections and commentary to the response as appropriate for the length and format. Style the response in markdown.
186
+ """
187
+
188
+ PROMPTS["keywords_extraction"] = """---Role---
189
+
190
+ You are a helpful assistant tasked with identifying both high-level and low-level keywords in the user's query.
191
+
192
+ ---Goal---
193
+
194
+ Given the query, list both high-level and low-level keywords. High-level keywords focus on overarching concepts or themes, while low-level keywords focus on specific entities, details, or concrete terms.
195
+
196
+ ---Instructions---
197
+
198
+ - Output the keywords in JSON format.
199
+ - The JSON should have two keys:
200
+ - "high_level_keywords" for overarching concepts or themes.
201
+ - "low_level_keywords" for specific entities or details.
202
+
203
+ ######################
204
+ -Examples-
205
+ ######################
206
+ Example 1:
207
+
208
+ Query: "How does international trade influence global economic stability?"
209
+ ################
210
+ Output:
211
+ {{
212
+ "high_level_keywords": ["International trade", "Global economic stability", "Economic impact"],
213
+ "low_level_keywords": ["Trade agreements", "Tariffs", "Currency exchange", "Imports", "Exports"]
214
+ }}
215
+ #############################
216
+ Example 2:
217
+
218
+ Query: "What are the environmental consequences of deforestation on biodiversity?"
219
+ ################
220
+ Output:
221
+ {{
222
+ "high_level_keywords": ["Environmental consequences", "Deforestation", "Biodiversity loss"],
223
+ "low_level_keywords": ["Species extinction", "Habitat destruction", "Carbon emissions", "Rainforest", "Ecosystem"]
224
+ }}
225
+ #############################
226
+ Example 3:
227
+
228
+ Query: "What is the role of education in reducing poverty?"
229
+ ################
230
+ Output:
231
+ {{
232
+ "high_level_keywords": ["Education", "Poverty reduction", "Socioeconomic development"],
233
+ "low_level_keywords": ["School access", "Literacy rates", "Job training", "Income inequality"]
234
+ }}
235
+ #############################
236
+ -Real Data-
237
+ ######################
238
+ Query: {query}
239
+ ######################
240
+ Output:
241
+
242
+ """
243
+
244
+ PROMPTS[
245
+ "naive_rag_response"
246
+ ] = """You're a helpful assistant
247
+ Below are the knowledge you know:
248
+ {content_data}
249
+ ---
250
+ If you don't know the answer or if the provided knowledge do not contain sufficient information to provide an answer, just say so. Do not make anything up.
251
+ Generate a response of the target length and format that responds to the user's question, summarizing all information in the input data tables appropriate for the response length and format, and incorporating any relevant general knowledge.
252
+ If you don't know the answer, just say so. Do not make anything up.
253
+ Do not include information where the supporting evidence for it is not provided.
254
+ ---Target response length and format---
255
+ {response_type}
256
+ """
lightrag/storage.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import html
3
+ import json
4
+ import os
5
+ from collections import defaultdict
6
+ from dataclasses import dataclass, field
7
+ from typing import Any, Union, cast
8
+ import pickle
9
+ import hnswlib
10
+ import networkx as nx
11
+ import numpy as np
12
+ from nano_vectordb import NanoVectorDB
13
+ import xxhash
14
+
15
+ from .utils import load_json, logger, write_json
16
+ from .base import (
17
+ BaseGraphStorage,
18
+ BaseKVStorage,
19
+ BaseVectorStorage,
20
+ )
21
+
22
+ @dataclass
23
+ class JsonKVStorage(BaseKVStorage):
24
+ def __post_init__(self):
25
+ working_dir = self.global_config["working_dir"]
26
+ self._file_name = os.path.join(working_dir, f"kv_store_{self.namespace}.json")
27
+ self._data = load_json(self._file_name) or {}
28
+ logger.info(f"Load KV {self.namespace} with {len(self._data)} data")
29
+
30
+ async def all_keys(self) -> list[str]:
31
+ return list(self._data.keys())
32
+
33
+ async def index_done_callback(self):
34
+ write_json(self._data, self._file_name)
35
+
36
+ async def get_by_id(self, id):
37
+ return self._data.get(id, None)
38
+
39
+ async def get_by_ids(self, ids, fields=None):
40
+ if fields is None:
41
+ return [self._data.get(id, None) for id in ids]
42
+ return [
43
+ (
44
+ {k: v for k, v in self._data[id].items() if k in fields}
45
+ if self._data.get(id, None)
46
+ else None
47
+ )
48
+ for id in ids
49
+ ]
50
+
51
+ async def filter_keys(self, data: list[str]) -> set[str]:
52
+ return set([s for s in data if s not in self._data])
53
+
54
+ async def upsert(self, data: dict[str, dict]):
55
+ left_data = {k: v for k, v in data.items() if k not in self._data}
56
+ self._data.update(left_data)
57
+ return left_data
58
+
59
+ async def drop(self):
60
+ self._data = {}
61
+
62
+ @dataclass
63
+ class NanoVectorDBStorage(BaseVectorStorage):
64
+ cosine_better_than_threshold: float = 0.2
65
+
66
+ def __post_init__(self):
67
+
68
+ self._client_file_name = os.path.join(
69
+ self.global_config["working_dir"], f"vdb_{self.namespace}.json"
70
+ )
71
+ self._max_batch_size = self.global_config["embedding_batch_num"]
72
+ self._client = NanoVectorDB(
73
+ self.embedding_func.embedding_dim, storage_file=self._client_file_name
74
+ )
75
+ self.cosine_better_than_threshold = self.global_config.get(
76
+ "cosine_better_than_threshold", self.cosine_better_than_threshold
77
+ )
78
+
79
+ async def upsert(self, data: dict[str, dict]):
80
+ logger.info(f"Inserting {len(data)} vectors to {self.namespace}")
81
+ if not len(data):
82
+ logger.warning("You insert an empty data to vector DB")
83
+ return []
84
+ list_data = [
85
+ {
86
+ "__id__": k,
87
+ **{k1: v1 for k1, v1 in v.items() if k1 in self.meta_fields},
88
+ }
89
+ for k, v in data.items()
90
+ ]
91
+ contents = [v["content"] for v in data.values()]
92
+ batches = [
93
+ contents[i : i + self._max_batch_size]
94
+ for i in range(0, len(contents), self._max_batch_size)
95
+ ]
96
+ embeddings_list = await asyncio.gather(
97
+ *[self.embedding_func(batch) for batch in batches]
98
+ )
99
+ embeddings = np.concatenate(embeddings_list)
100
+ for i, d in enumerate(list_data):
101
+ d["__vector__"] = embeddings[i]
102
+ results = self._client.upsert(datas=list_data)
103
+ return results
104
+
105
+ async def query(self, query: str, top_k=5):
106
+ embedding = await self.embedding_func([query])
107
+ embedding = embedding[0]
108
+ results = self._client.query(
109
+ query=embedding,
110
+ top_k=top_k,
111
+ better_than_threshold=self.cosine_better_than_threshold,
112
+ )
113
+ results = [
114
+ {**dp, "id": dp["__id__"], "distance": dp["__metrics__"]} for dp in results
115
+ ]
116
+ return results
117
+
118
+ async def index_done_callback(self):
119
+ self._client.save()
120
+
121
+ @dataclass
122
+ class NetworkXStorage(BaseGraphStorage):
123
+ @staticmethod
124
+ def load_nx_graph(file_name) -> nx.Graph:
125
+ if os.path.exists(file_name):
126
+ return nx.read_graphml(file_name)
127
+ return None
128
+
129
+ @staticmethod
130
+ def write_nx_graph(graph: nx.Graph, file_name):
131
+ logger.info(
132
+ f"Writing graph with {graph.number_of_nodes()} nodes, {graph.number_of_edges()} edges"
133
+ )
134
+ nx.write_graphml(graph, file_name)
135
+
136
+ @staticmethod
137
+ def stable_largest_connected_component(graph: nx.Graph) -> nx.Graph:
138
+ """Refer to https://github.com/microsoft/graphrag/index/graph/utils/stable_lcc.py
139
+ Return the largest connected component of the graph, with nodes and edges sorted in a stable way.
140
+ """
141
+ from graspologic.utils import largest_connected_component
142
+
143
+ graph = graph.copy()
144
+ graph = cast(nx.Graph, largest_connected_component(graph))
145
+ node_mapping = {node: html.unescape(node.upper().strip()) for node in graph.nodes()} # type: ignore
146
+ graph = nx.relabel_nodes(graph, node_mapping)
147
+ return NetworkXStorage._stabilize_graph(graph)
148
+
149
+ @staticmethod
150
+ def _stabilize_graph(graph: nx.Graph) -> nx.Graph:
151
+ """Refer to https://github.com/microsoft/graphrag/index/graph/utils/stable_lcc.py
152
+ Ensure an undirected graph with the same relationships will always be read the same way.
153
+ """
154
+ fixed_graph = nx.DiGraph() if graph.is_directed() else nx.Graph()
155
+
156
+ sorted_nodes = graph.nodes(data=True)
157
+ sorted_nodes = sorted(sorted_nodes, key=lambda x: x[0])
158
+
159
+ fixed_graph.add_nodes_from(sorted_nodes)
160
+ edges = list(graph.edges(data=True))
161
+
162
+ if not graph.is_directed():
163
+
164
+ def _sort_source_target(edge):
165
+ source, target, edge_data = edge
166
+ if source > target:
167
+ temp = source
168
+ source = target
169
+ target = temp
170
+ return source, target, edge_data
171
+
172
+ edges = [_sort_source_target(edge) for edge in edges]
173
+
174
+ def _get_edge_key(source: Any, target: Any) -> str:
175
+ return f"{source} -> {target}"
176
+
177
+ edges = sorted(edges, key=lambda x: _get_edge_key(x[0], x[1]))
178
+
179
+ fixed_graph.add_edges_from(edges)
180
+ return fixed_graph
181
+
182
+ def __post_init__(self):
183
+ self._graphml_xml_file = os.path.join(
184
+ self.global_config["working_dir"], f"graph_{self.namespace}.graphml"
185
+ )
186
+ preloaded_graph = NetworkXStorage.load_nx_graph(self._graphml_xml_file)
187
+ if preloaded_graph is not None:
188
+ logger.info(
189
+ f"Loaded graph from {self._graphml_xml_file} with {preloaded_graph.number_of_nodes()} nodes, {preloaded_graph.number_of_edges()} edges"
190
+ )
191
+ self._graph = preloaded_graph or nx.Graph()
192
+ self._node_embed_algorithms = {
193
+ "node2vec": self._node2vec_embed,
194
+ }
195
+
196
+ async def index_done_callback(self):
197
+ NetworkXStorage.write_nx_graph(self._graph, self._graphml_xml_file)
198
+
199
+ async def has_node(self, node_id: str) -> bool:
200
+ return self._graph.has_node(node_id)
201
+
202
+ async def has_edge(self, source_node_id: str, target_node_id: str) -> bool:
203
+ return self._graph.has_edge(source_node_id, target_node_id)
204
+
205
+ async def get_node(self, node_id: str) -> Union[dict, None]:
206
+ return self._graph.nodes.get(node_id)
207
+
208
+ async def node_degree(self, node_id: str) -> int:
209
+ return self._graph.degree(node_id)
210
+
211
+ async def edge_degree(self, src_id: str, tgt_id: str) -> int:
212
+ return self._graph.degree(src_id) + self._graph.degree(tgt_id)
213
+
214
+ async def get_edge(
215
+ self, source_node_id: str, target_node_id: str
216
+ ) -> Union[dict, None]:
217
+ return self._graph.edges.get((source_node_id, target_node_id))
218
+
219
+ async def get_node_edges(self, source_node_id: str):
220
+ if self._graph.has_node(source_node_id):
221
+ return list(self._graph.edges(source_node_id))
222
+ return None
223
+
224
+ async def upsert_node(self, node_id: str, node_data: dict[str, str]):
225
+ self._graph.add_node(node_id, **node_data)
226
+
227
+ async def upsert_edge(
228
+ self, source_node_id: str, target_node_id: str, edge_data: dict[str, str]
229
+ ):
230
+ self._graph.add_edge(source_node_id, target_node_id, **edge_data)
231
+
232
+ async def embed_nodes(self, algorithm: str) -> tuple[np.ndarray, list[str]]:
233
+ if algorithm not in self._node_embed_algorithms:
234
+ raise ValueError(f"Node embedding algorithm {algorithm} not supported")
235
+ return await self._node_embed_algorithms[algorithm]()
236
+
237
+ async def _node2vec_embed(self):
238
+ from graspologic import embed
239
+
240
+ embeddings, nodes = embed.node2vec_embed(
241
+ self._graph,
242
+ **self.global_config["node2vec_params"],
243
+ )
244
+
245
+ nodes_ids = [self._graph.nodes[node_id]["id"] for node_id in nodes]
246
+ return embeddings, nodes_ids
lightrag/utils.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import html
3
+ import json
4
+ import logging
5
+ import os
6
+ import re
7
+ from dataclasses import dataclass
8
+ from functools import wraps
9
+ from hashlib import md5
10
+ from typing import Any, Union
11
+
12
+ import numpy as np
13
+ import tiktoken
14
+
15
+ ENCODER = None
16
+
17
+ logger = logging.getLogger("lightrag")
18
+
19
+ def set_logger(log_file: str):
20
+ logger.setLevel(logging.DEBUG)
21
+
22
+ file_handler = logging.FileHandler(log_file)
23
+ file_handler.setLevel(logging.DEBUG)
24
+
25
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
26
+ file_handler.setFormatter(formatter)
27
+
28
+ if not logger.handlers:
29
+ logger.addHandler(file_handler)
30
+
31
+ @dataclass
32
+ class EmbeddingFunc:
33
+ embedding_dim: int
34
+ max_token_size: int
35
+ func: callable
36
+
37
+ async def __call__(self, *args, **kwargs) -> np.ndarray:
38
+ return await self.func(*args, **kwargs)
39
+
40
+ def locate_json_string_body_from_string(content: str) -> Union[str, None]:
41
+ """Locate the JSON string body from a string"""
42
+ maybe_json_str = re.search(r"{.*}", content, re.DOTALL)
43
+ if maybe_json_str is not None:
44
+ return maybe_json_str.group(0)
45
+ else:
46
+ return None
47
+
48
+ def convert_response_to_json(response: str) -> dict:
49
+ json_str = locate_json_string_body_from_string(response)
50
+ assert json_str is not None, f"Unable to parse JSON from response: {response}"
51
+ try:
52
+ data = json.loads(json_str)
53
+ return data
54
+ except json.JSONDecodeError as e:
55
+ logger.error(f"Failed to parse JSON: {json_str}")
56
+ raise e from None
57
+
58
+ def compute_args_hash(*args):
59
+ return md5(str(args).encode()).hexdigest()
60
+
61
+ def compute_mdhash_id(content, prefix: str = ""):
62
+ return prefix + md5(content.encode()).hexdigest()
63
+
64
+ def limit_async_func_call(max_size: int, waitting_time: float = 0.0001):
65
+ """Add restriction of maximum async calling times for a async func"""
66
+
67
+ def final_decro(func):
68
+ """Not using async.Semaphore to aovid use nest-asyncio"""
69
+ __current_size = 0
70
+
71
+ @wraps(func)
72
+ async def wait_func(*args, **kwargs):
73
+ nonlocal __current_size
74
+ while __current_size >= max_size:
75
+ await asyncio.sleep(waitting_time)
76
+ __current_size += 1
77
+ result = await func(*args, **kwargs)
78
+ __current_size -= 1
79
+ return result
80
+
81
+ return wait_func
82
+
83
+ return final_decro
84
+
85
+ def wrap_embedding_func_with_attrs(**kwargs):
86
+ """Wrap a function with attributes"""
87
+
88
+ def final_decro(func) -> EmbeddingFunc:
89
+ new_func = EmbeddingFunc(**kwargs, func=func)
90
+ return new_func
91
+
92
+ return final_decro
93
+
94
+ def load_json(file_name):
95
+ if not os.path.exists(file_name):
96
+ return None
97
+ with open(file_name) as f:
98
+ return json.load(f)
99
+
100
+ def write_json(json_obj, file_name):
101
+ with open(file_name, "w") as f:
102
+ json.dump(json_obj, f, indent=2, ensure_ascii=False)
103
+
104
+ def encode_string_by_tiktoken(content: str, model_name: str = "gpt-4o"):
105
+ global ENCODER
106
+ if ENCODER is None:
107
+ ENCODER = tiktoken.encoding_for_model(model_name)
108
+ tokens = ENCODER.encode(content)
109
+ return tokens
110
+
111
+
112
+ def decode_tokens_by_tiktoken(tokens: list[int], model_name: str = "gpt-4o"):
113
+ global ENCODER
114
+ if ENCODER is None:
115
+ ENCODER = tiktoken.encoding_for_model(model_name)
116
+ content = ENCODER.decode(tokens)
117
+ return content
118
+
119
+ def pack_user_ass_to_openai_messages(*args: str):
120
+ roles = ["user", "assistant"]
121
+ return [
122
+ {"role": roles[i % 2], "content": content} for i, content in enumerate(args)
123
+ ]
124
+
125
+ def split_string_by_multi_markers(content: str, markers: list[str]) -> list[str]:
126
+ """Split a string by multiple markers"""
127
+ if not markers:
128
+ return [content]
129
+ results = re.split("|".join(re.escape(marker) for marker in markers), content)
130
+ return [r.strip() for r in results if r.strip()]
131
+
132
+ # Refer the utils functions of the official GraphRAG implementation:
133
+ # https://github.com/microsoft/graphrag
134
+ def clean_str(input: Any) -> str:
135
+ """Clean an input string by removing HTML escapes, control characters, and other unwanted characters."""
136
+ # If we get non-string input, just give it back
137
+ if not isinstance(input, str):
138
+ return input
139
+
140
+ result = html.unescape(input.strip())
141
+ # https://stackoverflow.com/questions/4324790/removing-control-characters-from-a-string-in-python
142
+ return re.sub(r"[\x00-\x1f\x7f-\x9f]", "", result)
143
+
144
+ def is_float_regex(value):
145
+ return bool(re.match(r"^[-+]?[0-9]*\.?[0-9]+$", value))
146
+
147
+ def truncate_list_by_token_size(list_data: list, key: callable, max_token_size: int):
148
+ """Truncate a list of data by token size"""
149
+ if max_token_size <= 0:
150
+ return []
151
+ tokens = 0
152
+ for i, data in enumerate(list_data):
153
+ tokens += len(encode_string_by_tiktoken(key(data)))
154
+ if tokens > max_token_size:
155
+ return list_data[:i]
156
+ return list_data
157
+
158
+ def list_of_list_to_csv(data: list[list]):
159
+ return "\n".join(
160
+ [",\t".join([str(data_dd) for data_dd in data_d]) for data_d in data]
161
+ )
162
+
163
+ def save_data_to_file(data, file_name):
164
+ with open(file_name, 'w', encoding='utf-8') as f:
165
+ json.dump(data, f, ensure_ascii=False, indent=4)
setup.py CHANGED
@@ -21,7 +21,7 @@ with open("./requirements.txt") as f:
21
  deps.append(line.strip())
22
 
23
  setuptools.setup(
24
- name="light-rag",
25
  url=vars2readme["__url__"],
26
  version=vars2readme["__version__"],
27
  author=vars2readme["__author__"],
 
21
  deps.append(line.strip())
22
 
23
  setuptools.setup(
24
+ name="lightrag-hku",
25
  url=vars2readme["__url__"],
26
  version=vars2readme["__version__"],
27
  author=vars2readme["__author__"],