message.py 13 KB

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