message.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import json
  2. import logging
  3. from typing import Generator, Union
  4. from flask import Response, stream_with_context
  5. from flask_login import current_user
  6. from flask_restful import Resource, fields, marshal_with, reqparse
  7. from flask_restful.inputs import int_range
  8. from werkzeug.exceptions import Forbidden, InternalServerError, NotFound
  9. from controllers.console import api
  10. from controllers.console.app import _get_app
  11. from controllers.console.app.error import (
  12. AppMoreLikeThisDisabledError,
  13. CompletionRequestError,
  14. ProviderModelCurrentlyNotSupportError,
  15. ProviderNotInitializeError,
  16. ProviderQuotaExceededError,
  17. )
  18. from controllers.console.setup import setup_required
  19. from controllers.console.wraps import account_initialization_required, cloud_edition_billing_resource_check
  20. from core.entities.application_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 login_required
  28. from models.model import Conversation, Message, MessageAnnotation, MessageFeedback
  29. from services.annotation_service import AppAnnotationService
  30. from services.completion_service import CompletionService
  31. from services.errors.app import MoreLikeThisDisabledError
  32. from services.errors.conversation import ConversationNotExistsError
  33. from services.errors.message import MessageNotExistsError
  34. from services.message_service import MessageService
  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. @account_initialization_required
  44. @marshal_with(message_infinite_scroll_pagination_fields)
  45. def get(self, app_id):
  46. app_id = str(app_id)
  47. # get app info
  48. app = _get_app(app_id, 'chat')
  49. parser = reqparse.RequestParser()
  50. parser.add_argument('conversation_id', required=True, type=uuid_value, location='args')
  51. parser.add_argument('first_id', type=uuid_value, location='args')
  52. parser.add_argument('limit', type=int_range(1, 100), required=False, default=20, location='args')
  53. args = parser.parse_args()
  54. conversation = db.session.query(Conversation).filter(
  55. Conversation.id == args['conversation_id'],
  56. Conversation.app_id == app.id
  57. ).first()
  58. if not conversation:
  59. raise NotFound("Conversation Not Exists.")
  60. if args['first_id']:
  61. first_message = db.session.query(Message) \
  62. .filter(Message.conversation_id == conversation.id, Message.id == args['first_id']).first()
  63. if not first_message:
  64. raise NotFound("First message not found")
  65. history_messages = db.session.query(Message).filter(
  66. Message.conversation_id == conversation.id,
  67. Message.created_at < first_message.created_at,
  68. Message.id != first_message.id
  69. ) \
  70. .order_by(Message.created_at.desc()).limit(args['limit']).all()
  71. else:
  72. history_messages = db.session.query(Message).filter(Message.conversation_id == conversation.id) \
  73. .order_by(Message.created_at.desc()).limit(args['limit']).all()
  74. has_more = False
  75. if len(history_messages) == args['limit']:
  76. current_page_first_message = history_messages[-1]
  77. rest_count = db.session.query(Message).filter(
  78. Message.conversation_id == conversation.id,
  79. Message.created_at < current_page_first_message.created_at,
  80. Message.id != current_page_first_message.id
  81. ).count()
  82. if rest_count > 0:
  83. has_more = True
  84. history_messages = list(reversed(history_messages))
  85. return InfiniteScrollPagination(
  86. data=history_messages,
  87. limit=args['limit'],
  88. has_more=has_more
  89. )
  90. class MessageFeedbackApi(Resource):
  91. @setup_required
  92. @login_required
  93. @account_initialization_required
  94. def post(self, app_id):
  95. app_id = str(app_id)
  96. # get app info
  97. app = _get_app(app_id)
  98. parser = reqparse.RequestParser()
  99. parser.add_argument('message_id', required=True, type=uuid_value, location='json')
  100. parser.add_argument('rating', type=str, choices=['like', 'dislike', None], location='json')
  101. args = parser.parse_args()
  102. message_id = str(args['message_id'])
  103. message = db.session.query(Message).filter(
  104. Message.id == message_id,
  105. Message.app_id == app.id
  106. ).first()
  107. if not message:
  108. raise NotFound("Message Not Exists.")
  109. feedback = message.admin_feedback
  110. if not args['rating'] and feedback:
  111. db.session.delete(feedback)
  112. elif args['rating'] and feedback:
  113. feedback.rating = args['rating']
  114. elif not args['rating'] and not feedback:
  115. raise ValueError('rating cannot be None when feedback not exists')
  116. else:
  117. feedback = MessageFeedback(
  118. app_id=app.id,
  119. conversation_id=message.conversation_id,
  120. message_id=message.id,
  121. rating=args['rating'],
  122. from_source='admin',
  123. from_account_id=current_user.id
  124. )
  125. db.session.add(feedback)
  126. db.session.commit()
  127. return {'result': 'success'}
  128. class MessageAnnotationApi(Resource):
  129. @setup_required
  130. @login_required
  131. @account_initialization_required
  132. @cloud_edition_billing_resource_check('annotation')
  133. @marshal_with(annotation_fields)
  134. def post(self, app_id):
  135. # The role of the current user in the ta table must be admin or owner
  136. if not current_user.is_admin_or_owner:
  137. raise Forbidden()
  138. app_id = str(app_id)
  139. parser = reqparse.RequestParser()
  140. parser.add_argument('message_id', required=False, type=uuid_value, location='json')
  141. parser.add_argument('question', required=True, type=str, location='json')
  142. parser.add_argument('answer', required=True, type=str, location='json')
  143. parser.add_argument('annotation_reply', required=False, type=dict, location='json')
  144. args = parser.parse_args()
  145. annotation = AppAnnotationService.up_insert_app_annotation_from_message(args, app_id)
  146. return annotation
  147. class MessageAnnotationCountApi(Resource):
  148. @setup_required
  149. @login_required
  150. @account_initialization_required
  151. def get(self, app_id):
  152. app_id = str(app_id)
  153. # get app info
  154. app = _get_app(app_id)
  155. count = db.session.query(MessageAnnotation).filter(
  156. MessageAnnotation.app_id == app.id
  157. ).count()
  158. return {'count': count}
  159. class MessageMoreLikeThisApi(Resource):
  160. @setup_required
  161. @login_required
  162. @account_initialization_required
  163. def get(self, app_id, message_id):
  164. app_id = str(app_id)
  165. message_id = str(message_id)
  166. parser = reqparse.RequestParser()
  167. parser.add_argument('response_mode', type=str, required=True, choices=['blocking', 'streaming'],
  168. location='args')
  169. args = parser.parse_args()
  170. streaming = args['response_mode'] == 'streaming'
  171. # get app info
  172. app_model = _get_app(app_id, 'completion')
  173. try:
  174. response = CompletionService.generate_more_like_this(
  175. app_model=app_model,
  176. user=current_user,
  177. message_id=message_id,
  178. invoke_from=InvokeFrom.DEBUGGER,
  179. streaming=streaming
  180. )
  181. return compact_response(response)
  182. except MessageNotExistsError:
  183. raise NotFound("Message Not Exists.")
  184. except MoreLikeThisDisabledError:
  185. raise AppMoreLikeThisDisabledError()
  186. except ProviderTokenNotInitError as ex:
  187. raise ProviderNotInitializeError(ex.description)
  188. except QuotaExceededError:
  189. raise ProviderQuotaExceededError()
  190. except ModelCurrentlyNotSupportError:
  191. raise ProviderModelCurrentlyNotSupportError()
  192. except InvokeError as e:
  193. raise CompletionRequestError(e.description)
  194. except ValueError as e:
  195. raise e
  196. except Exception as e:
  197. logging.exception("internal server error.")
  198. raise InternalServerError()
  199. def compact_response(response: Union[dict, Generator]) -> Response:
  200. if isinstance(response, dict):
  201. return Response(response=json.dumps(response), status=200, mimetype='application/json')
  202. else:
  203. def generate() -> Generator:
  204. for chunk in response:
  205. yield chunk
  206. return Response(stream_with_context(generate()), status=200,
  207. mimetype='text/event-stream')
  208. class MessageSuggestedQuestionApi(Resource):
  209. @setup_required
  210. @login_required
  211. @account_initialization_required
  212. def get(self, app_id, message_id):
  213. app_id = str(app_id)
  214. message_id = str(message_id)
  215. # get app info
  216. app_model = _get_app(app_id, 'chat')
  217. try:
  218. questions = MessageService.get_suggested_questions_after_answer(
  219. app_model=app_model,
  220. message_id=message_id,
  221. user=current_user,
  222. check_enabled=False
  223. )
  224. except MessageNotExistsError:
  225. raise NotFound("Message not found")
  226. except ConversationNotExistsError:
  227. raise NotFound("Conversation not found")
  228. except ProviderTokenNotInitError as ex:
  229. raise ProviderNotInitializeError(ex.description)
  230. except QuotaExceededError:
  231. raise ProviderQuotaExceededError()
  232. except ModelCurrentlyNotSupportError:
  233. raise ProviderModelCurrentlyNotSupportError()
  234. except InvokeError as e:
  235. raise CompletionRequestError(e.description)
  236. except Exception:
  237. logging.exception("internal server error.")
  238. raise InternalServerError()
  239. return {'data': questions}
  240. class MessageApi(Resource):
  241. @setup_required
  242. @login_required
  243. @account_initialization_required
  244. @marshal_with(message_detail_fields)
  245. def get(self, app_id, message_id):
  246. app_id = str(app_id)
  247. message_id = str(message_id)
  248. # get app info
  249. app_model = _get_app(app_id)
  250. message = db.session.query(Message).filter(
  251. Message.id == message_id,
  252. Message.app_id == app_model.id
  253. ).first()
  254. if not message:
  255. raise NotFound("Message Not Exists.")
  256. return message
  257. api.add_resource(MessageMoreLikeThisApi, '/apps/<uuid:app_id>/completion-messages/<uuid:message_id>/more-like-this')
  258. api.add_resource(MessageSuggestedQuestionApi, '/apps/<uuid:app_id>/chat-messages/<uuid:message_id>/suggested-questions')
  259. api.add_resource(ChatMessageListApi, '/apps/<uuid:app_id>/chat-messages', endpoint='console_chat_messages')
  260. api.add_resource(MessageFeedbackApi, '/apps/<uuid:app_id>/feedbacks')
  261. api.add_resource(MessageAnnotationApi, '/apps/<uuid:app_id>/annotations')
  262. api.add_resource(MessageAnnotationCountApi, '/apps/<uuid:app_id>/annotations/count')
  263. api.add_resource(MessageApi, '/apps/<uuid:app_id>/messages/<uuid:message_id>', endpoint='console_message')