message_service.py 11 KB

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