conversation_service.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. from collections.abc import Callable, Sequence
  2. from datetime import UTC, datetime
  3. from typing import Optional, Union
  4. from sqlalchemy import asc, desc, func, or_, select
  5. from sqlalchemy.orm import Session
  6. from core.app.entities.app_invoke_entities import InvokeFrom
  7. from core.llm_generator.llm_generator import LLMGenerator
  8. from extensions.ext_database import db
  9. from libs.infinite_scroll_pagination import InfiniteScrollPagination
  10. from models.account import Account
  11. from models.model import App, Conversation, EndUser, Message
  12. from services.errors.conversation import ConversationNotExistsError, LastConversationNotExistsError
  13. from services.errors.message import MessageNotExistsError
  14. class ConversationService:
  15. @classmethod
  16. def pagination_by_last_id(
  17. cls,
  18. *,
  19. session: Session,
  20. app_model: App,
  21. user: Optional[Union[Account, EndUser]],
  22. last_id: Optional[str],
  23. limit: int,
  24. invoke_from: InvokeFrom,
  25. include_ids: Optional[Sequence[str]] = None,
  26. exclude_ids: Optional[Sequence[str]] = None,
  27. sort_by: str = "-updated_at",
  28. ) -> InfiniteScrollPagination:
  29. if not user:
  30. return InfiniteScrollPagination(data=[], limit=limit, has_more=False)
  31. stmt = select(Conversation).where(
  32. Conversation.is_deleted == False,
  33. Conversation.app_id == app_model.id,
  34. Conversation.from_source == ("api" if isinstance(user, EndUser) else "console"),
  35. Conversation.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
  36. Conversation.from_account_id == (user.id if isinstance(user, Account) else None),
  37. or_(Conversation.invoke_from.is_(None), Conversation.invoke_from == invoke_from.value),
  38. )
  39. if include_ids is not None:
  40. stmt = stmt.where(Conversation.id.in_(include_ids))
  41. if exclude_ids is not None:
  42. stmt = stmt.where(~Conversation.id.in_(exclude_ids))
  43. # define sort fields and directions
  44. sort_field, sort_direction = cls._get_sort_params(sort_by)
  45. if last_id:
  46. last_conversation = session.scalar(stmt.where(Conversation.id == last_id))
  47. if not last_conversation:
  48. raise LastConversationNotExistsError()
  49. # build filters based on sorting
  50. filter_condition = cls._build_filter_condition(
  51. sort_field=sort_field,
  52. sort_direction=sort_direction,
  53. reference_conversation=last_conversation,
  54. )
  55. stmt = stmt.where(filter_condition)
  56. query_stmt = stmt.order_by(sort_direction(getattr(Conversation, sort_field))).limit(limit)
  57. conversations = session.scalars(query_stmt).all()
  58. has_more = False
  59. if len(conversations) == limit:
  60. current_page_last_conversation = conversations[-1]
  61. rest_filter_condition = cls._build_filter_condition(
  62. sort_field=sort_field,
  63. sort_direction=sort_direction,
  64. reference_conversation=current_page_last_conversation,
  65. )
  66. count_stmt = stmt.where(rest_filter_condition)
  67. count_stmt = select(func.count()).select_from(count_stmt.subquery())
  68. rest_count = session.scalar(count_stmt) or 0
  69. if rest_count > 0:
  70. has_more = True
  71. return InfiniteScrollPagination(data=conversations, limit=limit, has_more=has_more)
  72. @classmethod
  73. def _get_sort_params(cls, sort_by: str):
  74. if sort_by.startswith("-"):
  75. return sort_by[1:], desc
  76. return sort_by, asc
  77. @classmethod
  78. def _build_filter_condition(cls, sort_field: str, sort_direction: Callable, reference_conversation: Conversation):
  79. field_value = getattr(reference_conversation, sort_field)
  80. if sort_direction == desc:
  81. return getattr(Conversation, sort_field) < field_value
  82. else:
  83. return getattr(Conversation, sort_field) > field_value
  84. @classmethod
  85. def rename(
  86. cls,
  87. app_model: App,
  88. conversation_id: str,
  89. user: Optional[Union[Account, EndUser]],
  90. name: str,
  91. auto_generate: bool,
  92. ):
  93. conversation = cls.get_conversation(app_model, conversation_id, user)
  94. if auto_generate:
  95. return cls.auto_generate_name(app_model, conversation)
  96. else:
  97. conversation.name = name
  98. conversation.updated_at = datetime.now(UTC).replace(tzinfo=None)
  99. db.session.commit()
  100. return conversation
  101. @classmethod
  102. def auto_generate_name(cls, app_model: App, conversation: Conversation):
  103. # get conversation first message
  104. message = (
  105. db.session.query(Message)
  106. .filter(Message.app_id == app_model.id, Message.conversation_id == conversation.id)
  107. .order_by(Message.created_at.asc())
  108. .first()
  109. )
  110. if not message:
  111. raise MessageNotExistsError()
  112. # generate conversation name
  113. try:
  114. name = LLMGenerator.generate_conversation_name(
  115. app_model.tenant_id, message.query, conversation.id, app_model.id
  116. )
  117. conversation.name = name
  118. except:
  119. pass
  120. db.session.commit()
  121. return conversation
  122. @classmethod
  123. def get_conversation(cls, app_model: App, conversation_id: str, user: Optional[Union[Account, EndUser]]):
  124. conversation = (
  125. db.session.query(Conversation)
  126. .filter(
  127. Conversation.id == conversation_id,
  128. Conversation.app_id == app_model.id,
  129. Conversation.from_source == ("api" if isinstance(user, EndUser) else "console"),
  130. Conversation.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
  131. Conversation.from_account_id == (user.id if isinstance(user, Account) else None),
  132. Conversation.is_deleted == False,
  133. )
  134. .first()
  135. )
  136. if not conversation:
  137. raise ConversationNotExistsError()
  138. return conversation
  139. @classmethod
  140. def delete(cls, app_model: App, conversation_id: str, user: Optional[Union[Account, EndUser]]):
  141. conversation = cls.get_conversation(app_model, conversation_id, user)
  142. conversation.is_deleted = True
  143. conversation.updated_at = datetime.now(UTC).replace(tzinfo=None)
  144. db.session.commit()