message_service.py 11 KB

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