Team Ai
Apppublic

Underground-Digital/Workflow-Engine

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
message.py174 linesDownload Raw Back to explore
1import logging2 3from flask_login import current_user4from flask_restful import marshal_with, reqparse5from flask_restful.inputs import int_range6from werkzeug.exceptions import InternalServerError, NotFound7 8import services9from controllers.console import api10from controllers.console.app.error import (11    AppMoreLikeThisDisabledError,12    CompletionRequestError,13    ProviderModelCurrentlyNotSupportError,14    ProviderNotInitializeError,15    ProviderQuotaExceededError,16)17from controllers.console.explore.error import (18    AppSuggestedQuestionsAfterAnswerDisabledError,19    NotChatAppError,20    NotCompletionAppError,21)22from controllers.console.explore.wraps import InstalledAppResource23from core.app.entities.app_invoke_entities import InvokeFrom24from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError25from core.model_runtime.errors.invoke import InvokeError26from fields.message_fields import message_infinite_scroll_pagination_fields27from libs import helper28from libs.helper import uuid_value29from models.model import AppMode30from services.app_generate_service import AppGenerateService31from services.errors.app import MoreLikeThisDisabledError32from services.errors.conversation import ConversationNotExistsError33from services.errors.message import MessageNotExistsError, SuggestedQuestionsAfterAnswerDisabledError34from services.message_service import MessageService35 36 37class MessageListApi(InstalledAppResource):38    @marshal_with(message_infinite_scroll_pagination_fields)39    def get(self, installed_app):40        app_model = installed_app.app41 42        app_mode = AppMode.value_of(app_model.mode)43        if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:44            raise NotChatAppError()45 46        parser = reqparse.RequestParser()47        parser.add_argument("conversation_id", required=True, type=uuid_value, location="args")48        parser.add_argument("first_id", type=uuid_value, location="args")49        parser.add_argument("limit", type=int_range(1, 100), required=False, default=20, location="args")50        args = parser.parse_args()51 52        try:53            return MessageService.pagination_by_first_id(54                app_model, current_user, args["conversation_id"], args["first_id"], args["limit"], "desc"55            )56        except services.errors.conversation.ConversationNotExistsError:57            raise NotFound("Conversation Not Exists.")58        except services.errors.message.FirstMessageNotExistsError:59            raise NotFound("First Message Not Exists.")60 61 62class MessageFeedbackApi(InstalledAppResource):63    def post(self, installed_app, message_id):64        app_model = installed_app.app65 66        message_id = str(message_id)67 68        parser = reqparse.RequestParser()69        parser.add_argument("rating", type=str, choices=["like", "dislike", None], location="json")70        args = parser.parse_args()71 72        try:73            MessageService.create_feedback(app_model, message_id, current_user, args["rating"])74        except services.errors.message.MessageNotExistsError:75            raise NotFound("Message Not Exists.")76 77        return {"result": "success"}78 79 80class MessageMoreLikeThisApi(InstalledAppResource):81    def get(self, installed_app, message_id):82        app_model = installed_app.app83        if app_model.mode != "completion":84            raise NotCompletionAppError()85 86        message_id = str(message_id)87 88        parser = reqparse.RequestParser()89        parser.add_argument(90            "response_mode", type=str, required=True, choices=["blocking", "streaming"], location="args"91        )92        args = parser.parse_args()93 94        streaming = args["response_mode"] == "streaming"95 96        try:97            response = AppGenerateService.generate_more_like_this(98                app_model=app_model,99                user=current_user,100                message_id=message_id,101                invoke_from=InvokeFrom.EXPLORE,102                streaming=streaming,103            )104            return helper.compact_generate_response(response)105        except MessageNotExistsError:106            raise NotFound("Message Not Exists.")107        except MoreLikeThisDisabledError:108            raise AppMoreLikeThisDisabledError()109        except ProviderTokenNotInitError as ex:110            raise ProviderNotInitializeError(ex.description)111        except QuotaExceededError:112            raise ProviderQuotaExceededError()113        except ModelCurrentlyNotSupportError:114            raise ProviderModelCurrentlyNotSupportError()115        except InvokeError as e:116            raise CompletionRequestError(e.description)117        except ValueError as e:118            raise e119        except Exception:120            logging.exception("internal server error.")121            raise InternalServerError()122 123 124class MessageSuggestedQuestionApi(InstalledAppResource):125    def get(self, installed_app, message_id):126        app_model = installed_app.app127        app_mode = AppMode.value_of(app_model.mode)128        if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:129            raise NotChatAppError()130 131        message_id = str(message_id)132 133        try:134            questions = MessageService.get_suggested_questions_after_answer(135                app_model=app_model, user=current_user, message_id=message_id, invoke_from=InvokeFrom.EXPLORE136            )137        except MessageNotExistsError:138            raise NotFound("Message not found")139        except ConversationNotExistsError:140            raise NotFound("Conversation not found")141        except SuggestedQuestionsAfterAnswerDisabledError:142            raise AppSuggestedQuestionsAfterAnswerDisabledError()143        except ProviderTokenNotInitError as ex:144            raise ProviderNotInitializeError(ex.description)145        except QuotaExceededError:146            raise ProviderQuotaExceededError()147        except ModelCurrentlyNotSupportError:148            raise ProviderModelCurrentlyNotSupportError()149        except InvokeError as e:150            raise CompletionRequestError(e.description)151        except Exception:152            logging.exception("internal server error.")153            raise InternalServerError()154 155        return {"data": questions}156 157 158api.add_resource(MessageListApi, "/installed-apps/<uuid:installed_app_id>/messages", endpoint="installed_app_messages")159api.add_resource(160    MessageFeedbackApi,161    "/installed-apps/<uuid:installed_app_id>/messages/<uuid:message_id>/feedbacks",162    endpoint="installed_app_message_feedback",163)164api.add_resource(165    MessageMoreLikeThisApi,166    "/installed-apps/<uuid:installed_app_id>/messages/<uuid:message_id>/more-like-this",167    endpoint="installed_app_more_like_this",168)169api.add_resource(170    MessageSuggestedQuestionApi,171    "/installed-apps/<uuid:installed_app_id>/messages/<uuid:message_id>/suggested-questions",172    endpoint="installed_app_suggested_question",173)174