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

conversation_service.py 8.6KB

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