Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

dify_retrieval.py 3.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. @manager.route('/dify/retrieval', methods=['POST']) # noqa: F821
  26. @apikey_required
  27. @validate_request("knowledge_id", "query")
  28. def retrieval(tenant_id):
  29. req = request.json
  30. question = req["query"]
  31. kb_id = req["knowledge_id"]
  32. use_kg = req.get("use_kg", False)
  33. retrieval_setting = req.get("retrieval_setting", {})
  34. similarity_threshold = float(retrieval_setting.get("score_threshold", 0.0))
  35. top = int(retrieval_setting.get("top_k", 1024))
  36. try:
  37. e, kb = KnowledgebaseService.get_by_id(kb_id)
  38. if not e:
  39. return build_error_result(message="Knowledgebase not found!", code=settings.RetCode.NOT_FOUND)
  40. if kb.tenant_id != tenant_id:
  41. return build_error_result(message="Knowledgebase not found!", code=settings.RetCode.NOT_FOUND)
  42. embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING.value, llm_name=kb.embd_id)
  43. ranks = settings.retrievaler.retrieval(
  44. question,
  45. embd_mdl,
  46. kb.tenant_id,
  47. [kb_id],
  48. page=1,
  49. page_size=top,
  50. similarity_threshold=similarity_threshold,
  51. vector_similarity_weight=0.3,
  52. top=top,
  53. rank_feature=label_question(question, [kb])
  54. )
  55. if use_kg:
  56. ck = settings.kg_retrievaler.retrieval(question,
  57. [tenant_id],
  58. [kb_id],
  59. embd_mdl,
  60. LLMBundle(kb.tenant_id, LLMType.CHAT))
  61. if ck["content_with_weight"]:
  62. ranks["chunks"].insert(0, ck)
  63. records = []
  64. for c in ranks["chunks"]:
  65. e, doc = DocumentService.get_by_id( c["doc_id"])
  66. c.pop("vector", None)
  67. records.append({
  68. "content": c["content_with_weight"],
  69. "score": c["similarity"],
  70. "title": c["docnm_kwd"],
  71. "metadata": getattr(doc, 'meta_fields', {})
  72. })
  73. return jsonify({"records": records})
  74. except Exception as e:
  75. if str(e).find("not_found") > 0:
  76. return build_error_result(
  77. message='No chunk found! Check the chunk status please!',
  78. code=settings.RetCode.NOT_FOUND
  79. )
  80. logging.exception(e)
  81. return build_error_result(message=str(e), code=settings.RetCode.SERVER_ERROR)