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.

session.py 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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 json
  17. from copy import deepcopy
  18. from uuid import uuid4
  19. from flask import request, Response
  20. from api.db import StatusEnum
  21. from api.db.services.dialog_service import DialogService, ConversationService, chat
  22. from api.utils import get_uuid
  23. from api.utils.api_utils import get_data_error_result
  24. from api.utils.api_utils import get_json_result, token_required
  25. @manager.route('/save', methods=['POST'])
  26. @token_required
  27. def set_conversation(tenant_id):
  28. req = request.json
  29. conv_id = req.get("id")
  30. if "messages" in req:
  31. req["message"] = req.pop("messages")
  32. if req["message"]:
  33. for message in req["message"]:
  34. if "reference" in message:
  35. req["reference"] = message.pop("reference")
  36. if "assistant_id" in req:
  37. req["dialog_id"] = req.pop("assistant_id")
  38. if "id" in req:
  39. del req["id"]
  40. conv = ConversationService.query(id=conv_id)
  41. if not conv:
  42. return get_data_error_result(retmsg="Session does not exist")
  43. if not DialogService.query(id=conv[0].dialog_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
  44. return get_data_error_result(retmsg="You do not own the session")
  45. if req.get("dialog_id"):
  46. dia = DialogService.query(tenant_id=tenant_id, id=req["dialog_id"], status=StatusEnum.VALID.value)
  47. if not dia:
  48. return get_data_error_result(retmsg="You do not own the assistant")
  49. if "dialog_id" in req and not req.get("dialog_id"):
  50. return get_data_error_result(retmsg="assistant_id can not be empty.")
  51. if "name" in req and not req.get("name"):
  52. return get_data_error_result(retmsg="name can not be empty.")
  53. if "message" in req and not req.get("message"):
  54. return get_data_error_result(retmsg="messages can not be empty")
  55. if not ConversationService.update_by_id(conv_id, req):
  56. return get_data_error_result(retmsg="Session updates error")
  57. return get_json_result(data=True)
  58. if not req.get("dialog_id"):
  59. return get_data_error_result(retmsg="assistant_id is required.")
  60. dia = DialogService.query(tenant_id=tenant_id, id=req["dialog_id"], status=StatusEnum.VALID.value)
  61. if not dia:
  62. return get_data_error_result(retmsg="You do not own the assistant")
  63. conv = {
  64. "id": get_uuid(),
  65. "dialog_id": req["dialog_id"],
  66. "name": req.get("name", "New session"),
  67. "message": req.get("message", [{"role": "assistant", "content": dia[0].prompt_config["prologue"]}]),
  68. "reference": req.get("reference", [])
  69. }
  70. if not conv.get("name"):
  71. return get_data_error_result(retmsg="name can not be empty.")
  72. if not conv.get("message"):
  73. return get_data_error_result(retmsg="messages can not be empty")
  74. ConversationService.save(**conv)
  75. e, conv = ConversationService.get_by_id(conv["id"])
  76. if not e:
  77. return get_data_error_result(retmsg="Fail to new session!")
  78. conv = conv.to_dict()
  79. conv["messages"] = conv.pop("message")
  80. conv["assistant_id"] = conv.pop("dialog_id")
  81. for message in conv["messages"]:
  82. message["reference"] = conv.get("reference")
  83. del conv["reference"]
  84. return get_json_result(data=conv)
  85. @manager.route('/completion', methods=['POST'])
  86. @token_required
  87. def completion(tenant_id):
  88. req = request.json
  89. # req = {"conversation_id": "9aaaca4c11d311efa461fa163e197198", "messages": [
  90. # {"role": "user", "content": "上海有吗?"}
  91. # ]}
  92. msg = []
  93. question = {
  94. "content": req.get("question"),
  95. "role": "user",
  96. "id": str(uuid4())
  97. }
  98. req["messages"].append(question)
  99. for m in req["messages"]:
  100. if m["role"] == "system": continue
  101. if m["role"] == "assistant" and not msg: continue
  102. m["id"] = m.get("id", str(uuid4()))
  103. msg.append(m)
  104. message_id = msg[-1].get("id")
  105. conv = ConversationService.query(id=req["id"])
  106. conv = conv[0]
  107. if not conv:
  108. return get_data_error_result(retmsg="Session does not exist")
  109. if not DialogService.query(id=conv.dialog_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
  110. return get_data_error_result(retmsg="You do not own the session")
  111. conv.message = deepcopy(req["messages"])
  112. e, dia = DialogService.get_by_id(conv.dialog_id)
  113. if not e:
  114. return get_data_error_result(retmsg="Dialog not found!")
  115. del req["id"]
  116. del req["messages"]
  117. if not conv.reference:
  118. conv.reference = []
  119. conv.message.append({"role": "assistant", "content": "", "id": message_id})
  120. conv.reference.append({"chunks": [], "doc_aggs": []})
  121. def fillin_conv(ans):
  122. nonlocal conv, message_id
  123. if not conv.reference:
  124. conv.reference.append(ans["reference"])
  125. else:
  126. conv.reference[-1] = ans["reference"]
  127. conv.message[-1] = {"role": "assistant", "content": ans["answer"],
  128. "id": message_id, "prompt": ans.get("prompt", "")}
  129. ans["id"] = message_id
  130. def stream():
  131. nonlocal dia, msg, req, conv
  132. try:
  133. for ans in chat(dia, msg, **req):
  134. fillin_conv(ans)
  135. yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": ans}, ensure_ascii=False) + "\n\n"
  136. ConversationService.update_by_id(conv.id, conv.to_dict())
  137. except Exception as e:
  138. yield "data:" + json.dumps({"retcode": 500, "retmsg": str(e),
  139. "data": {"answer": "**ERROR**: " + str(e), "reference": []}},
  140. ensure_ascii=False) + "\n\n"
  141. yield "data:" + json.dumps({"retcode": 0, "retmsg": "", "data": True}, ensure_ascii=False) + "\n\n"
  142. if req.get("stream", True):
  143. resp = Response(stream(), mimetype="text/event-stream")
  144. resp.headers.add_header("Cache-control", "no-cache")
  145. resp.headers.add_header("Connection", "keep-alive")
  146. resp.headers.add_header("X-Accel-Buffering", "no")
  147. resp.headers.add_header("Content-Type", "text/event-stream; charset=utf-8")
  148. return resp
  149. else:
  150. answer = None
  151. for ans in chat(dia, msg, **req):
  152. answer = ans
  153. fillin_conv(ans)
  154. ConversationService.update_by_id(conv.id, conv.to_dict())
  155. break
  156. return get_json_result(data=answer)