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.

conversation_service.py 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. from collections.abc import Callable, Sequence
  2. from typing import Optional, Union
  3. from sqlalchemy import asc, desc, func, or_, select
  4. from sqlalchemy.orm import Session
  5. from core.app.entities.app_invoke_entities import InvokeFrom
  6. from core.llm_generator.llm_generator import LLMGenerator
  7. from extensions.ext_database import db
  8. from libs.datetime_utils import naive_utc_now
  9. from libs.infinite_scroll_pagination import InfiniteScrollPagination
  10. from models import ConversationVariable
  11. from models.account import Account
  12. from models.model import App, Conversation, EndUser, Message
  13. from services.errors.conversation import (
  14. ConversationNotExistsError,
  15. ConversationVariableNotExistsError,
  16. LastConversationNotExistsError,
  17. )
  18. from services.errors.message import MessageNotExistsError
  19. class ConversationService:
  20. @classmethod
  21. def pagination_by_last_id(
  22. cls,
  23. *,
  24. session: Session,
  25. app_model: App,
  26. user: Optional[Union[Account, EndUser]],
  27. last_id: Optional[str],
  28. limit: int,
  29. invoke_from: InvokeFrom,
  30. include_ids: Optional[Sequence[str]] = None,
  31. exclude_ids: Optional[Sequence[str]] = None,
  32. sort_by: str = "-updated_at",
  33. ) -> InfiniteScrollPagination:
  34. if not user:
  35. return InfiniteScrollPagination(data=[], limit=limit, has_more=False)
  36. stmt = select(Conversation).where(
  37. Conversation.is_deleted == False,
  38. Conversation.app_id == app_model.id,
  39. Conversation.from_source == ("api" if isinstance(user, EndUser) else "console"),
  40. Conversation.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
  41. Conversation.from_account_id == (user.id if isinstance(user, Account) else None),
  42. or_(Conversation.invoke_from.is_(None), Conversation.invoke_from == invoke_from.value),
  43. )
  44. # Check if include_ids is not None and not empty to avoid WHERE false condition
  45. if include_ids is not None and len(include_ids) > 0:
  46. stmt = stmt.where(Conversation.id.in_(include_ids))
  47. # Check if exclude_ids is not None and not empty to avoid WHERE false condition
  48. if exclude_ids is not None and len(exclude_ids) > 0:
  49. stmt = stmt.where(~Conversation.id.in_(exclude_ids))
  50. # define sort fields and directions
  51. sort_field, sort_direction = cls._get_sort_params(sort_by)
  52. if last_id:
  53. last_conversation = session.scalar(stmt.where(Conversation.id == last_id))
  54. if not last_conversation:
  55. raise LastConversationNotExistsError()
  56. # build filters based on sorting
  57. filter_condition = cls._build_filter_condition(
  58. sort_field=sort_field,
  59. sort_direction=sort_direction,
  60. reference_conversation=last_conversation,
  61. )
  62. stmt = stmt.where(filter_condition)
  63. query_stmt = stmt.order_by(sort_direction(getattr(Conversation, sort_field))).limit(limit)
  64. conversations = session.scalars(query_stmt).all()
  65. has_more = False
  66. if len(conversations) == limit:
  67. current_page_last_conversation = conversations[-1]
  68. rest_filter_condition = cls._build_filter_condition(
  69. sort_field=sort_field,
  70. sort_direction=sort_direction,
  71. reference_conversation=current_page_last_conversation,
  72. )
  73. count_stmt = select(func.count()).select_from(stmt.where(rest_filter_condition).subquery())
  74. rest_count = session.scalar(count_stmt) or 0
  75. if rest_count > 0:
  76. has_more = True
  77. return InfiniteScrollPagination(data=conversations, limit=limit, has_more=has_more)
  78. @classmethod
  79. def _get_sort_params(cls, sort_by: str):
  80. if sort_by.startswith("-"):
  81. return sort_by[1:], desc
  82. return sort_by, asc
  83. @classmethod
  84. def _build_filter_condition(cls, sort_field: str, sort_direction: Callable, reference_conversation: Conversation):
  85. field_value = getattr(reference_conversation, sort_field)
  86. if sort_direction == desc:
  87. return getattr(Conversation, sort_field) < field_value
  88. else:
  89. return getattr(Conversation, sort_field) > field_value
  90. @classmethod
  91. def rename(
  92. cls,
  93. app_model: App,
  94. conversation_id: str,
  95. user: Optional[Union[Account, EndUser]],
  96. name: str,
  97. auto_generate: bool,
  98. ):
  99. conversation = cls.get_conversation(app_model, conversation_id, user)
  100. if auto_generate:
  101. return cls.auto_generate_name(app_model, conversation)
  102. else:
  103. conversation.name = name
  104. conversation.updated_at = naive_utc_now()
  105. db.session.commit()
  106. return conversation
  107. @classmethod
  108. def auto_generate_name(cls, app_model: App, conversation: Conversation):
  109. # get conversation first message
  110. message = (
  111. db.session.query(Message)
  112. .where(Message.app_id == app_model.id, Message.conversation_id == conversation.id)
  113. .order_by(Message.created_at.asc())
  114. .first()
  115. )
  116. if not message:
  117. raise MessageNotExistsError()
  118. # generate conversation name
  119. try:
  120. name = LLMGenerator.generate_conversation_name(
  121. app_model.tenant_id, message.query, conversation.id, app_model.id
  122. )
  123. conversation.name = name
  124. except:
  125. pass
  126. db.session.commit()
  127. return conversation
  128. @classmethod
  129. def get_conversation(cls, app_model: App, conversation_id: str, user: Optional[Union[Account, EndUser]]):
  130. conversation = (
  131. db.session.query(Conversation)
  132. .where(
  133. Conversation.id == conversation_id,
  134. Conversation.app_id == app_model.id,
  135. Conversation.from_source == ("api" if isinstance(user, EndUser) else "console"),
  136. Conversation.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
  137. Conversation.from_account_id == (user.id if isinstance(user, Account) else None),
  138. Conversation.is_deleted == False,
  139. )
  140. .first()
  141. )
  142. if not conversation:
  143. raise ConversationNotExistsError()
  144. return conversation
  145. @classmethod
  146. def delete(cls, app_model: App, conversation_id: str, user: Optional[Union[Account, EndUser]]):
  147. conversation = cls.get_conversation(app_model, conversation_id, user)
  148. conversation.is_deleted = True
  149. conversation.updated_at = naive_utc_now()
  150. db.session.commit()
  151. @classmethod
  152. def get_conversational_variable(
  153. cls,
  154. app_model: App,
  155. conversation_id: str,
  156. user: Optional[Union[Account, EndUser]],
  157. limit: int,
  158. last_id: Optional[str],
  159. ) -> InfiniteScrollPagination:
  160. conversation = cls.get_conversation(app_model, conversation_id, user)
  161. stmt = (
  162. select(ConversationVariable)
  163. .where(ConversationVariable.app_id == app_model.id)
  164. .where(ConversationVariable.conversation_id == conversation.id)
  165. .order_by(ConversationVariable.created_at)
  166. )
  167. with Session(db.engine) as session:
  168. if last_id:
  169. last_variable = session.scalar(stmt.where(ConversationVariable.id == last_id))
  170. if not last_variable:
  171. raise ConversationVariableNotExistsError()
  172. # Filter for variables created after the last_id
  173. stmt = stmt.where(ConversationVariable.created_at > last_variable.created_at)
  174. # Apply limit to query
  175. query_stmt = stmt.limit(limit) # Get one extra to check if there are more
  176. rows = session.scalars(query_stmt).all()
  177. has_more = False
  178. if len(rows) > limit:
  179. has_more = True
  180. rows = rows[:limit] # Remove the extra item
  181. variables = [
  182. {
  183. "created_at": row.created_at,
  184. "updated_at": row.updated_at,
  185. **row.to_variable().model_dump(),
  186. }
  187. for row in rows
  188. ]
  189. return InfiniteScrollPagination(variables, limit, has_more)