message.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. # -*- coding:utf-8 -*-
  2. import logging
  3. from flask_login import current_user
  4. from flask_restful import reqparse, fields, marshal_with
  5. from flask_restful.inputs import int_range
  6. from werkzeug.exceptions import NotFound, InternalServerError
  7. import services
  8. from controllers.console import api
  9. from controllers.console.app.error import ProviderNotInitializeError, \
  10. ProviderQuotaExceededError, ProviderModelCurrentlyNotSupportError, CompletionRequestError
  11. from controllers.console.explore.error import AppSuggestedQuestionsAfterAnswerDisabledError
  12. from controllers.console.universal_chat.wraps import UniversalChatResource
  13. from core.llm.error import LLMRateLimitError, LLMBadRequestError, LLMAuthorizationError, LLMAPIConnectionError, \
  14. ProviderTokenNotInitError, LLMAPIUnavailableError, QuotaExceededError, ModelCurrentlyNotSupportError
  15. from libs.helper import uuid_value, TimestampField
  16. from services.errors.conversation import ConversationNotExistsError
  17. from services.errors.message import MessageNotExistsError, SuggestedQuestionsAfterAnswerDisabledError
  18. from services.message_service import MessageService
  19. class UniversalChatMessageListApi(UniversalChatResource):
  20. feedback_fields = {
  21. 'rating': fields.String
  22. }
  23. agent_thought_fields = {
  24. 'id': fields.String,
  25. 'chain_id': fields.String,
  26. 'message_id': fields.String,
  27. 'position': fields.Integer,
  28. 'thought': fields.String,
  29. 'tool': fields.String,
  30. 'tool_input': fields.String,
  31. 'created_at': TimestampField
  32. }
  33. message_fields = {
  34. 'id': fields.String,
  35. 'conversation_id': fields.String,
  36. 'inputs': fields.Raw,
  37. 'query': fields.String,
  38. 'answer': fields.String,
  39. 'feedback': fields.Nested(feedback_fields, attribute='user_feedback', allow_null=True),
  40. 'created_at': TimestampField,
  41. 'agent_thoughts': fields.List(fields.Nested(agent_thought_fields))
  42. }
  43. message_infinite_scroll_pagination_fields = {
  44. 'limit': fields.Integer,
  45. 'has_more': fields.Boolean,
  46. 'data': fields.List(fields.Nested(message_fields))
  47. }
  48. @marshal_with(message_infinite_scroll_pagination_fields)
  49. def get(self, universal_app):
  50. app_model = universal_app
  51. parser = reqparse.RequestParser()
  52. parser.add_argument('conversation_id', required=True, type=uuid_value, location='args')
  53. parser.add_argument('first_id', type=uuid_value, location='args')
  54. parser.add_argument('limit', type=int_range(1, 100), required=False, default=20, location='args')
  55. args = parser.parse_args()
  56. try:
  57. return MessageService.pagination_by_first_id(app_model, current_user,
  58. args['conversation_id'], args['first_id'], args['limit'])
  59. except services.errors.conversation.ConversationNotExistsError:
  60. raise NotFound("Conversation Not Exists.")
  61. except services.errors.message.FirstMessageNotExistsError:
  62. raise NotFound("First Message Not Exists.")
  63. class UniversalChatMessageFeedbackApi(UniversalChatResource):
  64. def post(self, universal_app, message_id):
  65. app_model = universal_app
  66. message_id = str(message_id)
  67. parser = reqparse.RequestParser()
  68. parser.add_argument('rating', type=str, choices=['like', 'dislike', None], location='json')
  69. args = parser.parse_args()
  70. try:
  71. MessageService.create_feedback(app_model, message_id, current_user, args['rating'])
  72. except services.errors.message.MessageNotExistsError:
  73. raise NotFound("Message Not Exists.")
  74. return {'result': 'success'}
  75. class UniversalChatMessageSuggestedQuestionApi(UniversalChatResource):
  76. def get(self, universal_app, message_id):
  77. app_model = universal_app
  78. message_id = str(message_id)
  79. try:
  80. questions = MessageService.get_suggested_questions_after_answer(
  81. app_model=app_model,
  82. user=current_user,
  83. message_id=message_id
  84. )
  85. except MessageNotExistsError:
  86. raise NotFound("Message not found")
  87. except ConversationNotExistsError:
  88. raise NotFound("Conversation not found")
  89. except SuggestedQuestionsAfterAnswerDisabledError:
  90. raise AppSuggestedQuestionsAfterAnswerDisabledError()
  91. except ProviderTokenNotInitError:
  92. raise ProviderNotInitializeError()
  93. except QuotaExceededError:
  94. raise ProviderQuotaExceededError()
  95. except ModelCurrentlyNotSupportError:
  96. raise ProviderModelCurrentlyNotSupportError()
  97. except (LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
  98. LLMRateLimitError, LLMAuthorizationError) as e:
  99. raise CompletionRequestError(str(e))
  100. except Exception:
  101. logging.exception("internal server error.")
  102. raise InternalServerError()
  103. return {'data': questions}
  104. api.add_resource(UniversalChatMessageListApi, '/universal-chat/messages')
  105. api.add_resource(UniversalChatMessageFeedbackApi, '/universal-chat/messages/<uuid:message_id>/feedbacks')
  106. api.add_resource(UniversalChatMessageSuggestedQuestionApi, '/universal-chat/messages/<uuid:message_id>/suggested-questions')