message.py 9.3 KB

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