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.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import json
  2. import logging
  3. from flask_restx import Api, Namespace, Resource, fields, reqparse
  4. from flask_restx.inputs import int_range
  5. from werkzeug.exceptions import BadRequest, InternalServerError, NotFound
  6. import services
  7. from controllers.service_api import service_api_ns
  8. from controllers.service_api.app.error import NotChatAppError
  9. from controllers.service_api.wraps import FetchUserArg, WhereisUserArg, validate_app_token
  10. from core.app.entities.app_invoke_entities import InvokeFrom
  11. from fields.conversation_fields import build_message_file_model
  12. from fields.message_fields import build_agent_thought_model, build_feedback_model
  13. from fields.raws import FilesContainedField
  14. from libs.helper import TimestampField, uuid_value
  15. from models.model import App, AppMode, EndUser
  16. from services.errors.message import (
  17. FirstMessageNotExistsError,
  18. MessageNotExistsError,
  19. SuggestedQuestionsAfterAnswerDisabledError,
  20. )
  21. from services.message_service import MessageService
  22. logger = logging.getLogger(__name__)
  23. # Define parsers for message APIs
  24. message_list_parser = reqparse.RequestParser()
  25. message_list_parser.add_argument(
  26. "conversation_id", required=True, type=uuid_value, location="args", help="Conversation ID"
  27. )
  28. message_list_parser.add_argument("first_id", type=uuid_value, location="args", help="First message ID for pagination")
  29. message_list_parser.add_argument(
  30. "limit", type=int_range(1, 100), required=False, default=20, location="args", help="Number of messages to return"
  31. )
  32. message_feedback_parser = reqparse.RequestParser()
  33. message_feedback_parser.add_argument(
  34. "rating", type=str, choices=["like", "dislike", None], location="json", help="Feedback rating"
  35. )
  36. message_feedback_parser.add_argument("content", type=str, location="json", help="Feedback content")
  37. feedback_list_parser = reqparse.RequestParser()
  38. feedback_list_parser.add_argument("page", type=int, default=1, location="args", help="Page number")
  39. feedback_list_parser.add_argument(
  40. "limit", type=int_range(1, 101), required=False, default=20, location="args", help="Number of feedbacks per page"
  41. )
  42. def build_message_model(api_or_ns: Api | Namespace):
  43. """Build the message model for the API or Namespace."""
  44. # First build the nested models
  45. feedback_model = build_feedback_model(api_or_ns)
  46. agent_thought_model = build_agent_thought_model(api_or_ns)
  47. message_file_model = build_message_file_model(api_or_ns)
  48. # Then build the message fields with nested models
  49. message_fields = {
  50. "id": fields.String,
  51. "conversation_id": fields.String,
  52. "parent_message_id": fields.String,
  53. "inputs": FilesContainedField,
  54. "query": fields.String,
  55. "answer": fields.String(attribute="re_sign_file_url_answer"),
  56. "message_files": fields.List(fields.Nested(message_file_model)),
  57. "feedback": fields.Nested(feedback_model, attribute="user_feedback", allow_null=True),
  58. "retriever_resources": fields.Raw(
  59. attribute=lambda obj: json.loads(obj.message_metadata).get("retriever_resources", [])
  60. if obj.message_metadata
  61. else []
  62. ),
  63. "created_at": TimestampField,
  64. "agent_thoughts": fields.List(fields.Nested(agent_thought_model)),
  65. "status": fields.String,
  66. "error": fields.String,
  67. }
  68. return api_or_ns.model("Message", message_fields)
  69. def build_message_infinite_scroll_pagination_model(api_or_ns: Api | Namespace):
  70. """Build the message infinite scroll pagination model for the API or Namespace."""
  71. # Build the nested message model first
  72. message_model = build_message_model(api_or_ns)
  73. message_infinite_scroll_pagination_fields = {
  74. "limit": fields.Integer,
  75. "has_more": fields.Boolean,
  76. "data": fields.List(fields.Nested(message_model)),
  77. }
  78. return api_or_ns.model("MessageInfiniteScrollPagination", message_infinite_scroll_pagination_fields)
  79. @service_api_ns.route("/messages")
  80. class MessageListApi(Resource):
  81. @service_api_ns.expect(message_list_parser)
  82. @service_api_ns.doc("list_messages")
  83. @service_api_ns.doc(description="List messages in a conversation")
  84. @service_api_ns.doc(
  85. responses={
  86. 200: "Messages retrieved successfully",
  87. 401: "Unauthorized - invalid API token",
  88. 404: "Conversation or first message not found",
  89. }
  90. )
  91. @validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY))
  92. @service_api_ns.marshal_with(build_message_infinite_scroll_pagination_model(service_api_ns))
  93. def get(self, app_model: App, end_user: EndUser):
  94. """List messages in a conversation.
  95. Retrieves messages with pagination support using first_id.
  96. """
  97. app_mode = AppMode.value_of(app_model.mode)
  98. if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:
  99. raise NotChatAppError()
  100. args = message_list_parser.parse_args()
  101. try:
  102. return MessageService.pagination_by_first_id(
  103. app_model, end_user, args["conversation_id"], args["first_id"], args["limit"]
  104. )
  105. except services.errors.conversation.ConversationNotExistsError:
  106. raise NotFound("Conversation Not Exists.")
  107. except FirstMessageNotExistsError:
  108. raise NotFound("First Message Not Exists.")
  109. @service_api_ns.route("/messages/<uuid:message_id>/feedbacks")
  110. class MessageFeedbackApi(Resource):
  111. @service_api_ns.expect(message_feedback_parser)
  112. @service_api_ns.doc("create_message_feedback")
  113. @service_api_ns.doc(description="Submit feedback for a message")
  114. @service_api_ns.doc(params={"message_id": "Message ID"})
  115. @service_api_ns.doc(
  116. responses={
  117. 200: "Feedback submitted successfully",
  118. 401: "Unauthorized - invalid API token",
  119. 404: "Message not found",
  120. }
  121. )
  122. @validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON, required=True))
  123. def post(self, app_model: App, end_user: EndUser, message_id):
  124. """Submit feedback for a message.
  125. Allows users to rate messages as like/dislike and provide optional feedback content.
  126. """
  127. message_id = str(message_id)
  128. args = message_feedback_parser.parse_args()
  129. try:
  130. MessageService.create_feedback(
  131. app_model=app_model,
  132. message_id=message_id,
  133. user=end_user,
  134. rating=args.get("rating"),
  135. content=args.get("content"),
  136. )
  137. except MessageNotExistsError:
  138. raise NotFound("Message Not Exists.")
  139. return {"result": "success"}
  140. @service_api_ns.route("/app/feedbacks")
  141. class AppGetFeedbacksApi(Resource):
  142. @service_api_ns.expect(feedback_list_parser)
  143. @service_api_ns.doc("get_app_feedbacks")
  144. @service_api_ns.doc(description="Get all feedbacks for the application")
  145. @service_api_ns.doc(
  146. responses={
  147. 200: "Feedbacks retrieved successfully",
  148. 401: "Unauthorized - invalid API token",
  149. }
  150. )
  151. @validate_app_token
  152. def get(self, app_model: App):
  153. """Get all feedbacks for the application.
  154. Returns paginated list of all feedback submitted for messages in this app.
  155. """
  156. args = feedback_list_parser.parse_args()
  157. feedbacks = MessageService.get_all_messages_feedbacks(app_model, page=args["page"], limit=args["limit"])
  158. return {"data": feedbacks}
  159. @service_api_ns.route("/messages/<uuid:message_id>/suggested")
  160. class MessageSuggestedApi(Resource):
  161. @service_api_ns.doc("get_suggested_questions")
  162. @service_api_ns.doc(description="Get suggested follow-up questions for a message")
  163. @service_api_ns.doc(params={"message_id": "Message ID"})
  164. @service_api_ns.doc(
  165. responses={
  166. 200: "Suggested questions retrieved successfully",
  167. 400: "Suggested questions feature is disabled",
  168. 401: "Unauthorized - invalid API token",
  169. 404: "Message not found",
  170. 500: "Internal server error",
  171. }
  172. )
  173. @validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY, required=True))
  174. def get(self, app_model: App, end_user: EndUser, message_id):
  175. """Get suggested follow-up questions for a message.
  176. Returns AI-generated follow-up questions based on the message content.
  177. """
  178. message_id = str(message_id)
  179. app_mode = AppMode.value_of(app_model.mode)
  180. if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:
  181. raise NotChatAppError()
  182. try:
  183. questions = MessageService.get_suggested_questions_after_answer(
  184. app_model=app_model, user=end_user, message_id=message_id, invoke_from=InvokeFrom.SERVICE_API
  185. )
  186. except MessageNotExistsError:
  187. raise NotFound("Message Not Exists.")
  188. except SuggestedQuestionsAfterAnswerDisabledError:
  189. raise BadRequest("Suggested Questions Is Disabled.")
  190. except Exception:
  191. logger.exception("internal server error.")
  192. raise InternalServerError()
  193. return {"result": "success", "data": questions}