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 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. import logging
  2. from flask_login import current_user
  3. from flask_restx import Resource, fields, marshal_with, reqparse
  4. from flask_restx.inputs import int_range
  5. from sqlalchemy import exists, select
  6. from werkzeug.exceptions import Forbidden, InternalServerError, NotFound
  7. from controllers.console import api
  8. from controllers.console.app.error import (
  9. CompletionRequestError,
  10. ProviderModelCurrentlyNotSupportError,
  11. ProviderNotInitializeError,
  12. ProviderQuotaExceededError,
  13. )
  14. from controllers.console.app.wraps import get_app_model
  15. from controllers.console.explore.error import AppSuggestedQuestionsAfterAnswerDisabledError
  16. from controllers.console.wraps import (
  17. account_initialization_required,
  18. cloud_edition_billing_resource_check,
  19. setup_required,
  20. )
  21. from core.app.entities.app_invoke_entities import InvokeFrom
  22. from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError
  23. from core.model_runtime.errors.invoke import InvokeError
  24. from extensions.ext_database import db
  25. from fields.conversation_fields import annotation_fields, message_detail_fields
  26. from libs.helper import uuid_value
  27. from libs.infinite_scroll_pagination import InfiniteScrollPagination
  28. from libs.login import login_required
  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. class ChatMessageListApi(Resource):
  36. message_infinite_scroll_pagination_fields = {
  37. "limit": fields.Integer,
  38. "has_more": fields.Boolean,
  39. "data": fields.List(fields.Nested(message_detail_fields)),
  40. }
  41. @setup_required
  42. @login_required
  43. @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT])
  44. @account_initialization_required
  45. @marshal_with(message_infinite_scroll_pagination_fields)
  46. def get(self, app_model):
  47. parser = reqparse.RequestParser()
  48. parser.add_argument("conversation_id", required=True, type=uuid_value, location="args")
  49. parser.add_argument("first_id", type=uuid_value, location="args")
  50. parser.add_argument("limit", type=int_range(1, 100), required=False, default=20, location="args")
  51. args = parser.parse_args()
  52. conversation = (
  53. db.session.query(Conversation)
  54. .where(Conversation.id == args["conversation_id"], Conversation.app_id == app_model.id)
  55. .first()
  56. )
  57. if not conversation:
  58. raise NotFound("Conversation Not Exists.")
  59. if args["first_id"]:
  60. first_message = (
  61. db.session.query(Message)
  62. .where(Message.conversation_id == conversation.id, Message.id == args["first_id"])
  63. .first()
  64. )
  65. if not first_message:
  66. raise NotFound("First message not found")
  67. history_messages = (
  68. db.session.query(Message)
  69. .where(
  70. Message.conversation_id == conversation.id,
  71. Message.created_at < first_message.created_at,
  72. Message.id != first_message.id,
  73. )
  74. .order_by(Message.created_at.desc())
  75. .limit(args["limit"])
  76. .all()
  77. )
  78. else:
  79. history_messages = (
  80. db.session.query(Message)
  81. .where(Message.conversation_id == conversation.id)
  82. .order_by(Message.created_at.desc())
  83. .limit(args["limit"])
  84. .all()
  85. )
  86. # Initialize has_more based on whether we have a full page
  87. if len(history_messages) == args["limit"]:
  88. current_page_first_message = history_messages[-1]
  89. # Check if there are more messages before the current page
  90. has_more = db.session.scalar(
  91. select(
  92. exists().where(
  93. Message.conversation_id == conversation.id,
  94. Message.created_at < current_page_first_message.created_at,
  95. Message.id != current_page_first_message.id,
  96. )
  97. )
  98. )
  99. else:
  100. # If we don't have a full page, there are no more messages
  101. has_more = False
  102. history_messages = list(reversed(history_messages))
  103. return InfiniteScrollPagination(data=history_messages, limit=args["limit"], has_more=has_more)
  104. class MessageFeedbackApi(Resource):
  105. @setup_required
  106. @login_required
  107. @account_initialization_required
  108. @get_app_model
  109. def post(self, app_model):
  110. parser = reqparse.RequestParser()
  111. parser.add_argument("message_id", required=True, type=uuid_value, location="json")
  112. parser.add_argument("rating", type=str, choices=["like", "dislike", None], location="json")
  113. args = parser.parse_args()
  114. message_id = str(args["message_id"])
  115. message = db.session.query(Message).where(Message.id == message_id, Message.app_id == app_model.id).first()
  116. if not message:
  117. raise NotFound("Message Not Exists.")
  118. feedback = message.admin_feedback
  119. if not args["rating"] and feedback:
  120. db.session.delete(feedback)
  121. elif args["rating"] and feedback:
  122. feedback.rating = args["rating"]
  123. elif not args["rating"] and not feedback:
  124. raise ValueError("rating cannot be None when feedback not exists")
  125. else:
  126. feedback = MessageFeedback(
  127. app_id=app_model.id,
  128. conversation_id=message.conversation_id,
  129. message_id=message.id,
  130. rating=args["rating"],
  131. from_source="admin",
  132. from_account_id=current_user.id,
  133. )
  134. db.session.add(feedback)
  135. db.session.commit()
  136. return {"result": "success"}
  137. class MessageAnnotationApi(Resource):
  138. @setup_required
  139. @login_required
  140. @account_initialization_required
  141. @cloud_edition_billing_resource_check("annotation")
  142. @get_app_model
  143. @marshal_with(annotation_fields)
  144. def post(self, app_model):
  145. if not current_user.is_editor:
  146. raise Forbidden()
  147. parser = reqparse.RequestParser()
  148. parser.add_argument("message_id", required=False, type=uuid_value, location="json")
  149. parser.add_argument("question", required=True, type=str, location="json")
  150. parser.add_argument("answer", required=True, type=str, location="json")
  151. parser.add_argument("annotation_reply", required=False, type=dict, location="json")
  152. args = parser.parse_args()
  153. annotation = AppAnnotationService.up_insert_app_annotation_from_message(args, app_model.id)
  154. return annotation
  155. class MessageAnnotationCountApi(Resource):
  156. @setup_required
  157. @login_required
  158. @account_initialization_required
  159. @get_app_model
  160. def get(self, app_model):
  161. count = db.session.query(MessageAnnotation).where(MessageAnnotation.app_id == app_model.id).count()
  162. return {"count": count}
  163. class MessageSuggestedQuestionApi(Resource):
  164. @setup_required
  165. @login_required
  166. @account_initialization_required
  167. @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT])
  168. def get(self, app_model, message_id):
  169. message_id = str(message_id)
  170. try:
  171. questions = MessageService.get_suggested_questions_after_answer(
  172. app_model=app_model, message_id=message_id, user=current_user, invoke_from=InvokeFrom.DEBUGGER
  173. )
  174. except MessageNotExistsError:
  175. raise NotFound("Message not found")
  176. except ConversationNotExistsError:
  177. raise NotFound("Conversation not found")
  178. except ProviderTokenNotInitError as ex:
  179. raise ProviderNotInitializeError(ex.description)
  180. except QuotaExceededError:
  181. raise ProviderQuotaExceededError()
  182. except ModelCurrentlyNotSupportError:
  183. raise ProviderModelCurrentlyNotSupportError()
  184. except InvokeError as e:
  185. raise CompletionRequestError(e.description)
  186. except SuggestedQuestionsAfterAnswerDisabledError:
  187. raise AppSuggestedQuestionsAfterAnswerDisabledError()
  188. except Exception:
  189. logger.exception("internal server error.")
  190. raise InternalServerError()
  191. return {"data": questions}
  192. class MessageApi(Resource):
  193. @setup_required
  194. @login_required
  195. @account_initialization_required
  196. @get_app_model
  197. @marshal_with(message_detail_fields)
  198. def get(self, app_model, message_id):
  199. message_id = str(message_id)
  200. message = db.session.query(Message).where(Message.id == message_id, Message.app_id == app_model.id).first()
  201. if not message:
  202. raise NotFound("Message Not Exists.")
  203. return message
  204. api.add_resource(MessageSuggestedQuestionApi, "/apps/<uuid:app_id>/chat-messages/<uuid:message_id>/suggested-questions")
  205. api.add_resource(ChatMessageListApi, "/apps/<uuid:app_id>/chat-messages", endpoint="console_chat_messages")
  206. api.add_resource(MessageFeedbackApi, "/apps/<uuid:app_id>/feedbacks")
  207. api.add_resource(MessageAnnotationApi, "/apps/<uuid:app_id>/annotations")
  208. api.add_resource(MessageAnnotationCountApi, "/apps/<uuid:app_id>/annotations/count")
  209. api.add_resource(MessageApi, "/apps/<uuid:app_id>/messages/<uuid:message_id>", endpoint="console_message")