You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import logging
  17. import re
  18. from dataclasses import dataclass
  19. from rag.settings import TAG_FLD, PAGERANK_FLD
  20. from rag.utils import rmSpace, get_float
  21. from rag.nlp import rag_tokenizer, query
  22. import numpy as np
  23. from rag.utils.doc_store_conn import DocStoreConnection, MatchDenseExpr, FusionExpr, OrderByExpr
  24. def index_name(uid): return f"ragflow_{uid}"
  25. class Dealer:
  26. def __init__(self, dataStore: DocStoreConnection):
  27. self.qryr = query.FulltextQueryer()
  28. self.dataStore = dataStore
  29. @dataclass
  30. class SearchResult:
  31. total: int
  32. ids: list[str]
  33. query_vector: list[float] | None = None
  34. field: dict | None = None
  35. highlight: dict | None = None
  36. aggregation: list | dict | None = None
  37. keywords: list[str] | None = None
  38. group_docs: list[list] | None = None
  39. def get_vector(self, txt, emb_mdl, topk=10, similarity=0.1):
  40. qv, _ = emb_mdl.encode_queries(txt)
  41. shape = np.array(qv).shape
  42. if len(shape) > 1:
  43. raise Exception(
  44. f"Dealer.get_vector returned array's shape {shape} doesn't match expectation(exact one dimension).")
  45. embedding_data = [get_float(v) for v in qv]
  46. vector_column_name = f"q_{len(embedding_data)}_vec"
  47. return MatchDenseExpr(vector_column_name, embedding_data, 'float', 'cosine', topk, {"similarity": similarity})
  48. def get_filters(self, req):
  49. condition = dict()
  50. for key, field in {"kb_ids": "kb_id", "doc_ids": "doc_id"}.items():
  51. if key in req and req[key] is not None:
  52. condition[field] = req[key]
  53. # TODO(yzc): `available_int` is nullable however infinity doesn't support nullable columns.
  54. for key in ["knowledge_graph_kwd", "available_int", "entity_kwd", "from_entity_kwd", "to_entity_kwd", "removed_kwd"]:
  55. if key in req and req[key] is not None:
  56. condition[key] = req[key]
  57. return condition
  58. def search(self, req, idx_names: str | list[str],
  59. kb_ids: list[str],
  60. emb_mdl=None,
  61. highlight=False,
  62. rank_feature: dict | None = None
  63. ):
  64. filters = self.get_filters(req)
  65. orderBy = OrderByExpr()
  66. pg = int(req.get("page", 1)) - 1
  67. topk = int(req.get("topk", 1024))
  68. ps = int(req.get("size", topk))
  69. offset, limit = pg * ps, ps
  70. src = req.get("fields",
  71. ["docnm_kwd", "content_ltks", "kb_id", "img_id", "title_tks", "important_kwd", "position_int",
  72. "doc_id", "page_num_int", "top_int", "create_timestamp_flt", "knowledge_graph_kwd",
  73. "question_kwd", "question_tks",
  74. "available_int", "content_with_weight", PAGERANK_FLD, TAG_FLD])
  75. kwds = set([])
  76. qst = req.get("question", "")
  77. q_vec = []
  78. if not qst:
  79. if req.get("sort"):
  80. orderBy.asc("page_num_int")
  81. orderBy.asc("top_int")
  82. orderBy.desc("create_timestamp_flt")
  83. res = self.dataStore.search(src, [], filters, [], orderBy, offset, limit, idx_names, kb_ids)
  84. total = self.dataStore.getTotal(res)
  85. logging.debug("Dealer.search TOTAL: {}".format(total))
  86. else:
  87. highlightFields = ["content_ltks", "title_tks"] if highlight else []
  88. matchText, keywords = self.qryr.question(qst, min_match=0.3)
  89. if emb_mdl is None:
  90. matchExprs = [matchText]
  91. res = self.dataStore.search(src, highlightFields, filters, matchExprs, orderBy, offset, limit,
  92. idx_names, kb_ids, rank_feature=rank_feature)
  93. total = self.dataStore.getTotal(res)
  94. logging.debug("Dealer.search TOTAL: {}".format(total))
  95. else:
  96. matchDense = self.get_vector(qst, emb_mdl, topk, req.get("similarity", 0.1))
  97. q_vec = matchDense.embedding_data
  98. src.append(f"q_{len(q_vec)}_vec")
  99. fusionExpr = FusionExpr("weighted_sum", topk, {"weights": "0.05, 0.95"})
  100. matchExprs = [matchText, matchDense, fusionExpr]
  101. res = self.dataStore.search(src, highlightFields, filters, matchExprs, orderBy, offset, limit,
  102. idx_names, kb_ids, rank_feature=rank_feature)
  103. total = self.dataStore.getTotal(res)
  104. logging.debug("Dealer.search TOTAL: {}".format(total))
  105. # If result is empty, try again with lower min_match
  106. if total == 0:
  107. if filters.get("doc_id"):
  108. res = self.dataStore.search(src, [], filters, [], orderBy, offset, limit, idx_names, kb_ids)
  109. total = self.dataStore.getTotal(res)
  110. else:
  111. matchText, _ = self.qryr.question(qst, min_match=0.1)
  112. filters.pop("doc_id", None)
  113. matchDense.extra_options["similarity"] = 0.17
  114. res = self.dataStore.search(src, highlightFields, filters, [matchText, matchDense, fusionExpr],
  115. orderBy, offset, limit, idx_names, kb_ids, rank_feature=rank_feature)
  116. total = self.dataStore.getTotal(res)
  117. logging.debug("Dealer.search 2 TOTAL: {}".format(total))
  118. for k in keywords:
  119. kwds.add(k)
  120. for kk in rag_tokenizer.fine_grained_tokenize(k).split():
  121. if len(kk) < 2:
  122. continue
  123. if kk in kwds:
  124. continue
  125. kwds.add(kk)
  126. logging.debug(f"TOTAL: {total}")
  127. ids = self.dataStore.getChunkIds(res)
  128. keywords = list(kwds)
  129. highlight = self.dataStore.getHighlight(res, keywords, "content_with_weight")
  130. aggs = self.dataStore.getAggregation(res, "docnm_kwd")
  131. return self.SearchResult(
  132. total=total,
  133. ids=ids,
  134. query_vector=q_vec,
  135. aggregation=aggs,
  136. highlight=highlight,
  137. field=self.dataStore.getFields(res, src),
  138. keywords=keywords
  139. )
  140. @staticmethod
  141. def trans2floats(txt):
  142. return [get_float(t) for t in txt.split("\t")]
  143. def insert_citations(self, answer, chunks, chunk_v,
  144. embd_mdl, tkweight=0.1, vtweight=0.9):
  145. assert len(chunks) == len(chunk_v)
  146. if not chunks:
  147. return answer, set([])
  148. pieces = re.split(r"(```)", answer)
  149. if len(pieces) >= 3:
  150. i = 0
  151. pieces_ = []
  152. while i < len(pieces):
  153. if pieces[i] == "```":
  154. st = i
  155. i += 1
  156. while i < len(pieces) and pieces[i] != "```":
  157. i += 1
  158. if i < len(pieces):
  159. i += 1
  160. pieces_.append("".join(pieces[st: i]) + "\n")
  161. else:
  162. pieces_.extend(
  163. re.split(
  164. r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])",
  165. pieces[i]))
  166. i += 1
  167. pieces = pieces_
  168. else:
  169. pieces = re.split(r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])", answer)
  170. for i in range(1, len(pieces)):
  171. if re.match(r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])", pieces[i]):
  172. pieces[i - 1] += pieces[i][0]
  173. pieces[i] = pieces[i][1:]
  174. idx = []
  175. pieces_ = []
  176. for i, t in enumerate(pieces):
  177. if len(t) < 5:
  178. continue
  179. idx.append(i)
  180. pieces_.append(t)
  181. logging.debug("{} => {}".format(answer, pieces_))
  182. if not pieces_:
  183. return answer, set([])
  184. ans_v, _ = embd_mdl.encode(pieces_)
  185. for i in range(len(chunk_v)):
  186. if len(ans_v[0]) != len(chunk_v[i]):
  187. chunk_v[i] = [0.0]*len(ans_v[0])
  188. logging.warning("The dimension of query and chunk do not match: {} vs. {}".format(len(ans_v[0]), len(chunk_v[i])))
  189. assert len(ans_v[0]) == len(chunk_v[0]), "The dimension of query and chunk do not match: {} vs. {}".format(
  190. len(ans_v[0]), len(chunk_v[0]))
  191. chunks_tks = [rag_tokenizer.tokenize(self.qryr.rmWWW(ck)).split()
  192. for ck in chunks]
  193. cites = {}
  194. thr = 0.63
  195. while thr > 0.3 and len(cites.keys()) == 0 and pieces_ and chunks_tks:
  196. for i, a in enumerate(pieces_):
  197. sim, tksim, vtsim = self.qryr.hybrid_similarity(ans_v[i],
  198. chunk_v,
  199. rag_tokenizer.tokenize(
  200. self.qryr.rmWWW(pieces_[i])).split(),
  201. chunks_tks,
  202. tkweight, vtweight)
  203. mx = np.max(sim) * 0.99
  204. logging.debug("{} SIM: {}".format(pieces_[i], mx))
  205. if mx < thr:
  206. continue
  207. cites[idx[i]] = list(
  208. set([str(ii) for ii in range(len(chunk_v)) if sim[ii] > mx]))[:4]
  209. thr *= 0.8
  210. res = ""
  211. seted = set([])
  212. for i, p in enumerate(pieces):
  213. res += p
  214. if i not in idx:
  215. continue
  216. if i not in cites:
  217. continue
  218. for c in cites[i]:
  219. assert int(c) < len(chunk_v)
  220. for c in cites[i]:
  221. if c in seted:
  222. continue
  223. res += f" ##{c}$$"
  224. seted.add(c)
  225. return res, seted
  226. def _rank_feature_scores(self, query_rfea, search_res):
  227. ## For rank feature(tag_fea) scores.
  228. rank_fea = []
  229. pageranks = []
  230. for chunk_id in search_res.ids:
  231. pageranks.append(search_res.field[chunk_id].get(PAGERANK_FLD, 0))
  232. pageranks = np.array(pageranks, dtype=float)
  233. if not query_rfea:
  234. return np.array([0 for _ in range(len(search_res.ids))]) + pageranks
  235. q_denor = np.sqrt(np.sum([s*s for t,s in query_rfea.items() if t != PAGERANK_FLD]))
  236. for i in search_res.ids:
  237. nor, denor = 0, 0
  238. if not search_res.field[i].get(TAG_FLD):
  239. rank_fea.append(0)
  240. continue
  241. for t, sc in eval(search_res.field[i].get(TAG_FLD, "{}")).items():
  242. if t in query_rfea:
  243. nor += query_rfea[t] * sc
  244. denor += sc * sc
  245. if denor == 0:
  246. rank_fea.append(0)
  247. else:
  248. rank_fea.append(nor/np.sqrt(denor)/q_denor)
  249. return np.array(rank_fea)*10. + pageranks
  250. def rerank(self, sres, query, tkweight=0.3,
  251. vtweight=0.7, cfield="content_ltks",
  252. rank_feature: dict | None = None
  253. ):
  254. _, keywords = self.qryr.question(query)
  255. vector_size = len(sres.query_vector)
  256. vector_column = f"q_{vector_size}_vec"
  257. zero_vector = [0.0] * vector_size
  258. ins_embd = []
  259. for chunk_id in sres.ids:
  260. vector = sres.field[chunk_id].get(vector_column, zero_vector)
  261. if isinstance(vector, str):
  262. vector = [get_float(v) for v in vector.split("\t")]
  263. ins_embd.append(vector)
  264. if not ins_embd:
  265. return [], [], []
  266. for i in sres.ids:
  267. if isinstance(sres.field[i].get("important_kwd", []), str):
  268. sres.field[i]["important_kwd"] = [sres.field[i]["important_kwd"]]
  269. ins_tw = []
  270. for i in sres.ids:
  271. content_ltks = sres.field[i][cfield].split()
  272. title_tks = [t for t in sres.field[i].get("title_tks", "").split() if t]
  273. question_tks = [t for t in sres.field[i].get("question_tks", "").split() if t]
  274. important_kwd = sres.field[i].get("important_kwd", [])
  275. tks = content_ltks + title_tks * 2 + important_kwd * 5 + question_tks * 6
  276. ins_tw.append(tks)
  277. ## For rank feature(tag_fea) scores.
  278. rank_fea = self._rank_feature_scores(rank_feature, sres)
  279. sim, tksim, vtsim = self.qryr.hybrid_similarity(sres.query_vector,
  280. ins_embd,
  281. keywords,
  282. ins_tw, tkweight, vtweight)
  283. return sim + rank_fea, tksim, vtsim
  284. def rerank_by_model(self, rerank_mdl, sres, query, tkweight=0.3,
  285. vtweight=0.7, cfield="content_ltks",
  286. rank_feature: dict | None = None):
  287. _, keywords = self.qryr.question(query)
  288. for i in sres.ids:
  289. if isinstance(sres.field[i].get("important_kwd", []), str):
  290. sres.field[i]["important_kwd"] = [sres.field[i]["important_kwd"]]
  291. ins_tw = []
  292. for i in sres.ids:
  293. content_ltks = sres.field[i][cfield].split()
  294. title_tks = [t for t in sres.field[i].get("title_tks", "").split() if t]
  295. important_kwd = sres.field[i].get("important_kwd", [])
  296. tks = content_ltks + title_tks + important_kwd
  297. ins_tw.append(tks)
  298. tksim = self.qryr.token_similarity(keywords, ins_tw)
  299. vtsim, _ = rerank_mdl.similarity(query, [rmSpace(" ".join(tks)) for tks in ins_tw])
  300. ## For rank feature(tag_fea) scores.
  301. rank_fea = self._rank_feature_scores(rank_feature, sres)
  302. return tkweight * (np.array(tksim)+rank_fea) + vtweight * vtsim, tksim, vtsim
  303. def hybrid_similarity(self, ans_embd, ins_embd, ans, inst):
  304. return self.qryr.hybrid_similarity(ans_embd,
  305. ins_embd,
  306. rag_tokenizer.tokenize(ans).split(),
  307. rag_tokenizer.tokenize(inst).split())
  308. def retrieval(self, question, embd_mdl, tenant_ids, kb_ids, page, page_size, similarity_threshold=0.2,
  309. vector_similarity_weight=0.3, top=1024, doc_ids=None, aggs=True,
  310. rerank_mdl=None, highlight=False,
  311. rank_feature: dict | None = {PAGERANK_FLD: 10}):
  312. ranks = {"total": 0, "chunks": [], "doc_aggs": {}}
  313. if not question:
  314. return ranks
  315. RERANK_LIMIT = 64
  316. req = {"kb_ids": kb_ids, "doc_ids": doc_ids, "page": page, "size": RERANK_LIMIT,
  317. "question": question, "vector": True, "topk": top,
  318. "similarity": similarity_threshold,
  319. "available_int": 1}
  320. if isinstance(tenant_ids, str):
  321. tenant_ids = tenant_ids.split(",")
  322. sres = self.search(req, [index_name(tid) for tid in tenant_ids],
  323. kb_ids, embd_mdl, highlight, rank_feature=rank_feature)
  324. ranks["total"] = sres.total
  325. if rerank_mdl and sres.total > 0:
  326. sim, tsim, vsim = self.rerank_by_model(rerank_mdl,
  327. sres, question, 1 - vector_similarity_weight,
  328. vector_similarity_weight,
  329. rank_feature=rank_feature)
  330. else:
  331. sim, tsim, vsim = self.rerank(
  332. sres, question, 1 - vector_similarity_weight, vector_similarity_weight,
  333. rank_feature=rank_feature)
  334. idx = np.argsort(sim * -1)[(page - 1) * page_size:page * page_size]
  335. dim = len(sres.query_vector)
  336. vector_column = f"q_{dim}_vec"
  337. zero_vector = [0.0] * dim
  338. if doc_ids:
  339. similarity_threshold = 0
  340. page_size = 30
  341. for i in idx:
  342. if sim[i] < similarity_threshold:
  343. break
  344. if len(ranks["chunks"]) >= page_size:
  345. if aggs:
  346. continue
  347. break
  348. id = sres.ids[i]
  349. chunk = sres.field[id]
  350. dnm = chunk.get("docnm_kwd", "")
  351. did = chunk.get("doc_id", "")
  352. position_int = chunk.get("position_int", [])
  353. d = {
  354. "chunk_id": id,
  355. "content_ltks": chunk["content_ltks"],
  356. "content_with_weight": chunk["content_with_weight"],
  357. "doc_id": did,
  358. "docnm_kwd": dnm,
  359. "kb_id": chunk["kb_id"],
  360. "important_kwd": chunk.get("important_kwd", []),
  361. "image_id": chunk.get("img_id", ""),
  362. "similarity": sim[i],
  363. "vector_similarity": vsim[i],
  364. "term_similarity": tsim[i],
  365. "vector": chunk.get(vector_column, zero_vector),
  366. "positions": position_int,
  367. }
  368. if highlight and sres.highlight:
  369. if id in sres.highlight:
  370. d["highlight"] = rmSpace(sres.highlight[id])
  371. else:
  372. d["highlight"] = d["content_with_weight"]
  373. ranks["chunks"].append(d)
  374. if dnm not in ranks["doc_aggs"]:
  375. ranks["doc_aggs"][dnm] = {"doc_id": did, "count": 0}
  376. ranks["doc_aggs"][dnm]["count"] += 1
  377. ranks["doc_aggs"] = [{"doc_name": k,
  378. "doc_id": v["doc_id"],
  379. "count": v["count"]} for k,
  380. v in sorted(ranks["doc_aggs"].items(),
  381. key=lambda x: x[1]["count"] * -1)]
  382. ranks["chunks"] = ranks["chunks"][:page_size]
  383. return ranks
  384. def sql_retrieval(self, sql, fetch_size=128, format="json"):
  385. tbl = self.dataStore.sql(sql, fetch_size, format)
  386. return tbl
  387. def chunk_list(self, doc_id: str, tenant_id: str,
  388. kb_ids: list[str], max_count=1024,
  389. offset=0,
  390. fields=["docnm_kwd", "content_with_weight", "img_id"]):
  391. condition = {"doc_id": doc_id}
  392. res = []
  393. bs = 128
  394. for p in range(offset, max_count, bs):
  395. es_res = self.dataStore.search(fields, [], condition, [], OrderByExpr(), p, bs, index_name(tenant_id),
  396. kb_ids)
  397. dict_chunks = self.dataStore.getFields(es_res, fields)
  398. for id, doc in dict_chunks.items():
  399. doc["id"] = id
  400. if dict_chunks:
  401. res.extend(dict_chunks.values())
  402. if len(dict_chunks.values()) < bs:
  403. break
  404. return res
  405. def all_tags(self, tenant_id: str, kb_ids: list[str], S=1000):
  406. if not self.dataStore.indexExist(index_name(tenant_id), kb_ids[0]):
  407. return []
  408. res = self.dataStore.search([], [], {}, [], OrderByExpr(), 0, 0, index_name(tenant_id), kb_ids, ["tag_kwd"])
  409. return self.dataStore.getAggregation(res, "tag_kwd")
  410. def all_tags_in_portion(self, tenant_id: str, kb_ids: list[str], S=1000):
  411. res = self.dataStore.search([], [], {}, [], OrderByExpr(), 0, 0, index_name(tenant_id), kb_ids, ["tag_kwd"])
  412. res = self.dataStore.getAggregation(res, "tag_kwd")
  413. total = np.sum([c for _, c in res])
  414. return {t: (c + 1) / (total + S) for t, c in res}
  415. def tag_content(self, tenant_id: str, kb_ids: list[str], doc, all_tags, topn_tags=3, keywords_topn=30, S=1000):
  416. idx_nm = index_name(tenant_id)
  417. match_txt = self.qryr.paragraph(doc["title_tks"] + " " + doc["content_ltks"], doc.get("important_kwd", []), keywords_topn)
  418. res = self.dataStore.search([], [], {}, [match_txt], OrderByExpr(), 0, 0, idx_nm, kb_ids, ["tag_kwd"])
  419. aggs = self.dataStore.getAggregation(res, "tag_kwd")
  420. if not aggs:
  421. return False
  422. cnt = np.sum([c for _, c in aggs])
  423. tag_fea = sorted([(a, round(0.1*(c + 1) / (cnt + S) / max(1e-6, all_tags.get(a, 0.0001)))) for a, c in aggs],
  424. key=lambda x: x[1] * -1)[:topn_tags]
  425. doc[TAG_FLD] = {a.replace(".", "_"): c for a, c in tag_fea if c > 0}
  426. return True
  427. def tag_query(self, question: str, tenant_ids: str | list[str], kb_ids: list[str], all_tags, topn_tags=3, S=1000):
  428. if isinstance(tenant_ids, str):
  429. idx_nms = index_name(tenant_ids)
  430. else:
  431. idx_nms = [index_name(tid) for tid in tenant_ids]
  432. match_txt, _ = self.qryr.question(question, min_match=0.0)
  433. res = self.dataStore.search([], [], {}, [match_txt], OrderByExpr(), 0, 0, idx_nms, kb_ids, ["tag_kwd"])
  434. aggs = self.dataStore.getAggregation(res, "tag_kwd")
  435. if not aggs:
  436. return {}
  437. cnt = np.sum([c for _, c in aggs])
  438. tag_fea = sorted([(a, round(0.1*(c + 1) / (cnt + S) / max(1e-6, all_tags.get(a, 0.0001)))) for a, c in aggs],
  439. key=lambda x: x[1] * -1)[:topn_tags]
  440. return {a.replace(".", "_"): max(1, c) for a, c in tag_fea}