Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

message.py 13KB

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