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 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. import services
  7. from controllers.console import api
  8. from controllers.console.app.error import (
  9. CompletionRequestError,
  10. ProviderModelCurrentlyNotSupportError,
  11. ProviderNotInitializeError,
  12. ProviderQuotaExceededError,
  13. )
  14. from controllers.console.app.wraps import get_app_model
  15. from controllers.console.explore.error import AppSuggestedQuestionsAfterAnswerDisabledError
  16. from controllers.console.wraps import (
  17. account_initialization_required,
  18. cloud_edition_billing_resource_check,
  19. setup_required,
  20. )
  21. from core.app.entities.app_invoke_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 AppMode, Conversation, Message, MessageAnnotation
  30. from services.annotation_service import AppAnnotationService
  31. from services.errors.conversation import ConversationNotExistsError
  32. from services.errors.message import MessageNotExistsError, SuggestedQuestionsAfterAnswerDisabledError
  33. from services.message_service import MessageService
  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. .filter(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. .filter(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. .filter(
  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. .filter(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. .filter(
  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. try:
  112. MessageService.create_feedback(
  113. app_model=app_model,
  114. message_id=str(args["message_id"]),
  115. user=current_user,
  116. rating=args.get("rating"),
  117. content=None,
  118. )
  119. except services.errors.message.MessageNotExistsError:
  120. raise NotFound("Message Not Exists.")
  121. return {"result": "success"}
  122. class MessageAnnotationApi(Resource):
  123. @setup_required
  124. @login_required
  125. @account_initialization_required
  126. @cloud_edition_billing_resource_check("annotation")
  127. @get_app_model
  128. @marshal_with(annotation_fields)
  129. def post(self, app_model):
  130. if not current_user.is_editor:
  131. raise Forbidden()
  132. parser = reqparse.RequestParser()
  133. parser.add_argument("message_id", required=False, type=uuid_value, location="json")
  134. parser.add_argument("question", required=True, type=str, location="json")
  135. parser.add_argument("answer", required=True, type=str, location="json")
  136. parser.add_argument("annotation_reply", required=False, type=dict, location="json")
  137. args = parser.parse_args()
  138. annotation = AppAnnotationService.up_insert_app_annotation_from_message(args, app_model.id)
  139. return annotation
  140. class MessageAnnotationCountApi(Resource):
  141. @setup_required
  142. @login_required
  143. @account_initialization_required
  144. @get_app_model
  145. def get(self, app_model):
  146. count = db.session.query(MessageAnnotation).filter(MessageAnnotation.app_id == app_model.id).count()
  147. return {"count": count}
  148. class MessageSuggestedQuestionApi(Resource):
  149. @setup_required
  150. @login_required
  151. @account_initialization_required
  152. @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT])
  153. def get(self, app_model, message_id):
  154. message_id = str(message_id)
  155. try:
  156. questions = MessageService.get_suggested_questions_after_answer(
  157. app_model=app_model, message_id=message_id, user=current_user, invoke_from=InvokeFrom.DEBUGGER
  158. )
  159. except MessageNotExistsError:
  160. raise NotFound("Message not found")
  161. except ConversationNotExistsError:
  162. raise NotFound("Conversation not found")
  163. except ProviderTokenNotInitError as ex:
  164. raise ProviderNotInitializeError(ex.description)
  165. except QuotaExceededError:
  166. raise ProviderQuotaExceededError()
  167. except ModelCurrentlyNotSupportError:
  168. raise ProviderModelCurrentlyNotSupportError()
  169. except InvokeError as e:
  170. raise CompletionRequestError(e.description)
  171. except SuggestedQuestionsAfterAnswerDisabledError:
  172. raise AppSuggestedQuestionsAfterAnswerDisabledError()
  173. except Exception:
  174. logging.exception("internal server error.")
  175. raise InternalServerError()
  176. return {"data": questions}
  177. class MessageApi(Resource):
  178. @setup_required
  179. @login_required
  180. @account_initialization_required
  181. @get_app_model
  182. @marshal_with(message_detail_fields)
  183. def get(self, app_model, message_id):
  184. message_id = str(message_id)
  185. message = db.session.query(Message).filter(Message.id == message_id, Message.app_id == app_model.id).first()
  186. if not message:
  187. raise NotFound("Message Not Exists.")
  188. return message
  189. api.add_resource(MessageSuggestedQuestionApi, "/apps/<uuid:app_id>/chat-messages/<uuid:message_id>/suggested-questions")
  190. api.add_resource(ChatMessageListApi, "/apps/<uuid:app_id>/chat-messages", endpoint="console_chat_messages")
  191. api.add_resource(MessageFeedbackApi, "/apps/<uuid:app_id>/feedbacks")
  192. api.add_resource(MessageAnnotationApi, "/apps/<uuid:app_id>/annotations")
  193. api.add_resource(MessageAnnotationCountApi, "/apps/<uuid:app_id>/annotations/count")
  194. api.add_resource(MessageApi, "/apps/<uuid:app_id>/messages/<uuid:message_id>", endpoint="console_message")