Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

utils.py 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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 copy import deepcopy
  15. from hashlib import md5
  16. from typing import Any, Callable
  17. import networkx as nx
  18. import numpy as np
  19. import xxhash
  20. from networkx.readwrite import json_graph
  21. from api import settings
  22. from rag.nlp import search, rag_tokenizer
  23. from rag.utils.redis_conn import REDIS_CONN
  24. ErrorHandlerFn = Callable[[BaseException | None, str | None, dict | None], None]
  25. def perform_variable_replacements(
  26. input: str, history: list[dict] | None = None, variables: dict | None = None
  27. ) -> str:
  28. """Perform variable replacements on the input string and in a chat log."""
  29. if history is None:
  30. history = []
  31. if variables is None:
  32. variables = {}
  33. result = input
  34. def replace_all(input: str) -> str:
  35. result = input
  36. for k, v in variables.items():
  37. result = result.replace(f"{{{k}}}", v)
  38. return result
  39. result = replace_all(result)
  40. for i, entry in enumerate(history):
  41. if entry.get("role") == "system":
  42. entry["content"] = replace_all(entry.get("content") or "")
  43. return result
  44. def clean_str(input: Any) -> str:
  45. """Clean an input string by removing HTML escapes, control characters, and other unwanted characters."""
  46. # If we get non-string input, just give it back
  47. if not isinstance(input, str):
  48. return input
  49. result = html.unescape(input.strip())
  50. # https://stackoverflow.com/questions/4324790/removing-control-characters-from-a-string-in-python
  51. return re.sub(r"[\"\x00-\x1f\x7f-\x9f]", "", result)
  52. def dict_has_keys_with_types(
  53. data: dict, expected_fields: list[tuple[str, type]]
  54. ) -> bool:
  55. """Return True if the given dictionary has the given keys with the given types."""
  56. for field, field_type in expected_fields:
  57. if field not in data:
  58. return False
  59. value = data[field]
  60. if not isinstance(value, field_type):
  61. return False
  62. return True
  63. def get_llm_cache(llmnm, txt, history, genconf):
  64. hasher = xxhash.xxh64()
  65. hasher.update(str(llmnm).encode("utf-8"))
  66. hasher.update(str(txt).encode("utf-8"))
  67. hasher.update(str(history).encode("utf-8"))
  68. hasher.update(str(genconf).encode("utf-8"))
  69. k = hasher.hexdigest()
  70. bin = REDIS_CONN.get(k)
  71. if not bin:
  72. return
  73. return bin
  74. def set_llm_cache(llmnm, txt, v, history, genconf):
  75. hasher = xxhash.xxh64()
  76. hasher.update(str(llmnm).encode("utf-8"))
  77. hasher.update(str(txt).encode("utf-8"))
  78. hasher.update(str(history).encode("utf-8"))
  79. hasher.update(str(genconf).encode("utf-8"))
  80. k = hasher.hexdigest()
  81. REDIS_CONN.set(k, v.encode("utf-8"), 24*3600)
  82. def get_embed_cache(llmnm, txt):
  83. hasher = xxhash.xxh64()
  84. hasher.update(str(llmnm).encode("utf-8"))
  85. hasher.update(str(txt).encode("utf-8"))
  86. k = hasher.hexdigest()
  87. bin = REDIS_CONN.get(k)
  88. if not bin:
  89. return
  90. return np.array(json.loads(bin))
  91. def set_embed_cache(llmnm, txt, arr):
  92. hasher = xxhash.xxh64()
  93. hasher.update(str(llmnm).encode("utf-8"))
  94. hasher.update(str(txt).encode("utf-8"))
  95. k = hasher.hexdigest()
  96. arr = json.dumps(arr.tolist() if isinstance(arr, np.ndarray) else arr)
  97. REDIS_CONN.set(k, arr.encode("utf-8"), 24*3600)
  98. def get_tags_from_cache(kb_ids):
  99. hasher = xxhash.xxh64()
  100. hasher.update(str(kb_ids).encode("utf-8"))
  101. k = hasher.hexdigest()
  102. bin = REDIS_CONN.get(k)
  103. if not bin:
  104. return
  105. return bin
  106. def set_tags_to_cache(kb_ids, tags):
  107. hasher = xxhash.xxh64()
  108. hasher.update(str(kb_ids).encode("utf-8"))
  109. k = hasher.hexdigest()
  110. REDIS_CONN.set(k, json.dumps(tags).encode("utf-8"), 600)
  111. def graph_merge(g1, g2):
  112. g = g2.copy()
  113. for n, attr in g1.nodes(data=True):
  114. if n not in g2.nodes():
  115. g.add_node(n, **attr)
  116. continue
  117. for source, target, attr in g1.edges(data=True):
  118. if g.has_edge(source, target):
  119. g[source][target].update({"weight": attr.get("weight", 0)+1})
  120. continue
  121. g.add_edge(source, target)#, **attr)
  122. for node_degree in g.degree:
  123. g.nodes[str(node_degree[0])]["rank"] = int(node_degree[1])
  124. return g
  125. def compute_args_hash(*args):
  126. return md5(str(args).encode()).hexdigest()
  127. def handle_single_entity_extraction(
  128. record_attributes: list[str],
  129. chunk_key: str,
  130. ):
  131. if len(record_attributes) < 4 or record_attributes[0] != '"entity"':
  132. return None
  133. # add this record as a node in the G
  134. entity_name = clean_str(record_attributes[1].upper())
  135. if not entity_name.strip():
  136. return None
  137. entity_type = clean_str(record_attributes[2].upper())
  138. entity_description = clean_str(record_attributes[3])
  139. entity_source_id = chunk_key
  140. return dict(
  141. entity_name=entity_name.upper(),
  142. entity_type=entity_type.upper(),
  143. description=entity_description,
  144. source_id=entity_source_id,
  145. )
  146. def handle_single_relationship_extraction(record_attributes: list[str], chunk_key: str):
  147. if len(record_attributes) < 5 or record_attributes[0] != '"relationship"':
  148. return None
  149. # add this record as edge
  150. source = clean_str(record_attributes[1].upper())
  151. target = clean_str(record_attributes[2].upper())
  152. edge_description = clean_str(record_attributes[3])
  153. edge_keywords = clean_str(record_attributes[4])
  154. edge_source_id = chunk_key
  155. weight = (
  156. float(record_attributes[-1]) if is_float_regex(record_attributes[-1]) else 1.0
  157. )
  158. pair = sorted([source.upper(), target.upper()])
  159. return dict(
  160. src_id=pair[0],
  161. tgt_id=pair[1],
  162. weight=weight,
  163. description=edge_description,
  164. keywords=edge_keywords,
  165. source_id=edge_source_id,
  166. metadata={"created_at": time.time()},
  167. )
  168. def pack_user_ass_to_openai_messages(*args: str):
  169. roles = ["user", "assistant"]
  170. return [
  171. {"role": roles[i % 2], "content": content} for i, content in enumerate(args)
  172. ]
  173. def split_string_by_multi_markers(content: str, markers: list[str]) -> list[str]:
  174. """Split a string by multiple markers"""
  175. if not markers:
  176. return [content]
  177. results = re.split("|".join(re.escape(marker) for marker in markers), content)
  178. return [r.strip() for r in results if r.strip()]
  179. def is_float_regex(value):
  180. return bool(re.match(r"^[-+]?[0-9]*\.?[0-9]+$", value))
  181. def chunk_id(chunk):
  182. return xxhash.xxh64((chunk["content_with_weight"] + chunk["kb_id"]).encode("utf-8")).hexdigest()
  183. def get_entity(tenant_id, kb_id, ent_name):
  184. conds = {
  185. "fields": ["content_with_weight"],
  186. "entity_kwd": ent_name,
  187. "size": 10000,
  188. "knowledge_graph_kwd": ["entity"]
  189. }
  190. res = []
  191. es_res = settings.retrievaler.search(conds, search.index_name(tenant_id), [kb_id])
  192. for id in es_res.ids:
  193. try:
  194. if isinstance(ent_name, str):
  195. return json.loads(es_res.field[id]["content_with_weight"])
  196. res.append(json.loads(es_res.field[id]["content_with_weight"]))
  197. except Exception:
  198. continue
  199. return res
  200. def set_entity(tenant_id, kb_id, embd_mdl, ent_name, meta):
  201. chunk = {
  202. "important_kwd": [ent_name],
  203. "title_tks": rag_tokenizer.tokenize(ent_name),
  204. "entity_kwd": ent_name,
  205. "knowledge_graph_kwd": "entity",
  206. "entity_type_kwd": meta["entity_type"],
  207. "content_with_weight": json.dumps(meta, ensure_ascii=False),
  208. "content_ltks": rag_tokenizer.tokenize(meta["description"]),
  209. "source_id": list(set(meta["source_id"])),
  210. "kb_id": kb_id,
  211. "available_int": 0
  212. }
  213. chunk["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(chunk["content_ltks"])
  214. res = settings.retrievaler.search({"entity_kwd": ent_name, "size": 1, "fields": []},
  215. search.index_name(tenant_id), [kb_id])
  216. if res.ids:
  217. settings.docStoreConn.update({"entity_kwd": ent_name}, chunk, search.index_name(tenant_id), kb_id)
  218. else:
  219. ebd = get_embed_cache(embd_mdl.llm_name, ent_name)
  220. if ebd is None:
  221. try:
  222. ebd, _ = embd_mdl.encode([ent_name])
  223. ebd = ebd[0]
  224. set_embed_cache(embd_mdl.llm_name, ent_name, ebd)
  225. except Exception as e:
  226. logging.exception(f"Fail to embed entity: {e}")
  227. if ebd is not None:
  228. chunk["q_%d_vec" % len(ebd)] = ebd
  229. settings.docStoreConn.insert([{"id": chunk_id(chunk), **chunk}], search.index_name(tenant_id))
  230. def get_relation(tenant_id, kb_id, from_ent_name, to_ent_name, size=1):
  231. ents = from_ent_name
  232. if isinstance(ents, str):
  233. ents = [from_ent_name]
  234. if isinstance(to_ent_name, str):
  235. to_ent_name = [to_ent_name]
  236. ents.extend(to_ent_name)
  237. ents = list(set(ents))
  238. conds = {
  239. "fields": ["content_with_weight"],
  240. "size": size,
  241. "from_entity_kwd": ents,
  242. "to_entity_kwd": ents,
  243. "knowledge_graph_kwd": ["relation"]
  244. }
  245. res = []
  246. es_res = settings.retrievaler.search(conds, search.index_name(tenant_id), [kb_id] if isinstance(kb_id, str) else kb_id)
  247. for id in es_res.ids:
  248. try:
  249. if size == 1:
  250. return json.loads(es_res.field[id]["content_with_weight"])
  251. res.append(json.loads(es_res.field[id]["content_with_weight"]))
  252. except Exception:
  253. continue
  254. return res
  255. def set_relation(tenant_id, kb_id, embd_mdl, from_ent_name, to_ent_name, meta):
  256. chunk = {
  257. "from_entity_kwd": from_ent_name,
  258. "to_entity_kwd": to_ent_name,
  259. "knowledge_graph_kwd": "relation",
  260. "content_with_weight": json.dumps(meta, ensure_ascii=False),
  261. "content_ltks": rag_tokenizer.tokenize(meta["description"]),
  262. "important_kwd": meta["keywords"],
  263. "source_id": list(set(meta["source_id"])),
  264. "weight_int": int(meta["weight"]),
  265. "kb_id": kb_id,
  266. "available_int": 0
  267. }
  268. chunk["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(chunk["content_ltks"])
  269. res = settings.retrievaler.search({"from_entity_kwd": to_ent_name, "to_entity_kwd": to_ent_name, "size": 1, "fields": []},
  270. search.index_name(tenant_id), [kb_id])
  271. if res.ids:
  272. settings.docStoreConn.update({"from_entity_kwd": from_ent_name, "to_entity_kwd": to_ent_name},
  273. chunk,
  274. search.index_name(tenant_id), kb_id)
  275. else:
  276. txt = f"{from_ent_name}->{to_ent_name}"
  277. ebd = get_embed_cache(embd_mdl.llm_name, txt)
  278. if ebd is None:
  279. try:
  280. ebd, _ = embd_mdl.encode([txt+f": {meta['description']}"])
  281. ebd = ebd[0]
  282. set_embed_cache(embd_mdl.llm_name, txt, ebd)
  283. except Exception as e:
  284. logging.exception(f"Fail to embed entity relation: {e}")
  285. if ebd is not None:
  286. chunk["q_%d_vec" % len(ebd)] = ebd
  287. settings.docStoreConn.insert([{"id": chunk_id(chunk), **chunk}], search.index_name(tenant_id))
  288. def get_graph(tenant_id, kb_id):
  289. conds = {
  290. "fields": ["content_with_weight", "source_id"],
  291. "removed_kwd": "N",
  292. "size": 1,
  293. "knowledge_graph_kwd": ["graph"]
  294. }
  295. res = settings.retrievaler.search(conds, search.index_name(tenant_id), [kb_id])
  296. for id in res.ids:
  297. try:
  298. return json_graph.node_link_graph(json.loads(res.field[id]["content_with_weight"]), edges="edges"), \
  299. res.field[id]["source_id"]
  300. except Exception:
  301. continue
  302. return None, None
  303. def set_graph(tenant_id, kb_id, graph, docids):
  304. chunk = {
  305. "content_with_weight": json.dumps(nx.node_link_data(graph, edges="edges"), ensure_ascii=False,
  306. indent=2),
  307. "knowledge_graph_kwd": "graph",
  308. "kb_id": kb_id,
  309. "source_id": list(docids),
  310. "available_int": 0,
  311. "removed_kwd": "N"
  312. }
  313. res = settings.retrievaler.search({"knowledge_graph_kwd": "graph", "size": 1, "fields": []}, search.index_name(tenant_id), [kb_id])
  314. if res.ids:
  315. settings.docStoreConn.update({"knowledge_graph_kwd": "graph"}, chunk,
  316. search.index_name(tenant_id), kb_id)
  317. else:
  318. settings.docStoreConn.insert([{"id": chunk_id(chunk), **chunk}], search.index_name(tenant_id))
  319. def is_continuous_subsequence(subseq, seq):
  320. def find_all_indexes(tup, value):
  321. indexes = []
  322. start = 0
  323. while True:
  324. try:
  325. index = tup.index(value, start)
  326. indexes.append(index)
  327. start = index + 1
  328. except ValueError:
  329. break
  330. return indexes
  331. index_list = find_all_indexes(seq,subseq[0])
  332. for idx in index_list:
  333. if idx!=len(seq)-1:
  334. if seq[idx+1]==subseq[-1]:
  335. return True
  336. return False
  337. def merge_tuples(list1, list2):
  338. result = []
  339. for tup in list1:
  340. last_element = tup[-1]
  341. if last_element in tup[:-1]:
  342. result.append(tup)
  343. else:
  344. matching_tuples = [t for t in list2 if t[0] == last_element]
  345. already_match_flag = 0
  346. for match in matching_tuples:
  347. matchh = (match[1], match[0])
  348. if is_continuous_subsequence(match, tup) or is_continuous_subsequence(matchh, tup):
  349. continue
  350. already_match_flag = 1
  351. merged_tuple = tup + match[1:]
  352. result.append(merged_tuple)
  353. if not already_match_flag:
  354. result.append(tup)
  355. return result
  356. def update_nodes_pagerank_nhop_neighbour(tenant_id, kb_id, graph, n_hop):
  357. def n_neighbor(id):
  358. nonlocal graph, n_hop
  359. count = 0
  360. source_edge = list(graph.edges(id))
  361. if not source_edge:
  362. return []
  363. count = count + 1
  364. while count < n_hop:
  365. count = count + 1
  366. sc_edge = deepcopy(source_edge)
  367. source_edge = []
  368. for pair in sc_edge:
  369. append_edge = list(graph.edges(pair[-1]))
  370. for tuples in merge_tuples([pair], append_edge):
  371. source_edge.append(tuples)
  372. nbrs = []
  373. for path in source_edge:
  374. n = {"path": path, "weights": []}
  375. wts = nx.get_edge_attributes(graph, 'weight')
  376. for i in range(len(path)-1):
  377. f, t = path[i], path[i+1]
  378. n["weights"].append(wts.get((f, t), 0))
  379. nbrs.append(n)
  380. return nbrs
  381. pr = nx.pagerank(graph)
  382. for n, p in pr.items():
  383. graph.nodes[n]["pagerank"] = p
  384. try:
  385. settings.docStoreConn.update({"entity_kwd": n, "kb_id": kb_id},
  386. {"rank_flt": p,
  387. "n_hop_with_weight": json.dumps(n_neighbor(n), ensure_ascii=False)},
  388. search.index_name(tenant_id), kb_id)
  389. except Exception as e:
  390. logging.exception(e)
  391. ty2ents = defaultdict(list)
  392. for p, r in sorted(pr.items(), key=lambda x: x[1], reverse=True):
  393. ty = graph.nodes[p].get("entity_type")
  394. if not ty or len(ty2ents[ty]) > 12:
  395. continue
  396. ty2ents[ty].append(p)
  397. chunk = {
  398. "content_with_weight": json.dumps(ty2ents, ensure_ascii=False),
  399. "kb_id": kb_id,
  400. "knowledge_graph_kwd": "ty2ents",
  401. "available_int": 0
  402. }
  403. res = settings.retrievaler.search({"knowledge_graph_kwd": "ty2ents", "size": 1, "fields": []},
  404. search.index_name(tenant_id), [kb_id])
  405. if res.ids:
  406. settings.docStoreConn.update({"knowledge_graph_kwd": "ty2ents"},
  407. chunk,
  408. search.index_name(tenant_id), kb_id)
  409. else:
  410. settings.docStoreConn.insert([{"id": chunk_id(chunk), **chunk}], search.index_name(tenant_id))
  411. def get_entity_type2sampels(idxnms, kb_ids: list):
  412. es_res = settings.retrievaler.search({"knowledge_graph_kwd": "ty2ents", "kb_id": kb_ids,
  413. "size": 10000,
  414. "fields": ["content_with_weight"]},
  415. idxnms, kb_ids)
  416. res = defaultdict(list)
  417. for id in es_res.ids:
  418. smp = es_res.field[id].get("content_with_weight")
  419. if not smp:
  420. continue
  421. try:
  422. smp = json.loads(smp)
  423. except Exception as e:
  424. logging.exception(e)
  425. for ty, ents in smp.items():
  426. res[ty].extend(ents)
  427. return res
  428. def flat_uniq_list(arr, key):
  429. res = []
  430. for a in arr:
  431. a = a[key]
  432. if isinstance(a, list):
  433. res.extend(a)
  434. else:
  435. res.append(a)
  436. return list(set(res))