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_service.py 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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 uuid import uuid4
  17. from api.db import StatusEnum
  18. from api.db.db_models import Conversation, DB
  19. from api.db.services.api_service import API4ConversationService
  20. from api.db.services.common_service import CommonService
  21. from api.db.services.dialog_service import DialogService, chat
  22. from api.utils import get_uuid
  23. import json
  24. from copy import deepcopy
  25. class ConversationService(CommonService):
  26. model = Conversation
  27. @classmethod
  28. @DB.connection_context()
  29. def get_list(cls,dialog_id,page_number, items_per_page, orderby, desc, id , name):
  30. sessions = cls.model.select().where(cls.model.dialog_id ==dialog_id)
  31. if id:
  32. sessions = sessions.where(cls.model.id == id)
  33. if name:
  34. sessions = sessions.where(cls.model.name == name)
  35. if desc:
  36. sessions = sessions.order_by(cls.model.getter_by(orderby).desc())
  37. else:
  38. sessions = sessions.order_by(cls.model.getter_by(orderby).asc())
  39. sessions = sessions.paginate(page_number, items_per_page)
  40. return list(sessions.dicts())
  41. def structure_answer(conv, ans, message_id, session_id):
  42. reference = ans["reference"]
  43. temp_reference = deepcopy(ans["reference"])
  44. if not conv.reference:
  45. conv.reference.append(temp_reference)
  46. else:
  47. conv.reference[-1] = temp_reference
  48. conv.message[-1] = {"role": "assistant", "content": ans["answer"], "id": message_id}
  49. chunk_list = [{
  50. "id": chunk["chunk_id"],
  51. "content": chunk["content"],
  52. "document_id": chunk["doc_id"],
  53. "document_name": chunk["docnm_kwd"],
  54. "dataset_id": chunk["kb_id"],
  55. "image_id": chunk["image_id"],
  56. "similarity": chunk["similarity"],
  57. "vector_similarity": chunk["vector_similarity"],
  58. "term_similarity": chunk["term_similarity"],
  59. "positions": chunk["positions"],
  60. } for chunk in reference.get("chunks", [])]
  61. reference["chunks"] = chunk_list
  62. ans["id"] = message_id
  63. ans["session_id"] = session_id
  64. return ans
  65. def completion(tenant_id, chat_id, question, name="New session", session_id=None, stream=True, **kwargs):
  66. assert name, "`name` can not be empty."
  67. dia = DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value)
  68. assert dia, "You do not own the chat."
  69. if not session_id:
  70. conv = {
  71. "id": get_uuid(),
  72. "dialog_id": chat_id,
  73. "name": name,
  74. "message": [{"role": "assistant", "content": dia[0].prompt_config.get("prologue")}]
  75. }
  76. ConversationService.save(**conv)
  77. yield "data:" + json.dumps({"code": 0, "message": "",
  78. "data": {
  79. "answer": conv["message"][0]["content"],
  80. "reference": {},
  81. "audio_binary": None,
  82. "id": None,
  83. "session_id": session_id
  84. }},
  85. ensure_ascii=False) + "\n\n"
  86. yield "data:" + json.dumps({"code": 0, "message": "", "data": True}, ensure_ascii=False) + "\n\n"
  87. return
  88. conv = ConversationService.query(id=session_id, dialog_id=chat_id)
  89. if not conv:
  90. raise LookupError("Session does not exist")
  91. conv = conv[0]
  92. msg = []
  93. question = {
  94. "content": question,
  95. "role": "user",
  96. "id": str(uuid4())
  97. }
  98. conv.message.append(question)
  99. for m in conv.message:
  100. if m["role"] == "system":
  101. continue
  102. if m["role"] == "assistant" and not msg:
  103. continue
  104. msg.append(m)
  105. message_id = msg[-1].get("id")
  106. e, dia = DialogService.get_by_id(conv.dialog_id)
  107. if not conv.reference:
  108. conv.reference = []
  109. conv.message.append({"role": "assistant", "content": "", "id": message_id})
  110. conv.reference.append({"chunks": [], "doc_aggs": []})
  111. if stream:
  112. try:
  113. for ans in chat(dia, msg, True, **kwargs):
  114. ans = structure_answer(conv, ans, message_id, session_id)
  115. yield "data:" + json.dumps({"code": 0, "data": ans}, ensure_ascii=False) + "\n\n"
  116. ConversationService.update_by_id(conv.id, conv.to_dict())
  117. except Exception as e:
  118. yield "data:" + json.dumps({"code": 500, "message": str(e),
  119. "data": {"answer": "**ERROR**: " + str(e), "reference": []}},
  120. ensure_ascii=False) + "\n\n"
  121. yield "data:" + json.dumps({"code": 0, "data": True}, ensure_ascii=False) + "\n\n"
  122. else:
  123. answer = None
  124. for ans in chat(dia, msg, False, **kwargs):
  125. answer = structure_answer(conv, ans, message_id, session_id)
  126. ConversationService.update_by_id(conv.id, conv.to_dict())
  127. break
  128. yield answer
  129. def iframe_completion(dialog_id, question, session_id=None, stream=True, **kwargs):
  130. e, dia = DialogService.get_by_id(dialog_id)
  131. assert e, "Dialog not found"
  132. if not session_id:
  133. session_id = get_uuid()
  134. conv = {
  135. "id": session_id,
  136. "dialog_id": dialog_id,
  137. "user_id": kwargs.get("user_id", ""),
  138. "message": [{"role": "assistant", "content": dia.prompt_config["prologue"]}]
  139. }
  140. API4ConversationService.save(**conv)
  141. yield "data:" + json.dumps({"code": 0, "message": "",
  142. "data": {
  143. "answer": conv["message"][0]["content"],
  144. "reference": {},
  145. "audio_binary": None,
  146. "id": None,
  147. "session_id": session_id
  148. }},
  149. ensure_ascii=False) + "\n\n"
  150. yield "data:" + json.dumps({"code": 0, "message": "", "data": True}, ensure_ascii=False) + "\n\n"
  151. return
  152. else:
  153. session_id = session_id
  154. e, conv = API4ConversationService.get_by_id(session_id)
  155. assert e, "Session not found!"
  156. messages = conv.message
  157. question = {
  158. "role": "user",
  159. "content": question,
  160. "id": str(uuid4())
  161. }
  162. messages.append(question)
  163. msg = []
  164. for m in messages:
  165. if m["role"] == "system":
  166. continue
  167. if m["role"] == "assistant" and not msg:
  168. continue
  169. msg.append(m)
  170. if not msg[-1].get("id"):
  171. msg[-1]["id"] = get_uuid()
  172. message_id = msg[-1]["id"]
  173. if not conv.reference:
  174. conv.reference = []
  175. conv.message.append({"role": "assistant", "content": "", "id": message_id})
  176. conv.reference.append({"chunks": [], "doc_aggs": []})
  177. if stream:
  178. try:
  179. for ans in chat(dia, msg, True, **kwargs):
  180. ans = structure_answer(conv, ans, message_id, session_id)
  181. yield "data:" + json.dumps({"code": 0, "message": "", "data": ans},
  182. ensure_ascii=False) + "\n\n"
  183. API4ConversationService.append_message(conv.id, conv.to_dict())
  184. except Exception as e:
  185. yield "data:" + json.dumps({"code": 500, "message": str(e),
  186. "data": {"answer": "**ERROR**: " + str(e), "reference": []}},
  187. ensure_ascii=False) + "\n\n"
  188. yield "data:" + json.dumps({"code": 0, "message": "", "data": True}, ensure_ascii=False) + "\n\n"
  189. else:
  190. answer = None
  191. for ans in chat(dia, msg, False, **kwargs):
  192. answer = structure_answer(conv, ans, message_id, session_id)
  193. API4ConversationService.append_message(conv.id, conv.to_dict())
  194. break
  195. yield answer