message.py 13 KB

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