Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

conversation_app.py 4.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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
  18. from api.db.services.dialog_service import DialogService, ConversationService, chat
  19. from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
  20. from api.utils import get_uuid
  21. from api.utils.api_utils import get_json_result
  22. @manager.route('/set', methods=['POST'])
  23. @login_required
  24. def set_conversation():
  25. req = request.json
  26. conv_id = req.get("conversation_id")
  27. if conv_id:
  28. del req["conversation_id"]
  29. try:
  30. if not ConversationService.update_by_id(conv_id, req):
  31. return get_data_error_result(retmsg="Conversation not found!")
  32. e, conv = ConversationService.get_by_id(conv_id)
  33. if not e:
  34. return get_data_error_result(
  35. retmsg="Fail to update a conversation!")
  36. conv = conv.to_dict()
  37. return get_json_result(data=conv)
  38. except Exception as e:
  39. return server_error_response(e)
  40. try:
  41. e, dia = DialogService.get_by_id(req["dialog_id"])
  42. if not e:
  43. return get_data_error_result(retmsg="Dialog not found")
  44. conv = {
  45. "id": get_uuid(),
  46. "dialog_id": req["dialog_id"],
  47. "name": req.get("name", "New conversation"),
  48. "message": [{"role": "assistant", "content": dia.prompt_config["prologue"]}]
  49. }
  50. ConversationService.save(**conv)
  51. e, conv = ConversationService.get_by_id(conv["id"])
  52. if not e:
  53. return get_data_error_result(retmsg="Fail to new a conversation!")
  54. conv = conv.to_dict()
  55. return get_json_result(data=conv)
  56. except Exception as e:
  57. return server_error_response(e)
  58. @manager.route('/get', methods=['GET'])
  59. @login_required
  60. def get():
  61. conv_id = request.args["conversation_id"]
  62. try:
  63. e, conv = ConversationService.get_by_id(conv_id)
  64. if not e:
  65. return get_data_error_result(retmsg="Conversation not found!")
  66. conv = conv.to_dict()
  67. return get_json_result(data=conv)
  68. except Exception as e:
  69. return server_error_response(e)
  70. @manager.route('/rm', methods=['POST'])
  71. @login_required
  72. def rm():
  73. conv_ids = request.json["conversation_ids"]
  74. try:
  75. for cid in conv_ids:
  76. ConversationService.delete_by_id(cid)
  77. return get_json_result(data=True)
  78. except Exception as e:
  79. return server_error_response(e)
  80. @manager.route('/list', methods=['GET'])
  81. @login_required
  82. def list_convsersation():
  83. dialog_id = request.args["dialog_id"]
  84. try:
  85. convs = ConversationService.query(
  86. dialog_id=dialog_id,
  87. order_by=ConversationService.model.create_time,
  88. reverse=True)
  89. convs = [d.to_dict() for d in convs]
  90. return get_json_result(data=convs)
  91. except Exception as e:
  92. return server_error_response(e)
  93. @manager.route('/completion', methods=['POST'])
  94. @login_required
  95. @validate_request("conversation_id", "messages")
  96. def completion():
  97. req = request.json
  98. msg = []
  99. for m in req["messages"]:
  100. if m["role"] == "system":
  101. continue
  102. if m["role"] == "assistant" and not msg:
  103. continue
  104. msg.append({"role": m["role"], "content": m["content"]})
  105. try:
  106. e, conv = ConversationService.get_by_id(req["conversation_id"])
  107. if not e:
  108. return get_data_error_result(retmsg="Conversation not found!")
  109. conv.message.append(msg[-1])
  110. e, dia = DialogService.get_by_id(conv.dialog_id)
  111. if not e:
  112. return get_data_error_result(retmsg="Dialog not found!")
  113. del req["conversation_id"]
  114. del req["messages"]
  115. ans = chat(dia, msg, **req)
  116. if not conv.reference:
  117. conv.reference = []
  118. conv.reference.append(ans["reference"])
  119. conv.message.append({"role": "assistant", "content": ans["answer"]})
  120. ConversationService.update_by_id(conv.id, conv.to_dict())
  121. return get_json_result(data=ans)
  122. except Exception as e:
  123. return server_error_response(e)