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.

dify_retrieval.py 2.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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, ParserType
  18. from api.db.services.knowledgebase_service import KnowledgebaseService
  19. from api.db.services.llm_service import LLMBundle
  20. from api import settings
  21. from api.utils.api_utils import validate_request, build_error_result, apikey_required
  22. @manager.route('/dify/retrieval', methods=['POST'])
  23. @apikey_required
  24. @validate_request("knowledge_id", "query")
  25. def retrieval(tenant_id):
  26. req = request.json
  27. question = req["query"]
  28. kb_id = req["knowledge_id"]
  29. retrieval_setting = req.get("retrieval_setting", {})
  30. similarity_threshold = float(retrieval_setting.get("score_threshold", 0.0))
  31. top = int(retrieval_setting.get("top_k", 1024))
  32. try:
  33. e, kb = KnowledgebaseService.get_by_id(kb_id)
  34. if not e:
  35. return build_error_result(message="Knowledgebase not found!", code=settings.RetCode.NOT_FOUND)
  36. if kb.tenant_id != tenant_id:
  37. return build_error_result(message="Knowledgebase not found!", code=settings.RetCode.NOT_FOUND)
  38. embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING.value, llm_name=kb.embd_id)
  39. retr = settings.retrievaler if kb.parser_id != ParserType.KG else settings.kg_retrievaler
  40. ranks = retr.retrieval(
  41. question,
  42. embd_mdl,
  43. kb.tenant_id,
  44. [kb_id],
  45. page=1,
  46. page_size=top,
  47. similarity_threshold=similarity_threshold,
  48. vector_similarity_weight=0.3,
  49. top=top
  50. )
  51. records = []
  52. for c in ranks["chunks"]:
  53. if "vector" in c:
  54. del c["vector"]
  55. records.append({
  56. "content": c["content_ltks"],
  57. "score": c["similarity"],
  58. "title": c["docnm_kwd"],
  59. "metadata": {}
  60. })
  61. return jsonify({"records": records})
  62. except Exception as e:
  63. if str(e).find("not_found") > 0:
  64. return build_error_result(
  65. message='No chunk found! Check the chunk status please!',
  66. code=settings.RetCode.NOT_FOUND
  67. )
  68. return build_error_result(message=str(e), code=settings.RetCode.SERVER_ERROR)