Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

conversation_service.py 12KB

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