chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,184 @@
"""Installed-app audio admission, error translation, and response serialization."""
import logging
from collections.abc import Callable
from functools import wraps
from http import HTTPStatus
from flask import Response, request
from flask_restx import Resource
from controllers.common.audio_response import audio_binary_response
from controllers.common.controller_schemas import TextToAudioPayload
from controllers.common.errors import InternalServerError
from controllers.common.fields import AudioBinaryResponse, AudioTranscriptResponse
from controllers.common.schema import register_response_schema_models, register_schema_model
from controllers.console import console_ns
from controllers.console.app.error import (
AppUnavailableError,
AudioTooLargeError,
CompletionRequestError,
NoAudioUploadedError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderNotSupportSpeechToTextError,
ProviderNotSupportTextToSpeechError,
ProviderQuotaExceededError,
SpeechToTextDisabledError,
UnsupportedAudioTypeError,
)
from controllers.console.explore.error import AgentVersionNotFoundHTTPError
from controllers.console.explore.installed_app_admission import get_installed_app
from controllers.console.flask_admission import console_account_admission
from controllers.console.wraps import model_validate
from core.base.tts.audio_mime import SUPPORTED_TTS_AUDIO_MIME_TYPES
from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError
from extensions.ext_application_services import application_services
from graphon.model_runtime.errors.invoke import InvokeError
from libs.exception import BaseHTTPException
from libs.external_api import error_responses
from libs.flask_restx_compat import BINARY_RESPONSE_MEDIA_TYPES_VENDOR_KEY
from libs.helper import dump_response
from machinery.context import RequestContext
from services.agent.errors import AgentVersionNotFoundError
from services.app_definition_query_service import AppDefinitionUnavailableError
from services.audio_types import AudioAppRef, AudioUpload
from services.errors.app_model_config import AppModelConfigBrokenError
from services.errors.audio import (
AudioTooLargeServiceError,
NoAudioUploadedServiceError,
ProviderNotSupportSpeechToTextServiceError,
ProviderNotSupportTextToSpeechServiceError,
SpeechToTextDisabledServiceError,
UnsupportedAudioTypeServiceError,
)
from services.installed_app_access_service import InstalledAppRef
logger = logging.getLogger(__name__)
register_schema_model(console_ns, TextToAudioPayload)
register_response_schema_models(console_ns, AudioBinaryResponse, AudioTranscriptResponse)
def _audio_errors[**P, R](view: Callable[P, R]) -> Callable[P, R]:
@wraps(view)
def decorated(*args: P.args, **kwargs: P.kwargs) -> R:
try:
return view(*args, **kwargs)
except AppDefinitionUnavailableError as error:
raise AppUnavailableError() from error
except AppModelConfigBrokenError as error:
logger.exception("App model config broken")
raise AppUnavailableError() from error
except NoAudioUploadedServiceError as error:
raise NoAudioUploadedError() from error
except AudioTooLargeServiceError as error:
raise AudioTooLargeError(str(error)) from error
except UnsupportedAudioTypeServiceError as error:
raise UnsupportedAudioTypeError() from error
except ProviderNotSupportSpeechToTextServiceError as error:
raise ProviderNotSupportSpeechToTextError() from error
except ProviderNotSupportTextToSpeechServiceError as error:
raise ProviderNotSupportTextToSpeechError() from error
except SpeechToTextDisabledServiceError as error:
raise SpeechToTextDisabledError() from error
except ProviderTokenNotInitError as error:
raise ProviderNotInitializeError(error.description) from error
except QuotaExceededError as error:
raise ProviderQuotaExceededError() from error
except ModelCurrentlyNotSupportError as error:
raise ProviderModelCurrentlyNotSupportError() from error
except InvokeError as error:
raise CompletionRequestError(error.description) from error
except AgentVersionNotFoundError as error:
raise AgentVersionNotFoundHTTPError() from error
except (BaseHTTPException, ValueError):
raise
except Exception as error:
logger.exception("Installed-app audio operation failed")
raise InternalServerError() from error
return decorated
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/audio-to-text",
endpoint="installed_app_audio",
)
class ChatAudioApi(Resource):
@error_responses(
AgentVersionNotFoundHTTPError,
AppUnavailableError,
AudioTooLargeError,
CompletionRequestError,
NoAudioUploadedError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderNotSupportSpeechToTextError,
ProviderQuotaExceededError,
SpeechToTextDisabledError,
UnsupportedAudioTypeError,
)
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[AudioTranscriptResponse.__name__])
@console_account_admission()
@get_installed_app
def post(self, request_context: RequestContext, installed_app: InstalledAppRef) -> dict[str, object]:
# Let Flask handle multipart parsing errors before mapping audio operation failures.
file = request.files.get("file")
audio = AudioUpload(stream=file.stream, mime_type=file.mimetype) if file is not None else None
return self._transcribe(installed_app, audio)
@_audio_errors
def _transcribe(self, installed_app: InstalledAppRef, audio: AudioUpload | None) -> dict[str, object]:
"""Transcribe an upload; None lets the audio service report a missing file."""
transcript = application_services().app_audio.transcript_asr(
app=AudioAppRef(
app_id=installed_app.app_id,
tenant_id=installed_app.app_owner_tenant_id,
app_mode=installed_app.app_mode,
),
audio=audio,
)
return dump_response(AudioTranscriptResponse, transcript)
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/text-to-audio",
endpoint="installed_app_text",
)
class ChatTextApi(Resource):
@error_responses(
AgentVersionNotFoundHTTPError,
AppUnavailableError,
CompletionRequestError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderNotSupportTextToSpeechError,
ProviderQuotaExceededError,
)
@console_ns.expect(console_ns.models[TextToAudioPayload.__name__])
@console_ns.doc(
produces=list(SUPPORTED_TTS_AUDIO_MIME_TYPES),
vendor={BINARY_RESPONSE_MEDIA_TYPES_VENDOR_KEY: list(SUPPORTED_TTS_AUDIO_MIME_TYPES)},
)
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[AudioBinaryResponse.__name__])
@console_account_admission()
@get_installed_app
@model_validate(TextToAudioPayload)
@_audio_errors
def post(
self, payload: TextToAudioPayload, request_context: RequestContext, installed_app: InstalledAppRef
) -> Response | None:
output = application_services().app_audio.transcript_tts(
app=AudioAppRef(
app_id=installed_app.app_id,
tenant_id=installed_app.app_owner_tenant_id,
app_mode=installed_app.app_mode,
),
account_id=request_context.account_id,
text=payload.text,
voice=payload.voice,
message_id=payload.message_id,
)
# response-contract:ignore audio_binary_response
return audio_binary_response(output)
@@ -0,0 +1,72 @@
from datetime import datetime
from http import HTTPStatus
from typing import cast
from flask_restx import Namespace, Resource
from pydantic import BaseModel, Field, RootModel, field_validator
from controllers.common.schema import query_params_from_model, register_response_schema_models
from controllers.console import api
from controllers.console.wraps import model_validate
from extensions.ext_application_services import application_services
from fields.base import ResponseModel
from libs.helper import dump_response
from models.enums import BannerStatus
class BannerListQuery(BaseModel):
language: str = Field(default="en-US", description="Banner language")
class BannerContentResponse(ResponseModel):
category: str
title: str = Field(min_length=1)
description: str
image_source: str = Field(
min_length=1,
validation_alias="img-src",
serialization_alias="img-src",
)
class BannerResponse(ResponseModel):
id: str
content: BannerContentResponse
link: str
sort: int
status: BannerStatus
created_at: str
@field_validator("created_at", mode="before")
@classmethod
def serialize_created_at(cls, value: datetime | str) -> str:
if isinstance(value, datetime):
return value.isoformat()
return value
class BannerListResponse(RootModel[list[BannerResponse]]):
root: list[BannerResponse]
register_response_schema_models(
cast(Namespace, api),
BannerContentResponse,
BannerResponse,
BannerListResponse,
)
class BannerApi(Resource):
"""Resource for banner list."""
@api.doc(params=query_params_from_model(BannerListQuery))
@api.response(HTTPStatus.OK, "Success", api.models[BannerListResponse.__name__])
@model_validate(BannerListQuery)
def get(self, req_data: BannerListQuery):
"""Get banner list."""
banners = application_services().explore_banner_queries.list_for_language(req_data.language)
return dump_response(BannerListResponse, banners)
api.add_resource(BannerApi, "/explore/banners")
@@ -0,0 +1,271 @@
import logging
from http import HTTPStatus
from typing import Any, Literal
from uuid import UUID
from flask import Response
from flask_restx import Resource
from pydantic import BaseModel, Field, field_validator
import services
from controllers.common.errors import InternalServerError, NotFoundError, UnauthorizedError
from controllers.common.fields import SimpleResultResponse
from controllers.common.schema import register_response_schema_models, register_schema_models
from controllers.console import console_ns
from controllers.console.app.error import (
AppUnavailableError,
CompletionRequestError,
ConversationCompletedError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
)
from controllers.console.explore.error import NotChatAppError, NotCompletionAppError
from controllers.console.explore.installed_app_admission import get_installed_app
from controllers.console.flask_admission import console_account_admission
from controllers.console.wraps import model_validate
from controllers.web.error import InvokeRateLimitError as InvokeRateLimitHttpError
from core.app.entities.app_invoke_entities import InvokeFrom
from core.errors.error import (
ModelCurrentlyNotSupportError,
ProviderTokenNotInitError,
QuotaExceededError,
)
from extensions.ext_application_services import application_services
from graphon.model_runtime.errors.invoke import InvokeError
from libs import helper
from libs.external_api import error_responses
from machinery.context import RequestContext
from models.enums import CreatorUserRole
from models.model import AppMode
from services.account_errors import AccountNotFoundError
from services.app_definition_query_service import AppDefinitionUnavailableError
from services.errors.llm import InvokeRateLimitError
from services.installed_app_access_service import InstalledAppNotFoundError, InstalledAppRef
from services.installed_app_generation_service import InstalledAppNotChatError, InstalledAppNotCompletionError
logger = logging.getLogger(__name__)
class CompletionMessageExplorePayload(BaseModel):
inputs: dict[str, Any]
query: str = ""
files: list[dict[str, Any]] | None = Field(default=None)
response_mode: Literal["blocking", "streaming"] | None = None
retriever_from: str = Field(default="explore_app")
class ChatMessageExplorePayload(BaseModel):
inputs: dict[str, Any]
query: str
files: list[dict[str, Any]] | None = Field(default=None)
conversation_id: str | None = None
parent_message_id: str | None = None
retriever_from: str = Field(default="explore_app")
@field_validator("conversation_id", "parent_message_id", mode="before")
@classmethod
def normalize_uuid(cls, value: str | UUID | None) -> str | None:
"""
Accept blank IDs and validate UUID format when provided.
"""
if not value:
return None
try:
return helper.uuid_value(value)
except ValueError as exc:
raise ValueError("must be a valid UUID") from exc
register_schema_models(console_ns, CompletionMessageExplorePayload, ChatMessageExplorePayload)
register_response_schema_models(console_ns, SimpleResultResponse)
# define completion api for user
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/completion-messages",
endpoint="installed_app_completion",
)
class CompletionApi(Resource):
@error_responses(
AppUnavailableError,
CompletionRequestError,
NotCompletionAppError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
)
@console_ns.expect(console_ns.models[CompletionMessageExplorePayload.__name__])
@console_ns.response(HTTPStatus.OK, "Success")
@console_account_admission()
@get_installed_app
@model_validate(CompletionMessageExplorePayload)
def post(
self,
req_data: CompletionMessageExplorePayload,
request_context: RequestContext,
installed_app: InstalledAppRef,
) -> Response:
try:
response = application_services().installed_apps.generation.generate_completion(
installed_app=installed_app,
account_id=request_context.account_id,
args=req_data.model_dump(exclude_none=True),
)
# response-contract:ignore compact_generate_response
return helper.compact_generate_response(response)
except AppDefinitionUnavailableError:
raise AppUnavailableError() from None
except InstalledAppNotCompletionError:
raise NotCompletionAppError() from None
except InstalledAppNotFoundError:
raise NotFoundError("Installed app not found") from None
except AccountNotFoundError:
raise UnauthorizedError("Account no longer exists.") from None
except services.errors.conversation.ConversationNotExistsError as caught_error:
raise NotFoundError("Conversation Not Exists.") from caught_error
except services.errors.conversation.ConversationCompletedError as caught_error:
raise ConversationCompletedError() from caught_error
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
logger.exception("App model config broken.")
raise AppUnavailableError() from caught_error
except ProviderTokenNotInitError as ex:
raise ProviderNotInitializeError(ex.description) from ex
except QuotaExceededError as caught_error:
raise ProviderQuotaExceededError() from caught_error
except ModelCurrentlyNotSupportError as caught_error:
raise ProviderModelCurrentlyNotSupportError() from caught_error
except InvokeError as e:
raise CompletionRequestError(e.description) from e
except ValueError as e:
raise e
except Exception as caught_error:
logger.exception("internal server error.")
raise InternalServerError() from caught_error
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/completion-messages/<string:task_id>/stop",
endpoint="installed_app_stop_completion",
)
class CompletionStopApi(Resource):
@error_responses(NotCompletionAppError)
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[SimpleResultResponse.__name__])
@console_account_admission()
@get_installed_app
def post(
self, request_context: RequestContext, installed_app: InstalledAppRef, task_id: str
) -> tuple[dict[str, object], int]:
app_mode = installed_app.app_mode
if app_mode != AppMode.COMPLETION:
raise NotCompletionAppError()
application_services().app_tasks.stop_task(
task_id=task_id,
invoke_from=InvokeFrom.EXPLORE,
user_id=request_context.account_id,
)
return SimpleResultResponse(result="success").model_dump(mode="json"), HTTPStatus.OK
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/chat-messages",
endpoint="installed_app_chat_completion",
)
class ChatApi(Resource):
@error_responses(
AppUnavailableError,
CompletionRequestError,
InvokeRateLimitHttpError,
NotChatAppError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
)
@console_ns.expect(console_ns.models[ChatMessageExplorePayload.__name__])
@console_ns.response(HTTPStatus.OK, "Success")
@console_account_admission()
@get_installed_app
@model_validate(ChatMessageExplorePayload)
def post(
self,
req_data: ChatMessageExplorePayload,
request_context: RequestContext,
installed_app: InstalledAppRef,
) -> Response:
try:
response = application_services().installed_apps.generation.generate_chat(
installed_app=installed_app,
account_id=request_context.account_id,
args=req_data.model_dump(exclude_none=True),
)
# response-contract:ignore compact_generate_response
return helper.compact_generate_response(response)
except AppDefinitionUnavailableError:
raise AppUnavailableError() from None
except InstalledAppNotChatError:
raise NotChatAppError() from None
except InstalledAppNotFoundError:
raise NotFoundError("Installed app not found") from None
except AccountNotFoundError:
raise UnauthorizedError("Account no longer exists.") from None
except services.errors.conversation.ConversationNotExistsError as caught_error:
raise NotFoundError("Conversation Not Exists.") from caught_error
except services.errors.conversation.ConversationCompletedError as caught_error:
raise ConversationCompletedError() from caught_error
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
logger.exception("App model config broken.")
raise AppUnavailableError() from caught_error
except ProviderTokenNotInitError as ex:
raise ProviderNotInitializeError(ex.description) from ex
except QuotaExceededError as caught_error:
raise ProviderQuotaExceededError() from caught_error
except ModelCurrentlyNotSupportError as caught_error:
raise ProviderModelCurrentlyNotSupportError() from caught_error
except InvokeError as e:
raise CompletionRequestError(e.description) from e
except InvokeRateLimitError as ex:
raise InvokeRateLimitHttpError(ex.description) from ex
except ValueError as e:
raise e
except Exception as caught_error:
logger.exception("internal server error.")
raise InternalServerError() from caught_error
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/chat-messages/<string:task_id>/stop",
endpoint="installed_app_stop_chat_completion",
)
class ChatStopApi(Resource):
@error_responses(NotChatAppError)
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[SimpleResultResponse.__name__])
@console_account_admission()
@get_installed_app
def post(
self, request_context: RequestContext, installed_app: InstalledAppRef, task_id: str
) -> tuple[dict[str, object], int]:
app_mode = AppMode.value_of(installed_app.app_mode)
if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:
raise NotChatAppError()
if app_mode == AppMode.ADVANCED_CHAT:
application_services().app_tasks.stop_workflow_task(
tenant_id=installed_app.app_owner_tenant_id,
app_id=installed_app.app_id,
task_id=task_id,
app_mode=app_mode,
owner=(CreatorUserRole.ACCOUNT, request_context.account_id),
)
else:
application_services().app_tasks.stop_task(
task_id=task_id,
invoke_from=InvokeFrom.EXPLORE,
user_id=request_context.account_id,
)
return SimpleResultResponse(result="success").model_dump(mode="json"), HTTPStatus.OK
@@ -0,0 +1,197 @@
"""HTTP admission and response contracts for installed-app conversations."""
from collections.abc import Callable
from functools import wraps
from http import HTTPStatus
from uuid import UUID
from flask_restx import Resource
from pydantic import BaseModel, Field, field_validator
from controllers.common.controller_schemas import ConversationRenamePayload
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
from controllers.console import console_ns
from controllers.console.explore.error import (
ConversationCursorNotFoundHTTPError,
ConversationFirstMessageNotFoundHTTPError,
ConversationNameRequiredHTTPError,
ConversationNotFoundHTTPError,
InstalledAppNotFoundHTTPError,
NotChatAppError,
)
from controllers.console.explore.installed_app_admission import get_installed_app
from controllers.console.flask_admission import console_account_admission
from controllers.console.wraps import model_validate
from extensions.ext_application_services import application_services
from fields.conversation_fields import ConversationInfiniteScrollPagination, ResultResponse, SimpleConversation
from libs.external_api import error_responses
from libs.helper import UUIDStrOrEmpty, dump_response
from machinery.context import RequestContext
from services.conversation_name_service import ConversationNameRequiredError
from services.errors.conversation import ConversationNotExistsError, LastConversationNotExistsError
from services.errors.message import MessageNotExistsError
from services.installed_app_access_service import InstalledAppNotFoundError, InstalledAppRef
from services.installed_app_conversation_service import ConversationNotChatAppError
class ConversationListQuery(BaseModel):
last_id: UUIDStrOrEmpty | None = None
limit: int = Field(default=20, ge=1, le=100)
pinned: bool | None = None
@field_validator("limit", mode="before")
@classmethod
def parse_limit(cls, value: object) -> object:
# Preserve request.args.get(..., default=20, type=int) coercion.
if isinstance(value, str):
try:
return int(value)
except ValueError:
return 20
return value
@field_validator("pinned", mode="before")
@classmethod
def parse_pinned(cls, value: object) -> object:
# Existing callers use the literal query string "true" for pinned items.
return value == "true" if isinstance(value, str) else value
register_schema_models(console_ns, ConversationListQuery, ConversationRenamePayload)
register_response_schema_models(console_ns, ConversationInfiniteScrollPagination, ResultResponse, SimpleConversation)
def _conversation_errors[**P, R](view: Callable[P, R]) -> Callable[P, R]:
"""Translate the shared conversation use-case errors at the Console boundary."""
@wraps(view)
def decorated(*args: P.args, **kwargs: P.kwargs) -> R:
try:
return view(*args, **kwargs)
except InstalledAppNotFoundError as error:
raise InstalledAppNotFoundHTTPError() from error
except ConversationNotChatAppError as error:
raise NotChatAppError() from error
except ConversationNotExistsError as error:
raise ConversationNotFoundHTTPError() from error
except LastConversationNotExistsError as error:
raise ConversationCursorNotFoundHTTPError() from error
except MessageNotExistsError as error:
raise ConversationFirstMessageNotFoundHTTPError() from error
except ConversationNameRequiredError as error:
raise ConversationNameRequiredHTTPError() from error
return decorated
@console_ns.route("/installed-apps/<uuid:installed_app_id>/conversations", endpoint="installed_app_conversations")
class ConversationListApi(Resource):
@error_responses(ConversationCursorNotFoundHTTPError, NotChatAppError)
@console_ns.doc(params=query_params_from_model(ConversationListQuery))
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[ConversationInfiniteScrollPagination.__name__])
@console_account_admission()
@get_installed_app
@model_validate(ConversationListQuery)
@_conversation_errors
def get(
self, query: ConversationListQuery, request_context: RequestContext, installed_app: InstalledAppRef
) -> dict[str, object]:
page = application_services().installed_apps.conversations.get_page(
installed_app=installed_app,
account_id=request_context.account_id,
last_id=query.last_id or None,
limit=query.limit,
pinned=query.pinned,
)
return dump_response(ConversationInfiniteScrollPagination, page)
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/conversations/<uuid:c_id>", endpoint="installed_app_conversation"
)
class ConversationApi(Resource):
@error_responses(ConversationNotFoundHTTPError, NotChatAppError)
@console_ns.response(HTTPStatus.NO_CONTENT, "Conversation deleted successfully")
@console_account_admission()
@get_installed_app
@_conversation_errors
def delete(self, request_context: RequestContext, installed_app: InstalledAppRef, c_id: UUID) -> tuple[str, int]:
application_services().installed_apps.conversations.delete(
installed_app=installed_app, account_id=request_context.account_id, conversation_id=str(c_id)
)
return "", HTTPStatus.NO_CONTENT
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/conversations/<uuid:c_id>/name",
endpoint="installed_app_conversation_rename",
)
class ConversationRenameApi(Resource):
@error_responses(
ConversationFirstMessageNotFoundHTTPError,
ConversationNameRequiredHTTPError,
ConversationNotFoundHTTPError,
NotChatAppError,
)
@console_ns.expect(console_ns.models[ConversationRenamePayload.__name__])
@console_ns.response(
HTTPStatus.OK, "Conversation renamed successfully", console_ns.models[SimpleConversation.__name__]
)
@console_account_admission()
@get_installed_app
@model_validate(ConversationRenamePayload)
@_conversation_errors
def post(
self,
payload: ConversationRenamePayload,
request_context: RequestContext,
installed_app: InstalledAppRef,
c_id: UUID,
) -> dict[str, object]:
conversation = application_services().installed_apps.conversations.rename(
installed_app=installed_app,
account_id=request_context.account_id,
conversation_id=str(c_id),
name=payload.name,
auto_generate=payload.auto_generate,
)
return dump_response(SimpleConversation, conversation)
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/conversations/<uuid:c_id>/pin", endpoint="installed_app_conversation_pin"
)
class ConversationPinApi(Resource):
@error_responses(ConversationNotFoundHTTPError, NotChatAppError)
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[ResultResponse.__name__])
@console_account_admission()
@get_installed_app
@_conversation_errors
def patch(self, request_context: RequestContext, installed_app: InstalledAppRef, c_id: UUID) -> dict[str, object]:
application_services().installed_apps.conversations.set_pinned(
installed_app=installed_app,
account_id=request_context.account_id,
conversation_id=str(c_id),
is_pinned=True,
)
return dump_response(ResultResponse, {"result": "success"})
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/conversations/<uuid:c_id>/unpin",
endpoint="installed_app_conversation_unpin",
)
class ConversationUnPinApi(Resource):
@error_responses(ConversationNotFoundHTTPError, NotChatAppError)
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[ResultResponse.__name__])
@console_account_admission()
@get_installed_app
@_conversation_errors
def patch(self, request_context: RequestContext, installed_app: InstalledAppRef, c_id: UUID) -> dict[str, object]:
application_services().installed_apps.conversations.set_pinned(
installed_app=installed_app,
account_id=request_context.account_id,
conversation_id=str(c_id),
is_pinned=False,
)
return dump_response(ResultResponse, {"result": "success"})
@@ -0,0 +1,155 @@
from http import HTTPStatus
from core.logging.context import get_request_id
from libs.exception import BaseHTTPException
class AgentVersionNotFoundHTTPError(BaseHTTPException):
error_code = "agent_version_not_found_error"
description = "Agent config version not found."
code = HTTPStatus.NOT_FOUND
class InstalledAppHTTPError(BaseHTTPException):
"""A Console error with safe details and a request ID for troubleshooting."""
def __init__(self) -> None:
super().__init__()
details: dict[str, object] = {"request_id": get_request_id()}
self.data = {"code": self.error_code, "message": self.description, "status": self.code, "details": details}
class InstalledAppNotFoundHTTPError(InstalledAppHTTPError):
error_code = "installed_app_not_found"
description = "The app was not found in this workspace."
code = HTTPStatus.NOT_FOUND
class InstalledAppUnavailableHTTPError(InstalledAppHTTPError):
error_code = "installed_app_unavailable"
description = "The app is not available in this app library."
code = HTTPStatus.NOT_FOUND
class InstalledAppInvalidCursorError(InstalledAppHTTPError):
error_code = "invalid_cursor"
description = "The app list cursor is invalid. Refresh the list and try again."
code = HTTPStatus.BAD_REQUEST
class WebAppAccessUnavailableHTTPError(InstalledAppHTTPError):
error_code = "web_app_access_unavailable"
description = "The app access service is unavailable. Try again later."
code = HTTPStatus.SERVICE_UNAVAILABLE
class ConversationNotFoundHTTPError(InstalledAppHTTPError):
error_code = "conversation_not_found"
description = "The conversation was not found for this account and app."
code = HTTPStatus.NOT_FOUND
class ConversationCursorNotFoundHTTPError(InstalledAppHTTPError):
error_code = "conversation_cursor_not_found"
description = "The conversation cursor is not in the current list. Refresh the list and try again."
code = HTTPStatus.NOT_FOUND
class ConversationFirstMessageNotFoundHTTPError(InstalledAppHTTPError):
error_code = "conversation_first_message_not_found"
description = "The conversation has no message from which to generate a name."
code = HTTPStatus.NOT_FOUND
class ConversationNameRequiredHTTPError(InstalledAppHTTPError):
error_code = "conversation_name_required"
description = "A name is required when automatic naming is disabled."
code = HTTPStatus.BAD_REQUEST
class MessageNotFoundHTTPError(InstalledAppHTTPError):
error_code = "message_not_found"
description = "The message was not found for this account and app."
code = HTTPStatus.NOT_FOUND
class MessageCursorNotFoundHTTPError(InstalledAppHTTPError):
error_code = "message_cursor_not_found"
description = "The message cursor is not in this conversation. Refresh the list and try again."
code = HTTPStatus.NOT_FOUND
class NotCompletionAppError(BaseHTTPException):
error_code = "not_completion_app"
description = "Not Completion App"
code = HTTPStatus.BAD_REQUEST
class NotChatAppError(BaseHTTPException):
error_code = "not_chat_app"
description = "App mode is invalid."
code = HTTPStatus.BAD_REQUEST
class NotWorkflowAppError(BaseHTTPException):
error_code = "not_workflow_app"
description = "Only support workflow app."
code = HTTPStatus.BAD_REQUEST
class AppSuggestedQuestionsAfterAnswerDisabledError(BaseHTTPException):
error_code = "app_suggested_questions_after_answer_disabled"
description = "Function Suggested questions after answer disabled."
code = HTTPStatus.FORBIDDEN
class AppAccessDeniedError(BaseHTTPException):
error_code = "access_denied"
description = "App access denied."
code = HTTPStatus.FORBIDDEN
class RecommendedAppNotFoundError(BaseHTTPException):
error_code = "recommended_app_not_found"
description = "Recommended app not found."
code = HTTPStatus.NOT_FOUND
class AppPreviewSiteUnavailableError(BaseHTTPException):
error_code = "app_site_unavailable"
description = "The app preview site is unavailable."
code = HTTPStatus.FORBIDDEN
class AppPreviewOwnerUnavailableError(BaseHTTPException):
error_code = "app_owner_unavailable"
description = "The app preview owner is unavailable."
code = HTTPStatus.FORBIDDEN
class TrialAppNotAllowed(BaseHTTPException):
"""*403* `Trial App Not Allowed`
Raise if the user has reached the trial app limit.
"""
error_code = "trial_app_not_allowed"
code = HTTPStatus.FORBIDDEN
description = "the app is not allowed to be trial."
class TrialAppLimitExceeded(BaseHTTPException):
"""*403* `Trial App Limit Exceeded`
Raise if the user has exceeded the trial app limit.
"""
error_code = "trial_app_limit_exceeded"
code = HTTPStatus.FORBIDDEN
description = "The user has exceeded the trial app limit."
class TrialAppFeatureDisabledError(BaseHTTPException):
error_code = "trial_app_feature_disabled"
code = HTTPStatus.FORBIDDEN
description = "Trial app feature is not enabled."
@@ -0,0 +1,231 @@
import base64
import binascii
import logging
from http import HTTPStatus
from flask_restx import Resource
from pydantic import BaseModel, Field, computed_field
from controllers.common.fields import SimpleResultMessageResponse
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
from controllers.console import console_ns
from controllers.console.explore.error import (
InstalledAppInvalidCursorError,
InstalledAppNotFoundHTTPError,
InstalledAppUnavailableHTTPError,
WebAppAccessUnavailableHTTPError,
)
from controllers.console.explore.installed_app_admission import get_installed_app
from controllers.console.flask_admission import console_account_admission
from controllers.console.wraps import model_validate
from extensions.ext_application_services import application_services
from fields.base import ResponseModel
from graphon.file import helpers as file_helpers
from libs.external_api import error_responses
from libs.helper import dump_response, to_timestamp
from machinery.context import RequestContext
from models.model import AppMode, IconType
from services.installed_app_access_service import InstalledAppNotFoundError, InstalledAppRef
from services.installed_app_service import (
InstalledAppCursor,
InstalledAppRecord,
InstalledAppUnavailableError,
)
from services.webapp_access_query_service import WebAppAccessUnavailableError
class InstalledAppUpdatePayload(BaseModel):
is_pinned: bool | None = None
class InstalledAppsListQuery(BaseModel):
app_id: str | None = Field(default=None, description="App ID to filter by")
name: str | None = Field(default=None, max_length=100, description="App name to search for")
cursor: str | None = Field(default=None, description="Opaque cursor returned by the previous page")
limit: int = Field(
default=20,
ge=1,
le=100,
description="Number of installed apps to return",
)
logger = logging.getLogger(__name__)
def _build_icon_url(icon_type: IconType | None, icon: str | None) -> str | None:
if icon is None or icon_type is None:
return None
if icon_type != IconType.IMAGE:
return None
return file_helpers.get_signed_file_url(icon)
def _encode_installed_app_cursor(cursor: InstalledAppCursor) -> str:
payload = cursor.model_dump_json().encode()
return base64.urlsafe_b64encode(payload).decode().rstrip("=")
def _decode_installed_app_cursor(cursor: str | None) -> InstalledAppCursor | None:
if cursor is None:
return None
try:
padded_cursor = cursor + "=" * (-len(cursor) % 4)
payload = base64.b64decode(padded_cursor, altchars=b"-_", validate=True)
return InstalledAppCursor.model_validate_json(payload)
except (binascii.Error, UnicodeDecodeError, ValueError) as error:
raise InstalledAppInvalidCursorError() from error
class InstalledAppInfoResponse(ResponseModel):
id: str
name: str
description: str
mode: AppMode
icon_type: IconType | None
icon: str | None
icon_background: str | None
use_icon_as_answer_icon: bool
@computed_field(return_type=str | None) # type: ignore[prop-decorator]
@property
def icon_url(self) -> str | None:
return _build_icon_url(self.icon_type, self.icon)
class InstalledAppResponse(ResponseModel):
id: str
app: InstalledAppInfoResponse
app_owner_tenant_id: str
is_pinned: bool
last_used_at: int | None
editable: bool
class InstalledAppListResponse(ResponseModel):
installed_apps: list[InstalledAppResponse]
has_more: bool
next_cursor: str | None
def _installed_app_response_data(
installed_app: InstalledAppRecord,
*,
editable: bool,
) -> InstalledAppResponse:
return InstalledAppResponse(
id=installed_app.id,
app=InstalledAppInfoResponse.model_validate(installed_app.app, from_attributes=True),
app_owner_tenant_id=installed_app.app_owner_tenant_id,
is_pinned=installed_app.is_pinned,
last_used_at=to_timestamp(installed_app.last_used_at),
editable=editable,
)
register_schema_models(
console_ns,
InstalledAppUpdatePayload,
InstalledAppsListQuery,
)
register_response_schema_models(
console_ns,
InstalledAppInfoResponse,
InstalledAppResponse,
InstalledAppListResponse,
SimpleResultMessageResponse,
)
@console_ns.route("/installed-apps")
class InstalledAppsListApi(Resource):
@error_responses(InstalledAppInvalidCursorError, WebAppAccessUnavailableHTTPError)
@console_ns.doc(params=query_params_from_model(InstalledAppsListQuery))
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[InstalledAppListResponse.__name__])
@console_account_admission()
@model_validate(InstalledAppsListQuery)
def get(self, query: InstalledAppsListQuery, request_context: RequestContext) -> dict[str, object]:
cursor = _decode_installed_app_cursor(query.cursor)
try:
page = application_services().installed_apps.management.get_visible_page(
tenant_id=request_context.active_workspace_id,
user_id=request_context.account_id,
cursor=cursor,
limit=query.limit,
app_id=query.app_id,
name=query.name,
)
except WebAppAccessUnavailableError as error:
logger.exception(
"Installed app list access check failed: workspace_id=%s account_id=%s request_id=%s",
request_context.active_workspace_id,
request_context.account_id,
request_context.request_id,
)
raise WebAppAccessUnavailableHTTPError() from error
installed_app_list = [
_installed_app_response_data(
installed_app,
editable=page.editable,
)
for installed_app in page.data
]
logger.debug("installed_app_list: %s, user_id: %s", installed_app_list, request_context.account_id)
return dump_response(
InstalledAppListResponse,
{
"installed_apps": installed_app_list,
"has_more": page.has_more,
"next_cursor": _encode_installed_app_cursor(page.next_cursor) if page.next_cursor else None,
},
)
@console_ns.route("/installed-apps/<uuid:installed_app_id>")
class InstalledAppApi(Resource):
"""Read or update an admitted workspace installation."""
@error_responses(InstalledAppNotFoundHTTPError, InstalledAppUnavailableHTTPError)
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[InstalledAppResponse.__name__])
@console_account_admission()
@get_installed_app
def get(
self,
request_context: RequestContext,
installed_app: InstalledAppRef,
) -> dict[str, object]:
try:
detail = application_services().installed_apps.management.get_detail(
installed_app=installed_app, account_id=request_context.account_id
)
except InstalledAppUnavailableError as error:
raise InstalledAppUnavailableHTTPError() from error
except InstalledAppNotFoundError as error:
raise InstalledAppNotFoundHTTPError() from error
return dump_response(
InstalledAppResponse,
_installed_app_response_data(
detail.installation,
editable=detail.editable,
),
)
@error_responses(InstalledAppNotFoundHTTPError)
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[SimpleResultMessageResponse.__name__])
@console_ns.expect(console_ns.models[InstalledAppUpdatePayload.__name__])
@console_account_admission()
@get_installed_app
@model_validate(InstalledAppUpdatePayload)
def patch(
self, req_data: InstalledAppUpdatePayload, request_context: RequestContext, installed_app: InstalledAppRef
) -> dict[str, str]:
try:
application_services().installed_apps.management.set_pinned(
installed_app=installed_app, is_pinned=req_data.is_pinned
)
except InstalledAppNotFoundError as error:
raise InstalledAppNotFoundHTTPError() from error
return {"result": "success", "message": "App info updated successfully"}
@@ -0,0 +1,60 @@
"""Installed-app admission for handlers using a pure installation reference."""
import logging
from collections.abc import Callable
from functools import wraps
from typing import Concatenate
from controllers.console.explore.error import (
AppAccessDeniedError,
InstalledAppNotFoundHTTPError,
WebAppAccessUnavailableHTTPError,
)
from extensions.ext_application_services import application_services
from libs.external_api import document_errors
from machinery.context import RequestContext
from services.installed_app_access_service import (
InstalledAppAccessDeniedError,
InstalledAppNotFoundError,
InstalledAppRef,
)
from services.webapp_access_query_service import WebAppAccessUnavailableError
logger = logging.getLogger(__name__)
def get_installed_app[T, **P, R](
view: Callable[Concatenate[T, RequestContext, InstalledAppRef, P], R],
) -> Callable[Concatenate[T, RequestContext, P], R]:
"""Resolve the route's installation after Console account admission."""
@wraps(view)
def decorated(self: T, request_context: RequestContext, /, *args: P.args, **kwargs: P.kwargs) -> R:
installed_app_id = kwargs.pop("installed_app_id", None)
if installed_app_id is None:
raise RuntimeError("The installed-app admission route must provide installed_app_id")
try:
installed_app = application_services().installed_apps.access.get_access(
installed_app_id=str(installed_app_id),
tenant_id=request_context.active_workspace_id,
account_id=request_context.account_id,
)
except InstalledAppNotFoundError as error:
raise InstalledAppNotFoundHTTPError() from error
except InstalledAppAccessDeniedError as error:
raise AppAccessDeniedError() from error
except WebAppAccessUnavailableError as error:
logger.exception(
"Installed app admission access check failed: installed_app_id=%s workspace_id=%s "
"account_id=%s request_id=%s",
installed_app_id,
request_context.active_workspace_id,
request_context.account_id,
request_context.request_id,
)
raise WebAppAccessUnavailableHTTPError() from error
return view(self, request_context, installed_app, *args, **kwargs)
return document_errors(
decorated, InstalledAppNotFoundHTTPError, AppAccessDeniedError, WebAppAccessUnavailableHTTPError
)
@@ -0,0 +1,280 @@
"""HTTP admission and response contracts for installed-app messages."""
import logging
from collections.abc import Callable
from functools import wraps
from http import HTTPStatus
from typing import Literal
from uuid import UUID
from flask import Response
from flask_restx import Resource
from pydantic import BaseModel
from controllers.common.controller_schemas import MessageFeedbackPayload, MessageListQuery
from controllers.common.errors import InternalServerError, MessageFeedbackRatingRequiredError, UnauthorizedError
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
from controllers.console import console_ns
from controllers.console.app.error import (
AppMoreLikeThisDisabledError,
AppUnavailableError,
CompletionRequestError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
)
from controllers.console.explore.error import (
AppSuggestedQuestionsAfterAnswerDisabledError,
ConversationNotFoundHTTPError,
InstalledAppNotFoundHTTPError,
MessageCursorNotFoundHTTPError,
MessageNotFoundHTTPError,
NotChatAppError,
NotCompletionAppError,
)
from controllers.console.explore.installed_app_admission import get_installed_app
from controllers.console.flask_admission import console_account_admission
from controllers.console.wraps import model_validate
from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError
from extensions.ext_application_services import application_services
from fields.conversation_fields import ResultResponse
from fields.message_fields import ExploreMessageInfiniteScrollPagination, SuggestedQuestionsResponse
from graphon.model_runtime.errors.invoke import InvokeError
from libs import helper
from libs.exception import BaseHTTPException
from libs.external_api import error_responses
from machinery.context import RequestContext
from models.enums import FeedbackRating
from services.account_errors import AccountNotFoundError
from services.app_definition_query_service import AppDefinitionUnavailableError
from services.entities.message_entities import MessageAccount
from services.errors.app import MoreLikeThisDisabledError
from services.errors.app_model_config import AppModelConfigBrokenError
from services.errors.base import BaseServiceError
from services.errors.conversation import ConversationNotExistsError
from services.errors.message import (
FeedbackRatingRequiredError,
FirstMessageNotExistsError,
MessageActorNotFoundError,
MessageNotExistsError,
SuggestedQuestionsAfterAnswerDisabledError,
)
from services.installed_app_access_service import InstalledAppNotFoundError, InstalledAppRef
from services.message_more_like_this_service import (
MoreLikeThisConfigNotFoundError,
MoreLikeThisNotCompletionError,
)
from services.message_query_service import MessageNotChatAppError
logger = logging.getLogger(__name__)
class MoreLikeThisQuery(BaseModel):
response_mode: Literal["blocking", "streaming"]
register_schema_models(console_ns, MessageListQuery, MessageFeedbackPayload, MoreLikeThisQuery)
register_response_schema_models(
console_ns,
ExploreMessageInfiniteScrollPagination,
ResultResponse,
SuggestedQuestionsResponse,
)
def _message_errors[**P, R](view: Callable[P, R]) -> Callable[P, R]:
@wraps(view)
def decorated(*args: P.args, **kwargs: P.kwargs) -> R:
try:
return view(*args, **kwargs)
except InstalledAppNotFoundError as error:
raise InstalledAppNotFoundHTTPError() from error
except (AppDefinitionUnavailableError, MoreLikeThisConfigNotFoundError, AppModelConfigBrokenError) as error:
raise AppUnavailableError() from error
except (AccountNotFoundError, MessageActorNotFoundError) as error:
raise UnauthorizedError("Account no longer exists.") from error
except MessageNotChatAppError as error:
raise NotChatAppError() from error
except MoreLikeThisNotCompletionError as error:
raise NotCompletionAppError() from error
except MessageNotExistsError as error:
raise MessageNotFoundHTTPError() from error
except FirstMessageNotExistsError as error:
raise MessageCursorNotFoundHTTPError() from error
except ConversationNotExistsError as error:
raise ConversationNotFoundHTTPError() from error
except FeedbackRatingRequiredError as error:
raise MessageFeedbackRatingRequiredError() from error
except MoreLikeThisDisabledError as error:
raise AppMoreLikeThisDisabledError() from error
except SuggestedQuestionsAfterAnswerDisabledError as error:
raise AppSuggestedQuestionsAfterAnswerDisabledError() from error
except ProviderTokenNotInitError as error:
raise ProviderNotInitializeError(error.description) from error
except QuotaExceededError as error:
raise ProviderQuotaExceededError() from error
except ModelCurrentlyNotSupportError as error:
raise ProviderModelCurrentlyNotSupportError() from error
except InvokeError as error:
raise CompletionRequestError(error.description) from error
except (BaseHTTPException, ValueError):
raise
except Exception as error:
logger.exception("Installed-app message operation failed")
raise InternalServerError() from error
return decorated
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/messages",
endpoint="installed_app_messages",
)
class MessageListApi(Resource):
@error_responses(
AppUnavailableError, ConversationNotFoundHTTPError, MessageCursorNotFoundHTTPError, NotChatAppError
)
@console_ns.doc(params=query_params_from_model(MessageListQuery))
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[ExploreMessageInfiniteScrollPagination.__name__])
@console_account_admission()
@get_installed_app
@model_validate(MessageListQuery)
@_message_errors
def get(
self, query: MessageListQuery, request_context: RequestContext, installed_app: InstalledAppRef
) -> dict[str, object]:
page = application_services().message_queries.get_page(
app_id=installed_app.app_id,
app_owner_tenant_id=installed_app.app_owner_tenant_id,
actor=MessageAccount(account_id=request_context.account_id),
installed_app=installed_app,
conversation_id=query.conversation_id,
first_id=query.first_id or None,
limit=query.limit,
)
return helper.dump_response(ExploreMessageInfiniteScrollPagination, page)
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/messages/<uuid:message_id>/feedbacks",
endpoint="installed_app_message_feedback",
)
class MessageFeedbackApi(Resource):
@error_responses(AppUnavailableError, MessageFeedbackRatingRequiredError, MessageNotFoundHTTPError)
@console_ns.expect(console_ns.models[MessageFeedbackPayload.__name__])
@console_ns.response(HTTPStatus.OK, "Feedback submitted successfully", console_ns.models[ResultResponse.__name__])
@console_account_admission()
@get_installed_app
@model_validate(MessageFeedbackPayload)
@_message_errors
def post(
self,
payload: MessageFeedbackPayload,
request_context: RequestContext,
installed_app: InstalledAppRef,
message_id: UUID,
) -> dict[str, object]:
application_services().message_feedbacks.set_feedback(
app_id=installed_app.app_id,
app_owner_tenant_id=installed_app.app_owner_tenant_id,
actor=MessageAccount(account_id=request_context.account_id),
installed_app=installed_app,
message_id=str(message_id),
rating=FeedbackRating(payload.rating) if payload.rating is not None else None,
content=payload.content,
)
return helper.dump_response(ResultResponse, {"result": "success"})
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/messages/<uuid:message_id>/more-like-this",
endpoint="installed_app_more_like_this",
)
class MessageMoreLikeThisApi(Resource):
@error_responses(
AppMoreLikeThisDisabledError,
AppUnavailableError,
CompletionRequestError,
MessageNotFoundHTTPError,
NotCompletionAppError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
)
@console_ns.doc(params=query_params_from_model(MoreLikeThisQuery))
@console_ns.response(HTTPStatus.OK, "Success")
@console_account_admission()
@get_installed_app
@model_validate(MoreLikeThisQuery)
@_message_errors
def get(
self,
query: MoreLikeThisQuery,
request_context: RequestContext,
installed_app: InstalledAppRef,
message_id: UUID,
) -> Response:
if installed_app.app_mode != "completion":
raise NotCompletionAppError()
response = application_services().message_more_like_this.generate(
app_id=installed_app.app_id,
app_owner_tenant_id=installed_app.app_owner_tenant_id,
actor=MessageAccount(account_id=request_context.account_id),
message_id=str(message_id),
streaming=query.response_mode == "streaming",
)
# response-contract:ignore compact_generate_response
return helper.compact_generate_response(response)
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/messages/<uuid:message_id>/suggested-questions",
endpoint="installed_app_suggested_question",
)
class MessageSuggestedQuestionApi(Resource):
@error_responses(
AppSuggestedQuestionsAfterAnswerDisabledError,
AppUnavailableError,
CompletionRequestError,
ConversationNotFoundHTTPError,
MessageNotFoundHTTPError,
NotChatAppError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
)
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[SuggestedQuestionsResponse.__name__])
@console_account_admission()
@get_installed_app
@_message_errors
def get(
self, request_context: RequestContext, installed_app: InstalledAppRef, message_id: UUID
) -> dict[str, object]:
if installed_app.app_mode not in {"chat", "agent-chat", "advanced-chat"}:
raise NotChatAppError()
try:
questions = application_services().message_suggested_questions.get_suggested_questions(
app_id=installed_app.app_id,
app_owner_tenant_id=installed_app.app_owner_tenant_id,
expected_app_mode=installed_app.app_mode,
actor=MessageAccount(account_id=request_context.account_id),
invoke_from="explore",
message_id=str(message_id),
)
except (
BaseServiceError,
AppDefinitionUnavailableError,
ProviderTokenNotInitError,
QuotaExceededError,
ModelCurrentlyNotSupportError,
InvokeError,
):
raise
except ValueError as error:
# Legacy model/history configuration failures are server failures,
# not invalid request parameters. Replace this when that runtime
# exposes typed configuration errors.
logger.exception("Suggested-question runtime failed for message %s", message_id)
raise InternalServerError() from error
return helper.dump_response(SuggestedQuestionsResponse, {"data": questions})
@@ -0,0 +1,67 @@
from http import HTTPStatus
from typing import Any
from flask_restx import Resource
from pydantic import BaseModel, Field
from controllers.common.fields import Parameters
from controllers.common.schema import register_response_schema_models
from controllers.console import console_ns
from controllers.console.app.error import AppUnavailableError
from controllers.console.explore.installed_app_admission import get_installed_app
from controllers.console.flask_admission import console_account_admission
from extensions.ext_application_services import application_services
from libs.external_api import error_responses
from libs.helper import dump_response
from machinery.context import RequestContext
from services.app_definition_query_service import AppDefinitionUnavailableError
from services.installed_app_access_service import InstalledAppRef
class ExploreAppMetaResponse(BaseModel):
"""Metadata consumed by the installed-app chat UI.
Built-in tool icons are URL strings; API-based tool icons are provider-defined payload objects.
"""
tool_icons: dict[str, str | dict[str, Any]] = Field(default_factory=dict)
register_response_schema_models(console_ns, Parameters, ExploreAppMetaResponse)
@console_ns.route("/installed-apps/<uuid:installed_app_id>/parameters", endpoint="installed_app_parameters")
class AppParameterApi(Resource):
"""Resource for app variables."""
@error_responses(AppUnavailableError)
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[Parameters.__name__])
@console_account_admission()
@get_installed_app
def get(self, request_context: RequestContext, installed_app: InstalledAppRef) -> dict[str, object]:
"""Retrieve app parameters."""
try:
parameters = application_services().app_definitions.get_parameters(installed_app.app_id)
except AppDefinitionUnavailableError:
raise AppUnavailableError() from None
return dump_response(Parameters, parameters)
@console_ns.route("/installed-apps/<uuid:installed_app_id>/meta", endpoint="installed_app_meta")
class ExploreAppMetaApi(Resource):
@error_responses(AppUnavailableError)
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[ExploreAppMetaResponse.__name__])
@console_account_admission()
@get_installed_app
def get(self, request_context: RequestContext, installed_app: InstalledAppRef) -> dict[str, object]:
"""Get app meta"""
try:
tool_icons = application_services().app_definitions.get_tool_icons(installed_app.app_id)
except AppDefinitionUnavailableError:
raise AppUnavailableError() from None
return dump_response(
ExploreAppMetaResponse,
{"tool_icons": tool_icons},
)
@@ -0,0 +1,189 @@
from http import HTTPStatus
from typing import Any, Literal
from uuid import UUID
from flask import make_response, send_file
from flask_restx import Resource
from pydantic import BaseModel, ConfigDict, Field, computed_field, field_validator
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
from controllers.console import console_ns
from controllers.console.explore.error import RecommendedAppNotFoundError
from controllers.console.flask_admission import console_account_admission
from controllers.console.wraps import model_validate
from extensions.ext_application_services import application_services
from fields.app_fields import AppExportResponse
from fields.base import ResponseModel
from libs.external_api import error_responses
from libs.flask_restx_compat import BINARY_RESPONSE_MEDIA_TYPES_VENDOR_KEY
from libs.helper import build_icon_url, dump_response
from machinery.context import RequestContext
from services.agent.errors import RosterAgentPackageExportFailedError
from services.recommended_app_query_service import RecommendedAppNotFoundError as RecommendedAppQueryNotFoundError
class RecommendedAppsQuery(BaseModel):
language: str = Field(default="en-US", description="Language code for recommended app localization")
class RecommendedAgentExportQuery(BaseModel):
model_config = ConfigDict(extra="forbid")
version_id: UUID = Field(description="Current published template snapshot ID")
format: Literal["yaml", "ifpkg"] = Field(default="ifpkg", description="Export format; defaults to ifpkg")
class RecommendedAppInfoResponse(ResponseModel):
id: str
name: str | None = None
mode: str | None = None
icon: str | None = None
icon_type: str | None = None
icon_background: str | None = None
@staticmethod
def _normalize_enum_like(value: Any) -> str | None:
if value is None:
return None
if isinstance(value, str):
return value
return str(getattr(value, "value", value))
@field_validator("mode", "icon_type", mode="before")
@classmethod
def _normalize_enum_fields(cls, value: Any) -> str | None:
return cls._normalize_enum_like(value)
@computed_field(return_type=str | None) # type: ignore[prop-decorator]
@property
def icon_url(self) -> str | None:
return build_icon_url(self.icon_type, self.icon)
class RecommendedAppResponse(ResponseModel):
app: RecommendedAppInfoResponse | None = None
app_id: str
description: str | None = None
copyright: str | None = None
privacy_policy: str | None = None
custom_disclaimer: str | None = None
categories: list[str] = Field(default_factory=list)
position: int | None = None
is_listed: bool | None = None
can_trial: bool
class RecommendedAppListResponse(ResponseModel):
recommended_apps: list[RecommendedAppResponse]
categories: list[str]
class LearnDifyAppListResponse(ResponseModel):
recommended_apps: list[RecommendedAppResponse]
class RecommendedAppDetailResponse(ResponseModel):
id: str
name: str
icon: str | None = None
icon_background: str | None = None
mode: str
export_data: str
can_trial: bool
package_url: str | None = Field(default=None, description="Download URL for a New Agent .ifpkg template")
version_id: str | None = Field(default=None, description="Published version for direct local template creation")
register_schema_models(
console_ns,
RecommendedAppsQuery,
RecommendedAgentExportQuery,
)
register_response_schema_models(
console_ns,
RecommendedAppInfoResponse,
RecommendedAppResponse,
RecommendedAppListResponse,
LearnDifyAppListResponse,
RecommendedAppDetailResponse,
AppExportResponse,
)
@console_ns.route("/explore/apps")
class RecommendedAppListApi(Resource):
@console_ns.doc(params=query_params_from_model(RecommendedAppsQuery))
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[RecommendedAppListResponse.__name__])
@console_account_admission()
@model_validate(RecommendedAppsQuery)
def get(self, req_data: RecommendedAppsQuery, _request_context: RequestContext):
return dump_response(
RecommendedAppListResponse,
application_services().recommended_app_queries.list_recommended(
language=req_data.language,
),
)
@console_ns.route("/explore/apps/learn-dify")
class LearnDifyAppListApi(Resource):
@console_ns.doc(params=query_params_from_model(RecommendedAppsQuery))
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[LearnDifyAppListResponse.__name__])
@console_account_admission()
@model_validate(RecommendedAppsQuery)
def get(self, req_data: RecommendedAppsQuery, _request_context: RequestContext):
return dump_response(
LearnDifyAppListResponse,
application_services().recommended_app_queries.list_learn_dify(
language=req_data.language,
),
)
@console_ns.route("/explore/apps/<uuid:app_id>")
class RecommendedAppApi(Resource):
@error_responses(RecommendedAppNotFoundError)
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[RecommendedAppDetailResponse.__name__])
@console_ns.response(HTTPStatus.NOT_FOUND, "Recommended app not found")
@console_account_admission()
def get(self, _request_context: RequestContext, app_id: UUID):
try:
result = application_services().recommended_app_queries.get_detail(str(app_id))
except RecommendedAppQueryNotFoundError:
raise RecommendedAppNotFoundError() from None
return dump_response(RecommendedAppDetailResponse, result)
@console_ns.route("/trial-apps/<uuid:app_id>/export")
class RecommendedAgentExportApi(Resource):
@error_responses(RecommendedAppNotFoundError, RosterAgentPackageExportFailedError)
@console_ns.doc(params=query_params_from_model(RecommendedAgentExportQuery))
@console_ns.doc(
produces=["application/json", "application/zip"],
vendor={BINARY_RESPONSE_MEDIA_TYPES_VENDOR_KEY: ["application/zip"]},
)
@console_ns.response(200, "Published Agent template export", console_ns.models[AppExportResponse.__name__])
@console_ns.response(404, "Published template unavailable")
@model_validate(RecommendedAgentExportQuery)
def get(self, query: RecommendedAgentExportQuery, app_id: UUID):
# Both formats require public catalog membership and the current published version.
try:
exported = application_services().recommended_app_packages.export(
app_id=str(app_id), version_id=query.version_id, format=query.format
)
except RecommendedAppQueryNotFoundError:
raise RecommendedAppNotFoundError() from None
if isinstance(exported, str):
response = make_response(dump_response(AppExportResponse, {"data": exported}))
response.headers["Cache-Control"] = "no-store"
return response
try:
response = send_file(
exported.archive, mimetype="application/zip", as_attachment=True, download_name=exported.filename
)
except Exception:
exported.close()
raise
response.headers["Cache-Control"] = "no-store"
response.call_on_close(exported.close)
return response
@@ -0,0 +1,104 @@
from http import HTTPStatus
from uuid import UUID
from flask_restx import Resource
from controllers.common.controller_schemas import SavedMessageCreatePayload, SavedMessageListQuery
from controllers.common.errors import NotFoundError
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
from controllers.console import console_ns
from controllers.console.explore.error import NotCompletionAppError
from controllers.console.explore.installed_app_admission import get_installed_app
from controllers.console.flask_admission import console_account_admission
from controllers.console.wraps import model_validate
from extensions.ext_application_services import application_services
from fields.conversation_fields import ResultResponse
from fields.message_fields import SavedMessageInfiniteScrollPagination
from libs.external_api import error_responses
from libs.helper import dump_response
from machinery.context import RequestContext
from services.errors.message import MessageNotExistsError
from services.installed_app_access_service import InstalledAppRef
from services.saved_message_service import SavedMessageActor
register_schema_models(console_ns, SavedMessageListQuery, SavedMessageCreatePayload)
register_response_schema_models(console_ns, ResultResponse, SavedMessageInfiniteScrollPagination)
def _require_completion_app(installed_app: InstalledAppRef) -> str:
if installed_app.app_mode != "completion":
raise NotCompletionAppError()
return installed_app.app_id
@console_ns.route("/installed-apps/<uuid:installed_app_id>/saved-messages", endpoint="installed_app_saved_messages")
class SavedMessageListApi(Resource):
@error_responses(NotCompletionAppError)
@console_ns.doc(params=query_params_from_model(SavedMessageListQuery))
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[SavedMessageInfiniteScrollPagination.__name__])
@console_account_admission()
@get_installed_app
@model_validate(SavedMessageListQuery)
def get(
self,
req_data: SavedMessageListQuery,
request_context: RequestContext,
installed_app: InstalledAppRef,
) -> dict[str, object]:
app_id = _require_completion_app(installed_app)
pagination = application_services().saved_messages.pagination_by_last_id(
app_id=app_id,
actor=SavedMessageActor.account(request_context.account_id),
last_id=str(req_data.last_id) if req_data.last_id else None,
limit=req_data.limit,
)
return dump_response(SavedMessageInfiniteScrollPagination, pagination)
@error_responses(NotCompletionAppError)
@console_ns.expect(console_ns.models[SavedMessageCreatePayload.__name__])
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[ResultResponse.__name__])
@console_account_admission()
@get_installed_app
@model_validate(SavedMessageCreatePayload)
def post(
self,
req_data: SavedMessageCreatePayload,
request_context: RequestContext,
installed_app: InstalledAppRef,
) -> dict[str, object]:
app_id = _require_completion_app(installed_app)
try:
application_services().saved_messages.save(
app_id=app_id,
actor=SavedMessageActor.account(request_context.account_id),
message_id=str(req_data.message_id),
)
except MessageNotExistsError as caught_error:
raise NotFoundError("Message Not Exists.") from caught_error
return ResultResponse(result="success").model_dump(mode="json")
@console_ns.route(
"/installed-apps/<uuid:installed_app_id>/saved-messages/<uuid:message_id>", endpoint="installed_app_saved_message"
)
class SavedMessageApi(Resource):
@error_responses(NotCompletionAppError)
@console_ns.response(HTTPStatus.NO_CONTENT, "Saved message deleted successfully")
@console_account_admission()
@get_installed_app
def delete(
self,
request_context: RequestContext,
installed_app: InstalledAppRef,
message_id: UUID,
) -> tuple[str, int]:
app_id = _require_completion_app(installed_app)
application_services().saved_messages.delete(
app_id=app_id,
actor=SavedMessageActor.account(request_context.account_id),
message_id=str(message_id),
)
return "", HTTPStatus.NO_CONTENT
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,60 @@
"""Trial execution admission for handlers using a detached app reference."""
from collections.abc import Callable
from functools import wraps
from typing import Concatenate
from controllers.console.explore.error import TrialAppFeatureDisabledError, TrialAppLimitExceeded, TrialAppNotAllowed
from extensions.ext_application_services import application_services
from libs.external_api import document_errors
from machinery.context import RequestContext
from services.trial_app_access_service import (
TrialAppRef,
TrialAppUnavailableError,
TrialAppUsageLimitExceededError,
)
def trial_feature_enable[**P, R](view: Callable[P, R]) -> Callable[P, R]:
"""Gate trial execution before resolving app membership or account usage."""
@wraps(view)
def decorated(*args: P.args, **kwargs: P.kwargs) -> R:
if not application_services().recommended_app_queries.is_trial_enabled():
raise TrialAppFeatureDisabledError()
return view(*args, **kwargs)
return document_errors(decorated, TrialAppFeatureDisabledError)
def get_trial_app[T, **P, R](
view: Callable[Concatenate[T, RequestContext, TrialAppRef, P], R],
*,
check_usage: bool = True,
) -> Callable[Concatenate[T, RequestContext, P], R]:
"""Admit the trial app, optionally skipping generation quota for task cancellation."""
@wraps(view)
def decorated(self: T, request_context: RequestContext, /, *args: P.args, **kwargs: P.kwargs) -> R:
app_id = kwargs.pop("app_id", None)
if app_id is None:
raise RuntimeError("The trial app admission route must provide app_id")
try:
trial_app = application_services().trial_apps.access.get_access(
app_id=str(app_id), account_id=request_context.account_id, check_usage=check_usage
)
except TrialAppUnavailableError as error:
raise TrialAppNotAllowed() from error
except TrialAppUsageLimitExceededError as error:
raise TrialAppLimitExceeded() from error
return view(self, request_context, trial_app, *args, **kwargs)
documented = (TrialAppNotAllowed, TrialAppLimitExceeded) if check_usage else (TrialAppNotAllowed,)
return trial_feature_enable(document_errors(decorated, *documented))
def get_trial_app_for_stop[T, **P, R](
view: Callable[Concatenate[T, RequestContext, TrialAppRef, P], R],
) -> Callable[Concatenate[T, RequestContext, P], R]:
"""Keep trial access checks without requiring remaining generation quota."""
return get_trial_app(view, check_usage=False)
@@ -0,0 +1,121 @@
import logging
from http import HTTPStatus
from flask import Response
from flask_restx import Resource
from controllers.common.controller_schemas import WorkflowRunPayload
from controllers.common.errors import InternalServerError, UnauthorizedError
from controllers.common.fields import SimpleResultResponse
from controllers.common.schema import register_response_schema_models, register_schema_model
from controllers.console import console_ns
from controllers.console.app.error import (
CompletionRequestError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
)
from controllers.console.explore.error import NotWorkflowAppError
from controllers.console.explore.installed_app_admission import get_installed_app
from controllers.console.flask_admission import console_account_admission
from controllers.console.wraps import model_validate
from controllers.web.error import InvokeRateLimitError as InvokeRateLimitHttpError
from core.errors.error import (
ModelCurrentlyNotSupportError,
ProviderTokenNotInitError,
QuotaExceededError,
)
from extensions.ext_application_services import application_services
from graphon.model_runtime.errors.invoke import InvokeError
from libs import helper
from libs.external_api import error_responses
from machinery.context import RequestContext
from models.model import AppMode
from services.account_errors import AccountNotFoundError
from services.app_definition_query_service import AppDefinitionUnavailableError
from services.errors.llm import InvokeRateLimitError
from services.installed_app_access_service import InstalledAppRef
from services.installed_app_generation_service import InstalledAppNotWorkflowError
logger = logging.getLogger(__name__)
register_schema_model(console_ns, WorkflowRunPayload)
register_response_schema_models(console_ns, SimpleResultResponse)
@console_ns.route("/installed-apps/<uuid:installed_app_id>/workflows/run")
class InstalledAppWorkflowRunApi(Resource):
@error_responses(
CompletionRequestError,
InvokeRateLimitHttpError,
NotWorkflowAppError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
)
@console_ns.expect(console_ns.models[WorkflowRunPayload.__name__])
@console_ns.response(HTTPStatus.OK, "Success")
@console_account_admission()
@get_installed_app
@model_validate(WorkflowRunPayload)
def post(
self,
req_data: WorkflowRunPayload,
request_context: RequestContext,
installed_app: InstalledAppRef,
) -> Response:
"""
Run workflow
"""
try:
response = application_services().installed_apps.generation.generate_workflow(
installed_app=installed_app,
account_id=request_context.account_id,
args=req_data.model_dump(exclude_none=True),
)
# response-contract:ignore compact_generate_response
return helper.compact_generate_response(response)
except (AppDefinitionUnavailableError, InstalledAppNotWorkflowError):
raise NotWorkflowAppError() from None
except AccountNotFoundError:
raise UnauthorizedError("Account no longer exists.") from None
except ProviderTokenNotInitError as ex:
raise ProviderNotInitializeError(ex.description) from ex
except QuotaExceededError as caught_error:
raise ProviderQuotaExceededError() from caught_error
except ModelCurrentlyNotSupportError as caught_error:
raise ProviderModelCurrentlyNotSupportError() from caught_error
except InvokeError as e:
raise CompletionRequestError(e.description) from e
except InvokeRateLimitError as ex:
raise InvokeRateLimitHttpError(ex.description) from ex
except ValueError as e:
raise e
except Exception as caught_error:
logger.exception("internal server error.")
raise InternalServerError() from caught_error
@console_ns.route("/installed-apps/<uuid:installed_app_id>/workflows/tasks/<string:task_id>/stop")
class InstalledAppWorkflowTaskStopApi(Resource):
@error_responses(NotWorkflowAppError)
@console_ns.response(HTTPStatus.OK, "Success", console_ns.models[SimpleResultResponse.__name__])
@console_account_admission()
@get_installed_app
def post(self, request_context: RequestContext, installed_app: InstalledAppRef, task_id: str) -> dict[str, object]:
"""
Stop workflow task
"""
if installed_app.app_mode != "workflow":
raise NotWorkflowAppError()
application_services().app_tasks.stop_workflow_task(
tenant_id=installed_app.app_owner_tenant_id,
app_id=installed_app.app_id,
task_id=task_id,
app_mode=AppMode.WORKFLOW,
owner=None,
)
return SimpleResultResponse(result="success").model_dump(mode="json")