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.

search.py 21KB

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