message_service.py 9.3 KB

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