message_service.py 11 KB

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