message.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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
  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
  15. from core.model_providers.error import LLMRateLimitError, LLMBadRequestError, LLMAuthorizationError, LLMAPIConnectionError, \
  16. ProviderTokenNotInitError, LLMAPIUnavailableError, QuotaExceededError, ModelCurrentlyNotSupportError
  17. from core.login.login import login_required
  18. from fields.conversation_fields import message_detail_fields
  19. from libs.helper import uuid_value, TimestampField
  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.completion_service import CompletionService
  24. from services.errors.app import MoreLikeThisDisabledError
  25. from services.errors.conversation import ConversationNotExistsError
  26. from services.errors.message import MessageNotExistsError
  27. from services.message_service import MessageService
  28. class ChatMessageListApi(Resource):
  29. message_infinite_scroll_pagination_fields = {
  30. 'limit': fields.Integer,
  31. 'has_more': fields.Boolean,
  32. 'data': fields.List(fields.Nested(message_detail_fields))
  33. }
  34. @setup_required
  35. @login_required
  36. @account_initialization_required
  37. @marshal_with(message_infinite_scroll_pagination_fields)
  38. def get(self, app_id):
  39. app_id = str(app_id)
  40. # get app info
  41. app = _get_app(app_id, 'chat')
  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.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. def post(self, app_id):
  88. app_id = str(app_id)
  89. # get app info
  90. app = _get_app(app_id)
  91. parser = reqparse.RequestParser()
  92. parser.add_argument('message_id', required=True, type=uuid_value, location='json')
  93. parser.add_argument('rating', type=str, choices=['like', 'dislike', None], location='json')
  94. args = parser.parse_args()
  95. message_id = str(args['message_id'])
  96. message = db.session.query(Message).filter(
  97. Message.id == message_id,
  98. Message.app_id == app.id
  99. ).first()
  100. if not message:
  101. raise NotFound("Message Not Exists.")
  102. feedback = message.admin_feedback
  103. if not args['rating'] and feedback:
  104. db.session.delete(feedback)
  105. elif args['rating'] and feedback:
  106. feedback.rating = args['rating']
  107. elif not args['rating'] and not feedback:
  108. raise ValueError('rating cannot be None when feedback not exists')
  109. else:
  110. feedback = MessageFeedback(
  111. app_id=app.id,
  112. conversation_id=message.conversation_id,
  113. message_id=message.id,
  114. rating=args['rating'],
  115. from_source='admin',
  116. from_account_id=current_user.id
  117. )
  118. db.session.add(feedback)
  119. db.session.commit()
  120. return {'result': 'success'}
  121. class MessageAnnotationApi(Resource):
  122. @setup_required
  123. @login_required
  124. @account_initialization_required
  125. def post(self, app_id):
  126. app_id = str(app_id)
  127. # get app info
  128. app = _get_app(app_id)
  129. parser = reqparse.RequestParser()
  130. parser.add_argument('message_id', required=True, type=uuid_value, location='json')
  131. parser.add_argument('content', type=str, location='json')
  132. args = parser.parse_args()
  133. message_id = str(args['message_id'])
  134. message = db.session.query(Message).filter(
  135. Message.id == message_id,
  136. Message.app_id == app.id
  137. ).first()
  138. if not message:
  139. raise NotFound("Message Not Exists.")
  140. annotation = message.annotation
  141. if annotation:
  142. annotation.content = args['content']
  143. else:
  144. annotation = MessageAnnotation(
  145. app_id=app.id,
  146. conversation_id=message.conversation_id,
  147. message_id=message.id,
  148. content=args['content'],
  149. account_id=current_user.id
  150. )
  151. db.session.add(annotation)
  152. db.session.commit()
  153. return {'result': 'success'}
  154. class MessageAnnotationCountApi(Resource):
  155. @setup_required
  156. @login_required
  157. @account_initialization_required
  158. def get(self, app_id):
  159. app_id = str(app_id)
  160. # get app info
  161. app = _get_app(app_id)
  162. count = db.session.query(MessageAnnotation).filter(
  163. MessageAnnotation.app_id == app.id
  164. ).count()
  165. return {'count': count}
  166. class MessageMoreLikeThisApi(Resource):
  167. @setup_required
  168. @login_required
  169. @account_initialization_required
  170. def get(self, app_id, message_id):
  171. app_id = str(app_id)
  172. message_id = str(message_id)
  173. parser = reqparse.RequestParser()
  174. parser.add_argument('response_mode', type=str, required=True, choices=['blocking', 'streaming'],
  175. location='args')
  176. args = parser.parse_args()
  177. streaming = args['response_mode'] == 'streaming'
  178. # get app info
  179. app_model = _get_app(app_id, 'completion')
  180. try:
  181. response = CompletionService.generate_more_like_this(app_model, current_user, message_id, streaming)
  182. return compact_response(response)
  183. except MessageNotExistsError:
  184. raise NotFound("Message Not Exists.")
  185. except MoreLikeThisDisabledError:
  186. raise AppMoreLikeThisDisabledError()
  187. except ProviderTokenNotInitError as ex:
  188. raise ProviderNotInitializeError(ex.description)
  189. except QuotaExceededError:
  190. raise ProviderQuotaExceededError()
  191. except ModelCurrentlyNotSupportError:
  192. raise ProviderModelCurrentlyNotSupportError()
  193. except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
  194. LLMRateLimitError, LLMAuthorizationError) as e:
  195. raise CompletionRequestError(str(e))
  196. except ValueError as e:
  197. raise e
  198. except Exception as e:
  199. logging.exception("internal server error.")
  200. raise InternalServerError()
  201. def compact_response(response: Union[dict | Generator]) -> Response:
  202. if isinstance(response, dict):
  203. return Response(response=json.dumps(response), status=200, mimetype='application/json')
  204. else:
  205. def generate() -> Generator:
  206. try:
  207. for chunk in response:
  208. yield chunk
  209. except MessageNotExistsError:
  210. yield "data: " + json.dumps(api.handle_error(NotFound("Message Not Exists.")).get_json()) + "\n\n"
  211. except MoreLikeThisDisabledError:
  212. yield "data: " + json.dumps(api.handle_error(AppMoreLikeThisDisabledError()).get_json()) + "\n\n"
  213. except ProviderTokenNotInitError as ex:
  214. yield "data: " + json.dumps(api.handle_error(ProviderNotInitializeError(ex.description)).get_json()) + "\n\n"
  215. except QuotaExceededError:
  216. yield "data: " + json.dumps(api.handle_error(ProviderQuotaExceededError()).get_json()) + "\n\n"
  217. except ModelCurrentlyNotSupportError:
  218. yield "data: " + json.dumps(
  219. api.handle_error(ProviderModelCurrentlyNotSupportError()).get_json()) + "\n\n"
  220. except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
  221. LLMRateLimitError, LLMAuthorizationError) as e:
  222. yield "data: " + json.dumps(api.handle_error(CompletionRequestError(str(e))).get_json()) + "\n\n"
  223. except ValueError as e:
  224. yield "data: " + json.dumps(api.handle_error(e).get_json()) + "\n\n"
  225. except Exception:
  226. logging.exception("internal server error.")
  227. yield "data: " + json.dumps(api.handle_error(InternalServerError()).get_json()) + "\n\n"
  228. return Response(stream_with_context(generate()), status=200,
  229. mimetype='text/event-stream')
  230. class MessageSuggestedQuestionApi(Resource):
  231. @setup_required
  232. @login_required
  233. @account_initialization_required
  234. def get(self, app_id, message_id):
  235. app_id = str(app_id)
  236. message_id = str(message_id)
  237. # get app info
  238. app_model = _get_app(app_id, 'chat')
  239. try:
  240. questions = MessageService.get_suggested_questions_after_answer(
  241. app_model=app_model,
  242. user=current_user,
  243. message_id=message_id,
  244. check_enabled=False
  245. )
  246. except MessageNotExistsError:
  247. raise NotFound("Message not found")
  248. except ConversationNotExistsError:
  249. raise NotFound("Conversation not found")
  250. except ProviderTokenNotInitError as ex:
  251. raise ProviderNotInitializeError(ex.description)
  252. except QuotaExceededError:
  253. raise ProviderQuotaExceededError()
  254. except ModelCurrentlyNotSupportError:
  255. raise ProviderModelCurrentlyNotSupportError()
  256. except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
  257. LLMRateLimitError, LLMAuthorizationError) as e:
  258. raise CompletionRequestError(str(e))
  259. except Exception:
  260. logging.exception("internal server error.")
  261. raise InternalServerError()
  262. return {'data': questions}
  263. class MessageApi(Resource):
  264. @setup_required
  265. @login_required
  266. @account_initialization_required
  267. @marshal_with(message_detail_fields)
  268. def get(self, app_id, message_id):
  269. app_id = str(app_id)
  270. message_id = str(message_id)
  271. # get app info
  272. app_model = _get_app(app_id, 'chat')
  273. message = db.session.query(Message).filter(
  274. Message.id == message_id,
  275. Message.app_id == app_model.id
  276. ).first()
  277. if not message:
  278. raise NotFound("Message Not Exists.")
  279. return message
  280. api.add_resource(MessageMoreLikeThisApi, '/apps/<uuid:app_id>/completion-messages/<uuid:message_id>/more-like-this')
  281. api.add_resource(MessageSuggestedQuestionApi, '/apps/<uuid:app_id>/chat-messages/<uuid:message_id>/suggested-questions')
  282. api.add_resource(ChatMessageListApi, '/apps/<uuid:app_id>/chat-messages', endpoint='console_chat_messages')
  283. api.add_resource(MessageFeedbackApi, '/apps/<uuid:app_id>/feedbacks')
  284. api.add_resource(MessageAnnotationApi, '/apps/<uuid:app_id>/annotations')
  285. api.add_resource(MessageAnnotationCountApi, '/apps/<uuid:app_id>/annotations/count')
  286. api.add_resource(MessageApi, '/apps/<uuid:app_id>/messages/<uuid:message_id>', endpoint='console_message')