Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. from flask import request, jsonify
  18. from api.db import LLMType
  19. from api.db.services.document_service import DocumentService
  20. from api.db.services.knowledgebase_service import KnowledgebaseService
  21. from api.db.services.llm_service import LLMBundle
  22. from api import settings
  23. from api.utils.api_utils import validate_request, build_error_result, apikey_required
  24. from rag.app.tag import label_question
  25. from api.db.services.dialog_service import meta_filter
  26. @manager.route('/dify/retrieval', methods=['POST']) # noqa: F821
  27. @apikey_required
  28. @validate_request("knowledge_id", "query")
  29. def retrieval(tenant_id):
  30. req = request.json
  31. question = req["query"]
  32. kb_id = req["knowledge_id"]
  33. use_kg = req.get("use_kg", False)
  34. retrieval_setting = req.get("retrieval_setting", {})
  35. similarity_threshold = float(retrieval_setting.get("score_threshold", 0.0))
  36. top = int(retrieval_setting.get("top_k", 1024))
  37. metadata_condition = req.get("metadata_condition",{})
  38. metas = DocumentService.get_meta_by_kbs([kb_id])
  39. doc_ids = []
  40. try:
  41. e, kb = KnowledgebaseService.get_by_id(kb_id)
  42. if not e:
  43. return build_error_result(message="Knowledgebase not found!", code=settings.RetCode.NOT_FOUND)
  44. embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING.value, llm_name=kb.embd_id)
  45. print(metadata_condition)
  46. print("after",convert_conditions(metadata_condition))
  47. doc_ids.extend(meta_filter(metas, convert_conditions(metadata_condition)))
  48. print("doc_ids",doc_ids)
  49. if not doc_ids and metadata_condition is not None:
  50. doc_ids = ['-999']
  51. ranks = settings.retrievaler.retrieval(
  52. question,
  53. embd_mdl,
  54. kb.tenant_id,
  55. [kb_id],
  56. page=1,
  57. page_size=top,
  58. similarity_threshold=similarity_threshold,
  59. vector_similarity_weight=0.3,
  60. top=top,
  61. doc_ids=doc_ids,
  62. rank_feature=label_question(question, [kb])
  63. )
  64. if use_kg:
  65. ck = settings.kg_retrievaler.retrieval(question,
  66. [tenant_id],
  67. [kb_id],
  68. embd_mdl,
  69. doc_ids,
  70. LLMBundle(kb.tenant_id, LLMType.CHAT))
  71. if ck["content_with_weight"]:
  72. ranks["chunks"].insert(0, ck)
  73. records = []
  74. for c in ranks["chunks"]:
  75. e, doc = DocumentService.get_by_id( c["doc_id"])
  76. c.pop("vector", None)
  77. meta = getattr(doc, 'meta_fields', {})
  78. meta["doc_id"] = c["doc_id"]
  79. records.append({
  80. "content": c["content_with_weight"],
  81. "score": c["similarity"],
  82. "title": c["docnm_kwd"],
  83. "metadata": meta
  84. })
  85. return jsonify({"records": records})
  86. except Exception as e:
  87. if str(e).find("not_found") > 0:
  88. return build_error_result(
  89. message='No chunk found! Check the chunk status please!',
  90. code=settings.RetCode.NOT_FOUND
  91. )
  92. logging.exception(e)
  93. return build_error_result(message=str(e), code=settings.RetCode.SERVER_ERROR)
  94. def convert_conditions(metadata_condition):
  95. if metadata_condition is None:
  96. metadata_condition = {}
  97. op_mapping = {
  98. "is": "=",
  99. "not is": "≠"
  100. }
  101. return [
  102. {
  103. "op": op_mapping.get(cond["comparison_operator"], cond["comparison_operator"]),
  104. "key": cond["name"],
  105. "value": cond["value"]
  106. }
  107. for cond in metadata_condition.get("conditions", [])
  108. ]