Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

dialog_app.py 6.4KB

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