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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. import logging
  2. from flask_restx import Resource, fields, marshal_with, reqparse
  3. from flask_restx.inputs import int_range
  4. from sqlalchemy import exists, select
  5. from werkzeug.exceptions import Forbidden, InternalServerError, NotFound
  6. from controllers.console import api
  7. from controllers.console.app.error import (
  8. CompletionRequestError,
  9. ProviderModelCurrentlyNotSupportError,
  10. ProviderNotInitializeError,
  11. ProviderQuotaExceededError,
  12. )
  13. from controllers.console.app.wraps import get_app_model
  14. from controllers.console.explore.error import AppSuggestedQuestionsAfterAnswerDisabledError
  15. from controllers.console.wraps import (
  16. account_initialization_required,
  17. cloud_edition_billing_resource_check,
  18. setup_required,
  19. )
  20. from core.app.entities.app_invoke_entities import InvokeFrom
  21. from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError
  22. from core.model_runtime.errors.invoke import InvokeError
  23. from extensions.ext_database import db
  24. from fields.conversation_fields import annotation_fields, message_detail_fields
  25. from libs.helper import uuid_value
  26. from libs.infinite_scroll_pagination import InfiniteScrollPagination
  27. from libs.login import current_user, login_required
  28. from models.account import Account
  29. from models.model import AppMode, Conversation, Message, MessageAnnotation, MessageFeedback
  30. from services.annotation_service import AppAnnotationService
  31. from services.errors.conversation import ConversationNotExistsError
  32. from services.errors.message import MessageNotExistsError, SuggestedQuestionsAfterAnswerDisabledError
  33. from services.message_service import MessageService
  34. logger = logging.getLogger(__name__)
  35. class ChatMessageListApi(Resource):
  36. message_infinite_scroll_pagination_fields = {
  37. "limit": fields.Integer,
  38. "has_more": fields.Boolean,
  39. "data": fields.List(fields.Nested(message_detail_fields)),
  40. }
  41. @setup_required
  42. @login_required
  43. @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT])
  44. @account_initialization_required
  45. @marshal_with(message_infinite_scroll_pagination_fields)
  46. def get(self, app_model):
  47. parser = reqparse.RequestParser()
  48. parser.add_argument("conversation_id", required=True, type=uuid_value, location="args")
  49. parser.add_argument("first_id", type=uuid_value, location="args")
  50. parser.add_argument("limit", type=int_range(1, 100), required=False, default=20, location="args")
  51. args = parser.parse_args()
  52. conversation = (
  53. db.session.query(Conversation)
  54. .where(Conversation.id == args["conversation_id"], Conversation.app_id == app_model.id)
  55. .first()
  56. )
  57. if not conversation:
  58. raise NotFound("Conversation Not Exists.")
  59. if args["first_id"]:
  60. first_message = (
  61. db.session.query(Message)
  62. .where(Message.conversation_id == conversation.id, Message.id == args["first_id"])
  63. .first()
  64. )
  65. if not first_message:
  66. raise NotFound("First message not found")
  67. history_messages = (
  68. db.session.query(Message)
  69. .where(
  70. Message.conversation_id == conversation.id,
  71. Message.created_at < first_message.created_at,
  72. Message.id != first_message.id,
  73. )
  74. .order_by(Message.created_at.desc())
  75. .limit(args["limit"])
  76. .all()
  77. )
  78. else:
  79. history_messages = (
  80. db.session.query(Message)
  81. .where(Message.conversation_id == conversation.id)
  82. .order_by(Message.created_at.desc())
  83. .limit(args["limit"])
  84. .all()
  85. )
  86. # Initialize has_more based on whether we have a full page
  87. if len(history_messages) == args["limit"]:
  88. current_page_first_message = history_messages[-1]
  89. # Check if there are more messages before the current page
  90. has_more = db.session.scalar(
  91. select(
  92. exists().where(
  93. Message.conversation_id == conversation.id,
  94. Message.created_at < current_page_first_message.created_at,
  95. Message.id != current_page_first_message.id,
  96. )
  97. )
  98. )
  99. else:
  100. # If we don't have a full page, there are no more messages
  101. has_more = False
  102. history_messages = list(reversed(history_messages))
  103. return InfiniteScrollPagination(data=history_messages, limit=args["limit"], has_more=has_more)
  104. class MessageFeedbackApi(Resource):
  105. @get_app_model
  106. @setup_required
  107. @login_required
  108. @account_initialization_required
  109. def post(self, app_model):
  110. if current_user is None:
  111. raise Forbidden()
  112. parser = reqparse.RequestParser()
  113. parser.add_argument("message_id", required=True, type=uuid_value, location="json")
  114. parser.add_argument("rating", type=str, choices=["like", "dislike", None], location="json")
  115. args = parser.parse_args()
  116. message_id = str(args["message_id"])
  117. message = db.session.query(Message).where(Message.id == message_id, Message.app_id == app_model.id).first()
  118. if not message:
  119. raise NotFound("Message Not Exists.")
  120. feedback = message.admin_feedback
  121. if not args["rating"] and feedback:
  122. db.session.delete(feedback)
  123. elif args["rating"] and feedback:
  124. feedback.rating = args["rating"]
  125. elif not args["rating"] and not feedback:
  126. raise ValueError("rating cannot be None when feedback not exists")
  127. else:
  128. feedback = MessageFeedback(
  129. app_id=app_model.id,
  130. conversation_id=message.conversation_id,
  131. message_id=message.id,
  132. rating=args["rating"],
  133. from_source="admin",
  134. from_account_id=current_user.id,
  135. )
  136. db.session.add(feedback)
  137. db.session.commit()
  138. return {"result": "success"}
  139. class MessageAnnotationApi(Resource):
  140. @setup_required
  141. @login_required
  142. @account_initialization_required
  143. @cloud_edition_billing_resource_check("annotation")
  144. @get_app_model
  145. @marshal_with(annotation_fields)
  146. def post(self, app_model):
  147. if not isinstance(current_user, Account):
  148. raise Forbidden()
  149. if not current_user.has_edit_permission:
  150. raise Forbidden()
  151. parser = reqparse.RequestParser()
  152. parser.add_argument("message_id", required=False, type=uuid_value, location="json")
  153. parser.add_argument("question", required=True, type=str, location="json")
  154. parser.add_argument("answer", required=True, type=str, location="json")
  155. parser.add_argument("annotation_reply", required=False, type=dict, location="json")
  156. args = parser.parse_args()
  157. annotation = AppAnnotationService.up_insert_app_annotation_from_message(args, app_model.id)
  158. return annotation
  159. class MessageAnnotationCountApi(Resource):
  160. @get_app_model
  161. @setup_required
  162. @login_required
  163. @account_initialization_required
  164. def get(self, app_model):
  165. count = db.session.query(MessageAnnotation).where(MessageAnnotation.app_id == app_model.id).count()
  166. return {"count": count}
  167. class MessageSuggestedQuestionApi(Resource):
  168. @setup_required
  169. @login_required
  170. @account_initialization_required
  171. @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT])
  172. def get(self, app_model, message_id):
  173. message_id = str(message_id)
  174. try:
  175. questions = MessageService.get_suggested_questions_after_answer(
  176. app_model=app_model, message_id=message_id, user=current_user, invoke_from=InvokeFrom.DEBUGGER
  177. )
  178. except MessageNotExistsError:
  179. raise NotFound("Message not found")
  180. except ConversationNotExistsError:
  181. raise NotFound("Conversation not found")
  182. except ProviderTokenNotInitError as ex:
  183. raise ProviderNotInitializeError(ex.description)
  184. except QuotaExceededError:
  185. raise ProviderQuotaExceededError()
  186. except ModelCurrentlyNotSupportError:
  187. raise ProviderModelCurrentlyNotSupportError()
  188. except InvokeError as e:
  189. raise CompletionRequestError(e.description)
  190. except SuggestedQuestionsAfterAnswerDisabledError:
  191. raise AppSuggestedQuestionsAfterAnswerDisabledError()
  192. except Exception:
  193. logger.exception("internal server error.")
  194. raise InternalServerError()
  195. return {"data": questions}
  196. class MessageApi(Resource):
  197. @setup_required
  198. @login_required
  199. @account_initialization_required
  200. @get_app_model
  201. @marshal_with(message_detail_fields)
  202. def get(self, app_model, message_id):
  203. message_id = str(message_id)
  204. message = db.session.query(Message).where(Message.id == message_id, Message.app_id == app_model.id).first()
  205. if not message:
  206. raise NotFound("Message Not Exists.")
  207. return message
  208. api.add_resource(MessageSuggestedQuestionApi, "/apps/<uuid:app_id>/chat-messages/<uuid:message_id>/suggested-questions")
  209. api.add_resource(ChatMessageListApi, "/apps/<uuid:app_id>/chat-messages", endpoint="console_chat_messages")
  210. api.add_resource(MessageFeedbackApi, "/apps/<uuid:app_id>/feedbacks")
  211. api.add_resource(MessageAnnotationApi, "/apps/<uuid:app_id>/annotations")
  212. api.add_resource(MessageAnnotationCountApi, "/apps/<uuid:app_id>/annotations/count")
  213. api.add_resource(MessageApi, "/apps/<uuid:app_id>/messages/<uuid:message_id>", endpoint="console_message")