retrieval_service.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. import json
  2. import threading
  3. from typing import Optional
  4. from flask import Flask, current_app
  5. from core.rag.data_post_processor.data_post_processor import DataPostProcessor
  6. from core.rag.datasource.keyword.keyword_factory import Keyword
  7. from core.rag.datasource.vdb.vector_factory import Vector
  8. from core.rag.embedding.retrieval import RetrievalSegments
  9. from core.rag.index_processor.constant.index_type import IndexType
  10. from core.rag.models.document import Document
  11. from core.rag.rerank.rerank_type import RerankMode
  12. from core.rag.retrieval.retrieval_methods import RetrievalMethod
  13. from extensions.ext_database import db
  14. from models.dataset import ChildChunk, Dataset, DocumentSegment
  15. from models.dataset import Document as DatasetDocument
  16. from services.external_knowledge_service import ExternalDatasetService
  17. default_retrieval_model = {
  18. "search_method": RetrievalMethod.SEMANTIC_SEARCH.value,
  19. "reranking_enable": False,
  20. "reranking_model": {"reranking_provider_name": "", "reranking_model_name": ""},
  21. "top_k": 2,
  22. "score_threshold_enabled": False,
  23. }
  24. class RetrievalService:
  25. @classmethod
  26. def retrieve(
  27. cls,
  28. retrieval_method: str,
  29. dataset_id: str,
  30. query: str,
  31. top_k: int,
  32. score_threshold: Optional[float] = 0.0,
  33. reranking_model: Optional[dict] = None,
  34. reranking_mode: str = "reranking_model",
  35. weights: Optional[dict] = None,
  36. ):
  37. if not query:
  38. return []
  39. dataset = db.session.query(Dataset).filter(Dataset.id == dataset_id).first()
  40. if not dataset:
  41. return []
  42. if not dataset or dataset.available_document_count == 0 or dataset.available_segment_count == 0:
  43. return []
  44. all_documents: list[Document] = []
  45. threads: list[threading.Thread] = []
  46. exceptions: list[str] = []
  47. # retrieval_model source with keyword
  48. if retrieval_method == "keyword_search":
  49. keyword_thread = threading.Thread(
  50. target=RetrievalService.keyword_search,
  51. kwargs={
  52. "flask_app": current_app._get_current_object(), # type: ignore
  53. "dataset_id": dataset_id,
  54. "query": query,
  55. "top_k": top_k,
  56. "all_documents": all_documents,
  57. "exceptions": exceptions,
  58. },
  59. )
  60. threads.append(keyword_thread)
  61. keyword_thread.start()
  62. # retrieval_model source with semantic
  63. if RetrievalMethod.is_support_semantic_search(retrieval_method):
  64. embedding_thread = threading.Thread(
  65. target=RetrievalService.embedding_search,
  66. kwargs={
  67. "flask_app": current_app._get_current_object(), # type: ignore
  68. "dataset_id": dataset_id,
  69. "query": query,
  70. "top_k": top_k,
  71. "score_threshold": score_threshold,
  72. "reranking_model": reranking_model,
  73. "all_documents": all_documents,
  74. "retrieval_method": retrieval_method,
  75. "exceptions": exceptions,
  76. },
  77. )
  78. threads.append(embedding_thread)
  79. embedding_thread.start()
  80. # retrieval source with full text
  81. if RetrievalMethod.is_support_fulltext_search(retrieval_method):
  82. full_text_index_thread = threading.Thread(
  83. target=RetrievalService.full_text_index_search,
  84. kwargs={
  85. "flask_app": current_app._get_current_object(), # type: ignore
  86. "dataset_id": dataset_id,
  87. "query": query,
  88. "retrieval_method": retrieval_method,
  89. "score_threshold": score_threshold,
  90. "top_k": top_k,
  91. "reranking_model": reranking_model,
  92. "all_documents": all_documents,
  93. "exceptions": exceptions,
  94. },
  95. )
  96. threads.append(full_text_index_thread)
  97. full_text_index_thread.start()
  98. for thread in threads:
  99. thread.join()
  100. if exceptions:
  101. exception_message = ";\n".join(exceptions)
  102. raise ValueError(exception_message)
  103. if retrieval_method == RetrievalMethod.HYBRID_SEARCH.value:
  104. data_post_processor = DataPostProcessor(
  105. str(dataset.tenant_id), reranking_mode, reranking_model, weights, False
  106. )
  107. all_documents = data_post_processor.invoke(
  108. query=query,
  109. documents=all_documents,
  110. score_threshold=score_threshold,
  111. top_n=top_k,
  112. )
  113. return all_documents
  114. @classmethod
  115. def external_retrieve(cls, dataset_id: str, query: str, external_retrieval_model: Optional[dict] = None):
  116. dataset = db.session.query(Dataset).filter(Dataset.id == dataset_id).first()
  117. if not dataset:
  118. return []
  119. all_documents = ExternalDatasetService.fetch_external_knowledge_retrieval(
  120. dataset.tenant_id, dataset_id, query, external_retrieval_model or {}
  121. )
  122. return all_documents
  123. @classmethod
  124. def keyword_search(
  125. cls, flask_app: Flask, dataset_id: str, query: str, top_k: int, all_documents: list, exceptions: list
  126. ):
  127. with flask_app.app_context():
  128. try:
  129. dataset = db.session.query(Dataset).filter(Dataset.id == dataset_id).first()
  130. if not dataset:
  131. raise ValueError("dataset not found")
  132. keyword = Keyword(dataset=dataset)
  133. documents = keyword.search(cls.escape_query_for_search(query), top_k=top_k)
  134. all_documents.extend(documents)
  135. except Exception as e:
  136. exceptions.append(str(e))
  137. @classmethod
  138. def embedding_search(
  139. cls,
  140. flask_app: Flask,
  141. dataset_id: str,
  142. query: str,
  143. top_k: int,
  144. score_threshold: Optional[float],
  145. reranking_model: Optional[dict],
  146. all_documents: list,
  147. retrieval_method: str,
  148. exceptions: list,
  149. ):
  150. with flask_app.app_context():
  151. try:
  152. dataset = db.session.query(Dataset).filter(Dataset.id == dataset_id).first()
  153. if not dataset:
  154. raise ValueError("dataset not found")
  155. vector = Vector(dataset=dataset)
  156. documents = vector.search_by_vector(
  157. query,
  158. search_type="similarity_score_threshold",
  159. top_k=top_k,
  160. score_threshold=score_threshold,
  161. filter={"group_id": [dataset.id]},
  162. )
  163. if documents:
  164. if (
  165. reranking_model
  166. and reranking_model.get("reranking_model_name")
  167. and reranking_model.get("reranking_provider_name")
  168. and retrieval_method == RetrievalMethod.SEMANTIC_SEARCH.value
  169. ):
  170. data_post_processor = DataPostProcessor(
  171. str(dataset.tenant_id), RerankMode.RERANKING_MODEL.value, reranking_model, None, False
  172. )
  173. all_documents.extend(
  174. data_post_processor.invoke(
  175. query=query,
  176. documents=documents,
  177. score_threshold=score_threshold,
  178. top_n=len(documents),
  179. )
  180. )
  181. else:
  182. all_documents.extend(documents)
  183. except Exception as e:
  184. exceptions.append(str(e))
  185. @classmethod
  186. def full_text_index_search(
  187. cls,
  188. flask_app: Flask,
  189. dataset_id: str,
  190. query: str,
  191. top_k: int,
  192. score_threshold: Optional[float],
  193. reranking_model: Optional[dict],
  194. all_documents: list,
  195. retrieval_method: str,
  196. exceptions: list,
  197. ):
  198. with flask_app.app_context():
  199. try:
  200. dataset = db.session.query(Dataset).filter(Dataset.id == dataset_id).first()
  201. if not dataset:
  202. raise ValueError("dataset not found")
  203. vector_processor = Vector(
  204. dataset=dataset,
  205. )
  206. documents = vector_processor.search_by_full_text(cls.escape_query_for_search(query), top_k=top_k)
  207. if documents:
  208. if (
  209. reranking_model
  210. and reranking_model.get("reranking_model_name")
  211. and reranking_model.get("reranking_provider_name")
  212. and retrieval_method == RetrievalMethod.FULL_TEXT_SEARCH.value
  213. ):
  214. data_post_processor = DataPostProcessor(
  215. str(dataset.tenant_id), RerankMode.RERANKING_MODEL.value, reranking_model, None, False
  216. )
  217. all_documents.extend(
  218. data_post_processor.invoke(
  219. query=query,
  220. documents=documents,
  221. score_threshold=score_threshold,
  222. top_n=len(documents),
  223. )
  224. )
  225. else:
  226. all_documents.extend(documents)
  227. except Exception as e:
  228. exceptions.append(str(e))
  229. @staticmethod
  230. def escape_query_for_search(query: str) -> str:
  231. return json.dumps(query).strip('"')
  232. @staticmethod
  233. def format_retrieval_documents(documents: list[Document]) -> list[RetrievalSegments]:
  234. records = []
  235. include_segment_ids = []
  236. segment_child_map = {}
  237. for document in documents:
  238. document_id = document.metadata.get("document_id")
  239. dataset_document = db.session.query(DatasetDocument).filter(DatasetDocument.id == document_id).first()
  240. if dataset_document:
  241. if dataset_document.doc_form == IndexType.PARENT_CHILD_INDEX:
  242. child_index_node_id = document.metadata.get("doc_id")
  243. result = (
  244. db.session.query(ChildChunk, DocumentSegment)
  245. .join(DocumentSegment, ChildChunk.segment_id == DocumentSegment.id)
  246. .filter(
  247. ChildChunk.index_node_id == child_index_node_id,
  248. DocumentSegment.dataset_id == dataset_document.dataset_id,
  249. DocumentSegment.enabled == True,
  250. DocumentSegment.status == "completed",
  251. )
  252. .first()
  253. )
  254. if result:
  255. child_chunk, segment = result
  256. if not segment:
  257. continue
  258. if segment.id not in include_segment_ids:
  259. include_segment_ids.append(segment.id)
  260. child_chunk_detail = {
  261. "id": child_chunk.id,
  262. "content": child_chunk.content,
  263. "position": child_chunk.position,
  264. "score": document.metadata.get("score", 0.0),
  265. }
  266. map_detail = {
  267. "max_score": document.metadata.get("score", 0.0),
  268. "child_chunks": [child_chunk_detail],
  269. }
  270. segment_child_map[segment.id] = map_detail
  271. record = {
  272. "segment": segment,
  273. }
  274. records.append(record)
  275. else:
  276. child_chunk_detail = {
  277. "id": child_chunk.id,
  278. "content": child_chunk.content,
  279. "position": child_chunk.position,
  280. "score": document.metadata.get("score", 0.0),
  281. }
  282. segment_child_map[segment.id]["child_chunks"].append(child_chunk_detail)
  283. segment_child_map[segment.id]["max_score"] = max(
  284. segment_child_map[segment.id]["max_score"], document.metadata.get("score", 0.0)
  285. )
  286. else:
  287. continue
  288. else:
  289. index_node_id = document.metadata["doc_id"]
  290. segment = (
  291. db.session.query(DocumentSegment)
  292. .filter(
  293. DocumentSegment.dataset_id == dataset_document.dataset_id,
  294. DocumentSegment.enabled == True,
  295. DocumentSegment.status == "completed",
  296. DocumentSegment.index_node_id == index_node_id,
  297. )
  298. .first()
  299. )
  300. if not segment:
  301. continue
  302. include_segment_ids.append(segment.id)
  303. record = {
  304. "segment": segment,
  305. "score": document.metadata.get("score", None),
  306. }
  307. records.append(record)
  308. for record in records:
  309. if record["segment"].id in segment_child_map:
  310. record["child_chunks"] = segment_child_map[record["segment"].id].get("child_chunks", None)
  311. record["score"] = segment_child_map[record["segment"].id]["max_score"]
  312. return [RetrievalSegments(**record) for record in records]