message_service.py 10 KB

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