Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

message.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import logging
  2. from flask_restx import Resource, fields, marshal_with, reqparse
  3. from flask_restx.inputs import int_range
  4. from sqlalchemy import exists, select
  5. from werkzeug.exceptions import Forbidden, InternalServerError, NotFound
  6. from controllers.console import api, console_ns
  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 current_user, login_required
  28. from models.account import Account
  29. from models.model import AppMode, Conversation, Message, MessageAnnotation, MessageFeedback
  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. logger = logging.getLogger(__name__)
  35. @console_ns.route("/apps/<uuid:app_id>/chat-messages")
  36. class ChatMessageListApi(Resource):
  37. message_infinite_scroll_pagination_fields = {
  38. "limit": fields.Integer,
  39. "has_more": fields.Boolean,
  40. "data": fields.List(fields.Nested(message_detail_fields)),
  41. }
  42. @api.doc("list_chat_messages")
  43. @api.doc(description="Get chat messages for a conversation with pagination")
  44. @api.doc(params={"app_id": "Application ID"})
  45. @api.expect(
  46. api.parser()
  47. .add_argument("conversation_id", type=str, required=True, location="args", help="Conversation ID")
  48. .add_argument("first_id", type=str, location="args", help="First message ID for pagination")
  49. .add_argument("limit", type=int, location="args", default=20, help="Number of messages to return (1-100)")
  50. )
  51. @api.response(200, "Success", message_infinite_scroll_pagination_fields)
  52. @api.response(404, "Conversation not found")
  53. @setup_required
  54. @login_required
  55. @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT])
  56. @account_initialization_required
  57. @marshal_with(message_infinite_scroll_pagination_fields)
  58. def get(self, app_model):
  59. if not isinstance(current_user, Account) or not current_user.has_edit_permission:
  60. raise Forbidden()
  61. parser = reqparse.RequestParser()
  62. parser.add_argument("conversation_id", required=True, type=uuid_value, location="args")
  63. parser.add_argument("first_id", type=uuid_value, location="args")
  64. parser.add_argument("limit", type=int_range(1, 100), required=False, default=20, location="args")
  65. args = parser.parse_args()
  66. conversation = (
  67. db.session.query(Conversation)
  68. .where(Conversation.id == args["conversation_id"], Conversation.app_id == app_model.id)
  69. .first()
  70. )
  71. if not conversation:
  72. raise NotFound("Conversation Not Exists.")
  73. if args["first_id"]:
  74. first_message = (
  75. db.session.query(Message)
  76. .where(Message.conversation_id == conversation.id, Message.id == args["first_id"])
  77. .first()
  78. )
  79. if not first_message:
  80. raise NotFound("First message not found")
  81. history_messages = (
  82. db.session.query(Message)
  83. .where(
  84. Message.conversation_id == conversation.id,
  85. Message.created_at < first_message.created_at,
  86. Message.id != first_message.id,
  87. )
  88. .order_by(Message.created_at.desc())
  89. .limit(args["limit"])
  90. .all()
  91. )
  92. else:
  93. history_messages = (
  94. db.session.query(Message)
  95. .where(Message.conversation_id == conversation.id)
  96. .order_by(Message.created_at.desc())
  97. .limit(args["limit"])
  98. .all()
  99. )
  100. # Initialize has_more based on whether we have a full page
  101. if len(history_messages) == args["limit"]:
  102. current_page_first_message = history_messages[-1]
  103. # Check if there are more messages before the current page
  104. has_more = db.session.scalar(
  105. select(
  106. exists().where(
  107. Message.conversation_id == conversation.id,
  108. Message.created_at < current_page_first_message.created_at,
  109. Message.id != current_page_first_message.id,
  110. )
  111. )
  112. )
  113. else:
  114. # If we don't have a full page, there are no more messages
  115. has_more = False
  116. history_messages = list(reversed(history_messages))
  117. return InfiniteScrollPagination(data=history_messages, limit=args["limit"], has_more=has_more)
  118. @console_ns.route("/apps/<uuid:app_id>/feedbacks")
  119. class MessageFeedbackApi(Resource):
  120. @api.doc("create_message_feedback")
  121. @api.doc(description="Create or update message feedback (like/dislike)")
  122. @api.doc(params={"app_id": "Application ID"})
  123. @api.expect(
  124. api.model(
  125. "MessageFeedbackRequest",
  126. {
  127. "message_id": fields.String(required=True, description="Message ID"),
  128. "rating": fields.String(enum=["like", "dislike"], description="Feedback rating"),
  129. },
  130. )
  131. )
  132. @api.response(200, "Feedback updated successfully")
  133. @api.response(404, "Message not found")
  134. @api.response(403, "Insufficient permissions")
  135. @get_app_model
  136. @setup_required
  137. @login_required
  138. @account_initialization_required
  139. def post(self, app_model):
  140. if current_user is None:
  141. raise Forbidden()
  142. parser = reqparse.RequestParser()
  143. parser.add_argument("message_id", required=True, type=uuid_value, location="json")
  144. parser.add_argument("rating", type=str, choices=["like", "dislike", None], location="json")
  145. args = parser.parse_args()
  146. message_id = str(args["message_id"])
  147. message = db.session.query(Message).where(Message.id == message_id, Message.app_id == app_model.id).first()
  148. if not message:
  149. raise NotFound("Message Not Exists.")
  150. feedback = message.admin_feedback
  151. if not args["rating"] and feedback:
  152. db.session.delete(feedback)
  153. elif args["rating"] and feedback:
  154. feedback.rating = args["rating"]
  155. elif not args["rating"] and not feedback:
  156. raise ValueError("rating cannot be None when feedback not exists")
  157. else:
  158. feedback = MessageFeedback(
  159. app_id=app_model.id,
  160. conversation_id=message.conversation_id,
  161. message_id=message.id,
  162. rating=args["rating"],
  163. from_source="admin",
  164. from_account_id=current_user.id,
  165. )
  166. db.session.add(feedback)
  167. db.session.commit()
  168. return {"result": "success"}
  169. @console_ns.route("/apps/<uuid:app_id>/annotations")
  170. class MessageAnnotationApi(Resource):
  171. @api.doc("create_message_annotation")
  172. @api.doc(description="Create message annotation")
  173. @api.doc(params={"app_id": "Application ID"})
  174. @api.expect(
  175. api.model(
  176. "MessageAnnotationRequest",
  177. {
  178. "message_id": fields.String(description="Message ID"),
  179. "question": fields.String(required=True, description="Question text"),
  180. "answer": fields.String(required=True, description="Answer text"),
  181. "annotation_reply": fields.Raw(description="Annotation reply"),
  182. },
  183. )
  184. )
  185. @api.response(200, "Annotation created successfully", annotation_fields)
  186. @api.response(403, "Insufficient permissions")
  187. @setup_required
  188. @login_required
  189. @account_initialization_required
  190. @cloud_edition_billing_resource_check("annotation")
  191. @get_app_model
  192. @marshal_with(annotation_fields)
  193. def post(self, app_model):
  194. if not isinstance(current_user, Account):
  195. raise Forbidden()
  196. if not current_user.has_edit_permission:
  197. raise Forbidden()
  198. parser = reqparse.RequestParser()
  199. parser.add_argument("message_id", required=False, type=uuid_value, location="json")
  200. parser.add_argument("question", required=True, type=str, location="json")
  201. parser.add_argument("answer", required=True, type=str, location="json")
  202. parser.add_argument("annotation_reply", required=False, type=dict, location="json")
  203. args = parser.parse_args()
  204. annotation = AppAnnotationService.up_insert_app_annotation_from_message(args, app_model.id)
  205. return annotation
  206. @console_ns.route("/apps/<uuid:app_id>/annotations/count")
  207. class MessageAnnotationCountApi(Resource):
  208. @api.doc("get_annotation_count")
  209. @api.doc(description="Get count of message annotations for the app")
  210. @api.doc(params={"app_id": "Application ID"})
  211. @api.response(
  212. 200,
  213. "Annotation count retrieved successfully",
  214. api.model("AnnotationCountResponse", {"count": fields.Integer(description="Number of annotations")}),
  215. )
  216. @get_app_model
  217. @setup_required
  218. @login_required
  219. @account_initialization_required
  220. def get(self, app_model):
  221. count = db.session.query(MessageAnnotation).where(MessageAnnotation.app_id == app_model.id).count()
  222. return {"count": count}
  223. @console_ns.route("/apps/<uuid:app_id>/chat-messages/<uuid:message_id>/suggested-questions")
  224. class MessageSuggestedQuestionApi(Resource):
  225. @api.doc("get_message_suggested_questions")
  226. @api.doc(description="Get suggested questions for a message")
  227. @api.doc(params={"app_id": "Application ID", "message_id": "Message ID"})
  228. @api.response(
  229. 200,
  230. "Suggested questions retrieved successfully",
  231. api.model("SuggestedQuestionsResponse", {"data": fields.List(fields.String(description="Suggested question"))}),
  232. )
  233. @api.response(404, "Message or conversation not found")
  234. @setup_required
  235. @login_required
  236. @account_initialization_required
  237. @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT])
  238. def get(self, app_model, message_id):
  239. message_id = str(message_id)
  240. try:
  241. questions = MessageService.get_suggested_questions_after_answer(
  242. app_model=app_model, message_id=message_id, user=current_user, invoke_from=InvokeFrom.DEBUGGER
  243. )
  244. except MessageNotExistsError:
  245. raise NotFound("Message not found")
  246. except ConversationNotExistsError:
  247. raise NotFound("Conversation not found")
  248. except ProviderTokenNotInitError as ex:
  249. raise ProviderNotInitializeError(ex.description)
  250. except QuotaExceededError:
  251. raise ProviderQuotaExceededError()
  252. except ModelCurrentlyNotSupportError:
  253. raise ProviderModelCurrentlyNotSupportError()
  254. except InvokeError as e:
  255. raise CompletionRequestError(e.description)
  256. except SuggestedQuestionsAfterAnswerDisabledError:
  257. raise AppSuggestedQuestionsAfterAnswerDisabledError()
  258. except Exception:
  259. logger.exception("internal server error.")
  260. raise InternalServerError()
  261. return {"data": questions}
  262. @console_ns.route("/apps/<uuid:app_id>/messages/<uuid:message_id>")
  263. class MessageApi(Resource):
  264. @api.doc("get_message")
  265. @api.doc(description="Get message details by ID")
  266. @api.doc(params={"app_id": "Application ID", "message_id": "Message ID"})
  267. @api.response(200, "Message retrieved successfully", message_detail_fields)
  268. @api.response(404, "Message not found")
  269. @setup_required
  270. @login_required
  271. @account_initialization_required
  272. @get_app_model
  273. @marshal_with(message_detail_fields)
  274. def get(self, app_model, message_id):
  275. message_id = str(message_id)
  276. message = db.session.query(Message).where(Message.id == message_id, Message.app_id == app_model.id).first()
  277. if not message:
  278. raise NotFound("Message Not Exists.")
  279. return message