message_service.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. import json
  2. from typing import Optional, Union, List
  3. from core.completion import Completion
  4. from core.generator.llm_generator import LLMGenerator
  5. from libs.infinite_scroll_pagination import InfiniteScrollPagination
  6. from extensions.ext_database import db
  7. from models.account import Account
  8. from models.model import App, EndUser, Message, MessageFeedback, AppModelConfig
  9. from services.conversation_service import ConversationService
  10. from services.errors.app_model_config import AppModelConfigBrokenError
  11. from services.errors.conversation import ConversationNotExistsError, ConversationCompletedError
  12. from services.errors.message import FirstMessageNotExistsError, MessageNotExistsError, LastMessageNotExistsError, \
  13. SuggestedQuestionsAfterAnswerDisabledError
  14. class MessageService:
  15. @classmethod
  16. def pagination_by_first_id(cls, app_model: App, user: Optional[Union[Account | EndUser]],
  17. conversation_id: str, first_id: Optional[str], limit: int) -> InfiniteScrollPagination:
  18. if not user:
  19. return InfiniteScrollPagination(data=[], limit=limit, has_more=False)
  20. if not conversation_id:
  21. return InfiniteScrollPagination(data=[], limit=limit, has_more=False)
  22. conversation = ConversationService.get_conversation(
  23. app_model=app_model,
  24. user=user,
  25. conversation_id=conversation_id
  26. )
  27. if first_id:
  28. first_message = db.session.query(Message) \
  29. .filter(Message.conversation_id == conversation.id, Message.id == first_id).first()
  30. if not first_message:
  31. raise FirstMessageNotExistsError()
  32. history_messages = db.session.query(Message).filter(
  33. Message.conversation_id == conversation.id,
  34. Message.created_at < first_message.created_at,
  35. Message.id != first_message.id
  36. ) \
  37. .order_by(Message.created_at.desc()).limit(limit).all()
  38. else:
  39. history_messages = db.session.query(Message).filter(Message.conversation_id == conversation.id) \
  40. .order_by(Message.created_at.desc()).limit(limit).all()
  41. has_more = False
  42. if len(history_messages) == limit:
  43. current_page_first_message = history_messages[-1]
  44. rest_count = db.session.query(Message).filter(
  45. Message.conversation_id == conversation.id,
  46. Message.created_at < current_page_first_message.created_at,
  47. Message.id != current_page_first_message.id
  48. ).count()
  49. if rest_count > 0:
  50. has_more = True
  51. history_messages = list(reversed(history_messages))
  52. return InfiniteScrollPagination(
  53. data=history_messages,
  54. limit=limit,
  55. has_more=has_more
  56. )
  57. @classmethod
  58. def pagination_by_last_id(cls, app_model: App, user: Optional[Union[Account | EndUser]],
  59. last_id: Optional[str], limit: int, conversation_id: Optional[str] = None,
  60. include_ids: Optional[list] = None) -> InfiniteScrollPagination:
  61. if not user:
  62. return InfiniteScrollPagination(data=[], limit=limit, has_more=False)
  63. base_query = db.session.query(Message)
  64. if conversation_id is not None:
  65. conversation = ConversationService.get_conversation(
  66. app_model=app_model,
  67. user=user,
  68. conversation_id=conversation_id
  69. )
  70. base_query = base_query.filter(Message.conversation_id == conversation.id)
  71. if include_ids is not None:
  72. base_query = base_query.filter(Message.id.in_(include_ids))
  73. if last_id:
  74. last_message = base_query.filter(Message.id == last_id).first()
  75. if not last_message:
  76. raise LastMessageNotExistsError()
  77. history_messages = base_query.filter(
  78. Message.created_at < last_message.created_at,
  79. Message.id != last_message.id
  80. ).order_by(Message.created_at.desc()).limit(limit).all()
  81. else:
  82. history_messages = base_query.order_by(Message.created_at.desc()).limit(limit).all()
  83. has_more = False
  84. if len(history_messages) == limit:
  85. current_page_first_message = history_messages[-1]
  86. rest_count = base_query.filter(
  87. Message.created_at < current_page_first_message.created_at,
  88. Message.id != current_page_first_message.id
  89. ).count()
  90. if rest_count > 0:
  91. has_more = True
  92. return InfiniteScrollPagination(
  93. data=history_messages,
  94. limit=limit,
  95. has_more=has_more
  96. )
  97. @classmethod
  98. def create_feedback(cls, app_model: App, message_id: str, user: Optional[Union[Account | EndUser]],
  99. rating: Optional[str]) -> MessageFeedback:
  100. if not user:
  101. raise ValueError('user cannot be None')
  102. message = cls.get_message(
  103. app_model=app_model,
  104. user=user,
  105. message_id=message_id
  106. )
  107. feedback = message.user_feedback if isinstance(user, EndUser) else message.admin_feedback
  108. if not rating and feedback:
  109. db.session.delete(feedback)
  110. elif rating and feedback:
  111. feedback.rating = rating
  112. elif not rating and not feedback:
  113. raise ValueError('rating cannot be None when feedback not exists')
  114. else:
  115. feedback = MessageFeedback(
  116. app_id=app_model.id,
  117. conversation_id=message.conversation_id,
  118. message_id=message.id,
  119. rating=rating,
  120. from_source=('user' if isinstance(user, EndUser) else 'admin'),
  121. from_end_user_id=(user.id if isinstance(user, EndUser) else None),
  122. from_account_id=(user.id if isinstance(user, Account) else None),
  123. )
  124. db.session.add(feedback)
  125. db.session.commit()
  126. return feedback
  127. @classmethod
  128. def get_message(cls, app_model: App, user: Optional[Union[Account | EndUser]], message_id: str):
  129. message = db.session.query(Message).filter(
  130. Message.id == message_id,
  131. Message.app_id == app_model.id,
  132. Message.from_source == ('api' if isinstance(user, EndUser) else 'console'),
  133. Message.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
  134. Message.from_account_id == (user.id if isinstance(user, Account) else None),
  135. ).first()
  136. if not message:
  137. raise MessageNotExistsError()
  138. return message
  139. @classmethod
  140. def get_suggested_questions_after_answer(cls, app_model: App, user: Optional[Union[Account | EndUser]],
  141. message_id: str, check_enabled: bool = True) -> List[Message]:
  142. if not user:
  143. raise ValueError('user cannot be None')
  144. message = cls.get_message(
  145. app_model=app_model,
  146. user=user,
  147. message_id=message_id
  148. )
  149. conversation = ConversationService.get_conversation(
  150. app_model=app_model,
  151. conversation_id=message.conversation_id,
  152. user=user
  153. )
  154. if not conversation:
  155. raise ConversationNotExistsError()
  156. if conversation.status != 'normal':
  157. raise ConversationCompletedError()
  158. if not conversation.override_model_configs:
  159. app_model_config = db.session.query(AppModelConfig).filter(
  160. AppModelConfig.id == conversation.app_model_config_id,
  161. AppModelConfig.app_id == app_model.id
  162. ).first()
  163. if not app_model_config:
  164. raise AppModelConfigBrokenError()
  165. else:
  166. conversation_override_model_configs = json.loads(conversation.override_model_configs)
  167. app_model_config = AppModelConfig(
  168. id=conversation.app_model_config_id,
  169. app_id=app_model.id,
  170. )
  171. app_model_config = app_model_config.from_model_config_dict(conversation_override_model_configs)
  172. suggested_questions_after_answer = app_model_config.suggested_questions_after_answer_dict
  173. if check_enabled and suggested_questions_after_answer.get("enabled", False) is False:
  174. raise SuggestedQuestionsAfterAnswerDisabledError()
  175. # get memory of conversation (read-only)
  176. memory = Completion.get_memory_from_conversation(
  177. tenant_id=app_model.tenant_id,
  178. app_model_config=app_model_config,
  179. conversation=conversation,
  180. max_token_limit=3000,
  181. message_limit=3,
  182. return_messages=False,
  183. memory_key="histories"
  184. )
  185. external_context = memory.load_memory_variables({})
  186. questions = LLMGenerator.generate_suggested_questions_after_answer(
  187. tenant_id=app_model.tenant_id,
  188. **external_context
  189. )
  190. return questions