message.py 13 KB

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