Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

conversation_service.py 12KB

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