message.py 9.3 KB

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