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 3.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. meta = getattr(doc, 'meta_fields', {})
  68. meta["doc_id"] = c["doc_id"]
  69. records.append({
  70. "content": c["content_with_weight"],
  71. "score": c["similarity"],
  72. "title": c["docnm_kwd"],
  73. "metadata": meta
  74. })
  75. return jsonify({"records": records})
  76. except Exception as e:
  77. if str(e).find("not_found") > 0:
  78. return build_error_result(
  79. message='No chunk found! Check the chunk status please!',
  80. code=settings.RetCode.NOT_FOUND
  81. )
  82. logging.exception(e)
  83. return build_error_result(message=str(e), code=settings.RetCode.SERVER_ERROR)