您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

conversation_service.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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 is desc:
  95. return getattr(Conversation, sort_field) < field_value
  96. return getattr(Conversation, sort_field) > field_value
  97. @classmethod
  98. def rename(
  99. cls,
  100. app_model: App,
  101. conversation_id: str,
  102. user: Optional[Union[Account, EndUser]],
  103. name: str,
  104. auto_generate: bool,
  105. ):
  106. conversation = cls.get_conversation(app_model, conversation_id, user)
  107. if auto_generate:
  108. return cls.auto_generate_name(app_model, conversation)
  109. else:
  110. conversation.name = name
  111. conversation.updated_at = naive_utc_now()
  112. db.session.commit()
  113. return conversation
  114. @classmethod
  115. def auto_generate_name(cls, app_model: App, conversation: Conversation):
  116. # get conversation first message
  117. message = (
  118. db.session.query(Message)
  119. .where(Message.app_id == app_model.id, Message.conversation_id == conversation.id)
  120. .order_by(Message.created_at.asc())
  121. .first()
  122. )
  123. if not message:
  124. raise MessageNotExistsError()
  125. # generate conversation name
  126. try:
  127. name = LLMGenerator.generate_conversation_name(
  128. app_model.tenant_id, message.query, conversation.id, app_model.id
  129. )
  130. conversation.name = name
  131. except Exception:
  132. pass
  133. db.session.commit()
  134. return conversation
  135. @classmethod
  136. def get_conversation(cls, app_model: App, conversation_id: str, user: Optional[Union[Account, EndUser]]):
  137. conversation = (
  138. db.session.query(Conversation)
  139. .where(
  140. Conversation.id == conversation_id,
  141. Conversation.app_id == app_model.id,
  142. Conversation.from_source == ("api" if isinstance(user, EndUser) else "console"),
  143. Conversation.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
  144. Conversation.from_account_id == (user.id if isinstance(user, Account) else None),
  145. Conversation.is_deleted == False,
  146. )
  147. .first()
  148. )
  149. if not conversation:
  150. raise ConversationNotExistsError()
  151. return conversation
  152. @classmethod
  153. def delete(cls, app_model: App, conversation_id: str, user: Optional[Union[Account, EndUser]]):
  154. conversation = cls.get_conversation(app_model, conversation_id, user)
  155. conversation.is_deleted = True
  156. conversation.updated_at = naive_utc_now()
  157. db.session.commit()
  158. @classmethod
  159. def get_conversational_variable(
  160. cls,
  161. app_model: App,
  162. conversation_id: str,
  163. user: Optional[Union[Account, EndUser]],
  164. limit: int,
  165. last_id: Optional[str],
  166. ) -> InfiniteScrollPagination:
  167. conversation = cls.get_conversation(app_model, conversation_id, user)
  168. stmt = (
  169. select(ConversationVariable)
  170. .where(ConversationVariable.app_id == app_model.id)
  171. .where(ConversationVariable.conversation_id == conversation.id)
  172. .order_by(ConversationVariable.created_at)
  173. )
  174. with Session(db.engine) as session:
  175. if last_id:
  176. last_variable = session.scalar(stmt.where(ConversationVariable.id == last_id))
  177. if not last_variable:
  178. raise ConversationVariableNotExistsError()
  179. # Filter for variables created after the last_id
  180. stmt = stmt.where(ConversationVariable.created_at > last_variable.created_at)
  181. # Apply limit to query
  182. query_stmt = stmt.limit(limit) # Get one extra to check if there are more
  183. rows = session.scalars(query_stmt).all()
  184. has_more = False
  185. if len(rows) > limit:
  186. has_more = True
  187. rows = rows[:limit] # Remove the extra item
  188. variables = [
  189. {
  190. "created_at": row.created_at,
  191. "updated_at": row.updated_at,
  192. **row.to_variable().model_dump(),
  193. }
  194. for row in rows
  195. ]
  196. return InfiniteScrollPagination(variables, limit, has_more)
  197. @classmethod
  198. def update_conversation_variable(
  199. cls,
  200. app_model: App,
  201. conversation_id: str,
  202. variable_id: str,
  203. user: Optional[Union[Account, EndUser]],
  204. new_value: Any,
  205. ) -> dict:
  206. """
  207. Update a conversation variable's value.
  208. Args:
  209. app_model: The app model
  210. conversation_id: The conversation ID
  211. variable_id: The variable ID to update
  212. user: The user (Account or EndUser)
  213. new_value: The new value for the variable
  214. Returns:
  215. Dictionary containing the updated variable information
  216. Raises:
  217. ConversationNotExistsError: If the conversation doesn't exist
  218. ConversationVariableNotExistsError: If the variable doesn't exist
  219. ConversationVariableTypeMismatchError: If the new value type doesn't match the variable's expected type
  220. """
  221. # Verify conversation exists and user has access
  222. conversation = cls.get_conversation(app_model, conversation_id, user)
  223. # Get the existing conversation variable
  224. stmt = (
  225. select(ConversationVariable)
  226. .where(ConversationVariable.app_id == app_model.id)
  227. .where(ConversationVariable.conversation_id == conversation.id)
  228. .where(ConversationVariable.id == variable_id)
  229. )
  230. with Session(db.engine) as session:
  231. existing_variable = session.scalar(stmt)
  232. if not existing_variable:
  233. raise ConversationVariableNotExistsError()
  234. # Convert existing variable to Variable object
  235. current_variable = existing_variable.to_variable()
  236. # Validate that the new value type matches the expected variable type
  237. expected_type = SegmentType(current_variable.value_type)
  238. # There is showing number in web ui but int in db
  239. if expected_type == SegmentType.INTEGER:
  240. expected_type = SegmentType.NUMBER
  241. if not expected_type.is_valid(new_value):
  242. inferred_type = SegmentType.infer_segment_type(new_value)
  243. raise ConversationVariableTypeMismatchError(
  244. f"Type mismatch: variable '{current_variable.name}' expects {expected_type.value}, "
  245. f"but got {inferred_type.value if inferred_type else 'unknown'} type"
  246. )
  247. # Create updated variable with new value only, preserving everything else
  248. updated_variable_dict = {
  249. "id": current_variable.id,
  250. "name": current_variable.name,
  251. "description": current_variable.description,
  252. "value_type": current_variable.value_type,
  253. "value": new_value,
  254. "selector": current_variable.selector,
  255. }
  256. updated_variable = variable_factory.build_conversation_variable_from_mapping(updated_variable_dict)
  257. # Use the conversation variable updater to persist the changes
  258. updater = conversation_variable_updater_factory()
  259. updater.update(conversation_id, updated_variable)
  260. updater.flush()
  261. # Return the updated variable data
  262. return {
  263. "created_at": existing_variable.created_at,
  264. "updated_at": naive_utc_now(), # Update timestamp
  265. **updated_variable.model_dump(),
  266. }