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 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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.utils import rmSpace
  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. embedding_data = [float(v) for v in qv]
  42. vector_column_name = f"q_{len(embedding_data)}_vec"
  43. return MatchDenseExpr(vector_column_name, embedding_data, 'float', 'cosine', topk, {"similarity": similarity})
  44. def get_filters(self, req):
  45. condition = dict()
  46. for key, field in {"kb_ids": "kb_id", "doc_ids": "doc_id"}.items():
  47. if key in req and req[key] is not None:
  48. condition[field] = req[key]
  49. # TODO(yzc): `available_int` is nullable however infinity doesn't support nullable columns.
  50. for key in ["knowledge_graph_kwd"]:
  51. if key in req and req[key] is not None:
  52. condition[key] = req[key]
  53. return condition
  54. def search(self, req, idx_names: list[str], kb_ids: list[str], emb_mdl=None, highlight = False):
  55. filters = self.get_filters(req)
  56. orderBy = OrderByExpr()
  57. pg = int(req.get("page", 1)) - 1
  58. topk = int(req.get("topk", 1024))
  59. ps = int(req.get("size", topk))
  60. offset, limit = pg * ps, (pg + 1) * ps
  61. src = req.get("fields", ["docnm_kwd", "content_ltks", "kb_id", "img_id", "title_tks", "important_kwd",
  62. "doc_id", "position_list", "knowledge_graph_kwd",
  63. "available_int", "content_with_weight"])
  64. kwds = set([])
  65. qst = req.get("question", "")
  66. q_vec = []
  67. if not qst:
  68. if req.get("sort"):
  69. orderBy.desc("create_timestamp_flt")
  70. res = self.dataStore.search(src, [], filters, [], orderBy, offset, limit, idx_names, kb_ids)
  71. total=self.dataStore.getTotal(res)
  72. logging.debug("Dealer.search TOTAL: {}".format(total))
  73. else:
  74. highlightFields = ["content_ltks", "title_tks"] if highlight else []
  75. matchText, keywords = self.qryr.question(qst, min_match=0.3)
  76. if emb_mdl is None:
  77. matchExprs = [matchText]
  78. res = self.dataStore.search(src, highlightFields, filters, matchExprs, orderBy, offset, limit, idx_names, kb_ids)
  79. total=self.dataStore.getTotal(res)
  80. logging.debug("Dealer.search TOTAL: {}".format(total))
  81. else:
  82. matchDense = self.get_vector(qst, emb_mdl, topk, req.get("similarity", 0.1))
  83. q_vec = matchDense.embedding_data
  84. src.append(f"q_{len(q_vec)}_vec")
  85. fusionExpr = FusionExpr("weighted_sum", topk, {"weights": "0.05, 0.95"})
  86. matchExprs = [matchText, matchDense, fusionExpr]
  87. res = self.dataStore.search(src, highlightFields, filters, matchExprs, orderBy, offset, limit, idx_names, kb_ids)
  88. total=self.dataStore.getTotal(res)
  89. logging.debug("Dealer.search TOTAL: {}".format(total))
  90. # If result is empty, try again with lower min_match
  91. if total == 0:
  92. matchText, _ = self.qryr.question(qst, min_match=0.1)
  93. filters.pop("doc_ids", None)
  94. matchDense.extra_options["similarity"] = 0.17
  95. res = self.dataStore.search(src, highlightFields, filters, [matchText, matchDense, fusionExpr], orderBy, offset, limit, idx_names, kb_ids)
  96. total=self.dataStore.getTotal(res)
  97. logging.debug("Dealer.search 2 TOTAL: {}".format(total))
  98. for k in keywords:
  99. kwds.add(k)
  100. for kk in rag_tokenizer.fine_grained_tokenize(k).split(" "):
  101. if len(kk) < 2:
  102. continue
  103. if kk in kwds:
  104. continue
  105. kwds.add(kk)
  106. logging.debug(f"TOTAL: {total}")
  107. ids=self.dataStore.getChunkIds(res)
  108. keywords=list(kwds)
  109. highlight = self.dataStore.getHighlight(res, keywords, "content_with_weight")
  110. aggs = self.dataStore.getAggregation(res, "docnm_kwd")
  111. return self.SearchResult(
  112. total=total,
  113. ids=ids,
  114. query_vector=q_vec,
  115. aggregation=aggs,
  116. highlight=highlight,
  117. field=self.dataStore.getFields(res, src),
  118. keywords=keywords
  119. )
  120. @staticmethod
  121. def trans2floats(txt):
  122. return [float(t) for t in txt.split("\t")]
  123. def insert_citations(self, answer, chunks, chunk_v,
  124. embd_mdl, tkweight=0.1, vtweight=0.9):
  125. assert len(chunks) == len(chunk_v)
  126. if not chunks:
  127. return answer, set([])
  128. pieces = re.split(r"(```)", answer)
  129. if len(pieces) >= 3:
  130. i = 0
  131. pieces_ = []
  132. while i < len(pieces):
  133. if pieces[i] == "```":
  134. st = i
  135. i += 1
  136. while i < len(pieces) and pieces[i] != "```":
  137. i += 1
  138. if i < len(pieces):
  139. i += 1
  140. pieces_.append("".join(pieces[st: i]) + "\n")
  141. else:
  142. pieces_.extend(
  143. re.split(
  144. r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])",
  145. pieces[i]))
  146. i += 1
  147. pieces = pieces_
  148. else:
  149. pieces = re.split(r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])", answer)
  150. for i in range(1, len(pieces)):
  151. if re.match(r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])", pieces[i]):
  152. pieces[i - 1] += pieces[i][0]
  153. pieces[i] = pieces[i][1:]
  154. idx = []
  155. pieces_ = []
  156. for i, t in enumerate(pieces):
  157. if len(t) < 5:
  158. continue
  159. idx.append(i)
  160. pieces_.append(t)
  161. logging.debug("{} => {}".format(answer, pieces_))
  162. if not pieces_:
  163. return answer, set([])
  164. ans_v, _ = embd_mdl.encode(pieces_)
  165. assert len(ans_v[0]) == len(chunk_v[0]), "The dimension of query and chunk do not match: {} vs. {}".format(
  166. len(ans_v[0]), len(chunk_v[0]))
  167. chunks_tks = [rag_tokenizer.tokenize(self.qryr.rmWWW(ck)).split(" ")
  168. for ck in chunks]
  169. cites = {}
  170. thr = 0.63
  171. while thr>0.3 and len(cites.keys()) == 0 and pieces_ and chunks_tks:
  172. for i, a in enumerate(pieces_):
  173. sim, tksim, vtsim = self.qryr.hybrid_similarity(ans_v[i],
  174. chunk_v,
  175. rag_tokenizer.tokenize(
  176. self.qryr.rmWWW(pieces_[i])).split(" "),
  177. chunks_tks,
  178. tkweight, vtweight)
  179. mx = np.max(sim) * 0.99
  180. logging.debug("{} SIM: {}".format(pieces_[i], mx))
  181. if mx < thr:
  182. continue
  183. cites[idx[i]] = list(
  184. set([str(ii) for ii in range(len(chunk_v)) if sim[ii] > mx]))[:4]
  185. thr *= 0.8
  186. res = ""
  187. seted = set([])
  188. for i, p in enumerate(pieces):
  189. res += p
  190. if i not in idx:
  191. continue
  192. if i not in cites:
  193. continue
  194. for c in cites[i]:
  195. assert int(c) < len(chunk_v)
  196. for c in cites[i]:
  197. if c in seted:
  198. continue
  199. res += f" ##{c}$$"
  200. seted.add(c)
  201. return res, seted
  202. def rerank(self, sres, query, tkweight=0.3,
  203. vtweight=0.7, cfield="content_ltks"):
  204. _, keywords = self.qryr.question(query)
  205. vector_size = len(sres.query_vector)
  206. vector_column = f"q_{vector_size}_vec"
  207. zero_vector = [0.0] * vector_size
  208. ins_embd = []
  209. for chunk_id in sres.ids:
  210. vector = sres.field[chunk_id].get(vector_column, zero_vector)
  211. if isinstance(vector, str):
  212. vector = [float(v) for v in vector.split("\t")]
  213. ins_embd.append(vector)
  214. if not ins_embd:
  215. return [], [], []
  216. for i in sres.ids:
  217. if isinstance(sres.field[i].get("important_kwd", []), str):
  218. sres.field[i]["important_kwd"] = [sres.field[i]["important_kwd"]]
  219. ins_tw = []
  220. for i in sres.ids:
  221. content_ltks = sres.field[i][cfield].split(" ")
  222. title_tks = [t for t in sres.field[i].get("title_tks", "").split(" ") if t]
  223. important_kwd = sres.field[i].get("important_kwd", [])
  224. tks = content_ltks + title_tks + important_kwd
  225. ins_tw.append(tks)
  226. sim, tksim, vtsim = self.qryr.hybrid_similarity(sres.query_vector,
  227. ins_embd,
  228. keywords,
  229. ins_tw, tkweight, vtweight)
  230. return sim, tksim, vtsim
  231. def rerank_by_model(self, rerank_mdl, sres, query, tkweight=0.3,
  232. vtweight=0.7, cfield="content_ltks"):
  233. _, keywords = self.qryr.question(query)
  234. for i in sres.ids:
  235. if isinstance(sres.field[i].get("important_kwd", []), str):
  236. sres.field[i]["important_kwd"] = [sres.field[i]["important_kwd"]]
  237. ins_tw = []
  238. for i in sres.ids:
  239. content_ltks = sres.field[i][cfield].split(" ")
  240. title_tks = [t for t in sres.field[i].get("title_tks", "").split(" ") if t]
  241. important_kwd = sres.field[i].get("important_kwd", [])
  242. tks = content_ltks + title_tks + important_kwd
  243. ins_tw.append(tks)
  244. tksim = self.qryr.token_similarity(keywords, ins_tw)
  245. vtsim,_ = rerank_mdl.similarity(query, [rmSpace(" ".join(tks)) for tks in ins_tw])
  246. return tkweight*np.array(tksim) + vtweight*vtsim, tksim, vtsim
  247. def hybrid_similarity(self, ans_embd, ins_embd, ans, inst):
  248. return self.qryr.hybrid_similarity(ans_embd,
  249. ins_embd,
  250. rag_tokenizer.tokenize(ans).split(" "),
  251. rag_tokenizer.tokenize(inst).split(" "))
  252. def retrieval(self, question, embd_mdl, tenant_ids, kb_ids, page, page_size, similarity_threshold=0.2,
  253. vector_similarity_weight=0.3, top=1024, doc_ids=None, aggs=True, rerank_mdl=None, highlight=False):
  254. ranks = {"total": 0, "chunks": [], "doc_aggs": {}}
  255. if not question:
  256. return ranks
  257. RERANK_PAGE_LIMIT = 3
  258. req = {"kb_ids": kb_ids, "doc_ids": doc_ids, "size": max(page_size*RERANK_PAGE_LIMIT, 128),
  259. "question": question, "vector": True, "topk": top,
  260. "similarity": similarity_threshold,
  261. "available_int": 1}
  262. if page > RERANK_PAGE_LIMIT:
  263. req["page"] = page
  264. req["size"] = page_size
  265. if isinstance(tenant_ids, str):
  266. tenant_ids = tenant_ids.split(",")
  267. sres = self.search(req, [index_name(tid) for tid in tenant_ids], kb_ids, embd_mdl, highlight)
  268. ranks["total"] = sres.total
  269. if page <= RERANK_PAGE_LIMIT:
  270. if rerank_mdl:
  271. sim, tsim, vsim = self.rerank_by_model(rerank_mdl,
  272. sres, question, 1 - vector_similarity_weight, vector_similarity_weight)
  273. else:
  274. sim, tsim, vsim = self.rerank(
  275. sres, question, 1 - vector_similarity_weight, vector_similarity_weight)
  276. idx = np.argsort(sim * -1)[(page-1)*page_size:page*page_size]
  277. else:
  278. sim = tsim = vsim = [1]*len(sres.ids)
  279. idx = list(range(len(sres.ids)))
  280. dim = len(sres.query_vector)
  281. vector_column = f"q_{dim}_vec"
  282. zero_vector = [0.0] * dim
  283. for i in idx:
  284. if sim[i] < similarity_threshold:
  285. break
  286. if len(ranks["chunks"]) >= page_size:
  287. if aggs:
  288. continue
  289. break
  290. id = sres.ids[i]
  291. chunk = sres.field[id]
  292. dnm = chunk["docnm_kwd"]
  293. did = chunk["doc_id"]
  294. position_list = chunk.get("position_list", "[]")
  295. if not position_list:
  296. position_list = "[]"
  297. d = {
  298. "chunk_id": id,
  299. "content_ltks": chunk["content_ltks"],
  300. "content_with_weight": chunk["content_with_weight"],
  301. "doc_id": chunk["doc_id"],
  302. "docnm_kwd": dnm,
  303. "kb_id": chunk["kb_id"],
  304. "important_kwd": chunk.get("important_kwd", []),
  305. "image_id": chunk.get("img_id", ""),
  306. "similarity": sim[i],
  307. "vector_similarity": vsim[i],
  308. "term_similarity": tsim[i],
  309. "vector": chunk.get(vector_column, zero_vector),
  310. "positions": json.loads(position_list)
  311. }
  312. if highlight:
  313. if id in sres.highlight:
  314. d["highlight"] = rmSpace(sres.highlight[id])
  315. else:
  316. d["highlight"] = d["content_with_weight"]
  317. ranks["chunks"].append(d)
  318. if dnm not in ranks["doc_aggs"]:
  319. ranks["doc_aggs"][dnm] = {"doc_id": did, "count": 0}
  320. ranks["doc_aggs"][dnm]["count"] += 1
  321. ranks["doc_aggs"] = [{"doc_name": k,
  322. "doc_id": v["doc_id"],
  323. "count": v["count"]} for k,
  324. v in sorted(ranks["doc_aggs"].items(),
  325. key=lambda x:x[1]["count"] * -1)]
  326. return ranks
  327. def sql_retrieval(self, sql, fetch_size=128, format="json"):
  328. tbl = self.dataStore.sql(sql, fetch_size, format)
  329. return tbl
  330. def chunk_list(self, doc_id: str, tenant_id: str, kb_ids: list[str], max_count=1024, fields=["docnm_kwd", "content_with_weight", "img_id"]):
  331. condition = {"doc_id": doc_id}
  332. res = self.dataStore.search(fields, [], condition, [], OrderByExpr(), 0, max_count, index_name(tenant_id), kb_ids)
  333. dict_chunks = self.dataStore.getFields(res, fields)
  334. return dict_chunks.values()