message_service.py 11 KB

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