message_service.py 9.3 KB

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