message.py 14 KB

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