Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. import json
  2. from flask_restful import Resource, marshal_with, reqparse
  3. from flask_restful.inputs import int_range
  4. from sqlalchemy.orm import Session
  5. from werkzeug.exceptions import BadRequest, NotFound
  6. import services
  7. from controllers.service_api import api
  8. from controllers.service_api.app.error import NotChatAppError
  9. from controllers.service_api.wraps import FetchUserArg, WhereisUserArg, validate_app_token
  10. from core.app.entities.app_invoke_entities import InvokeFrom
  11. from extensions.ext_database import db
  12. from fields.conversation_fields import (
  13. conversation_delete_fields,
  14. conversation_infinite_scroll_pagination_fields,
  15. simple_conversation_fields,
  16. )
  17. from fields.conversation_variable_fields import (
  18. conversation_variable_fields,
  19. conversation_variable_infinite_scroll_pagination_fields,
  20. )
  21. from libs.helper import uuid_value
  22. from models.model import App, AppMode, EndUser
  23. from services.conversation_service import ConversationService
  24. class ConversationApi(Resource):
  25. @validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY))
  26. @marshal_with(conversation_infinite_scroll_pagination_fields)
  27. def get(self, app_model: App, end_user: EndUser):
  28. app_mode = AppMode.value_of(app_model.mode)
  29. if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:
  30. raise NotChatAppError()
  31. parser = reqparse.RequestParser()
  32. parser.add_argument("last_id", type=uuid_value, location="args")
  33. parser.add_argument("limit", type=int_range(1, 100), required=False, default=20, location="args")
  34. parser.add_argument(
  35. "sort_by",
  36. type=str,
  37. choices=["created_at", "-created_at", "updated_at", "-updated_at"],
  38. required=False,
  39. default="-updated_at",
  40. location="args",
  41. )
  42. args = parser.parse_args()
  43. try:
  44. with Session(db.engine) as session:
  45. return ConversationService.pagination_by_last_id(
  46. session=session,
  47. app_model=app_model,
  48. user=end_user,
  49. last_id=args["last_id"],
  50. limit=args["limit"],
  51. invoke_from=InvokeFrom.SERVICE_API,
  52. sort_by=args["sort_by"],
  53. )
  54. except services.errors.conversation.LastConversationNotExistsError:
  55. raise NotFound("Last Conversation Not Exists.")
  56. class ConversationDetailApi(Resource):
  57. @validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON))
  58. @marshal_with(conversation_delete_fields)
  59. def delete(self, app_model: App, end_user: EndUser, c_id):
  60. app_mode = AppMode.value_of(app_model.mode)
  61. if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:
  62. raise NotChatAppError()
  63. conversation_id = str(c_id)
  64. try:
  65. ConversationService.delete(app_model, conversation_id, end_user)
  66. except services.errors.conversation.ConversationNotExistsError:
  67. raise NotFound("Conversation Not Exists.")
  68. return {"result": "success"}, 204
  69. class ConversationRenameApi(Resource):
  70. @validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON))
  71. @marshal_with(simple_conversation_fields)
  72. def post(self, app_model: App, end_user: EndUser, c_id):
  73. app_mode = AppMode.value_of(app_model.mode)
  74. if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:
  75. raise NotChatAppError()
  76. conversation_id = str(c_id)
  77. parser = reqparse.RequestParser()
  78. parser.add_argument("name", type=str, required=False, location="json")
  79. parser.add_argument("auto_generate", type=bool, required=False, default=False, location="json")
  80. args = parser.parse_args()
  81. try:
  82. return ConversationService.rename(app_model, conversation_id, end_user, args["name"], args["auto_generate"])
  83. except services.errors.conversation.ConversationNotExistsError:
  84. raise NotFound("Conversation Not Exists.")
  85. class ConversationVariablesApi(Resource):
  86. @validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY))
  87. @marshal_with(conversation_variable_infinite_scroll_pagination_fields)
  88. def get(self, app_model: App, end_user: EndUser, c_id):
  89. # conversational variable only for chat app
  90. app_mode = AppMode.value_of(app_model.mode)
  91. if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:
  92. raise NotChatAppError()
  93. conversation_id = str(c_id)
  94. parser = reqparse.RequestParser()
  95. parser.add_argument("last_id", type=uuid_value, location="args")
  96. parser.add_argument("limit", type=int_range(1, 100), required=False, default=20, location="args")
  97. args = parser.parse_args()
  98. try:
  99. return ConversationService.get_conversational_variable(
  100. app_model, conversation_id, end_user, args["limit"], args["last_id"]
  101. )
  102. except services.errors.conversation.ConversationNotExistsError:
  103. raise NotFound("Conversation Not Exists.")
  104. class ConversationVariableDetailApi(Resource):
  105. @validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON))
  106. @marshal_with(conversation_variable_fields)
  107. def put(self, app_model: App, end_user: EndUser, c_id, variable_id):
  108. """Update a conversation variable's value"""
  109. app_mode = AppMode.value_of(app_model.mode)
  110. if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:
  111. raise NotChatAppError()
  112. conversation_id = str(c_id)
  113. variable_id = str(variable_id)
  114. parser = reqparse.RequestParser()
  115. parser.add_argument("value", required=True, location="json")
  116. args = parser.parse_args()
  117. try:
  118. return ConversationService.update_conversation_variable(
  119. app_model, conversation_id, variable_id, end_user, json.loads(args["value"])
  120. )
  121. except services.errors.conversation.ConversationNotExistsError:
  122. raise NotFound("Conversation Not Exists.")
  123. except services.errors.conversation.ConversationVariableNotExistsError:
  124. raise NotFound("Conversation Variable Not Exists.")
  125. except services.errors.conversation.ConversationVariableTypeMismatchError as e:
  126. raise BadRequest(str(e))
  127. api.add_resource(ConversationRenameApi, "/conversations/<uuid:c_id>/name", endpoint="conversation_name")
  128. api.add_resource(ConversationApi, "/conversations")
  129. api.add_resource(ConversationDetailApi, "/conversations/<uuid:c_id>", endpoint="conversation_detail")
  130. api.add_resource(ConversationVariablesApi, "/conversations/<uuid:c_id>/variables", endpoint="conversation_variables")
  131. api.add_resource(
  132. ConversationVariableDetailApi,
  133. "/conversations/<uuid:c_id>/variables/<uuid:variable_id>",
  134. endpoint="conversation_variable_detail",
  135. methods=["PUT"],
  136. )