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.

conversation_app.py 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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, Response, jsonify
  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. import json
  23. @manager.route('/set', methods=['POST'])
  24. @login_required
  25. def set_conversation():
  26. req = request.json
  27. conv_id = req.get("conversation_id")
  28. if conv_id:
  29. del req["conversation_id"]
  30. try:
  31. if not ConversationService.update_by_id(conv_id, req):
  32. return get_data_error_result(retmsg="Conversation not found!")
  33. e, conv = ConversationService.get_by_id(conv_id)
  34. if not e:
  35. return get_data_error_result(
  36. retmsg="Fail to update a conversation!")
  37. conv = conv.to_dict()
  38. return get_json_result(data=conv)
  39. except Exception as e:
  40. return server_error_response(e)
  41. try:
  42. e, dia = DialogService.get_by_id(req["dialog_id"])
  43. if not e:
  44. return get_data_error_result(retmsg="Dialog not found")
  45. conv = {
  46. "id": get_uuid(),
  47. "dialog_id": req["dialog_id"],
  48. "name": req.get("name", "New conversation"),
  49. "message": [{"role": "assistant", "content": dia.prompt_config["prologue"]}]
  50. }
  51. ConversationService.save(**conv)
  52. e, conv = ConversationService.get_by_id(conv["id"])
  53. if not e:
  54. return get_data_error_result(retmsg="Fail to new a conversation!")
  55. conv = conv.to_dict()
  56. return get_json_result(data=conv)
  57. except Exception as e:
  58. return server_error_response(e)
  59. @manager.route('/get', methods=['GET'])
  60. @login_required
  61. def get():
  62. conv_id = request.args["conversation_id"]
  63. try:
  64. e, conv = ConversationService.get_by_id(conv_id)
  65. if not e:
  66. return get_data_error_result(retmsg="Conversation not found!")
  67. conv = conv.to_dict()
  68. return get_json_result(data=conv)
  69. except Exception as e:
  70. return server_error_response(e)
  71. @manager.route('/rm', methods=['POST'])
  72. @login_required
  73. def rm():
  74. conv_ids = request.json["conversation_ids"]
  75. try:
  76. for cid in conv_ids:
  77. ConversationService.delete_by_id(cid)
  78. return get_json_result(data=True)
  79. except Exception as e:
  80. return server_error_response(e)
  81. @manager.route('/list', methods=['GET'])
  82. @login_required
  83. def list_convsersation():
  84. dialog_id = request.args["dialog_id"]
  85. try:
  86. convs = ConversationService.query(
  87. dialog_id=dialog_id,
  88. order_by=ConversationService.model.create_time,
  89. reverse=True)
  90. convs = [d.to_dict() for d in convs]
  91. return get_json_result(data=convs)
  92. except Exception as e:
  93. return server_error_response(e)
  94. @manager.route('/completion', methods=['POST'])
  95. @login_required
  96. #@validate_request("conversation_id", "messages")
  97. def completion():
  98. req = request.json
  99. #req = {"conversation_id": "9aaaca4c11d311efa461fa163e197198", "messages": [
  100. # {"role": "user", "content": "上海有吗?"}
  101. #]}
  102. msg = []
  103. for m in req["messages"]:
  104. if m["role"] == "system":
  105. continue
  106. if m["role"] == "assistant" and not msg:
  107. continue
  108. msg.append({"role": m["role"], "content": m["content"]})
  109. try:
  110. e, conv = ConversationService.get_by_id(req["conversation_id"])
  111. if not e:
  112. return get_data_error_result(retmsg="Conversation not found!")
  113. conv.message.append(msg[-1])
  114. e, dia = DialogService.get_by_id(conv.dialog_id)
  115. if not e:
  116. return get_data_error_result(retmsg="Dialog not found!")
  117. del req["conversation_id"]
  118. del req["messages"]
  119. if not conv.reference:
  120. conv.reference = []
  121. conv.message.append({"role": "assistant", "content": ""})
  122. conv.reference.append({"chunks": [], "doc_aggs": []})
  123. def fillin_conv(ans):
  124. nonlocal conv
  125. if not conv.reference:
  126. conv.reference.append(ans["reference"])
  127. else: conv.reference[-1] = ans["reference"]
  128. conv.message[-1] = {"role": "assistant", "content": ans["answer"]}
  129. def stream():
  130. nonlocal dia, msg, req, conv
  131. try:
  132. for ans in chat(dia, msg, True, **req):
  133. fillin_conv(ans)
  134. yield "data:"+json.dumps({"retcode": 0, "retmsg": "", "data": ans}, ensure_ascii=False) + "\n\n"
  135. ConversationService.update_by_id(conv.id, conv.to_dict())
  136. except Exception as e:
  137. yield "data:" + json.dumps({"retcode": 500, "retmsg": str(e),
  138. "data": {"answer": "**ERROR**: "+str(e), "reference": []}},
  139. ensure_ascii=False) + "\n\n"
  140. yield "data:"+json.dumps({"retcode": 0, "retmsg": "", "data": True}, ensure_ascii=False) + "\n\n"
  141. if req.get("stream", True):
  142. resp = Response(stream(), mimetype="text/event-stream")
  143. resp.headers.add_header("Cache-control", "no-cache")
  144. resp.headers.add_header("Connection", "keep-alive")
  145. resp.headers.add_header("X-Accel-Buffering", "no")
  146. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  147. return resp
  148. else:
  149. ans = chat(dia, msg, False, **req)
  150. fillin_conv(ans)
  151. ConversationService.update_by_id(conv.id, conv.to_dict())
  152. return get_json_result(data=ans)
  153. except Exception as e:
  154. return server_error_response(e)