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 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. from collections.abc import Callable, Sequence
  2. from typing import Any, 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 core.variables.types import SegmentType
  8. from core.workflow.nodes.variable_assigner.common.impl import conversation_variable_updater_factory
  9. from extensions.ext_database import db
  10. from factories import variable_factory
  11. from libs.datetime_utils import naive_utc_now
  12. from libs.infinite_scroll_pagination import InfiniteScrollPagination
  13. from models import ConversationVariable
  14. from models.account import Account
  15. from models.model import App, Conversation, EndUser, Message
  16. from services.errors.conversation import (
  17. ConversationNotExistsError,
  18. ConversationVariableNotExistsError,
  19. ConversationVariableTypeMismatchError,
  20. LastConversationNotExistsError,
  21. )
  22. from services.errors.message import MessageNotExistsError
  23. class ConversationService:
  24. @classmethod
  25. def pagination_by_last_id(
  26. cls,
  27. *,
  28. session: Session,
  29. app_model: App,
  30. user: Optional[Union[Account, EndUser]],
  31. last_id: Optional[str],
  32. limit: int,
  33. invoke_from: InvokeFrom,
  34. include_ids: Optional[Sequence[str]] = None,
  35. exclude_ids: Optional[Sequence[str]] = None,
  36. sort_by: str = "-updated_at",
  37. ) -> InfiniteScrollPagination:
  38. if not user:
  39. return InfiniteScrollPagination(data=[], limit=limit, has_more=False)
  40. stmt = select(Conversation).where(
  41. Conversation.is_deleted == False,
  42. Conversation.app_id == app_model.id,
  43. Conversation.from_source == ("api" if isinstance(user, EndUser) else "console"),
  44. Conversation.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
  45. Conversation.from_account_id == (user.id if isinstance(user, Account) else None),
  46. or_(Conversation.invoke_from.is_(None), Conversation.invoke_from == invoke_from.value),
  47. )
  48. # Check if include_ids is not None to apply filter
  49. if include_ids is not None:
  50. if len(include_ids) == 0:
  51. # If include_ids is empty, return empty result
  52. return InfiniteScrollPagination(data=[], limit=limit, has_more=False)
  53. stmt = stmt.where(Conversation.id.in_(include_ids))
  54. # Check if exclude_ids is not None to apply filter
  55. if exclude_ids is not None:
  56. if len(exclude_ids) > 0:
  57. stmt = stmt.where(~Conversation.id.in_(exclude_ids))
  58. # define sort fields and directions
  59. sort_field, sort_direction = cls._get_sort_params(sort_by)
  60. if last_id:
  61. last_conversation = session.scalar(stmt.where(Conversation.id == last_id))
  62. if not last_conversation:
  63. raise LastConversationNotExistsError()
  64. # build filters based on sorting
  65. filter_condition = cls._build_filter_condition(
  66. sort_field=sort_field,
  67. sort_direction=sort_direction,
  68. reference_conversation=last_conversation,
  69. )
  70. stmt = stmt.where(filter_condition)
  71. query_stmt = stmt.order_by(sort_direction(getattr(Conversation, sort_field))).limit(limit)
  72. conversations = session.scalars(query_stmt).all()
  73. has_more = False
  74. if len(conversations) == limit:
  75. current_page_last_conversation = conversations[-1]
  76. rest_filter_condition = cls._build_filter_condition(
  77. sort_field=sort_field,
  78. sort_direction=sort_direction,
  79. reference_conversation=current_page_last_conversation,
  80. )
  81. count_stmt = select(func.count()).select_from(stmt.where(rest_filter_condition).subquery())
  82. rest_count = session.scalar(count_stmt) or 0
  83. if rest_count > 0:
  84. has_more = True
  85. return InfiniteScrollPagination(data=conversations, limit=limit, has_more=has_more)
  86. @classmethod
  87. def _get_sort_params(cls, sort_by: str):
  88. if sort_by.startswith("-"):
  89. return sort_by[1:], desc
  90. return sort_by, asc
  91. @classmethod
  92. def _build_filter_condition(cls, sort_field: str, sort_direction: Callable, reference_conversation: Conversation):
  93. field_value = getattr(reference_conversation, sort_field)
  94. if sort_direction == desc:
  95. return getattr(Conversation, sort_field) < field_value
  96. else:
  97. return getattr(Conversation, sort_field) > field_value
  98. @classmethod
  99. def rename(
  100. cls,
  101. app_model: App,
  102. conversation_id: str,
  103. user: Optional[Union[Account, EndUser]],
  104. name: str,
  105. auto_generate: bool,
  106. ):
  107. conversation = cls.get_conversation(app_model, conversation_id, user)
  108. if auto_generate:
  109. return cls.auto_generate_name(app_model, conversation)
  110. else:
  111. conversation.name = name
  112. conversation.updated_at = naive_utc_now()
  113. db.session.commit()
  114. return conversation
  115. @classmethod
  116. def auto_generate_name(cls, app_model: App, conversation: Conversation):
  117. # get conversation first message
  118. message = (
  119. db.session.query(Message)
  120. .where(Message.app_id == app_model.id, Message.conversation_id == conversation.id)
  121. .order_by(Message.created_at.asc())
  122. .first()
  123. )
  124. if not message:
  125. raise MessageNotExistsError()
  126. # generate conversation name
  127. try:
  128. name = LLMGenerator.generate_conversation_name(
  129. app_model.tenant_id, message.query, conversation.id, app_model.id
  130. )
  131. conversation.name = name
  132. except:
  133. pass
  134. db.session.commit()
  135. return conversation
  136. @classmethod
  137. def get_conversation(cls, app_model: App, conversation_id: str, user: Optional[Union[Account, EndUser]]):
  138. conversation = (
  139. db.session.query(Conversation)
  140. .where(
  141. Conversation.id == conversation_id,
  142. Conversation.app_id == app_model.id,
  143. Conversation.from_source == ("api" if isinstance(user, EndUser) else "console"),
  144. Conversation.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
  145. Conversation.from_account_id == (user.id if isinstance(user, Account) else None),
  146. Conversation.is_deleted == False,
  147. )
  148. .first()
  149. )
  150. if not conversation:
  151. raise ConversationNotExistsError()
  152. return conversation
  153. @classmethod
  154. def delete(cls, app_model: App, conversation_id: str, user: Optional[Union[Account, EndUser]]):
  155. conversation = cls.get_conversation(app_model, conversation_id, user)
  156. conversation.is_deleted = True
  157. conversation.updated_at = naive_utc_now()
  158. db.session.commit()
  159. @classmethod
  160. def get_conversational_variable(
  161. cls,
  162. app_model: App,
  163. conversation_id: str,
  164. user: Optional[Union[Account, EndUser]],
  165. limit: int,
  166. last_id: Optional[str],
  167. ) -> InfiniteScrollPagination:
  168. conversation = cls.get_conversation(app_model, conversation_id, user)
  169. stmt = (
  170. select(ConversationVariable)
  171. .where(ConversationVariable.app_id == app_model.id)
  172. .where(ConversationVariable.conversation_id == conversation.id)
  173. .order_by(ConversationVariable.created_at)
  174. )
  175. with Session(db.engine) as session:
  176. if last_id:
  177. last_variable = session.scalar(stmt.where(ConversationVariable.id == last_id))
  178. if not last_variable:
  179. raise ConversationVariableNotExistsError()
  180. # Filter for variables created after the last_id
  181. stmt = stmt.where(ConversationVariable.created_at > last_variable.created_at)
  182. # Apply limit to query
  183. query_stmt = stmt.limit(limit) # Get one extra to check if there are more
  184. rows = session.scalars(query_stmt).all()
  185. has_more = False
  186. if len(rows) > limit:
  187. has_more = True
  188. rows = rows[:limit] # Remove the extra item
  189. variables = [
  190. {
  191. "created_at": row.created_at,
  192. "updated_at": row.updated_at,
  193. **row.to_variable().model_dump(),
  194. }
  195. for row in rows
  196. ]
  197. return InfiniteScrollPagination(variables, limit, has_more)
  198. @classmethod
  199. def update_conversation_variable(
  200. cls,
  201. app_model: App,
  202. conversation_id: str,
  203. variable_id: str,
  204. user: Optional[Union[Account, EndUser]],
  205. new_value: Any,
  206. ) -> dict:
  207. """
  208. Update a conversation variable's value.
  209. Args:
  210. app_model: The app model
  211. conversation_id: The conversation ID
  212. variable_id: The variable ID to update
  213. user: The user (Account or EndUser)
  214. new_value: The new value for the variable
  215. Returns:
  216. Dictionary containing the updated variable information
  217. Raises:
  218. ConversationNotExistsError: If the conversation doesn't exist
  219. ConversationVariableNotExistsError: If the variable doesn't exist
  220. ConversationVariableTypeMismatchError: If the new value type doesn't match the variable's expected type
  221. """
  222. # Verify conversation exists and user has access
  223. conversation = cls.get_conversation(app_model, conversation_id, user)
  224. # Get the existing conversation variable
  225. stmt = (
  226. select(ConversationVariable)
  227. .where(ConversationVariable.app_id == app_model.id)
  228. .where(ConversationVariable.conversation_id == conversation.id)
  229. .where(ConversationVariable.id == variable_id)
  230. )
  231. with Session(db.engine) as session:
  232. existing_variable = session.scalar(stmt)
  233. if not existing_variable:
  234. raise ConversationVariableNotExistsError()
  235. # Convert existing variable to Variable object
  236. current_variable = existing_variable.to_variable()
  237. # Validate that the new value type matches the expected variable type
  238. expected_type = SegmentType(current_variable.value_type)
  239. if not expected_type.is_valid(new_value):
  240. inferred_type = SegmentType.infer_segment_type(new_value)
  241. raise ConversationVariableTypeMismatchError(
  242. f"Type mismatch: variable '{current_variable.name}' expects {expected_type.value}, "
  243. f"but got {inferred_type.value if inferred_type else 'unknown'} type"
  244. )
  245. # Create updated variable with new value only, preserving everything else
  246. updated_variable_dict = {
  247. "id": current_variable.id,
  248. "name": current_variable.name,
  249. "description": current_variable.description,
  250. "value_type": current_variable.value_type,
  251. "value": new_value,
  252. "selector": current_variable.selector,
  253. }
  254. updated_variable = variable_factory.build_conversation_variable_from_mapping(updated_variable_dict)
  255. # Use the conversation variable updater to persist the changes
  256. updater = conversation_variable_updater_factory()
  257. updater.update(conversation_id, updated_variable)
  258. updater.flush()
  259. # Return the updated variable data
  260. return {
  261. "created_at": existing_variable.created_at,
  262. "updated_at": naive_utc_now(), # Update timestamp
  263. **updated_variable.model_dump(),
  264. }