message.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import logging
  2. from flask_login import current_user # type: ignore
  3. from flask_restful import Resource, fields, marshal_with, reqparse # type: ignore
  4. from flask_restful.inputs import int_range # type: ignore
  5. from werkzeug.exceptions import Forbidden, InternalServerError, NotFound
  6. from controllers.console import api
  7. from controllers.console.app.error import (
  8. CompletionRequestError,
  9. ProviderModelCurrentlyNotSupportError,
  10. ProviderNotInitializeError,
  11. ProviderQuotaExceededError,
  12. )
  13. from controllers.console.app.wraps import get_app_model
  14. from controllers.console.explore.error import AppSuggestedQuestionsAfterAnswerDisabledError
  15. from controllers.console.wraps import (
  16. account_initialization_required,
  17. cloud_edition_billing_resource_check,
  18. setup_required,
  19. )
  20. from core.app.entities.app_invoke_entities import InvokeFrom
  21. from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError
  22. from core.model_runtime.errors.invoke import InvokeError
  23. from extensions.ext_database import db
  24. from fields.conversation_fields import annotation_fields, message_detail_fields
  25. from libs.helper import uuid_value
  26. from libs.infinite_scroll_pagination import InfiniteScrollPagination
  27. from libs.login import login_required
  28. from models.model import AppMode, Conversation, Message, MessageAnnotation, MessageFeedback
  29. from services.annotation_service import AppAnnotationService
  30. from services.errors.conversation import ConversationNotExistsError
  31. from services.errors.message import MessageNotExistsError, SuggestedQuestionsAfterAnswerDisabledError
  32. from services.message_service import MessageService
  33. class ChatMessageListApi(Resource):
  34. message_infinite_scroll_pagination_fields = {
  35. "limit": fields.Integer,
  36. "has_more": fields.Boolean,
  37. "data": fields.List(fields.Nested(message_detail_fields)),
  38. }
  39. @setup_required
  40. @login_required
  41. @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT])
  42. @account_initialization_required
  43. @marshal_with(message_infinite_scroll_pagination_fields)
  44. def get(self, app_model):
  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 = (
  51. db.session.query(Conversation)
  52. .filter(Conversation.id == args["conversation_id"], Conversation.app_id == app_model.id)
  53. .first()
  54. )
  55. if not conversation:
  56. raise NotFound("Conversation Not Exists.")
  57. if args["first_id"]:
  58. first_message = (
  59. db.session.query(Message)
  60. .filter(Message.conversation_id == conversation.id, Message.id == args["first_id"])
  61. .first()
  62. )
  63. if not first_message:
  64. raise NotFound("First message not found")
  65. history_messages = (
  66. db.session.query(Message)
  67. .filter(
  68. Message.conversation_id == conversation.id,
  69. Message.created_at < first_message.created_at,
  70. Message.id != first_message.id,
  71. )
  72. .order_by(Message.created_at.desc())
  73. .limit(args["limit"])
  74. .all()
  75. )
  76. else:
  77. history_messages = (
  78. db.session.query(Message)
  79. .filter(Message.conversation_id == conversation.id)
  80. .order_by(Message.created_at.desc())
  81. .limit(args["limit"])
  82. .all()
  83. )
  84. has_more = False
  85. if len(history_messages) == args["limit"]:
  86. current_page_first_message = history_messages[-1]
  87. rest_count = (
  88. db.session.query(Message)
  89. .filter(
  90. Message.conversation_id == conversation.id,
  91. Message.created_at < current_page_first_message.created_at,
  92. Message.id != current_page_first_message.id,
  93. )
  94. .count()
  95. )
  96. if rest_count > 0:
  97. has_more = True
  98. history_messages = list(reversed(history_messages))
  99. return InfiniteScrollPagination(data=history_messages, limit=args["limit"], has_more=has_more)
  100. class MessageFeedbackApi(Resource):
  101. @setup_required
  102. @login_required
  103. @account_initialization_required
  104. @get_app_model
  105. def post(self, app_model):
  106. parser = reqparse.RequestParser()
  107. parser.add_argument("message_id", required=True, type=uuid_value, location="json")
  108. parser.add_argument("rating", type=str, choices=["like", "dislike", None], location="json")
  109. args = parser.parse_args()
  110. message_id = str(args["message_id"])
  111. message = db.session.query(Message).filter(Message.id == message_id, Message.app_id == app_model.id).first()
  112. if not message:
  113. raise NotFound("Message Not Exists.")
  114. feedback = message.admin_feedback
  115. if not args["rating"] and feedback:
  116. db.session.delete(feedback)
  117. elif args["rating"] and feedback:
  118. feedback.rating = args["rating"]
  119. elif not args["rating"] and not feedback:
  120. raise ValueError("rating cannot be None when feedback not exists")
  121. else:
  122. feedback = MessageFeedback(
  123. app_id=app_model.id,
  124. conversation_id=message.conversation_id,
  125. message_id=message.id,
  126. rating=args["rating"],
  127. from_source="admin",
  128. from_account_id=current_user.id,
  129. )
  130. db.session.add(feedback)
  131. db.session.commit()
  132. return {"result": "success"}
  133. class MessageAnnotationApi(Resource):
  134. @setup_required
  135. @login_required
  136. @account_initialization_required
  137. @cloud_edition_billing_resource_check("annotation")
  138. @get_app_model
  139. @marshal_with(annotation_fields)
  140. def post(self, app_model):
  141. if not current_user.is_editor:
  142. raise Forbidden()
  143. parser = reqparse.RequestParser()
  144. parser.add_argument("message_id", required=False, type=uuid_value, location="json")
  145. parser.add_argument("question", required=True, type=str, location="json")
  146. parser.add_argument("answer", required=True, type=str, location="json")
  147. parser.add_argument("annotation_reply", required=False, type=dict, location="json")
  148. args = parser.parse_args()
  149. annotation = AppAnnotationService.up_insert_app_annotation_from_message(args, app_model.id)
  150. return annotation
  151. class MessageAnnotationCountApi(Resource):
  152. @setup_required
  153. @login_required
  154. @account_initialization_required
  155. @get_app_model
  156. def get(self, app_model):
  157. count = db.session.query(MessageAnnotation).filter(MessageAnnotation.app_id == app_model.id).count()
  158. return {"count": count}
  159. class MessageSuggestedQuestionApi(Resource):
  160. @setup_required
  161. @login_required
  162. @account_initialization_required
  163. @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT])
  164. def get(self, app_model, message_id):
  165. message_id = str(message_id)
  166. try:
  167. questions = MessageService.get_suggested_questions_after_answer(
  168. app_model=app_model, message_id=message_id, user=current_user, invoke_from=InvokeFrom.DEBUGGER
  169. )
  170. except MessageNotExistsError:
  171. raise NotFound("Message not found")
  172. except ConversationNotExistsError:
  173. raise NotFound("Conversation not found")
  174. except ProviderTokenNotInitError as ex:
  175. raise ProviderNotInitializeError(ex.description)
  176. except QuotaExceededError:
  177. raise ProviderQuotaExceededError()
  178. except ModelCurrentlyNotSupportError:
  179. raise ProviderModelCurrentlyNotSupportError()
  180. except InvokeError as e:
  181. raise CompletionRequestError(e.description)
  182. except SuggestedQuestionsAfterAnswerDisabledError:
  183. raise AppSuggestedQuestionsAfterAnswerDisabledError()
  184. except Exception:
  185. logging.exception("internal server error.")
  186. raise InternalServerError()
  187. return {"data": questions}
  188. class MessageApi(Resource):
  189. @setup_required
  190. @login_required
  191. @account_initialization_required
  192. @get_app_model
  193. @marshal_with(message_detail_fields)
  194. def get(self, app_model, message_id):
  195. message_id = str(message_id)
  196. message = db.session.query(Message).filter(Message.id == message_id, Message.app_id == app_model.id).first()
  197. if not message:
  198. raise NotFound("Message Not Exists.")
  199. return message
  200. api.add_resource(MessageSuggestedQuestionApi, "/apps/<uuid:app_id>/chat-messages/<uuid:message_id>/suggested-questions")
  201. api.add_resource(ChatMessageListApi, "/apps/<uuid:app_id>/chat-messages", endpoint="console_chat_messages")
  202. api.add_resource(MessageFeedbackApi, "/apps/<uuid:app_id>/feedbacks")
  203. api.add_resource(MessageAnnotationApi, "/apps/<uuid:app_id>/annotations")
  204. api.add_resource(MessageAnnotationCountApi, "/apps/<uuid:app_id>/annotations/count")
  205. api.add_resource(MessageApi, "/apps/<uuid:app_id>/messages/<uuid:message_id>", endpoint="console_message")