Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

dify_retrieval.py 3.4KB

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