您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. # Copyright (c) 2024 Microsoft Corporation.
  2. # Licensed under the MIT License
  3. """
  4. Reference:
  5. - [graphrag](https://github.com/microsoft/graphrag)
  6. - [LightRag](https://github.com/HKUDS/LightRAG)
  7. """
  8. import html
  9. import json
  10. import logging
  11. import re
  12. import time
  13. from collections import defaultdict
  14. from hashlib import md5
  15. from typing import Any, Callable
  16. import os
  17. import trio
  18. from typing import Set, Tuple
  19. import networkx as nx
  20. import numpy as np
  21. import xxhash
  22. from networkx.readwrite import json_graph
  23. import dataclasses
  24. from api import settings
  25. from api.utils import get_uuid
  26. from rag.nlp import search, rag_tokenizer
  27. from rag.utils.doc_store_conn import OrderByExpr
  28. from rag.utils.redis_conn import REDIS_CONN
  29. GRAPH_FIELD_SEP = "<SEP>"
  30. ErrorHandlerFn = Callable[[BaseException | None, str | None, dict | None], None]
  31. chat_limiter = trio.CapacityLimiter(int(os.environ.get('MAX_CONCURRENT_CHATS', 10)))
  32. @dataclasses.dataclass
  33. class GraphChange:
  34. removed_nodes: Set[str] = dataclasses.field(default_factory=set)
  35. added_updated_nodes: Set[str] = dataclasses.field(default_factory=set)
  36. removed_edges: Set[Tuple[str, str]] = dataclasses.field(default_factory=set)
  37. added_updated_edges: Set[Tuple[str, str]] = dataclasses.field(default_factory=set)
  38. def perform_variable_replacements(
  39. input: str, history: list[dict] | None = None, variables: dict | None = None
  40. ) -> str:
  41. """Perform variable replacements on the input string and in a chat log."""
  42. if history is None:
  43. history = []
  44. if variables is None:
  45. variables = {}
  46. result = input
  47. def replace_all(input: str) -> str:
  48. result = input
  49. for k, v in variables.items():
  50. result = result.replace(f"{{{k}}}", str(v))
  51. return result
  52. result = replace_all(result)
  53. for i, entry in enumerate(history):
  54. if entry.get("role") == "system":
  55. entry["content"] = replace_all(entry.get("content") or "")
  56. return result
  57. def clean_str(input: Any) -> str:
  58. """Clean an input string by removing HTML escapes, control characters, and other unwanted characters."""
  59. # If we get non-string input, just give it back
  60. if not isinstance(input, str):
  61. return input
  62. result = html.unescape(input.strip())
  63. # https://stackoverflow.com/questions/4324790/removing-control-characters-from-a-string-in-python
  64. return re.sub(r"[\"\x00-\x1f\x7f-\x9f]", "", result)
  65. def dict_has_keys_with_types(
  66. data: dict, expected_fields: list[tuple[str, type]]
  67. ) -> bool:
  68. """Return True if the given dictionary has the given keys with the given types."""
  69. for field, field_type in expected_fields:
  70. if field not in data:
  71. return False
  72. value = data[field]
  73. if not isinstance(value, field_type):
  74. return False
  75. return True
  76. def get_llm_cache(llmnm, txt, history, genconf):
  77. hasher = xxhash.xxh64()
  78. hasher.update(str(llmnm).encode("utf-8"))
  79. hasher.update(str(txt).encode("utf-8"))
  80. hasher.update(str(history).encode("utf-8"))
  81. hasher.update(str(genconf).encode("utf-8"))
  82. k = hasher.hexdigest()
  83. bin = REDIS_CONN.get(k)
  84. if not bin:
  85. return
  86. return bin
  87. def set_llm_cache(llmnm, txt, v, history, genconf):
  88. hasher = xxhash.xxh64()
  89. hasher.update(str(llmnm).encode("utf-8"))
  90. hasher.update(str(txt).encode("utf-8"))
  91. hasher.update(str(history).encode("utf-8"))
  92. hasher.update(str(genconf).encode("utf-8"))
  93. k = hasher.hexdigest()
  94. REDIS_CONN.set(k, v.encode("utf-8"), 24*3600)
  95. def get_embed_cache(llmnm, txt):
  96. hasher = xxhash.xxh64()
  97. hasher.update(str(llmnm).encode("utf-8"))
  98. hasher.update(str(txt).encode("utf-8"))
  99. k = hasher.hexdigest()
  100. bin = REDIS_CONN.get(k)
  101. if not bin:
  102. return
  103. return np.array(json.loads(bin))
  104. def set_embed_cache(llmnm, txt, arr):
  105. hasher = xxhash.xxh64()
  106. hasher.update(str(llmnm).encode("utf-8"))
  107. hasher.update(str(txt).encode("utf-8"))
  108. k = hasher.hexdigest()
  109. arr = json.dumps(arr.tolist() if isinstance(arr, np.ndarray) else arr)
  110. REDIS_CONN.set(k, arr.encode("utf-8"), 24*3600)
  111. def get_tags_from_cache(kb_ids):
  112. hasher = xxhash.xxh64()
  113. hasher.update(str(kb_ids).encode("utf-8"))
  114. k = hasher.hexdigest()
  115. bin = REDIS_CONN.get(k)
  116. if not bin:
  117. return
  118. return bin
  119. def set_tags_to_cache(kb_ids, tags):
  120. hasher = xxhash.xxh64()
  121. hasher.update(str(kb_ids).encode("utf-8"))
  122. k = hasher.hexdigest()
  123. REDIS_CONN.set(k, json.dumps(tags).encode("utf-8"), 600)
  124. def tidy_graph(graph: nx.Graph, callback):
  125. """
  126. Ensure all nodes and edges in the graph have some essential attribute.
  127. """
  128. def is_valid_node(node_attrs: dict) -> bool:
  129. valid_node = True
  130. for attr in ["description", "source_id"]:
  131. if attr not in node_attrs:
  132. valid_node = False
  133. break
  134. return valid_node
  135. purged_nodes = []
  136. for node, node_attrs in graph.nodes(data=True):
  137. if not is_valid_node(node_attrs):
  138. purged_nodes.append(node)
  139. for node in purged_nodes:
  140. graph.remove_node(node)
  141. if purged_nodes and callback:
  142. callback(msg=f"Purged {len(purged_nodes)} nodes from graph due to missing essential attributes.")
  143. purged_edges = []
  144. for source, target, attr in graph.edges(data=True):
  145. if not is_valid_node(attr):
  146. purged_edges.append((source, target))
  147. if "keywords" not in attr:
  148. attr["keywords"] = []
  149. for source, target in purged_edges:
  150. graph.remove_edge(source, target)
  151. if purged_edges and callback:
  152. callback(msg=f"Purged {len(purged_edges)} edges from graph due to missing essential attributes.")
  153. def get_from_to(node1, node2):
  154. if node1 < node2:
  155. return (node1, node2)
  156. else:
  157. return (node2, node1)
  158. def graph_merge(g1: nx.Graph, g2: nx.Graph, change: GraphChange):
  159. """Merge graph g2 into g1 in place."""
  160. for node_name, attr in g2.nodes(data=True):
  161. change.added_updated_nodes.add(node_name)
  162. if not g1.has_node(node_name):
  163. g1.add_node(node_name, **attr)
  164. continue
  165. node = g1.nodes[node_name]
  166. node["description"] += GRAPH_FIELD_SEP + attr["description"]
  167. # A node's source_id indicates which chunks it came from.
  168. node["source_id"] += attr["source_id"]
  169. for source, target, attr in g2.edges(data=True):
  170. change.added_updated_edges.add(get_from_to(source, target))
  171. edge = g1.get_edge_data(source, target)
  172. if edge is None:
  173. g1.add_edge(source, target, **attr)
  174. continue
  175. edge["weight"] += attr.get("weight", 0)
  176. edge["description"] += GRAPH_FIELD_SEP + attr["description"]
  177. edge["keywords"] += attr["keywords"]
  178. # A edge's source_id indicates which chunks it came from.
  179. edge["source_id"] += attr["source_id"]
  180. for node_degree in g1.degree:
  181. g1.nodes[str(node_degree[0])]["rank"] = int(node_degree[1])
  182. # A graph's source_id indicates which documents it came from.
  183. if "source_id" not in g1.graph:
  184. g1.graph["source_id"] = []
  185. g1.graph["source_id"] += g2.graph.get("source_id", [])
  186. return g1
  187. def compute_args_hash(*args):
  188. return md5(str(args).encode()).hexdigest()
  189. def handle_single_entity_extraction(
  190. record_attributes: list[str],
  191. chunk_key: str,
  192. ):
  193. if len(record_attributes) < 4 or record_attributes[0] != '"entity"':
  194. return None
  195. # add this record as a node in the G
  196. entity_name = clean_str(record_attributes[1].upper())
  197. if not entity_name.strip():
  198. return None
  199. entity_type = clean_str(record_attributes[2].upper())
  200. entity_description = clean_str(record_attributes[3])
  201. entity_source_id = chunk_key
  202. return dict(
  203. entity_name=entity_name.upper(),
  204. entity_type=entity_type.upper(),
  205. description=entity_description,
  206. source_id=entity_source_id,
  207. )
  208. def handle_single_relationship_extraction(record_attributes: list[str], chunk_key: str):
  209. if len(record_attributes) < 5 or record_attributes[0] != '"relationship"':
  210. return None
  211. # add this record as edge
  212. source = clean_str(record_attributes[1].upper())
  213. target = clean_str(record_attributes[2].upper())
  214. edge_description = clean_str(record_attributes[3])
  215. edge_keywords = clean_str(record_attributes[4])
  216. edge_source_id = chunk_key
  217. weight = (
  218. float(record_attributes[-1]) if is_float_regex(record_attributes[-1]) else 1.0
  219. )
  220. pair = sorted([source.upper(), target.upper()])
  221. return dict(
  222. src_id=pair[0],
  223. tgt_id=pair[1],
  224. weight=weight,
  225. description=edge_description,
  226. keywords=edge_keywords,
  227. source_id=edge_source_id,
  228. metadata={"created_at": time.time()},
  229. )
  230. def pack_user_ass_to_openai_messages(*args: str):
  231. roles = ["user", "assistant"]
  232. return [
  233. {"role": roles[i % 2], "content": content} for i, content in enumerate(args)
  234. ]
  235. def split_string_by_multi_markers(content: str, markers: list[str]) -> list[str]:
  236. """Split a string by multiple markers"""
  237. if not markers:
  238. return [content]
  239. results = re.split("|".join(re.escape(marker) for marker in markers), content)
  240. return [r.strip() for r in results if r.strip()]
  241. def is_float_regex(value):
  242. return bool(re.match(r"^[-+]?[0-9]*\.?[0-9]+$", value))
  243. def chunk_id(chunk):
  244. return xxhash.xxh64((chunk["content_with_weight"] + chunk["kb_id"]).encode("utf-8")).hexdigest()
  245. async def graph_node_to_chunk(kb_id, embd_mdl, ent_name, meta, chunks):
  246. chunk = {
  247. "id": get_uuid(),
  248. "important_kwd": [ent_name],
  249. "title_tks": rag_tokenizer.tokenize(ent_name),
  250. "entity_kwd": ent_name,
  251. "knowledge_graph_kwd": "entity",
  252. "entity_type_kwd": meta["entity_type"],
  253. "content_with_weight": json.dumps(meta, ensure_ascii=False),
  254. "content_ltks": rag_tokenizer.tokenize(meta["description"]),
  255. "source_id": meta["source_id"],
  256. "kb_id": kb_id,
  257. "available_int": 0
  258. }
  259. chunk["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(chunk["content_ltks"])
  260. ebd = get_embed_cache(embd_mdl.llm_name, ent_name)
  261. if ebd is None:
  262. ebd, _ = await trio.to_thread.run_sync(lambda: embd_mdl.encode([ent_name]))
  263. ebd = ebd[0]
  264. set_embed_cache(embd_mdl.llm_name, ent_name, ebd)
  265. assert ebd is not None
  266. chunk["q_%d_vec" % len(ebd)] = ebd
  267. chunks.append(chunk)
  268. def get_relation(tenant_id, kb_id, from_ent_name, to_ent_name, size=1):
  269. ents = from_ent_name
  270. if isinstance(ents, str):
  271. ents = [from_ent_name]
  272. if isinstance(to_ent_name, str):
  273. to_ent_name = [to_ent_name]
  274. ents.extend(to_ent_name)
  275. ents = list(set(ents))
  276. conds = {
  277. "fields": ["content_with_weight"],
  278. "size": size,
  279. "from_entity_kwd": ents,
  280. "to_entity_kwd": ents,
  281. "knowledge_graph_kwd": ["relation"]
  282. }
  283. res = []
  284. es_res = settings.retrievaler.search(conds, search.index_name(tenant_id), [kb_id] if isinstance(kb_id, str) else kb_id)
  285. for id in es_res.ids:
  286. try:
  287. if size == 1:
  288. return json.loads(es_res.field[id]["content_with_weight"])
  289. res.append(json.loads(es_res.field[id]["content_with_weight"]))
  290. except Exception:
  291. continue
  292. return res
  293. async def graph_edge_to_chunk(kb_id, embd_mdl, from_ent_name, to_ent_name, meta, chunks):
  294. chunk = {
  295. "id": get_uuid(),
  296. "from_entity_kwd": from_ent_name,
  297. "to_entity_kwd": to_ent_name,
  298. "knowledge_graph_kwd": "relation",
  299. "content_with_weight": json.dumps(meta, ensure_ascii=False),
  300. "content_ltks": rag_tokenizer.tokenize(meta["description"]),
  301. "important_kwd": meta["keywords"],
  302. "source_id": meta["source_id"],
  303. "weight_int": int(meta["weight"]),
  304. "kb_id": kb_id,
  305. "available_int": 0
  306. }
  307. chunk["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(chunk["content_ltks"])
  308. txt = f"{from_ent_name}->{to_ent_name}"
  309. ebd = get_embed_cache(embd_mdl.llm_name, txt)
  310. if ebd is None:
  311. ebd, _ = await trio.to_thread.run_sync(lambda: embd_mdl.encode([txt+f": {meta['description']}"]))
  312. ebd = ebd[0]
  313. set_embed_cache(embd_mdl.llm_name, txt, ebd)
  314. assert ebd is not None
  315. chunk["q_%d_vec" % len(ebd)] = ebd
  316. chunks.append(chunk)
  317. async def does_graph_contains(tenant_id, kb_id, doc_id):
  318. # Get doc_ids of graph
  319. fields = ["source_id"]
  320. condition = {
  321. "knowledge_graph_kwd": ["graph"],
  322. "removed_kwd": "N",
  323. }
  324. res = await trio.to_thread.run_sync(lambda: settings.docStoreConn.search(fields, [], condition, [], OrderByExpr(), 0, 1, search.index_name(tenant_id), [kb_id]))
  325. fields2 = settings.docStoreConn.getFields(res, fields)
  326. graph_doc_ids = set()
  327. for chunk_id in fields2.keys():
  328. graph_doc_ids = set(fields2[chunk_id]["source_id"])
  329. return doc_id in graph_doc_ids
  330. async def get_graph_doc_ids(tenant_id, kb_id) -> list[str]:
  331. conds = {
  332. "fields": ["source_id"],
  333. "removed_kwd": "N",
  334. "size": 1,
  335. "knowledge_graph_kwd": ["graph"]
  336. }
  337. res = await trio.to_thread.run_sync(lambda: settings.retrievaler.search(conds, search.index_name(tenant_id), [kb_id]))
  338. doc_ids = []
  339. if res.total == 0:
  340. return doc_ids
  341. for id in res.ids:
  342. doc_ids = res.field[id]["source_id"]
  343. return doc_ids
  344. async def get_graph(tenant_id, kb_id):
  345. conds = {
  346. "fields": ["content_with_weight", "source_id"],
  347. "removed_kwd": "N",
  348. "size": 1,
  349. "knowledge_graph_kwd": ["graph"]
  350. }
  351. res = await trio.to_thread.run_sync(lambda: settings.retrievaler.search(conds, search.index_name(tenant_id), [kb_id]))
  352. if res.total == 0:
  353. return None
  354. for id in res.ids:
  355. try:
  356. g = json_graph.node_link_graph(json.loads(res.field[id]["content_with_weight"]), edges="edges")
  357. if "source_id" not in g.graph:
  358. g.graph["source_id"] = res.field[id]["source_id"]
  359. return g
  360. except Exception:
  361. continue
  362. result = await rebuild_graph(tenant_id, kb_id)
  363. return result
  364. async def set_graph(tenant_id: str, kb_id: str, embd_mdl, graph: nx.Graph, change: GraphChange, callback):
  365. start = trio.current_time()
  366. await trio.to_thread.run_sync(lambda: settings.docStoreConn.delete({"knowledge_graph_kwd": ["graph"]}, search.index_name(tenant_id), kb_id))
  367. if change.removed_nodes:
  368. await trio.to_thread.run_sync(lambda: settings.docStoreConn.delete({"knowledge_graph_kwd": ["entity"], "entity_kwd": sorted(change.removed_nodes)}, search.index_name(tenant_id), kb_id))
  369. if change.removed_edges:
  370. async with trio.open_nursery() as nursery:
  371. for from_node, to_node in change.removed_edges:
  372. nursery.start_soon(lambda from_node=from_node, to_node=to_node: trio.to_thread.run_sync(lambda: settings.docStoreConn.delete({"knowledge_graph_kwd": ["relation"], "from_entity_kwd": from_node, "to_entity_kwd": to_node}, search.index_name(tenant_id), kb_id)))
  373. now = trio.current_time()
  374. if callback:
  375. callback(msg=f"set_graph removed {len(change.removed_nodes)} nodes and {len(change.removed_edges)} edges from index in {now - start:.2f}s.")
  376. start = now
  377. chunks = [{
  378. "id": get_uuid(),
  379. "content_with_weight": json.dumps(nx.node_link_data(graph, edges="edges"), ensure_ascii=False),
  380. "knowledge_graph_kwd": "graph",
  381. "kb_id": kb_id,
  382. "source_id": graph.graph.get("source_id", []),
  383. "available_int": 0,
  384. "removed_kwd": "N"
  385. }]
  386. async with trio.open_nursery() as nursery:
  387. for node in change.added_updated_nodes:
  388. node_attrs = graph.nodes[node]
  389. nursery.start_soon(graph_node_to_chunk, kb_id, embd_mdl, node, node_attrs, chunks)
  390. for from_node, to_node in change.added_updated_edges:
  391. edge_attrs = graph.get_edge_data(from_node, to_node)
  392. if not edge_attrs:
  393. # added_updated_edges could record a non-existing edge if both from_node and to_node participate in nodes merging.
  394. continue
  395. nursery.start_soon(graph_edge_to_chunk, kb_id, embd_mdl, from_node, to_node, edge_attrs, chunks)
  396. now = trio.current_time()
  397. if callback:
  398. callback(msg=f"set_graph converted graph change to {len(chunks)} chunks in {now - start:.2f}s.")
  399. start = now
  400. es_bulk_size = 4
  401. for b in range(0, len(chunks), es_bulk_size):
  402. doc_store_result = await trio.to_thread.run_sync(lambda: settings.docStoreConn.insert(chunks[b:b + es_bulk_size], search.index_name(tenant_id), kb_id))
  403. if doc_store_result:
  404. error_message = f"Insert chunk error: {doc_store_result}, please check log file and Elasticsearch/Infinity status!"
  405. raise Exception(error_message)
  406. now = trio.current_time()
  407. if callback:
  408. callback(msg=f"set_graph added/updated {len(change.added_updated_nodes)} nodes and {len(change.added_updated_edges)} edges from index in {now - start:.2f}s.")
  409. def is_continuous_subsequence(subseq, seq):
  410. def find_all_indexes(tup, value):
  411. indexes = []
  412. start = 0
  413. while True:
  414. try:
  415. index = tup.index(value, start)
  416. indexes.append(index)
  417. start = index + 1
  418. except ValueError:
  419. break
  420. return indexes
  421. index_list = find_all_indexes(seq,subseq[0])
  422. for idx in index_list:
  423. if idx!=len(seq)-1:
  424. if seq[idx+1]==subseq[-1]:
  425. return True
  426. return False
  427. def merge_tuples(list1, list2):
  428. result = []
  429. for tup in list1:
  430. last_element = tup[-1]
  431. if last_element in tup[:-1]:
  432. result.append(tup)
  433. else:
  434. matching_tuples = [t for t in list2 if t[0] == last_element]
  435. already_match_flag = 0
  436. for match in matching_tuples:
  437. matchh = (match[1], match[0])
  438. if is_continuous_subsequence(match, tup) or is_continuous_subsequence(matchh, tup):
  439. continue
  440. already_match_flag = 1
  441. merged_tuple = tup + match[1:]
  442. result.append(merged_tuple)
  443. if not already_match_flag:
  444. result.append(tup)
  445. return result
  446. async def get_entity_type2sampels(idxnms, kb_ids: list):
  447. es_res = await trio.to_thread.run_sync(lambda: settings.retrievaler.search({"knowledge_graph_kwd": "ty2ents", "kb_id": kb_ids,
  448. "size": 10000,
  449. "fields": ["content_with_weight"]},
  450. idxnms, kb_ids))
  451. res = defaultdict(list)
  452. for id in es_res.ids:
  453. smp = es_res.field[id].get("content_with_weight")
  454. if not smp:
  455. continue
  456. try:
  457. smp = json.loads(smp)
  458. except Exception as e:
  459. logging.exception(e)
  460. for ty, ents in smp.items():
  461. res[ty].extend(ents)
  462. return res
  463. def flat_uniq_list(arr, key):
  464. res = []
  465. for a in arr:
  466. a = a[key]
  467. if isinstance(a, list):
  468. res.extend(a)
  469. else:
  470. res.append(a)
  471. return list(set(res))
  472. async def rebuild_graph(tenant_id, kb_id):
  473. graph = nx.Graph()
  474. src_ids = set()
  475. flds = ["entity_kwd", "from_entity_kwd", "to_entity_kwd", "knowledge_graph_kwd", "content_with_weight", "source_id"]
  476. bs = 256
  477. for i in range(0, 1024*bs, bs):
  478. es_res = await trio.to_thread.run_sync(lambda: settings.docStoreConn.search(flds, [],
  479. {"kb_id": kb_id, "knowledge_graph_kwd": ["entity"]},
  480. [],
  481. OrderByExpr(),
  482. i, bs, search.index_name(tenant_id), [kb_id]
  483. ))
  484. tot = settings.docStoreConn.getTotal(es_res)
  485. if tot == 0:
  486. break
  487. es_res = settings.docStoreConn.getFields(es_res, flds)
  488. for id, d in es_res.items():
  489. assert d["knowledge_graph_kwd"] == "relation"
  490. src_ids.update(d.get("source_id", []))
  491. attrs = json.load(d["content_with_weight"])
  492. graph.add_node(d["entity_kwd"], **attrs)
  493. for i in range(0, 1024*bs, bs):
  494. es_res = await trio.to_thread.run_sync(lambda: settings.docStoreConn.search(flds, [],
  495. {"kb_id": kb_id, "knowledge_graph_kwd": ["relation"]},
  496. [],
  497. OrderByExpr(),
  498. i, bs, search.index_name(tenant_id), [kb_id]
  499. ))
  500. tot = settings.docStoreConn.getTotal(es_res)
  501. if tot == 0:
  502. return None
  503. es_res = settings.docStoreConn.getFields(es_res, flds)
  504. for id, d in es_res.items():
  505. assert d["knowledge_graph_kwd"] == "relation"
  506. src_ids.update(d.get("source_id", []))
  507. if graph.has_node(d["from_entity_kwd"]) and graph.has_node(d["to_entity_kwd"]):
  508. attrs = json.load(d["content_with_weight"])
  509. graph.add_edge(d["from_entity_kwd"], d["to_entity_kwd"], **attrs)
  510. src_ids = sorted(src_ids)
  511. graph.graph["source_id"] = src_ids
  512. return graph