You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

message.py 9.3KB

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