message.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. history_messages = list(reversed(history_messages))
  96. return InfiniteScrollPagination(data=history_messages, limit=args["limit"], has_more=has_more)
  97. class MessageFeedbackApi(Resource):
  98. @setup_required
  99. @login_required
  100. @account_initialization_required
  101. @get_app_model
  102. def post(self, app_model):
  103. parser = reqparse.RequestParser()
  104. parser.add_argument("message_id", required=True, type=uuid_value, location="json")
  105. parser.add_argument("rating", type=str, choices=["like", "dislike", None], location="json")
  106. args = parser.parse_args()
  107. message_id = str(args["message_id"])
  108. message = db.session.query(Message).filter(Message.id == message_id, Message.app_id == app_model.id).first()
  109. if not message:
  110. raise NotFound("Message Not Exists.")
  111. feedback = message.admin_feedback
  112. if not args["rating"] and feedback:
  113. db.session.delete(feedback)
  114. elif args["rating"] and feedback:
  115. feedback.rating = args["rating"]
  116. elif not args["rating"] and not feedback:
  117. raise ValueError("rating cannot be None when feedback not exists")
  118. else:
  119. feedback = MessageFeedback(
  120. app_id=app_model.id,
  121. conversation_id=message.conversation_id,
  122. message_id=message.id,
  123. rating=args["rating"],
  124. from_source="admin",
  125. from_account_id=current_user.id,
  126. )
  127. db.session.add(feedback)
  128. db.session.commit()
  129. return {"result": "success"}
  130. class MessageAnnotationApi(Resource):
  131. @setup_required
  132. @login_required
  133. @account_initialization_required
  134. @cloud_edition_billing_resource_check("annotation")
  135. @get_app_model
  136. @marshal_with(annotation_fields)
  137. def post(self, app_model):
  138. if not current_user.is_editor:
  139. raise Forbidden()
  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_model.id)
  147. return annotation
  148. class MessageAnnotationCountApi(Resource):
  149. @setup_required
  150. @login_required
  151. @account_initialization_required
  152. @get_app_model
  153. def get(self, app_model):
  154. count = db.session.query(MessageAnnotation).filter(MessageAnnotation.app_id == app_model.id).count()
  155. return {"count": count}
  156. class MessageSuggestedQuestionApi(Resource):
  157. @setup_required
  158. @login_required
  159. @account_initialization_required
  160. @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT])
  161. def get(self, app_model, message_id):
  162. message_id = str(message_id)
  163. try:
  164. questions = MessageService.get_suggested_questions_after_answer(
  165. app_model=app_model, message_id=message_id, user=current_user, invoke_from=InvokeFrom.DEBUGGER
  166. )
  167. except MessageNotExistsError:
  168. raise NotFound("Message not found")
  169. except ConversationNotExistsError:
  170. raise NotFound("Conversation not found")
  171. except ProviderTokenNotInitError as ex:
  172. raise ProviderNotInitializeError(ex.description)
  173. except QuotaExceededError:
  174. raise ProviderQuotaExceededError()
  175. except ModelCurrentlyNotSupportError:
  176. raise ProviderModelCurrentlyNotSupportError()
  177. except InvokeError as e:
  178. raise CompletionRequestError(e.description)
  179. except SuggestedQuestionsAfterAnswerDisabledError:
  180. raise AppSuggestedQuestionsAfterAnswerDisabledError()
  181. except Exception:
  182. logging.exception("internal server error.")
  183. raise InternalServerError()
  184. return {"data": questions}
  185. class MessageApi(Resource):
  186. @setup_required
  187. @login_required
  188. @account_initialization_required
  189. @get_app_model
  190. @marshal_with(message_detail_fields)
  191. def get(self, app_model, message_id):
  192. message_id = str(message_id)
  193. message = db.session.query(Message).filter(Message.id == message_id, Message.app_id == app_model.id).first()
  194. if not message:
  195. raise NotFound("Message Not Exists.")
  196. return message
  197. api.add_resource(MessageSuggestedQuestionApi, "/apps/<uuid:app_id>/chat-messages/<uuid:message_id>/suggested-questions")
  198. api.add_resource(ChatMessageListApi, "/apps/<uuid:app_id>/chat-messages", endpoint="console_chat_messages")
  199. api.add_resource(MessageFeedbackApi, "/apps/<uuid:app_id>/feedbacks")
  200. api.add_resource(MessageAnnotationApi, "/apps/<uuid:app_id>/annotations")
  201. api.add_resource(MessageAnnotationCountApi, "/apps/<uuid:app_id>/annotations/count")
  202. api.add_resource(MessageApi, "/apps/<uuid:app_id>/messages/<uuid:message_id>", endpoint="console_message")