message_service.py 10 KB

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