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

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