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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. if len(history_messages) == args["limit"]:
  87. current_page_first_message = history_messages[-1]
  88. has_more = db.session.scalar(
  89. select(
  90. exists().where(
  91. Message.conversation_id == conversation.id,
  92. Message.created_at < current_page_first_message.created_at,
  93. Message.id != current_page_first_message.id,
  94. )
  95. )
  96. )
  97. history_messages = list(reversed(history_messages))
  98. return InfiniteScrollPagination(data=history_messages, limit=args["limit"], has_more=has_more)
  99. class MessageFeedbackApi(Resource):
  100. @setup_required
  101. @login_required
  102. @account_initialization_required
  103. @get_app_model
  104. def post(self, app_model):
  105. parser = reqparse.RequestParser()
  106. parser.add_argument("message_id", required=True, type=uuid_value, location="json")
  107. parser.add_argument("rating", type=str, choices=["like", "dislike", None], location="json")
  108. args = parser.parse_args()
  109. message_id = str(args["message_id"])
  110. message = db.session.query(Message).filter(Message.id == message_id, Message.app_id == app_model.id).first()
  111. if not message:
  112. raise NotFound("Message Not Exists.")
  113. feedback = message.admin_feedback
  114. if not args["rating"] and feedback:
  115. db.session.delete(feedback)
  116. elif args["rating"] and feedback:
  117. feedback.rating = args["rating"]
  118. elif not args["rating"] and not feedback:
  119. raise ValueError("rating cannot be None when feedback not exists")
  120. else:
  121. feedback = MessageFeedback(
  122. app_id=app_model.id,
  123. conversation_id=message.conversation_id,
  124. message_id=message.id,
  125. rating=args["rating"],
  126. from_source="admin",
  127. from_account_id=current_user.id,
  128. )
  129. db.session.add(feedback)
  130. db.session.commit()
  131. return {"result": "success"}
  132. class MessageAnnotationApi(Resource):
  133. @setup_required
  134. @login_required
  135. @account_initialization_required
  136. @cloud_edition_billing_resource_check("annotation")
  137. @get_app_model
  138. @marshal_with(annotation_fields)
  139. def post(self, app_model):
  140. if not current_user.is_editor:
  141. raise Forbidden()
  142. parser = reqparse.RequestParser()
  143. parser.add_argument("message_id", required=False, type=uuid_value, location="json")
  144. parser.add_argument("question", required=True, type=str, location="json")
  145. parser.add_argument("answer", required=True, type=str, location="json")
  146. parser.add_argument("annotation_reply", required=False, type=dict, location="json")
  147. args = parser.parse_args()
  148. annotation = AppAnnotationService.up_insert_app_annotation_from_message(args, app_model.id)
  149. return annotation
  150. class MessageAnnotationCountApi(Resource):
  151. @setup_required
  152. @login_required
  153. @account_initialization_required
  154. @get_app_model
  155. def get(self, app_model):
  156. count = db.session.query(MessageAnnotation).where(MessageAnnotation.app_id == app_model.id).count()
  157. return {"count": count}
  158. class MessageSuggestedQuestionApi(Resource):
  159. @setup_required
  160. @login_required
  161. @account_initialization_required
  162. @get_app_model(mode=[AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT])
  163. def get(self, app_model, message_id):
  164. message_id = str(message_id)
  165. try:
  166. questions = MessageService.get_suggested_questions_after_answer(
  167. app_model=app_model, message_id=message_id, user=current_user, invoke_from=InvokeFrom.DEBUGGER
  168. )
  169. except MessageNotExistsError:
  170. raise NotFound("Message not found")
  171. except ConversationNotExistsError:
  172. raise NotFound("Conversation not found")
  173. except ProviderTokenNotInitError as ex:
  174. raise ProviderNotInitializeError(ex.description)
  175. except QuotaExceededError:
  176. raise ProviderQuotaExceededError()
  177. except ModelCurrentlyNotSupportError:
  178. raise ProviderModelCurrentlyNotSupportError()
  179. except InvokeError as e:
  180. raise CompletionRequestError(e.description)
  181. except SuggestedQuestionsAfterAnswerDisabledError:
  182. raise AppSuggestedQuestionsAfterAnswerDisabledError()
  183. except Exception:
  184. logger.exception("internal server error.")
  185. raise InternalServerError()
  186. return {"data": questions}
  187. class MessageApi(Resource):
  188. @setup_required
  189. @login_required
  190. @account_initialization_required
  191. @get_app_model
  192. @marshal_with(message_detail_fields)
  193. def get(self, app_model, message_id):
  194. message_id = str(message_id)
  195. message = db.session.query(Message).where(Message.id == message_id, Message.app_id == app_model.id).first()
  196. if not message:
  197. raise NotFound("Message Not Exists.")
  198. return message
  199. api.add_resource(MessageSuggestedQuestionApi, "/apps/<uuid:app_id>/chat-messages/<uuid:message_id>/suggested-questions")
  200. api.add_resource(ChatMessageListApi, "/apps/<uuid:app_id>/chat-messages", endpoint="console_chat_messages")
  201. api.add_resource(MessageFeedbackApi, "/apps/<uuid:app_id>/feedbacks")
  202. api.add_resource(MessageAnnotationApi, "/apps/<uuid:app_id>/annotations")
  203. api.add_resource(MessageAnnotationCountApi, "/apps/<uuid:app_id>/annotations/count")
  204. api.add_resource(MessageApi, "/apps/<uuid:app_id>/messages/<uuid:message_id>", endpoint="console_message")