message_service.py 8.0 KB

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