選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

conversation_service.py 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. if include_ids is not None:
  45. stmt = stmt.where(Conversation.id.in_(include_ids))
  46. if exclude_ids is not None:
  47. stmt = stmt.where(~Conversation.id.in_(exclude_ids))
  48. # define sort fields and directions
  49. sort_field, sort_direction = cls._get_sort_params(sort_by)
  50. if last_id:
  51. last_conversation = session.scalar(stmt.where(Conversation.id == last_id))
  52. if not last_conversation:
  53. raise LastConversationNotExistsError()
  54. # build filters based on sorting
  55. filter_condition = cls._build_filter_condition(
  56. sort_field=sort_field,
  57. sort_direction=sort_direction,
  58. reference_conversation=last_conversation,
  59. )
  60. stmt = stmt.where(filter_condition)
  61. query_stmt = stmt.order_by(sort_direction(getattr(Conversation, sort_field))).limit(limit)
  62. conversations = session.scalars(query_stmt).all()
  63. has_more = False
  64. if len(conversations) == limit:
  65. current_page_last_conversation = conversations[-1]
  66. rest_filter_condition = cls._build_filter_condition(
  67. sort_field=sort_field,
  68. sort_direction=sort_direction,
  69. reference_conversation=current_page_last_conversation,
  70. )
  71. count_stmt = select(func.count()).select_from(stmt.where(rest_filter_condition).subquery())
  72. rest_count = session.scalar(count_stmt) or 0
  73. if rest_count > 0:
  74. has_more = True
  75. return InfiniteScrollPagination(data=conversations, limit=limit, has_more=has_more)
  76. @classmethod
  77. def _get_sort_params(cls, sort_by: str):
  78. if sort_by.startswith("-"):
  79. return sort_by[1:], desc
  80. return sort_by, asc
  81. @classmethod
  82. def _build_filter_condition(cls, sort_field: str, sort_direction: Callable, reference_conversation: Conversation):
  83. field_value = getattr(reference_conversation, sort_field)
  84. if sort_direction == desc:
  85. return getattr(Conversation, sort_field) < field_value
  86. else:
  87. return getattr(Conversation, sort_field) > field_value
  88. @classmethod
  89. def rename(
  90. cls,
  91. app_model: App,
  92. conversation_id: str,
  93. user: Optional[Union[Account, EndUser]],
  94. name: str,
  95. auto_generate: bool,
  96. ):
  97. conversation = cls.get_conversation(app_model, conversation_id, user)
  98. if auto_generate:
  99. return cls.auto_generate_name(app_model, conversation)
  100. else:
  101. conversation.name = name
  102. conversation.updated_at = naive_utc_now()
  103. db.session.commit()
  104. return conversation
  105. @classmethod
  106. def auto_generate_name(cls, app_model: App, conversation: Conversation):
  107. # get conversation first message
  108. message = (
  109. db.session.query(Message)
  110. .filter(Message.app_id == app_model.id, Message.conversation_id == conversation.id)
  111. .order_by(Message.created_at.asc())
  112. .first()
  113. )
  114. if not message:
  115. raise MessageNotExistsError()
  116. # generate conversation name
  117. try:
  118. name = LLMGenerator.generate_conversation_name(
  119. app_model.tenant_id, message.query, conversation.id, app_model.id
  120. )
  121. conversation.name = name
  122. except:
  123. pass
  124. db.session.commit()
  125. return conversation
  126. @classmethod
  127. def get_conversation(cls, app_model: App, conversation_id: str, user: Optional[Union[Account, EndUser]]):
  128. conversation = (
  129. db.session.query(Conversation)
  130. .filter(
  131. Conversation.id == conversation_id,
  132. Conversation.app_id == app_model.id,
  133. Conversation.from_source == ("api" if isinstance(user, EndUser) else "console"),
  134. Conversation.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
  135. Conversation.from_account_id == (user.id if isinstance(user, Account) else None),
  136. Conversation.is_deleted == False,
  137. )
  138. .first()
  139. )
  140. if not conversation:
  141. raise ConversationNotExistsError()
  142. return conversation
  143. @classmethod
  144. def delete(cls, app_model: App, conversation_id: str, user: Optional[Union[Account, EndUser]]):
  145. conversation = cls.get_conversation(app_model, conversation_id, user)
  146. conversation.is_deleted = True
  147. conversation.updated_at = naive_utc_now()
  148. db.session.commit()
  149. @classmethod
  150. def get_conversational_variable(
  151. cls,
  152. app_model: App,
  153. conversation_id: str,
  154. user: Optional[Union[Account, EndUser]],
  155. limit: int,
  156. last_id: Optional[str],
  157. ) -> InfiniteScrollPagination:
  158. conversation = cls.get_conversation(app_model, conversation_id, user)
  159. stmt = (
  160. select(ConversationVariable)
  161. .where(ConversationVariable.app_id == app_model.id)
  162. .where(ConversationVariable.conversation_id == conversation.id)
  163. .order_by(ConversationVariable.created_at)
  164. )
  165. with Session(db.engine) as session:
  166. if last_id:
  167. last_variable = session.scalar(stmt.where(ConversationVariable.id == last_id))
  168. if not last_variable:
  169. raise ConversationVariableNotExistsError()
  170. # Filter for variables created after the last_id
  171. stmt = stmt.where(ConversationVariable.created_at > last_variable.created_at)
  172. # Apply limit to query
  173. query_stmt = stmt.limit(limit) # Get one extra to check if there are more
  174. rows = session.scalars(query_stmt).all()
  175. has_more = False
  176. if len(rows) > limit:
  177. has_more = True
  178. rows = rows[:limit] # Remove the extra item
  179. variables = [
  180. {
  181. "created_at": row.created_at,
  182. "updated_at": row.updated_at,
  183. **row.to_variable().model_dump(),
  184. }
  185. for row in rows
  186. ]
  187. return InfiniteScrollPagination(variables, limit, has_more)