message.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. import logging
  2. from flask_restful import fields, marshal_with, reqparse # type: ignore
  3. from flask_restful.inputs import int_range # type: ignore
  4. from werkzeug.exceptions import InternalServerError, NotFound
  5. import services
  6. from controllers.web import api
  7. from controllers.web.error import (
  8. AppMoreLikeThisDisabledError,
  9. AppSuggestedQuestionsAfterAnswerDisabledError,
  10. CompletionRequestError,
  11. NotChatAppError,
  12. NotCompletionAppError,
  13. ProviderModelCurrentlyNotSupportError,
  14. ProviderNotInitializeError,
  15. ProviderQuotaExceededError,
  16. )
  17. from controllers.web.wraps import WebApiResource
  18. from core.app.entities.app_invoke_entities import InvokeFrom
  19. from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError
  20. from core.model_runtime.errors.invoke import InvokeError
  21. from fields.conversation_fields import message_file_fields
  22. from fields.message_fields import agent_thought_fields, feedback_fields, retriever_resource_fields
  23. from fields.raws import FilesContainedField
  24. from libs import helper
  25. from libs.helper import TimestampField, uuid_value
  26. from models.model import AppMode
  27. from services.app_generate_service import AppGenerateService
  28. from services.errors.app import MoreLikeThisDisabledError
  29. from services.errors.conversation import ConversationNotExistsError
  30. from services.errors.message import MessageNotExistsError, SuggestedQuestionsAfterAnswerDisabledError
  31. from services.message_service import MessageService
  32. class MessageListApi(WebApiResource):
  33. message_fields = {
  34. "id": fields.String,
  35. "conversation_id": fields.String,
  36. "parent_message_id": fields.String,
  37. "inputs": FilesContainedField,
  38. "query": fields.String,
  39. "answer": fields.String(attribute="re_sign_file_url_answer"),
  40. "message_files": fields.List(fields.Nested(message_file_fields)),
  41. "feedback": fields.Nested(feedback_fields, attribute="user_feedback", allow_null=True),
  42. "retriever_resources": fields.List(fields.Nested(retriever_resource_fields)),
  43. "created_at": TimestampField,
  44. "agent_thoughts": fields.List(fields.Nested(agent_thought_fields)),
  45. "status": fields.String,
  46. "error": fields.String,
  47. }
  48. message_infinite_scroll_pagination_fields = {
  49. "limit": fields.Integer,
  50. "has_more": fields.Boolean,
  51. "data": fields.List(fields.Nested(message_fields)),
  52. }
  53. @marshal_with(message_infinite_scroll_pagination_fields)
  54. def get(self, app_model, end_user):
  55. app_mode = AppMode.value_of(app_model.mode)
  56. if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:
  57. raise NotChatAppError()
  58. parser = reqparse.RequestParser()
  59. parser.add_argument("conversation_id", required=True, type=uuid_value, location="args")
  60. parser.add_argument("first_id", type=uuid_value, location="args")
  61. parser.add_argument("limit", type=int_range(1, 100), required=False, default=20, location="args")
  62. args = parser.parse_args()
  63. try:
  64. return MessageService.pagination_by_first_id(
  65. app_model, end_user, args["conversation_id"], args["first_id"], args["limit"]
  66. )
  67. except services.errors.conversation.ConversationNotExistsError:
  68. raise NotFound("Conversation Not Exists.")
  69. except services.errors.message.FirstMessageNotExistsError:
  70. raise NotFound("First Message Not Exists.")
  71. class MessageFeedbackApi(WebApiResource):
  72. def post(self, app_model, end_user, message_id):
  73. message_id = str(message_id)
  74. parser = reqparse.RequestParser()
  75. parser.add_argument("rating", type=str, choices=["like", "dislike", None], location="json")
  76. parser.add_argument("content", type=str, location="json", default=None)
  77. args = parser.parse_args()
  78. try:
  79. MessageService.create_feedback(
  80. app_model=app_model,
  81. message_id=message_id,
  82. user=end_user,
  83. rating=args.get("rating"),
  84. content=args.get("content"),
  85. )
  86. except services.errors.message.MessageNotExistsError:
  87. raise NotFound("Message Not Exists.")
  88. return {"result": "success"}
  89. class MessageMoreLikeThisApi(WebApiResource):
  90. def get(self, app_model, end_user, message_id):
  91. if app_model.mode != "completion":
  92. raise NotCompletionAppError()
  93. message_id = str(message_id)
  94. parser = reqparse.RequestParser()
  95. parser.add_argument(
  96. "response_mode", type=str, required=True, choices=["blocking", "streaming"], location="args"
  97. )
  98. args = parser.parse_args()
  99. streaming = args["response_mode"] == "streaming"
  100. try:
  101. response = AppGenerateService.generate_more_like_this(
  102. app_model=app_model,
  103. user=end_user,
  104. message_id=message_id,
  105. invoke_from=InvokeFrom.WEB_APP,
  106. streaming=streaming,
  107. )
  108. return helper.compact_generate_response(response)
  109. except MessageNotExistsError:
  110. raise NotFound("Message Not Exists.")
  111. except MoreLikeThisDisabledError:
  112. raise AppMoreLikeThisDisabledError()
  113. except ProviderTokenNotInitError as ex:
  114. raise ProviderNotInitializeError(ex.description)
  115. except QuotaExceededError:
  116. raise ProviderQuotaExceededError()
  117. except ModelCurrentlyNotSupportError:
  118. raise ProviderModelCurrentlyNotSupportError()
  119. except InvokeError as e:
  120. raise CompletionRequestError(e.description)
  121. except ValueError as e:
  122. raise e
  123. except Exception:
  124. logging.exception("internal server error.")
  125. raise InternalServerError()
  126. class MessageSuggestedQuestionApi(WebApiResource):
  127. def get(self, app_model, end_user, message_id):
  128. app_mode = AppMode.value_of(app_model.mode)
  129. if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:
  130. raise NotCompletionAppError()
  131. message_id = str(message_id)
  132. try:
  133. questions = MessageService.get_suggested_questions_after_answer(
  134. app_model=app_model, user=end_user, message_id=message_id, invoke_from=InvokeFrom.WEB_APP
  135. )
  136. except MessageNotExistsError:
  137. raise NotFound("Message not found")
  138. except ConversationNotExistsError:
  139. raise NotFound("Conversation not found")
  140. except SuggestedQuestionsAfterAnswerDisabledError:
  141. raise AppSuggestedQuestionsAfterAnswerDisabledError()
  142. except ProviderTokenNotInitError as ex:
  143. raise ProviderNotInitializeError(ex.description)
  144. except QuotaExceededError:
  145. raise ProviderQuotaExceededError()
  146. except ModelCurrentlyNotSupportError:
  147. raise ProviderModelCurrentlyNotSupportError()
  148. except InvokeError as e:
  149. raise CompletionRequestError(e.description)
  150. except Exception:
  151. logging.exception("internal server error.")
  152. raise InternalServerError()
  153. return {"data": questions}
  154. api.add_resource(MessageListApi, "/messages")
  155. api.add_resource(MessageFeedbackApi, "/messages/<uuid:message_id>/feedbacks")
  156. api.add_resource(MessageMoreLikeThisApi, "/messages/<uuid:message_id>/more-like-this")
  157. api.add_resource(MessageSuggestedQuestionApi, "/messages/<uuid:message_id>/suggested-questions")