message.py 14 KB

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