You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

message_service.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import json
  2. from typing import 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: Union[Account, EndUser] | None,
  30. conversation_id: str,
  31. first_id: str | None,
  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. .where(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. .where(
  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. .where(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: Union[Account, EndUser] | None,
  82. last_id: str | None,
  83. limit: int,
  84. conversation_id: str | None = None,
  85. include_ids: list | None = 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.where(Message.conversation_id == conversation.id)
  96. # Check if include_ids is not None and not empty to avoid WHERE false condition
  97. if include_ids is not None:
  98. if len(include_ids) == 0:
  99. return InfiniteScrollPagination(data=[], limit=limit, has_more=False)
  100. base_query = base_query.where(Message.id.in_(include_ids))
  101. if last_id:
  102. last_message = base_query.where(Message.id == last_id).first()
  103. if not last_message:
  104. raise LastMessageNotExistsError()
  105. history_messages = (
  106. base_query.where(Message.created_at < last_message.created_at, Message.id != last_message.id)
  107. .order_by(Message.created_at.desc())
  108. .limit(fetch_limit)
  109. .all()
  110. )
  111. else:
  112. history_messages = base_query.order_by(Message.created_at.desc()).limit(fetch_limit).all()
  113. has_more = False
  114. if len(history_messages) > limit:
  115. has_more = True
  116. history_messages = history_messages[:-1]
  117. return InfiniteScrollPagination(data=history_messages, limit=limit, has_more=has_more)
  118. @classmethod
  119. def create_feedback(
  120. cls,
  121. *,
  122. app_model: App,
  123. message_id: str,
  124. user: Union[Account, EndUser] | None,
  125. rating: str | None,
  126. content: str | None,
  127. ):
  128. if not user:
  129. raise ValueError("user cannot be None")
  130. message = cls.get_message(app_model=app_model, user=user, message_id=message_id)
  131. feedback = message.user_feedback if isinstance(user, EndUser) else message.admin_feedback
  132. if not rating and feedback:
  133. db.session.delete(feedback)
  134. elif rating and feedback:
  135. feedback.rating = rating
  136. feedback.content = content
  137. elif not rating and not feedback:
  138. raise ValueError("rating cannot be None when feedback not exists")
  139. else:
  140. feedback = MessageFeedback(
  141. app_id=app_model.id,
  142. conversation_id=message.conversation_id,
  143. message_id=message.id,
  144. rating=rating,
  145. content=content,
  146. from_source=("user" if isinstance(user, EndUser) else "admin"),
  147. from_end_user_id=(user.id if isinstance(user, EndUser) else None),
  148. from_account_id=(user.id if isinstance(user, Account) else None),
  149. )
  150. db.session.add(feedback)
  151. db.session.commit()
  152. return feedback
  153. @classmethod
  154. def get_all_messages_feedbacks(cls, app_model: App, page: int, limit: int):
  155. """Get all feedbacks of an app"""
  156. offset = (page - 1) * limit
  157. feedbacks = (
  158. db.session.query(MessageFeedback)
  159. .where(MessageFeedback.app_id == app_model.id)
  160. .order_by(MessageFeedback.created_at.desc(), MessageFeedback.id.desc())
  161. .limit(limit)
  162. .offset(offset)
  163. .all()
  164. )
  165. return [record.to_dict() for record in feedbacks]
  166. @classmethod
  167. def get_message(cls, app_model: App, user: Union[Account, EndUser] | None, message_id: str):
  168. message = (
  169. db.session.query(Message)
  170. .where(
  171. Message.id == message_id,
  172. Message.app_id == app_model.id,
  173. Message.from_source == ("api" if isinstance(user, EndUser) else "console"),
  174. Message.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
  175. Message.from_account_id == (user.id if isinstance(user, Account) else None),
  176. )
  177. .first()
  178. )
  179. if not message:
  180. raise MessageNotExistsError()
  181. return message
  182. @classmethod
  183. def get_suggested_questions_after_answer(
  184. cls, app_model: App, user: Union[Account, EndUser] | None, message_id: str, invoke_from: InvokeFrom
  185. ) -> list[str]:
  186. if not user:
  187. raise ValueError("user cannot be None")
  188. message = cls.get_message(app_model=app_model, user=user, message_id=message_id)
  189. conversation = ConversationService.get_conversation(
  190. app_model=app_model, conversation_id=message.conversation_id, user=user
  191. )
  192. model_manager = ModelManager()
  193. if app_model.mode == AppMode.ADVANCED_CHAT:
  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:
  203. raise ValueError("Additional features not found")
  204. if not app_config.additional_features.suggested_questions_after_answer:
  205. raise SuggestedQuestionsAfterAnswerDisabledError()
  206. model_instance = model_manager.get_default_model_instance(
  207. tenant_id=app_model.tenant_id, model_type=ModelType.LLM
  208. )
  209. else:
  210. if not conversation.override_model_configs:
  211. app_model_config = (
  212. db.session.query(AppModelConfig)
  213. .where(AppModelConfig.id == conversation.app_model_config_id, AppModelConfig.app_id == app_model.id)
  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. if not app_model_config:
  224. raise ValueError("did not find app model config")
  225. suggested_questions_after_answer = app_model_config.suggested_questions_after_answer_dict
  226. if suggested_questions_after_answer.get("enabled", False) is False:
  227. raise SuggestedQuestionsAfterAnswerDisabledError()
  228. model_instance = model_manager.get_model_instance(
  229. tenant_id=app_model.tenant_id,
  230. provider=app_model_config.model_dict["provider"],
  231. model_type=ModelType.LLM,
  232. model=app_model_config.model_dict["name"],
  233. )
  234. # get memory of conversation (read-only)
  235. memory = TokenBufferMemory(conversation=conversation, model_instance=model_instance)
  236. histories = memory.get_history_prompt_text(
  237. max_token_limit=3000,
  238. message_limit=3,
  239. )
  240. with measure_time() as timer:
  241. questions: list[str] = LLMGenerator.generate_suggested_questions_after_answer(
  242. tenant_id=app_model.tenant_id, histories=histories
  243. )
  244. # get tracing instance
  245. trace_manager = TraceQueueManager(app_id=app_model.id)
  246. trace_manager.add_trace_task(
  247. TraceTask(
  248. TraceTaskName.SUGGESTED_QUESTION_TRACE, message_id=message_id, suggested_question=questions, timer=timer
  249. )
  250. )
  251. return questions