Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. .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: 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.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 and len(include_ids) > 0:
  98. base_query = base_query.where(Message.id.in_(include_ids))
  99. if last_id:
  100. last_message = base_query.where(Message.id == last_id).first()
  101. if not last_message:
  102. raise LastMessageNotExistsError()
  103. history_messages = (
  104. base_query.where(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_all_messages_feedbacks(cls, app_model: App, page: int, limit: int):
  153. """Get all feedbacks of an app"""
  154. offset = (page - 1) * limit
  155. feedbacks = (
  156. db.session.query(MessageFeedback)
  157. .where(MessageFeedback.app_id == app_model.id)
  158. .order_by(MessageFeedback.created_at.desc(), MessageFeedback.id.desc())
  159. .limit(limit)
  160. .offset(offset)
  161. .all()
  162. )
  163. return [record.to_dict() for record in feedbacks]
  164. @classmethod
  165. def get_message(cls, app_model: App, user: Optional[Union[Account, EndUser]], message_id: str):
  166. message = (
  167. db.session.query(Message)
  168. .where(
  169. Message.id == message_id,
  170. Message.app_id == app_model.id,
  171. Message.from_source == ("api" if isinstance(user, EndUser) else "console"),
  172. Message.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
  173. Message.from_account_id == (user.id if isinstance(user, Account) else None),
  174. )
  175. .first()
  176. )
  177. if not message:
  178. raise MessageNotExistsError()
  179. return message
  180. @classmethod
  181. def get_suggested_questions_after_answer(
  182. cls, app_model: App, user: Optional[Union[Account, EndUser]], message_id: str, invoke_from: InvokeFrom
  183. ) -> list[Message]:
  184. if not user:
  185. raise ValueError("user cannot be None")
  186. message = cls.get_message(app_model=app_model, user=user, message_id=message_id)
  187. conversation = ConversationService.get_conversation(
  188. app_model=app_model, conversation_id=message.conversation_id, user=user
  189. )
  190. model_manager = ModelManager()
  191. if app_model.mode == AppMode.ADVANCED_CHAT.value:
  192. workflow_service = WorkflowService()
  193. if invoke_from == InvokeFrom.DEBUGGER:
  194. workflow = workflow_service.get_draft_workflow(app_model=app_model)
  195. else:
  196. workflow = workflow_service.get_published_workflow(app_model=app_model)
  197. if workflow is None:
  198. return []
  199. app_config = AdvancedChatAppConfigManager.get_app_config(app_model=app_model, workflow=workflow)
  200. if not app_config.additional_features.suggested_questions_after_answer:
  201. raise SuggestedQuestionsAfterAnswerDisabledError()
  202. model_instance = model_manager.get_default_model_instance(
  203. tenant_id=app_model.tenant_id, model_type=ModelType.LLM
  204. )
  205. else:
  206. if not conversation.override_model_configs:
  207. app_model_config = (
  208. db.session.query(AppModelConfig)
  209. .where(AppModelConfig.id == conversation.app_model_config_id, AppModelConfig.app_id == app_model.id)
  210. .first()
  211. )
  212. else:
  213. conversation_override_model_configs = json.loads(conversation.override_model_configs)
  214. app_model_config = AppModelConfig(
  215. id=conversation.app_model_config_id,
  216. app_id=app_model.id,
  217. )
  218. app_model_config = app_model_config.from_model_config_dict(conversation_override_model_configs)
  219. if not app_model_config:
  220. raise ValueError("did not find app model config")
  221. suggested_questions_after_answer = app_model_config.suggested_questions_after_answer_dict
  222. if suggested_questions_after_answer.get("enabled", False) is False:
  223. raise SuggestedQuestionsAfterAnswerDisabledError()
  224. model_instance = model_manager.get_model_instance(
  225. tenant_id=app_model.tenant_id,
  226. provider=app_model_config.model_dict["provider"],
  227. model_type=ModelType.LLM,
  228. model=app_model_config.model_dict["name"],
  229. )
  230. # get memory of conversation (read-only)
  231. memory = TokenBufferMemory(conversation=conversation, model_instance=model_instance)
  232. histories = memory.get_history_prompt_text(
  233. max_token_limit=3000,
  234. message_limit=3,
  235. )
  236. with measure_time() as timer:
  237. questions: list[Message] = LLMGenerator.generate_suggested_questions_after_answer(
  238. tenant_id=app_model.tenant_id, histories=histories
  239. )
  240. # get tracing instance
  241. trace_manager = TraceQueueManager(app_id=app_model.id)
  242. trace_manager.add_trace_task(
  243. TraceTask(
  244. TraceTaskName.SUGGESTED_QUESTION_TRACE, message_id=message_id, suggested_question=questions, timer=timer
  245. )
  246. )
  247. return questions