message.py 12 KB

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