Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

message.py 9.0KB

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