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.

dialog_app.py 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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
  17. from flask_login import login_required, current_user
  18. from api.db.services.dialog_service import DialogService
  19. from api.db import StatusEnum
  20. from api.db.services.kb_service import KnowledgebaseService
  21. from api.db.services.user_service import TenantService
  22. from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
  23. from api.utils import get_uuid
  24. from api.utils.api_utils import get_json_result
  25. @manager.route('/set', methods=['POST'])
  26. @login_required
  27. def set():
  28. req = request.json
  29. dialog_id = req.get("dialog_id")
  30. name = req.get("name", "New Dialog")
  31. description = req.get("description", "A helpful Dialog")
  32. language = req.get("language", "Chinese")
  33. llm_setting_type = req.get("llm_setting_type", "Precise")
  34. llm_setting = req.get("llm_setting", {
  35. "Creative": {
  36. "temperature": 0.9,
  37. "top_p": 0.9,
  38. "frequency_penalty": 0.2,
  39. "presence_penalty": 0.4,
  40. "max_tokens": 512
  41. },
  42. "Precise": {
  43. "temperature": 0.1,
  44. "top_p": 0.3,
  45. "frequency_penalty": 0.7,
  46. "presence_penalty": 0.4,
  47. "max_tokens": 215
  48. },
  49. "Evenly": {
  50. "temperature": 0.5,
  51. "top_p": 0.5,
  52. "frequency_penalty": 0.7,
  53. "presence_penalty": 0.4,
  54. "max_tokens": 215
  55. },
  56. "Custom": {
  57. "temperature": 0.2,
  58. "top_p": 0.3,
  59. "frequency_penalty": 0.6,
  60. "presence_penalty": 0.3,
  61. "max_tokens": 215
  62. },
  63. })
  64. prompt_config = req.get("prompt_config", {
  65. "system": """你是一个智能助手,请总结知识库的内容来回答问题,请列举知识库中的数据详细回答。当所有知识库内容都与问题无关时,你的回答必须包括“知识库中未找到您要的答案!”这句话。回答需要考虑聊天历史。
  66. 以下是知识库:
  67. {knowledge}
  68. 以上是知识库。""",
  69. "prologue": "您好,我是您的助手小樱,长得可爱又善良,can I help you?",
  70. "parameters": [
  71. {"key": "knowledge", "optional": False}
  72. ],
  73. "empty_response": "Sorry! 知识库中未找到相关内容!"
  74. })
  75. if len(prompt_config["parameters"]) < 1:
  76. return get_data_error_result(retmsg="'knowledge' should be in parameters")
  77. for p in prompt_config["parameters"]:
  78. if prompt_config["system"].find("{%s}"%p["key"]) < 0:
  79. return get_data_error_result(retmsg="Parameter '{}' is not used".format(p["key"]))
  80. try:
  81. e, tenant = TenantService.get_by_id(current_user.id)
  82. if not e:return get_data_error_result(retmsg="Tenant not found!")
  83. llm_id = req.get("llm_id", tenant.llm_id)
  84. if not dialog_id:
  85. dia = {
  86. "id": get_uuid(),
  87. "tenant_id": current_user.id,
  88. "name": name,
  89. "description": description,
  90. "language": language,
  91. "llm_id": llm_id,
  92. "llm_setting_type": llm_setting_type,
  93. "llm_setting": llm_setting,
  94. "prompt_config": prompt_config
  95. }
  96. if not DialogService.save(**dia): return get_data_error_result(retmsg="Fail to new a dialog!")
  97. e, dia = DialogService.get_by_id(dia["id"])
  98. if not e: return get_data_error_result(retmsg="Fail to new a dialog!")
  99. return get_json_result(data=dia.to_json())
  100. else:
  101. del req["dialog_id"]
  102. if "kb_names" in req: del req["kb_names"]
  103. if not DialogService.update_by_id(dialog_id, req):
  104. return get_data_error_result(retmsg="Dialog not found!")
  105. e, dia = DialogService.get_by_id(dialog_id)
  106. if not e: return get_data_error_result(retmsg="Fail to update a dialog!")
  107. dia = dia.to_dict()
  108. dia["kb_ids"], dia["kb_names"] = get_kb_names(dia["kb_ids"])
  109. return get_json_result(data=dia)
  110. except Exception as e:
  111. return server_error_response(e)
  112. @manager.route('/get', methods=['GET'])
  113. @login_required
  114. def get():
  115. dialog_id = request.args["dialog_id"]
  116. try:
  117. e,dia = DialogService.get_by_id(dialog_id)
  118. if not e: return get_data_error_result(retmsg="Dialog not found!")
  119. dia = dia.to_dict()
  120. dia["kb_ids"], dia["kb_names"] = get_kb_names(dia["kb_ids"])
  121. return get_json_result(data=dia)
  122. except Exception as e:
  123. return server_error_response(e)
  124. def get_kb_names(kb_ids):
  125. ids, nms = [], []
  126. for kid in kb_ids:
  127. e, kb = KnowledgebaseService.get_by_id(kid)
  128. if not e or kb.status != StatusEnum.VALID.value:continue
  129. ids.append(kid)
  130. nms.append(kb.name)
  131. return ids, nms
  132. @manager.route('/list', methods=['GET'])
  133. @login_required
  134. def list():
  135. try:
  136. diags = DialogService.query(tenant_id=current_user.id, status=StatusEnum.VALID.value)
  137. diags = [d.to_dict() for d in diags]
  138. for d in diags:
  139. d["kb_ids"], d["kb_names"] = get_kb_names(d["kb_ids"])
  140. return get_json_result(data=diags)
  141. except Exception as e:
  142. return server_error_response(e)
  143. @manager.route('/rm', methods=['POST'])
  144. @login_required
  145. @validate_request("dialog_id")
  146. def rm():
  147. req = request.json
  148. try:
  149. if not DialogService.update_by_id(req["dialog_id"], {"status": StatusEnum.INVALID.value}):
  150. return get_data_error_result(retmsg="Dialog not found!")
  151. return get_json_result(data=True)
  152. except Exception as e:
  153. return server_error_response(e)