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

Whitespace-only changes.
@@ -0,0 +1,354 @@
from http import HTTPStatus
from uuid import UUID
from flask_restx import Resource
from pydantic import BaseModel, Field, TypeAdapter
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.wraps import model_validate
from controllers.service_api import service_api_ns
from controllers.service_api.flask_admission import service_api_account_admission
from extensions.ext_application_services import application_services
from fields.annotation_fields import (
Annotation,
AnnotationJobStatusDetailResponse,
AnnotationJobStatusResponse,
AnnotationList,
)
from libs.helper import dump_response
from machinery.context import ServiceApiAccountRequestContext
from services.annotation_query import AnnotationAppNotFoundError, AnnotationNotFoundError
from services.annotation_reply_service import AnnotationReplyAction, AnnotationReplyJobNotFoundError
class AnnotationCreatePayload(BaseModel):
question: str = Field(description="Annotation question.")
answer: str = Field(description="Annotation answer.")
class AnnotationReplyActionPayload(BaseModel):
score_threshold: float = Field(
description=(
"Minimum similarity score for an annotation to be considered a match. Higher values require closer matches."
),
json_schema_extra={"format": "float"},
)
embedding_provider_name: str = Field(description="Name of the embedding model provider.")
embedding_model_name: str = Field(description="Name of the embedding model to use for annotation matching.")
class AnnotationListQuery(BaseModel):
page: int = Field(default=1, ge=1, description="Page number for pagination.")
limit: int = Field(default=20, ge=1, description="Number of items per page.")
keyword: str = Field(default="", description="Keyword to filter annotations by question or answer content.")
ANNOTATION_REPLY_ACTION_PARAM = {
"description": "Action to perform: `enable` or `disable`.",
"enum": ["enable", "disable"],
"type": "string",
}
register_schema_models(
service_api_ns,
AnnotationCreatePayload,
AnnotationReplyActionPayload,
AnnotationListQuery,
)
register_response_schema_models(
service_api_ns,
Annotation,
AnnotationList,
AnnotationJobStatusResponse,
AnnotationJobStatusDetailResponse,
)
@service_api_ns.route("/apps/annotation-reply/<string:action>")
class AnnotationReplyActionApi(Resource):
@service_api_ns.doc(
summary="Configure Annotation Reply",
description=(
"Enables or disables the annotation reply feature. Requires embedding model configuration "
"when enabling. Executes asynchronously — use [Get Annotation Reply Job "
"Status](/api-reference/annotations/get-annotation-reply-job-status) to track progress."
),
tags=["Annotations"],
responses={
HTTPStatus.OK: "Annotation reply settings task initiated.",
},
)
@service_api_ns.expect(service_api_ns.models[AnnotationReplyActionPayload.__name__])
@service_api_ns.doc("annotation_reply_action")
@service_api_ns.doc(description="Enable or disable annotation reply feature")
@service_api_ns.doc(params={"action": ANNOTATION_REPLY_ACTION_PARAM})
@service_api_ns.doc(
responses={
HTTPStatus.OK: "Action completed successfully",
HTTPStatus.BAD_REQUEST: "`invalid_param` : Invalid action or app selection.",
HTTPStatus.UNAUTHORIZED: "`unauthorized` : Invalid API credential or workspace owner unavailable.",
HTTPStatus.NOT_FOUND: "`not_found` : App no longer exists.",
HTTPStatus.UNPROCESSABLE_ENTITY: "`unprocessable_entity` : Invalid annotation reply payload.",
}
)
@service_api_ns.response(
HTTPStatus.OK,
"Action completed successfully",
service_api_ns.models[AnnotationJobStatusResponse.__name__],
)
@service_api_account_admission
@model_validate(AnnotationReplyActionPayload)
def post(
self, payload: AnnotationReplyActionPayload, context: ServiceApiAccountRequestContext, action: str
) -> tuple[dict[str, object], HTTPStatus]:
"""Enable or disable annotation reply feature."""
validated_action = TypeAdapter(AnnotationReplyAction).validate_python(action)
service = application_services().annotation_reply
try:
if validated_action == "enable":
result = service.enable(
tenant_id=context.tenant_id,
app_id=context.app_id,
account_id=context.account_id,
score_threshold=payload.score_threshold,
embedding_provider_name=payload.embedding_provider_name,
embedding_model_name=payload.embedding_model_name,
)
else:
result = service.disable(tenant_id=context.tenant_id, app_id=context.app_id)
except AnnotationAppNotFoundError as exc:
raise NotFoundError("App not found") from exc
return dump_response(AnnotationJobStatusResponse, result), HTTPStatus.OK
@service_api_ns.route("/apps/annotation-reply/<string:action>/status/<uuid:job_id>")
class AnnotationReplyActionStatusApi(Resource):
@service_api_ns.doc(
summary="Get Annotation Reply Job Status",
description=(
"Retrieves the status of an asynchronous annotation reply configuration job started by "
"[Configure Annotation Reply](/api-reference/annotations/configure-annotation-reply)."
),
tags=["Annotations"],
responses={
HTTPStatus.OK: "Successfully retrieved task status.",
HTTPStatus.BAD_REQUEST: "`invalid_param` : Invalid action or app selection.",
HTTPStatus.NOT_FOUND: "`not_found` : The specified job does not belong to this app or no longer exists.",
},
)
@service_api_ns.doc("get_annotation_reply_action_status")
@service_api_ns.doc(description="Get the status of an annotation reply action job")
@service_api_ns.doc(
params={
"action": ANNOTATION_REPLY_ACTION_PARAM,
"job_id": (
"Job ID returned by "
"[Configure Annotation Reply](/api-reference/annotations/configure-annotation-reply)."
),
}
)
@service_api_ns.doc(
responses={
HTTPStatus.OK: "Job status retrieved successfully",
HTTPStatus.UNAUTHORIZED: "`unauthorized` : Invalid API credential or workspace owner unavailable.",
}
)
@service_api_ns.response(
HTTPStatus.OK,
"Job status retrieved successfully",
service_api_ns.models[AnnotationJobStatusDetailResponse.__name__],
)
@service_api_account_admission
def get(
self, context: ServiceApiAccountRequestContext, job_id: UUID, action: str
) -> tuple[dict[str, object], HTTPStatus]:
"""Get the status of an annotation reply action job."""
validated_action = TypeAdapter(AnnotationReplyAction).validate_python(action)
try:
result = application_services().annotation_reply.get_status(
tenant_id=context.tenant_id, app_id=context.app_id, action=validated_action, job_id=str(job_id)
)
except AnnotationAppNotFoundError as exc:
raise NotFoundError("App not found") from exc
except AnnotationReplyJobNotFoundError as exc:
raise NotFoundError("The job does not exist.") from exc
return dump_response(AnnotationJobStatusDetailResponse, result), HTTPStatus.OK
@service_api_ns.route("/apps/annotations")
class AnnotationListApi(Resource):
@service_api_ns.doc(
summary="List Annotations",
description="Retrieves a paginated list of annotations for the application. Supports keyword search filtering.",
tags=["Annotations"],
responses={
HTTPStatus.OK: "Successfully retrieved annotation list.",
},
)
@service_api_ns.doc("list_annotations")
@service_api_ns.doc(description="List annotations for the application")
@service_api_ns.doc(params=query_params_from_model(AnnotationListQuery))
@service_api_ns.doc(
responses={
HTTPStatus.OK: "Annotations retrieved successfully",
HTTPStatus.BAD_REQUEST: "`invalid_param` : Invalid app selection.",
HTTPStatus.UNAUTHORIZED: "`unauthorized` : Invalid API credential or workspace owner unavailable.",
HTTPStatus.NOT_FOUND: "`not_found` : App no longer exists.",
HTTPStatus.UNPROCESSABLE_ENTITY: "`unprocessable_entity` : Invalid pagination query.",
}
)
@service_api_ns.response(
HTTPStatus.OK,
"Annotations retrieved successfully",
service_api_ns.models[AnnotationList.__name__],
)
@service_api_account_admission
@model_validate(AnnotationListQuery)
def get(self, query: AnnotationListQuery, context: ServiceApiAccountRequestContext) -> dict[str, object]:
"""List annotations for the application."""
try:
result = application_services().annotation_queries.get_page(
tenant_id=context.tenant_id,
app_id=context.app_id,
page=query.page,
limit=query.limit,
keyword=query.keyword,
)
except AnnotationAppNotFoundError as exc:
raise NotFoundError("App not found") from exc
return dump_response(AnnotationList, result)
@service_api_ns.doc(
summary="Create Annotation",
description=(
"Creates a new annotation. Annotations provide predefined question-answer pairs that the app "
"can match and return directly instead of generating a response."
),
tags=["Annotations"],
responses={
HTTPStatus.CREATED: "Annotation created successfully.",
},
)
@service_api_ns.expect(service_api_ns.models[AnnotationCreatePayload.__name__])
@service_api_ns.doc("create_annotation")
@service_api_ns.doc(description="Create a new annotation")
@service_api_ns.doc(
responses={
HTTPStatus.CREATED: "Annotation created successfully",
HTTPStatus.BAD_REQUEST: "`invalid_param` : Invalid app selection.",
HTTPStatus.UNAUTHORIZED: "`unauthorized` : Invalid API credential or workspace owner unavailable.",
HTTPStatus.NOT_FOUND: "`not_found` : App no longer exists.",
HTTPStatus.UNPROCESSABLE_ENTITY: "`unprocessable_entity` : Invalid annotation payload.",
}
)
@service_api_ns.response(
HTTPStatus.CREATED,
"Annotation created successfully",
service_api_ns.models[Annotation.__name__],
)
@service_api_account_admission
@model_validate(AnnotationCreatePayload)
def post(
self, payload: AnnotationCreatePayload, context: ServiceApiAccountRequestContext
) -> tuple[dict[str, object], HTTPStatus]:
"""Create a new annotation."""
try:
annotation = application_services().annotation_commands.create(
tenant_id=context.tenant_id,
app_id=context.app_id,
account_id=context.account_id,
question=payload.question,
answer=payload.answer,
)
except AnnotationAppNotFoundError as exc:
raise NotFoundError("App not found") from exc
return dump_response(Annotation, annotation), HTTPStatus.CREATED
@service_api_ns.route("/apps/annotations/<uuid:annotation_id>")
class AnnotationUpdateDeleteApi(Resource):
@service_api_ns.doc(
summary="Update Annotation",
description="Updates the question and answer of an existing annotation.",
tags=["Annotations"],
responses={
HTTPStatus.OK: "Annotation updated successfully.",
HTTPStatus.FORBIDDEN: "`forbidden` : API credential scope, app, or workspace access denied.",
HTTPStatus.NOT_FOUND: "`not_found` : App or annotation no longer exists.",
},
)
@service_api_ns.expect(service_api_ns.models[AnnotationCreatePayload.__name__])
@service_api_ns.doc("update_annotation")
@service_api_ns.doc(description="Update an existing annotation")
@service_api_ns.doc(params={"annotation_id": "The unique identifier of the annotation to update."})
@service_api_ns.doc(
responses={
HTTPStatus.OK: "Annotation updated successfully",
HTTPStatus.BAD_REQUEST: "`invalid_param` : Invalid app selection.",
HTTPStatus.UNAUTHORIZED: "`unauthorized` : Invalid API credential or workspace owner unavailable.",
HTTPStatus.FORBIDDEN: "`forbidden` : API credential scope, app, or workspace access denied.",
HTTPStatus.NOT_FOUND: "Annotation not found",
HTTPStatus.UNPROCESSABLE_ENTITY: "`unprocessable_entity` : Invalid annotation payload.",
}
)
@service_api_ns.response(
HTTPStatus.OK,
"Annotation updated successfully",
service_api_ns.models[Annotation.__name__],
)
@service_api_account_admission
@model_validate(AnnotationCreatePayload)
def put(
self, payload: AnnotationCreatePayload, context: ServiceApiAccountRequestContext, annotation_id: UUID
) -> dict[str, object]:
"""Update an existing annotation."""
try:
annotation = application_services().annotation_commands.update(
tenant_id=context.tenant_id,
app_id=context.app_id,
annotation_id=str(annotation_id),
question=payload.question,
answer=payload.answer,
)
except AnnotationAppNotFoundError as exc:
raise NotFoundError("App not found") from exc
except AnnotationNotFoundError as exc:
raise NotFoundError("Annotation not found") from exc
return dump_response(Annotation, annotation)
@service_api_ns.doc(
summary="Delete Annotation",
description="Deletes an annotation and its associated hit history.",
tags=["Annotations"],
responses={
HTTPStatus.NO_CONTENT: "Annotation deleted successfully.",
HTTPStatus.FORBIDDEN: "`forbidden` : API credential scope, app, or workspace access denied.",
HTTPStatus.NOT_FOUND: "`not_found` : App or annotation no longer exists.",
},
)
@service_api_ns.doc("delete_annotation")
@service_api_ns.doc(description="Delete an annotation")
@service_api_ns.doc(params={"annotation_id": "The unique identifier of the annotation to delete."})
@service_api_ns.doc(
responses={
HTTPStatus.NO_CONTENT: "Annotation deleted successfully",
HTTPStatus.BAD_REQUEST: "`invalid_param` : Invalid app selection.",
HTTPStatus.UNAUTHORIZED: "`unauthorized` : Invalid API credential or workspace owner unavailable.",
HTTPStatus.FORBIDDEN: "`forbidden` : API credential scope, app, or workspace access denied.",
HTTPStatus.NOT_FOUND: "Annotation not found",
}
)
@service_api_account_admission
def delete(self, context: ServiceApiAccountRequestContext, annotation_id: UUID) -> tuple[str, HTTPStatus]:
"""Delete an annotation."""
try:
application_services().annotation_commands.delete(
tenant_id=context.tenant_id, app_id=context.app_id, annotation_id=str(annotation_id)
)
except AnnotationAppNotFoundError as exc:
raise NotFoundError("App not found") from exc
except AnnotationNotFoundError as exc:
raise NotFoundError("Annotation not found") from exc
return "", HTTPStatus.NO_CONTENT
@@ -0,0 +1,154 @@
from typing import Annotated
from flask_restx import Resource
from pydantic import Field, WithJsonSchema
from controllers.common.fields import Parameters
from controllers.common.schema import register_response_schema_models
from controllers.service_api import service_api_ns
from controllers.service_api.app.error import AgentNotPublishedError, AppUnavailableError
from controllers.service_api.wraps import validate_app_token
from extensions.ext_application_services import application_services
from fields.base import ResponseModel
from libs.external_api import error_responses
from libs.helper import dump_response
from models.model import App
from services.app_definition_query_service import AppDefinitionNotPublishedError, AppDefinitionUnavailableError
class AppInfoResponse(ResponseModel):
name: str
description: str | None
tags: list[str]
mode: str
author_name: str | None
URLString = Annotated[str, WithJsonSchema({"format": "url", "type": "string"})]
class ToolIcon(ResponseModel):
background: str
content: str
class AppMetaResponse(ResponseModel):
tool_icons: dict[str, URLString | ToolIcon] = Field(default_factory=dict)
register_response_schema_models(service_api_ns, Parameters, AppMetaResponse, AppInfoResponse)
@service_api_ns.route("/parameters")
class AppParameterApi(Resource):
"""Resource for app variables."""
@error_responses(AgentNotPublishedError, AppUnavailableError)
@service_api_ns.doc(
summary="Get App Parameters",
description=(
"Retrieve the application's input form configuration, including feature switches, input "
"parameter names, types, and default values."
),
tags=["Applications"],
responses={
200: "Application parameters information.",
400: "`app_unavailable` : App unavailable or misconfigured.",
},
)
@service_api_ns.doc("get_app_parameters")
@service_api_ns.doc(description="Retrieve application input parameters and configuration")
@service_api_ns.doc(
responses={
200: "Parameters retrieved successfully",
401: "Unauthorized - invalid API token",
}
)
@service_api_ns.response(200, "Parameters retrieved successfully", service_api_ns.models[Parameters.__name__])
@validate_app_token
def get(self, app_model: App):
"""Retrieve app parameters.
Returns the input form parameters and configuration for the application.
"""
try:
parameters = application_services().app_definitions.get_public_parameters(app_model.id)
except AppDefinitionNotPublishedError:
raise AgentNotPublishedError() from None
except AppDefinitionUnavailableError:
raise AppUnavailableError() from None
return dump_response(Parameters, parameters)
@service_api_ns.route("/meta")
class AppMetaApi(Resource):
@error_responses(AppUnavailableError)
@service_api_ns.doc(
summary="Get App Meta",
description="Retrieve metadata about this application, including tool icons and other configuration details.",
tags=["Applications"],
responses={
200: "Successfully retrieved application meta information.",
400: "`app_unavailable` : App unavailable or misconfigured.",
},
)
@service_api_ns.doc("get_app_meta")
@service_api_ns.doc(description="Get application metadata")
@service_api_ns.doc(
responses={
200: "Metadata retrieved successfully",
401: "Unauthorized - invalid API token",
}
)
@service_api_ns.response(200, "Metadata retrieved successfully", service_api_ns.models[AppMetaResponse.__name__])
@validate_app_token
def get(self, app_model: App):
"""Get app metadata.
Returns metadata about the application including configuration and settings.
"""
try:
tool_icons = application_services().app_definitions.get_tool_icons(app_model.id)
except AppDefinitionUnavailableError:
raise AppUnavailableError() from None
return dump_response(AppMetaResponse, {"tool_icons": tool_icons})
@service_api_ns.route("/info")
class AppInfoApi(Resource):
@error_responses(AppUnavailableError)
@service_api_ns.doc(
summary="Get App Info",
description="Retrieve basic information about this application, including name, description, tags, and mode.",
tags=["Applications"],
responses={
200: "Basic information of the application.",
400: "`app_unavailable` : App unavailable or misconfigured.",
},
)
@service_api_ns.doc("get_app_info")
@service_api_ns.doc(description="Get basic application information")
@service_api_ns.doc(
responses={
200: "Application info retrieved successfully",
401: "Unauthorized - invalid API token",
}
)
@service_api_ns.response(
200,
"Application info retrieved successfully",
service_api_ns.models[AppInfoResponse.__name__],
)
@validate_app_token
def get(self, app_model: App):
"""Get app information.
Returns basic information about the application including name, description, tags, and mode.
"""
try:
summary = application_services().app_definitions.get_summary(app_model.id)
except AppDefinitionUnavailableError:
raise AppUnavailableError() from None
return dump_response(AppInfoResponse, summary)
@@ -0,0 +1,249 @@
import logging
from flask import request
from flask_restx import Resource
from sqlalchemy.orm import Session
from werkzeug.exceptions import InternalServerError
import services
from controllers.common.controller_schemas import TextToAudioPayload
from controllers.common.fields import AudioBinaryResponse, AudioTranscriptResponse
from controllers.common.schema import register_response_schema_models, register_schema_model
from controllers.common.session import with_session
from controllers.console.wraps import model_validate
from controllers.service_api import service_api_ns
from controllers.service_api.app.error import (
AppUnavailableError,
AudioTooLargeError,
CompletionRequestError,
NoAudioUploadedError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderNotSupportSpeechToTextError,
ProviderQuotaExceededError,
SpeechToTextDisabledError,
UnsupportedAudioTypeError,
)
from controllers.service_api.schema import binary_response, expect_with_user, multipart_file_params
from controllers.service_api.wraps import FetchUserArg, WhereisUserArg, validate_app_token
from core.base.tts.audio_mime import SUPPORTED_TTS_AUDIO_MIME_TYPES
from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError
from graphon.model_runtime.errors.invoke import InvokeError
from libs.external_api import error_responses
from libs.helper import dump_response
from models.model import App, EndUser
from services.app_ref_service import AppRefService
from services.audio_service import AudioService
from services.errors.audio import (
AudioTooLargeServiceError,
NoAudioUploadedServiceError,
ProviderNotSupportSpeechToTextServiceError,
SpeechToTextDisabledServiceError,
UnsupportedAudioTypeServiceError,
)
logger = logging.getLogger(__name__)
register_response_schema_models(service_api_ns, AudioBinaryResponse, AudioTranscriptResponse)
@service_api_ns.route("/audio-to-text")
class AudioApi(Resource):
@error_responses(
AppUnavailableError,
AudioTooLargeError,
CompletionRequestError,
NoAudioUploadedError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderNotSupportSpeechToTextError,
ProviderQuotaExceededError,
SpeechToTextDisabledError,
UnsupportedAudioTypeError,
)
@service_api_ns.doc(
summary="Convert Audio to Text",
description=(
"Convert audio file to text. Supported MIME types: `audio/mp3`, `audio/mpga`, `audio/m4a`, "
"`audio/x-m4a`, `audio/wav`, and `audio/amr`. File size limit is `30 MB`."
),
tags=["TTS"],
responses={
200: "Successfully converted audio to text.",
400: (
"- `app_unavailable` : App unavailable or misconfigured.\n"
"- `speech_to_text_disabled` : Speech-to-text is disabled for this app.\n"
"- `provider_not_support_speech_to_text` : Model provider does not support speech-to-text.\n"
"- `provider_not_initialize` : No valid model provider credentials found.\n"
"- `provider_quota_exceeded` : Model provider quota exhausted.\n"
"- `model_currently_not_support` : Current model does not support this operation.\n"
"- `completion_request_error` : Speech recognition request failed."
),
413: "`audio_too_large` : Audio file size exceeded the limit.",
415: "`unsupported_audio_type` : Audio type is not allowed.",
500: "`internal_server_error` : Internal server error.",
},
)
@service_api_ns.doc("audio_to_text")
@service_api_ns.doc(description="Convert audio to text using speech-to-text")
@service_api_ns.doc(
consumes=["multipart/form-data"],
params=multipart_file_params(
include_user=True,
file_description=(
"Audio file to transcribe. Supported MIME types: `audio/mp3`, `audio/mpga`, `audio/m4a`, "
"`audio/x-m4a`, `audio/wav`, and `audio/amr`. File size limit is `30 MB`."
),
),
)
@service_api_ns.doc(
responses={
200: "Audio successfully transcribed",
400: "Bad request - no audio or invalid audio",
401: "Unauthorized - invalid API token",
413: "Audio file too large",
415: "Unsupported audio type",
500: "Internal server error",
}
)
@service_api_ns.response(
200,
"Audio successfully transcribed",
service_api_ns.models[AudioTranscriptResponse.__name__],
)
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.FORM))
@with_session(write=False)
def post(self, session: Session, app_model: App, end_user: EndUser):
"""Convert audio to text using speech-to-text.
Accepts an audio file upload and returns the transcribed text.
"""
file = request.files.get("file")
try:
response = AudioService.transcript_asr(
app_model=app_model,
file=file,
session=session,
end_user=end_user.id,
)
return dump_response(AudioTranscriptResponse, response)
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
logger.exception("App model config broken.")
raise AppUnavailableError() from caught_error
except NoAudioUploadedServiceError as caught_error:
raise NoAudioUploadedError() from caught_error
except AudioTooLargeServiceError as e:
raise AudioTooLargeError(str(e)) from e
except UnsupportedAudioTypeServiceError as caught_error:
raise UnsupportedAudioTypeError() from caught_error
except ProviderNotSupportSpeechToTextServiceError as caught_error:
raise ProviderNotSupportSpeechToTextError() from caught_error
except SpeechToTextDisabledServiceError as caught_error:
raise SpeechToTextDisabledError() 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 e:
logger.exception("internal server error.")
raise InternalServerError() from e
register_schema_model(service_api_ns, TextToAudioPayload)
@service_api_ns.route("/text-to-audio")
class TextApi(Resource):
@error_responses(
AppUnavailableError,
CompletionRequestError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
)
@service_api_ns.doc(
summary="Convert Text to Audio",
description="Convert text to speech.",
tags=["TTS"],
responses={
200: (
"Returns the generated audio. The `Content-Type` header reflects the provider audio container, "
"verified from the response bytes when recognizable. The binary response can be AAC, FLAC, MP4, "
"MP3, Ogg, WAV, or WebM."
),
400: (
"- `app_unavailable` : App unavailable or misconfigured.\n"
"- `provider_not_initialize` : No valid model provider credentials found.\n"
"- `provider_quota_exceeded` : Model provider quota exhausted.\n"
"- `model_currently_not_support` : Current model does not support this operation.\n"
"- `completion_request_error` : Text-to-speech request failed."
),
500: "`internal_server_error` : Internal server error.",
},
)
@expect_with_user(service_api_ns, TextToAudioPayload)
@binary_response(service_api_ns, SUPPORTED_TTS_AUDIO_MIME_TYPES)
@service_api_ns.doc("text_to_audio")
@service_api_ns.doc(description="Convert text to audio using text-to-speech")
@service_api_ns.doc(
responses={
200: "Text successfully converted to audio",
400: "Bad request - invalid parameters",
401: "Unauthorized - invalid API token",
500: "Internal server error",
}
)
# TTS returns provider audio bytes, so the success response is intentionally schema-less.
@service_api_ns.response(200, "Text successfully converted to audio")
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON))
@with_session(write=False)
@model_validate(TextToAudioPayload)
def post(self, payload: TextToAudioPayload, session: Session, app_model: App, end_user: EndUser):
"""Convert text to audio using text-to-speech.
Converts the provided text to audio using the specified voice.
"""
try:
message_id = payload.message_id
text = payload.text
voice = payload.voice
message_ref = None
if message_id:
app_ref = AppRefService.create_app_ref(app_model)
message_ref = AppRefService.create_message_ref(
app_ref,
message_id,
end_user_id=end_user.id,
)
return AudioService.transcript_tts(
app_model=app_model,
session=session,
text=text,
voice=voice,
end_user=end_user.external_user_id,
message_ref=message_ref,
)
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 e:
logger.exception("internal server error.")
raise InternalServerError() from e
@@ -0,0 +1,533 @@
import logging
from typing import Any, Literal
from uuid import UUID
from flask import request
from flask_restx import Resource
from pydantic import BaseModel, Field, field_validator
from pydantic.json_schema import SkipJsonSchema
from sqlalchemy.orm import Session
from werkzeug.exceptions import BadRequest, InternalServerError, NotFound
import services
from configs import dify_config
from controllers.common.fields import ChatBlockingResponse, CompletionBlockingResponse, SimpleResultResponse
from controllers.common.schema import register_response_schema_models, register_schema_models
from controllers.console.app.wraps import with_session
from controllers.service_api import service_api_ns
from controllers.service_api.app.error import (
AgentNotPublishedError,
AppUnavailableError,
CompletionRequestError,
ConversationCompletedError,
NotChatAppError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
WorkflowVersionExecutionNotAllowedError,
)
from controllers.service_api.schema import (
SCOPED_TASK_STOP_USER_DESCRIPTION,
InputFileList,
expect_user_json,
expect_with_user,
json_or_event_stream_response,
)
from controllers.service_api.wraps import FetchUserArg, WhereisUserArg, validate_app_token
from controllers.web.error import InvokeRateLimitError as InvokeRateLimitHttpError
from core.app.apps.agent_app.errors import AgentAppNotPublishedError
from core.app.entities.app_invoke_entities import InvokeFrom
from core.errors.error import (
ModelCurrentlyNotSupportError,
ProviderTokenNotInitError,
QuotaExceededError,
)
from core.helper.trace_id_helper import get_external_trace_id, get_trace_session_id, omit_trace_session_id_from_payload
from enums import CloudPlan, DeploymentEdition
from graphon.model_runtime.errors.invoke import InvokeError
from libs import helper
from libs.external_api import error_responses
from libs.helper import UUIDStrOrEmpty
from models.model import App, AppMode, EndUser
from services.app_generate_service import AppGenerateService
from services.app_task_service import AppTaskService
from services.billing_service import BillingService
from services.conversation_service import ConversationService
from services.errors.app import IsDraftWorkflowError, WorkflowIdFormatError, WorkflowNotFoundError
from services.errors.llm import InvokeRateLimitError
logger = logging.getLogger(__name__)
def _resolve_agent_app_streaming(*, app_mode: AppMode, response_mode: str | None) -> bool:
"""Agent App runtime is SSE-only until backend blocking runs are supported."""
if app_mode != AppMode.AGENT:
return response_mode == "streaming"
if response_mode == "blocking":
raise BadRequest("Agent App only supports streaming response mode.")
return True
class CompletionRequestPayload(BaseModel):
inputs: dict[str, Any] = Field(
description=(
"Values for app-defined variables. Refer to the `user_input_form` field in the "
"[Get App Parameters](/api-reference/applications/get-app-parameters) response to discover expected "
"variable names and types."
)
)
query: str = Field(default="", description="User input or prompt content.")
files: InputFileList = Field(
default=None,
description=(
"File list for multimodal understanding, including images, documents, audio, and video. To attach a "
"local file, first upload it via [Upload File](/api-reference/files/upload-file) and use the returned "
"`id` as `upload_file_id` with `transfer_method: local_file`."
),
)
response_mode: Literal["blocking", "streaming"] | None = Field(
default=None,
description=(
"Response mode. `streaming` uses Server-Sent Events; `blocking` returns after completion. When omitted, "
"the request runs in blocking mode."
),
)
retriever_from: SkipJsonSchema[str] = Field(default="dev")
trace_session_id: SkipJsonSchema[str | None] = Field(
default=None, description="Trace session ID for observability grouping"
)
class ChatRequestPayload(BaseModel):
inputs: dict[str, Any] = Field(
description=(
"Values for app-defined variables. Refer to the `user_input_form` field in the "
"[Get App Parameters](/api-reference/applications/get-app-parameters) response to discover expected "
"variable names and types."
)
)
query: str = Field(description="User input or question content.")
files: InputFileList = Field(
default=None,
description=(
"File list for multimodal understanding, including images, documents, audio, and video. To attach a "
"local file, first upload it via [Upload File](/api-reference/files/upload-file) and use the returned "
"`id` as `upload_file_id` with `transfer_method: local_file`."
),
)
response_mode: Literal["blocking", "streaming"] | None = Field(
default=None,
description=(
"Response mode. `streaming` uses Server-Sent Events; `blocking` returns after completion. New Agent app "
"mode supports streaming only. When omitted, non-Agent apps run in blocking mode and new Agent apps stream."
),
)
conversation_id: UUIDStrOrEmpty | None = Field(
default=None,
description=(
"Conversation ID to continue a conversation. Omit this field or pass an empty string to start a new "
"conversation, then pass the returned `conversation_id` in subsequent requests."
),
)
retriever_from: SkipJsonSchema[str] = Field(default="dev")
auto_generate_name: bool = Field(
default=True,
description=(
"Auto-generate the conversation title. If `false`, use the Rename Conversation API with "
"`auto_generate: true` to generate the title asynchronously."
),
)
workflow_id: str | None = Field(
default=None,
description=(
"Published workflow version ID to execute for advanced chat. If omitted, the app's current published "
"workflow is used."
),
)
trace_session_id: SkipJsonSchema[str | None] = Field(
default=None, description="Trace session ID for observability grouping"
)
@field_validator("conversation_id", mode="before")
@classmethod
def normalize_conversation_id(cls, value: str | UUID | None) -> str | None:
"""Allow missing or blank conversation IDs; enforce UUID format when provided."""
if isinstance(value, str):
value = value.strip()
if not value:
return None
try:
return helper.uuid_value(value)
except ValueError as exc:
raise ValueError("conversation_id must be a valid UUID") from exc
register_schema_models(service_api_ns, CompletionRequestPayload, ChatRequestPayload)
register_response_schema_models(
service_api_ns,
SimpleResultResponse,
ChatBlockingResponse,
CompletionBlockingResponse,
)
@service_api_ns.route("/completion-messages")
class CompletionApi(Resource):
@error_responses(
AppUnavailableError,
CompletionRequestError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
)
@service_api_ns.doc(
summary="Send Completion Message",
description="Send a request to the text generation application.",
tags=["Completions"],
responses={
200: (
"Successful response. The content type and structure depend on the `response_mode` parameter "
"in the request.\n"
"\n"
"- If `response_mode` is `blocking`, returns `application/json` with a `CompletionResponse` "
"object.\n"
"- If `response_mode` is `streaming`, returns `text/event-stream` with a stream of "
"`ChunkCompletionEvent` objects."
),
400: (
"- `app_unavailable` : App unavailable or misconfigured.\n"
"- `provider_not_initialize` : No valid model provider credentials found.\n"
"- `provider_quota_exceeded` : Model provider quota exhausted.\n"
"- `model_currently_not_support` : Current model unavailable.\n"
"- `completion_request_error` : Text generation failed."
),
429: "`too_many_requests` : Too many concurrent requests for this app.",
500: "`internal_server_error` : Internal server error.",
},
)
@expect_with_user(service_api_ns, CompletionRequestPayload)
@json_or_event_stream_response(service_api_ns)
@service_api_ns.doc("create_completion")
@service_api_ns.doc(description="Create a completion for the given prompt")
@service_api_ns.doc(
responses={
200: "Completion created successfully",
400: "Bad request - invalid parameters",
401: "Unauthorized - invalid API token",
500: "Internal server error",
}
)
@service_api_ns.response(
200,
"Completion created successfully",
service_api_ns.models[CompletionBlockingResponse.__name__],
)
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON, required=True))
@with_session
def post(self, session: Session, app_model: App, end_user: EndUser):
"""Create a completion for the given prompt.
This endpoint generates a completion based on the provided inputs and query.
Supports both blocking and streaming response modes.
"""
if app_model.mode != AppMode.COMPLETION:
raise AppUnavailableError()
payload = CompletionRequestPayload.model_validate(
omit_trace_session_id_from_payload(service_api_ns.payload) or {}
)
external_trace_id = get_external_trace_id(request)
args = payload.model_dump(exclude_none=True)
trace_session_id = get_trace_session_id(request)
if trace_session_id:
args["trace_session_id"] = trace_session_id
if external_trace_id:
args["external_trace_id"] = external_trace_id
streaming = payload.response_mode == "streaming"
args["auto_generate_name"] = False
try:
response = AppGenerateService.generate(
session=session,
app_model=app_model,
user=end_user,
args=args,
invoke_from=InvokeFrom.SERVICE_API,
streaming=streaming,
)
# response-contract:ignore compact_generate_response
return helper.compact_generate_response(response)
except services.errors.conversation.ConversationNotExistsError as caught_error:
raise NotFound("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 AgentAppNotPublishedError as caught_error:
raise AgentNotPublishedError() 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
@service_api_ns.route("/completion-messages/<string:task_id>/stop")
class CompletionStopApi(Resource):
@error_responses(AppUnavailableError)
@service_api_ns.doc(
summary="Stop Completion Message Generation",
description="Stops a completion message generation task. Only supported in `streaming` mode.",
tags=["Completions"],
responses={
400: "`app_unavailable` : App unavailable or misconfigured.",
},
)
@expect_user_json(
service_api_ns,
model_name="ScopedTaskStopPayload",
user_description=SCOPED_TASK_STOP_USER_DESCRIPTION,
)
@service_api_ns.doc("stop_completion")
@service_api_ns.doc(description="Stop a running completion task")
@service_api_ns.doc(
params={"task_id": ("Task ID, obtained from a streaming chunk returned by the Send Completion Message API.")}
)
@service_api_ns.doc(
responses={
200: "Task stopped successfully",
401: "Unauthorized - invalid API token",
}
)
@service_api_ns.response(200, "Task stopped successfully", service_api_ns.models[SimpleResultResponse.__name__])
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON, required=True))
def post(self, app_model: App, end_user: EndUser, task_id: str):
"""Stop a running completion task."""
if app_model.mode != AppMode.COMPLETION:
raise AppUnavailableError()
AppTaskService.stop_task(
tenant_id=app_model.tenant_id,
app_id=app_model.id,
task_id=task_id,
invoke_from=InvokeFrom.SERVICE_API,
user_id=end_user.id,
app_mode=AppMode.value_of(app_model.mode),
)
return SimpleResultResponse(result="success").model_dump(mode="json"), 200
@service_api_ns.route("/chat-messages")
class ChatApi(Resource):
@error_responses(
AgentNotPublishedError,
AppUnavailableError,
CompletionRequestError,
InvokeRateLimitHttpError,
NotChatAppError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
WorkflowVersionExecutionNotAllowedError,
)
@service_api_ns.doc(
summary="Send Chat Message",
description="Send a request to the chat application.",
tags=["Chats", "Chatflows"],
responses={
200: (
"Successful response. The content type and structure depend on the `response_mode` parameter "
"in the request.\n"
"\n"
"- If `response_mode` is `blocking`, returns `application/json` with a "
"`ChatCompletionResponse` object.\n"
"- If `response_mode` is `streaming`, returns `text/event-stream` with a stream of "
"Server-Sent Events."
),
400: (
"- `app_unavailable` : App unavailable or misconfigured.\n"
"- `not_chat_app` : App mode does not match the API route.\n"
"- `conversation_completed` : The conversation has ended.\n"
"- `provider_not_initialize` : No valid model provider credentials found.\n"
"- `provider_quota_exceeded` : Model provider quota exhausted.\n"
"- `model_currently_not_support` : Current model unavailable.\n"
"- `completion_request_error` : Text generation failed."
),
403: (
"`workflow_version_execution_not_allowed` : Workflow version execution is unavailable on the "
"current plan. Upgrade to a paid plan."
),
404: "`not_found` : Conversation does not exist.",
429: (
"- `too_many_requests` : Too many concurrent requests for this app.\n"
"- `rate_limit_error` : The Dify Cloud workflow execution quota for this workspace has been reached."
),
500: "`internal_server_error` : Internal server error.",
},
)
@expect_with_user(service_api_ns, ChatRequestPayload)
@json_or_event_stream_response(service_api_ns)
@service_api_ns.doc("create_chat_message")
@service_api_ns.doc(description="Send a message in a chat conversation")
@service_api_ns.doc(
responses={
200: "Message sent successfully",
400: "Bad request - invalid parameters or workflow issues",
401: "Unauthorized - invalid API token",
403: "Forbidden - upgrade to a paid plan to execute a specific workflow version",
404: "Conversation or workflow not found",
429: "Rate limit exceeded",
500: "Internal server error",
}
)
@service_api_ns.response(
200,
"Message sent successfully",
service_api_ns.models[ChatBlockingResponse.__name__],
)
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON, required=True))
@with_session
def post(self, session: Session, app_model: App, end_user: EndUser):
"""Send a message in a chat conversation.
This endpoint handles chat messages for chat, agent chat, and advanced chat applications.
Supports conversation management and both blocking and streaming response modes.
"""
app_mode = AppMode.value_of(app_model.mode)
if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}:
raise NotChatAppError()
payload = ChatRequestPayload.model_validate(omit_trace_session_id_from_payload(service_api_ns.payload) or {})
if (
app_mode == AppMode.ADVANCED_CHAT
and payload.workflow_id
and dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD
):
billing_info = BillingService.get_info(app_model.tenant_id, exclude_vector_space=True)
if billing_info.subscription.plan == CloudPlan.SANDBOX:
raise WorkflowVersionExecutionNotAllowedError()
external_trace_id = get_external_trace_id(request)
args = payload.model_dump(exclude_none=True)
trace_session_id = get_trace_session_id(request)
if trace_session_id:
args["trace_session_id"] = trace_session_id
if external_trace_id:
args["external_trace_id"] = external_trace_id
streaming = _resolve_agent_app_streaming(app_mode=app_mode, response_mode=payload.response_mode)
try:
# Eagerly validate conversation to avoid hanging on invalid conversation_id
if payload.conversation_id:
ConversationService.get_conversation(
app_model=app_model,
conversation_id=payload.conversation_id,
user=end_user,
session=session,
)
response = AppGenerateService.generate(
session=session,
app_model=app_model,
user=end_user,
args=args,
invoke_from=InvokeFrom.SERVICE_API,
streaming=streaming,
)
# response-contract:ignore compact_generate_response
return helper.compact_generate_response(response)
except WorkflowNotFoundError as ex:
raise NotFound(str(ex)) from ex
except IsDraftWorkflowError as ex:
raise BadRequest(str(ex)) from ex
except WorkflowIdFormatError as ex:
raise BadRequest(str(ex)) from ex
except services.errors.conversation.ConversationNotExistsError as caught_error:
raise NotFound("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 AgentAppNotPublishedError as caught_error:
raise AgentNotPublishedError() 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 InvokeRateLimitError as ex:
raise InvokeRateLimitHttpError(ex.description) from ex
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
@service_api_ns.route("/chat-messages/<string:task_id>/stop")
class ChatStopApi(Resource):
@error_responses(NotChatAppError)
@service_api_ns.doc(
summary="Stop Chat Message Generation",
description="Stops a chat message generation task. Only supported in `streaming` mode.",
tags=["Chats", "Chatflows"],
responses={
400: "`not_chat_app` : App mode does not match the API route.",
},
)
@expect_user_json(
service_api_ns,
model_name="ScopedTaskStopPayload",
user_description=SCOPED_TASK_STOP_USER_DESCRIPTION,
)
@service_api_ns.doc("stop_chat_message")
@service_api_ns.doc(description="Stop a running chat message generation")
@service_api_ns.doc(
params={"task_id": "Task ID, obtained from a streaming chunk returned by the Send Chat Message API."}
)
@service_api_ns.doc(
responses={
200: "Task stopped successfully",
401: "Unauthorized - invalid API token",
}
)
@service_api_ns.response(200, "Task stopped successfully", service_api_ns.models[SimpleResultResponse.__name__])
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON, required=True))
def post(self, app_model: App, end_user: EndUser, task_id: str):
"""Stop a running chat message generation."""
app_mode = AppMode.value_of(app_model.mode)
if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}:
raise NotChatAppError()
AppTaskService.stop_task(
tenant_id=app_model.tenant_id,
app_id=app_model.id,
task_id=task_id,
invoke_from=InvokeFrom.SERVICE_API,
user_id=end_user.id,
app_mode=app_mode,
)
return SimpleResultResponse(result="success").model_dump(mode="json"), 200
@@ -0,0 +1,469 @@
from datetime import datetime
from http import HTTPStatus
from typing import Annotated, Any, Literal
from uuid import UUID
from flask_restx import Resource
from pydantic import BaseModel, Field, JsonValue, WithJsonSchema, field_validator
import services
from controllers.common.controller_schemas import ConversationRenamePayload
from controllers.common.errors import (
ConversationCursorNotFoundHTTPError,
ConversationFirstMessageNotFoundHTTPError,
ConversationNotFoundHTTPError,
ConversationVariableNotFoundHTTPError,
ConversationVariableTypeMismatchHTTPError,
)
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
from controllers.console.wraps import model_validate
from controllers.service_api import service_api_ns
from controllers.service_api.app.error import NotChatAppError
from controllers.service_api.flask_admission import service_api_end_user_admission
from controllers.service_api.schema import expect_user_json, expect_with_user
from controllers.service_api.wraps import FetchUserArg, WhereisUserArg
from extensions.ext_application_services import application_services
from fields._value_type_serializer import serialize_value_type
from fields.base import ResponseModel
from fields.conversation_fields import (
ConversationInfiniteScrollPagination,
SimpleConversation,
)
from graphon.variables.types import SegmentType
from libs.external_api import error_responses
from libs.helper import UUIDStrOrEmpty, dump_response, to_timestamp
from machinery.context import ServiceApiEndUserContext
from models.model import AppMode
from services.entities.conversation_entities import EndUserConversationRef, EndUserConversationScope
from services.errors.message import MessageNotExistsError
UUIDString = Annotated[str, WithJsonSchema({"format": "uuid", "type": "string"})]
Int64 = Annotated[int, WithJsonSchema({"format": "int64", "type": "integer"})]
class ConversationListQuery(BaseModel):
last_id: UUIDStrOrEmpty | None = Field(
default=None,
description="The ID of the last record on the current page. Used to fetch the next page.",
)
limit: int = Field(default=20, ge=1, le=100, description="Number of records to return.")
sort_by: Literal["created_at", "-created_at", "updated_at", "-updated_at"] = Field(
default="-updated_at",
description="Sorting field. Use the `-` prefix for descending order.",
)
class ConversationVariablesQuery(BaseModel):
last_id: UUIDStrOrEmpty | None = Field(
default=None,
description="The ID of the last record on the current page. Used to fetch the next page.",
)
limit: int = Field(default=20, ge=1, le=100, description="Number of records to return.")
variable_name: str | None = Field(
default=None,
description="Filter variables by a specific name.",
min_length=1,
max_length=255,
)
@field_validator("variable_name", mode="before")
@classmethod
def validate_variable_name(cls, v: str | None) -> str | None:
"""
Validate variable_name to prevent injection attacks.
"""
if v is None:
return v
# Only allow safe characters: alphanumeric, underscore, hyphen, period
if not v.replace("-", "").replace("_", "").replace(".", "").isalnum():
raise ValueError(
"Variable name can only contain letters, numbers, hyphens (-), underscores (_), and periods (.)"
)
# Prevent SQL injection patterns
dangerous_patterns = ["'", '"', ";", "--", "/*", "*/", "xp_", "sp_"]
for pattern in dangerous_patterns:
if pattern in v.lower():
raise ValueError(f"Variable name contains invalid characters: {pattern}")
return v
class ConversationVariableUpdatePayload(BaseModel):
value: JsonValue = Field(description="The new value for the variable. Must match the variable's expected type.")
class ConversationVariableResponse(ResponseModel):
id: UUIDString
name: str
value_type: str
value: str | None = None
description: str | None = None
created_at: Int64 | None = None
updated_at: Int64 | None = None
@field_validator("value_type", mode="before")
@classmethod
def normalize_value_type(cls, value: Any) -> str:
exposed_type = getattr(value, "exposed_type", None)
if callable(exposed_type):
return str(exposed_type())
if isinstance(value, str):
try:
return str(SegmentType(value).exposed_type())
except ValueError:
return value
try:
return serialize_value_type(value)
except (AttributeError, TypeError, ValueError):
pass
try:
return serialize_value_type({"value_type": value})
except (AttributeError, TypeError, ValueError):
value_attr = getattr(value, "value", None)
if value_attr is not None:
return str(value_attr)
return str(value)
@field_validator("value", mode="before")
@classmethod
def normalize_value(cls, value: Any | None) -> str | None:
if value is None:
return None
if isinstance(value, str):
return value
return str(value)
@field_validator("created_at", "updated_at", mode="before")
@classmethod
def normalize_timestamp(cls, value: datetime | int | None) -> int | None:
return to_timestamp(value)
class ConversationVariableInfiniteScrollPaginationResponse(ResponseModel):
limit: int
has_more: bool
data: list[ConversationVariableResponse]
register_schema_models(
service_api_ns,
ConversationListQuery,
ConversationRenamePayload,
ConversationVariablesQuery,
ConversationVariableUpdatePayload,
)
register_response_schema_models(
service_api_ns,
ConversationVariableResponse,
ConversationVariableInfiniteScrollPaginationResponse,
ConversationInfiniteScrollPagination,
SimpleConversation,
)
@service_api_ns.route("/conversations")
class ConversationApi(Resource):
@error_responses(NotChatAppError, ConversationCursorNotFoundHTTPError, ConversationNotFoundHTTPError)
@service_api_ns.doc(
summary="List Conversations",
description="Retrieve the conversation list for the current user, ordered by most recently active.",
tags=["Conversations"],
responses={
HTTPStatus.OK: "Conversations retrieved successfully.",
HTTPStatus.BAD_REQUEST: "Invalid app selection or app mode does not match the API route.",
HTTPStatus.UNAUTHORIZED: "Invalid API credentials.",
HTTPStatus.FORBIDDEN: "API credential, app or workspace access is unavailable.",
HTTPStatus.NOT_FOUND: (
"`conversation_cursor_not_found`: Cursor is outside the current list. "
"`conversation_not_found`: The app or user is no longer available."
),
HTTPStatus.UNPROCESSABLE_ENTITY: "Invalid conversation list query.",
},
)
@service_api_ns.doc("list_conversations")
@service_api_ns.doc(params=query_params_from_model(ConversationListQuery))
@service_api_ns.response(
HTTPStatus.OK,
"Conversations retrieved successfully",
service_api_ns.models[ConversationInfiniteScrollPagination.__name__],
)
@service_api_end_user_admission(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY))
@model_validate(ConversationListQuery)
def get(self, query_args: ConversationListQuery, context: ServiceApiEndUserContext) -> dict[str, object]:
"""List the current user's conversations, optionally continuing from a cursor."""
app_mode = AppMode.value_of(context.app_mode)
if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}:
raise NotChatAppError()
try:
pagination = application_services().conversation_queries.get_page(
scope=EndUserConversationScope(
app_id=context.app_id,
tenant_id=context.tenant_id,
end_user_id=context.end_user_id,
),
invoke_from="service-api",
last_id=query_args.last_id or None,
limit=query_args.limit,
pinned=None,
sort_by=query_args.sort_by,
)
return dump_response(ConversationInfiniteScrollPagination, pagination)
except services.errors.conversation.LastConversationNotExistsError as error:
raise ConversationCursorNotFoundHTTPError() from error
except services.errors.conversation.ConversationNotExistsError as error:
raise ConversationNotFoundHTTPError() from error
@service_api_ns.route("/conversations/<uuid:conversation_id>")
class ConversationDetailApi(Resource):
@error_responses(NotChatAppError, ConversationNotFoundHTTPError)
@service_api_ns.doc(
summary="Delete Conversation",
description="Delete a conversation.",
tags=["Conversations"],
responses={
HTTPStatus.NO_CONTENT: "Conversation deleted successfully.",
HTTPStatus.BAD_REQUEST: "Invalid app selection or app mode does not match the API route.",
HTTPStatus.UNAUTHORIZED: "Invalid API credentials.",
HTTPStatus.FORBIDDEN: "API credential, app or workspace access is unavailable.",
HTTPStatus.NOT_FOUND: "`conversation_not_found`: Conversation does not exist for this user and app.",
},
)
@expect_user_json(service_api_ns)
@service_api_ns.doc("delete_conversation")
@service_api_ns.doc(params={"conversation_id": "Conversation ID."})
@service_api_end_user_admission(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON))
def delete(self, context: ServiceApiEndUserContext, conversation_id: UUID) -> tuple[str, HTTPStatus]:
"""Delete a specific conversation."""
app_mode = AppMode.value_of(context.app_mode)
if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}:
raise NotChatAppError()
try:
application_services().conversation_commands.delete(
ref=EndUserConversationRef(
app_id=context.app_id,
tenant_id=context.tenant_id,
end_user_id=context.end_user_id,
conversation_id=str(conversation_id),
)
)
except services.errors.conversation.ConversationNotExistsError as error:
raise ConversationNotFoundHTTPError() from error
return "", HTTPStatus.NO_CONTENT
@service_api_ns.route("/conversations/<uuid:conversation_id>/name")
class ConversationRenameApi(Resource):
@error_responses(NotChatAppError, ConversationNotFoundHTTPError, ConversationFirstMessageNotFoundHTTPError)
@service_api_ns.doc(
summary="Rename Conversation",
description=(
"Rename a conversation or auto-generate a name. The conversation name is used for display on "
"clients that support multiple conversations."
),
tags=["Conversations"],
responses={
HTTPStatus.OK: "Conversation renamed successfully; model failure preserves the existing name.",
HTTPStatus.BAD_REQUEST: "Invalid app selection or app mode does not match the API route.",
HTTPStatus.UNAUTHORIZED: "Invalid API credentials.",
HTTPStatus.FORBIDDEN: "API credential, app or workspace access is unavailable.",
HTTPStatus.NOT_FOUND: (
"`conversation_not_found`: Conversation does not exist. "
"`conversation_first_message_not_found`: No first message is available for automatic naming."
),
HTTPStatus.UNPROCESSABLE_ENTITY: "Invalid conversation rename payload.",
},
)
@expect_with_user(service_api_ns, ConversationRenamePayload)
@service_api_ns.doc("rename_conversation")
@service_api_ns.doc(description="Rename a conversation or auto-generate a name")
@service_api_ns.doc(params={"conversation_id": "Conversation ID."})
@service_api_ns.response(
HTTPStatus.OK,
"Conversation renamed successfully",
service_api_ns.models[SimpleConversation.__name__],
)
@service_api_end_user_admission(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON))
@model_validate(ConversationRenamePayload)
def post(
self, payload: ConversationRenamePayload, context: ServiceApiEndUserContext, conversation_id: UUID
) -> dict[str, object]:
"""Rename a conversation or auto-generate a name."""
app_mode = AppMode.value_of(context.app_mode)
if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}:
raise NotChatAppError()
conversation_id_str = str(conversation_id)
try:
conversation = application_services().conversation_names.rename(
ref=EndUserConversationRef(
app_id=context.app_id,
tenant_id=context.tenant_id,
end_user_id=context.end_user_id,
conversation_id=conversation_id_str,
),
app_mode=context.app_mode,
name=payload.name,
auto_generate=payload.auto_generate,
)
return dump_response(SimpleConversation, conversation)
except services.errors.conversation.ConversationNotExistsError as error:
raise ConversationNotFoundHTTPError() from error
except MessageNotExistsError as error:
raise ConversationFirstMessageNotFoundHTTPError() from error
@service_api_ns.route("/conversations/<uuid:conversation_id>/variables")
class ConversationVariablesApi(Resource):
@error_responses(NotChatAppError, ConversationNotFoundHTTPError, ConversationVariableNotFoundHTTPError)
@service_api_ns.doc(
summary="List Conversation Variables",
description="Retrieve variables from a specific conversation.",
tags=["Conversations"],
responses={
HTTPStatus.OK: "Conversation variables retrieved successfully.",
HTTPStatus.BAD_REQUEST: "Invalid app selection or app mode does not match the API route.",
HTTPStatus.UNAUTHORIZED: "Invalid API credentials.",
HTTPStatus.FORBIDDEN: "API credential, app or workspace access is unavailable.",
HTTPStatus.NOT_FOUND: (
"`conversation_not_found`: Conversation does not exist for this user and app. "
"`conversation_variable_not_found`: Cursor variable is outside the current list."
),
HTTPStatus.UNPROCESSABLE_ENTITY: "Invalid conversation variables query.",
},
)
@service_api_ns.doc("list_conversation_variables")
@service_api_ns.doc(
params={"conversation_id": "Conversation ID.", **query_params_from_model(ConversationVariablesQuery)}
)
@service_api_ns.response(
HTTPStatus.OK,
"Variables retrieved successfully",
service_api_ns.models[ConversationVariableInfiniteScrollPaginationResponse.__name__],
)
@service_api_end_user_admission(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY))
@model_validate(ConversationVariablesQuery)
def get(
self, query_args: ConversationVariablesQuery, context: ServiceApiEndUserContext, conversation_id: UUID
) -> dict[str, object]:
"""List the current user's conversation variables."""
app_mode = AppMode.value_of(context.app_mode)
if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:
raise NotChatAppError()
try:
pagination = application_services().conversation_variables.get_page(
ref=EndUserConversationRef(
app_id=context.app_id,
tenant_id=context.tenant_id,
end_user_id=context.end_user_id,
conversation_id=str(conversation_id),
),
last_id=query_args.last_id or None,
limit=query_args.limit,
variable_name=query_args.variable_name,
)
return dump_response(
ConversationVariableInfiniteScrollPaginationResponse,
{
"limit": pagination.limit,
"has_more": pagination.has_more,
"data": [
{
"created_at": row.created_at,
"updated_at": row.updated_at,
**row.variable.model_dump(),
"id": row.id,
}
for row in pagination.data
],
},
)
except services.errors.conversation.ConversationNotExistsError as error:
raise ConversationNotFoundHTTPError() from error
except services.errors.conversation.ConversationVariableNotExistsError as error:
raise ConversationVariableNotFoundHTTPError() from error
@service_api_ns.route("/conversations/<uuid:conversation_id>/variables/<uuid:variable_id>")
class ConversationVariableDetailApi(Resource):
@error_responses(
NotChatAppError,
ConversationNotFoundHTTPError,
ConversationVariableNotFoundHTTPError,
ConversationVariableTypeMismatchHTTPError,
)
@service_api_ns.doc(
summary="Update Conversation Variable",
description="Update the value of a specific conversation variable. The value must match the expected type.",
tags=["Conversations"],
responses={
HTTPStatus.OK: "Variable updated successfully.",
HTTPStatus.BAD_REQUEST: (
"Invalid app selection or app mode does not match the API route. "
"`conversation_variable_type_mismatch`: Value does not match the variable's expected type. "
"`invalid_param`: Value violates variable constraints, including the size limit."
),
HTTPStatus.UNAUTHORIZED: "Invalid API credentials.",
HTTPStatus.FORBIDDEN: "API credential, app or workspace access is unavailable.",
HTTPStatus.NOT_FOUND: (
"`conversation_not_found`: Conversation does not exist for this user and app. "
"`conversation_variable_not_found`: Variable does not exist for this conversation."
),
HTTPStatus.UNPROCESSABLE_ENTITY: "Invalid conversation variable update payload.",
},
)
@expect_with_user(service_api_ns, ConversationVariableUpdatePayload)
@service_api_ns.doc("update_conversation_variable")
@service_api_ns.doc(params={"conversation_id": "Conversation ID.", "variable_id": "Variable ID."})
@service_api_ns.response(
HTTPStatus.OK,
"Variable updated successfully",
service_api_ns.models[ConversationVariableResponse.__name__],
)
@service_api_end_user_admission(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON))
@model_validate(ConversationVariableUpdatePayload)
def put(
self,
payload: ConversationVariableUpdatePayload,
context: ServiceApiEndUserContext,
conversation_id: UUID,
variable_id: UUID,
) -> dict[str, object]:
"""Update a value without changing the variable's identity, type, or metadata."""
app_mode = AppMode.value_of(context.app_mode)
if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:
raise NotChatAppError()
try:
row = application_services().conversation_variable_commands.update_value(
ref=EndUserConversationRef(
app_id=context.app_id,
tenant_id=context.tenant_id,
end_user_id=context.end_user_id,
conversation_id=str(conversation_id),
),
variable_id=str(variable_id),
new_value=payload.value,
)
return dump_response(
ConversationVariableResponse,
{
"created_at": row.created_at,
"updated_at": row.updated_at,
**row.variable.model_dump(),
"id": row.id,
},
)
except services.errors.conversation.ConversationNotExistsError as error:
raise ConversationNotFoundHTTPError() from error
except services.errors.conversation.ConversationVariableNotExistsError as error:
raise ConversationVariableNotFoundHTTPError() from error
except services.errors.conversation.ConversationVariableTypeMismatchError as error:
raise ConversationVariableTypeMismatchHTTPError(str(error)) from error
@@ -0,0 +1,163 @@
from http import HTTPStatus
from libs.exception import BaseHTTPException
from services.errors.app import (
TRIGGER_WORKFLOW_SERVICE_MODE_UNAVAILABLE_CODE,
TRIGGER_WORKFLOW_SERVICE_MODE_UNAVAILABLE_MESSAGE,
)
class AppNotFoundError(BaseHTTPException):
error_code = "app_not_found"
description = "The app no longer exists."
code = HTTPStatus.FORBIDDEN
class AppAbnormalStatusError(BaseHTTPException):
error_code = "app_abnormal_status"
description = "The app's status is abnormal."
code = HTTPStatus.FORBIDDEN
class AppApiDisabledError(BaseHTTPException):
error_code = "app_api_disabled"
description = "The app's API service has been disabled."
code = HTTPStatus.FORBIDDEN
class WorkspaceNotFoundError(BaseHTTPException):
error_code = "workspace_not_found"
description = "Tenant does not exist."
code = HTTPStatus.FORBIDDEN
class WorkspaceArchivedError(BaseHTTPException):
error_code = "workspace_archived"
description = "The workspace's status is archived."
code = HTTPStatus.FORBIDDEN
class AppUnavailableError(BaseHTTPException):
error_code = "app_unavailable"
description = "App unavailable, please check your app configurations."
code = 400
class AgentNotPublishedError(BaseHTTPException):
error_code = "agent_not_published"
description = "Agent has not been published. Please publish the Agent before using the API."
code = 400
class NotCompletionAppError(BaseHTTPException):
error_code = "not_completion_app"
description = "Please check if your Completion app mode matches the right API route."
code = 400
class NotChatAppError(BaseHTTPException):
error_code = "not_chat_app"
description = "Please check if your app mode matches the right API route."
code = 400
class NotWorkflowAppError(BaseHTTPException):
error_code = "not_workflow_app"
description = "Please check if your app mode matches the right API route."
code = 400
class WorkflowVersionExecutionNotAllowedError(BaseHTTPException):
error_code = "workflow_version_execution_not_allowed"
description = "Workflow version execution is not available on your current plan. Please upgrade to a paid plan."
code = 403
class TriggerWorkflowServiceModeUnavailableError(BaseHTTPException):
error_code = TRIGGER_WORKFLOW_SERVICE_MODE_UNAVAILABLE_CODE
description = TRIGGER_WORKFLOW_SERVICE_MODE_UNAVAILABLE_MESSAGE
code = 403
class ConversationCompletedError(BaseHTTPException):
error_code = "conversation_completed"
description = "The conversation has ended. Please start a new conversation."
code = 400
class ProviderNotInitializeError(BaseHTTPException):
error_code = "provider_not_initialize"
description = (
"No valid model provider credentials found. "
"Please go to Settings -> Model Provider to complete your provider credentials."
)
code = 400
class ProviderQuotaExceededError(BaseHTTPException):
error_code = "provider_quota_exceeded"
description = (
"Your quota for Dify Hosted OpenAI has been exhausted. "
"Please go to Settings -> Model Provider to complete your own provider credentials."
)
code = 400
class ProviderModelCurrentlyNotSupportError(BaseHTTPException):
error_code = "model_currently_not_support"
description = "Dify Hosted OpenAI trial currently not support the GPT-4 model."
code = 400
class CompletionRequestError(BaseHTTPException):
error_code = "completion_request_error"
description = "Completion request failed."
code = 400
class AppSuggestedQuestionsAfterAnswerDisabledError(BaseHTTPException):
error_code = "app_suggested_questions_after_answer_disabled"
description = "The 'Suggested Questions After Answer' feature is disabled."
code = 403
class NoAudioUploadedError(BaseHTTPException):
error_code = "no_audio_uploaded"
description = "Please upload your audio."
code = 400
class AudioTooLargeError(BaseHTTPException):
error_code = "audio_too_large"
description = "Audio size exceeded. {message}"
code = 413
class UnsupportedAudioTypeError(BaseHTTPException):
error_code = "unsupported_audio_type"
description = "Audio type not allowed."
code = 415
class ProviderNotSupportSpeechToTextError(BaseHTTPException):
error_code = "provider_not_support_speech_to_text"
description = "Provider not support speech to text."
code = 400
class SpeechToTextDisabledError(BaseHTTPException):
error_code = "speech_to_text_disabled"
description = "Speech to text is disabled."
code = 400
class FileNotFoundError(BaseHTTPException):
error_code = "file_not_found"
description = "The requested file was not found."
code = 404
class FileAccessDeniedError(BaseHTTPException):
error_code = "file_access_denied"
description = "Access to the requested file is denied."
code = 403
@@ -0,0 +1,103 @@
from flask import request
from flask_restx import Resource
from flask_restx.api import HTTPStatus
import services
from controllers.common.errors import (
BlockedFileExtensionError,
FilenameNotExistsError,
FileTooLargeError,
NoFileUploadedError,
TooManyFilesError,
UnsupportedFileTypeError,
)
from controllers.common.schema import JsonResponseWithStatus, register_response_schema_models
from controllers.service_api import service_api_ns
from controllers.service_api.schema import multipart_file_params
from controllers.service_api.wraps import FetchUserArg, WhereisUserArg, validate_app_token
from extensions.ext_application_services import application_services
from fields.file_fields import FileResponse
from libs.external_api import error_responses
from libs.helper import dump_response
from models import App, EndUser
register_response_schema_models(service_api_ns, FileResponse)
@service_api_ns.route("/files/upload")
class FileApi(Resource):
@error_responses(
BlockedFileExtensionError,
FilenameNotExistsError,
FileTooLargeError,
NoFileUploadedError,
TooManyFilesError,
UnsupportedFileTypeError,
)
@service_api_ns.doc(
summary="Upload File",
description=(
"Upload a file for use when sending messages, enabling multimodal understanding of images, "
"documents, audio, and video. Uploaded files are for use by the current end-user only."
),
tags=["Files"],
responses={
201: "File uploaded successfully.",
400: (
"- `no_file_uploaded` : No file was provided in the request.\n"
"- `too_many_files` : Only one file is allowed per request.\n"
"- `filename_not_exists_error` : The uploaded file has no filename.\n"
"- `file_extension_blocked` : The file extension is blocked for security reasons."
),
413: "`file_too_large` : File size exceeded.",
415: "`unsupported_file_type` : File type not allowed.",
},
)
@service_api_ns.doc("upload_file")
@service_api_ns.doc(description="Upload a file for use in conversations")
@service_api_ns.doc(consumes=["multipart/form-data"], params=multipart_file_params(include_user=True))
@service_api_ns.doc(
responses={
201: "File uploaded successfully",
400: "Bad request - no file or invalid file",
401: "Unauthorized - invalid API token",
413: "File too large",
415: "Unsupported file type",
}
)
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.FORM)) # type: ignore
@service_api_ns.response(HTTPStatus.CREATED, "File uploaded", service_api_ns.models[FileResponse.__name__])
def post(self, app_model: App, end_user: EndUser) -> JsonResponseWithStatus:
"""Upload a file for use in conversations.
Accepts a single file upload via multipart/form-data.
"""
# check file
if "file" not in request.files:
raise NoFileUploadedError()
if len(request.files) > 1:
raise TooManyFilesError()
file = request.files["file"]
if not file.mimetype:
raise UnsupportedFileTypeError()
if not file.filename:
raise FilenameNotExistsError()
try:
upload_file = application_services().files.upload_file(
filename=file.filename,
content=file.stream.read(),
mimetype=file.mimetype,
user=end_user,
)
except services.errors.file.FileTooLargeError as file_too_large_error:
raise FileTooLargeError(file_too_large_error.description) from file_too_large_error
except services.errors.file.UnsupportedFileTypeError as unsupported_file_type_error:
raise UnsupportedFileTypeError() from unsupported_file_type_error
except services.errors.file.BlockedFileExtensionError as blocked_file_extension_error:
raise BlockedFileExtensionError() from blocked_file_extension_error
return dump_response(FileResponse, upload_file), 201
@@ -0,0 +1,171 @@
from urllib.parse import quote
from uuid import UUID
from flask import Response
from flask_restx import Resource
from pydantic import BaseModel, Field
from controllers.common.fields import BinaryFileResponse
from controllers.common.file_response import enforce_download_for_html
from controllers.common.schema import query_params_from_model, register_response_schema_model, register_schema_model
from controllers.console.wraps import model_validate
from controllers.service_api import service_api_ns
from controllers.service_api.app.error import (
FileAccessDeniedError,
FileNotFoundError,
)
from controllers.service_api.schema import binary_response
from controllers.service_api.wraps import FetchUserArg, WhereisUserArg, validate_app_token
from extensions.ext_application_services import application_services
from libs.external_api import error_responses
from models.model import App, EndUser
from services.message_file_preview_service import (
MessageFilePreview,
MessageFilePreviewAccessDeniedError,
MessageFilePreviewNotFoundError,
)
class FilePreviewQuery(BaseModel):
as_attachment: bool = Field(
default=False,
description="If `true`, forces the file to download as an attachment instead of previewing in browser.",
)
register_schema_model(service_api_ns, FilePreviewQuery)
register_response_schema_model(service_api_ns, BinaryFileResponse)
FILE_PREVIEW_RESPONSE_MEDIA_TYPE = "*/*"
_RANGE_MEDIA_TYPES = frozenset(
{
"audio/aac",
"audio/flac",
"audio/mp4",
"audio/mpeg",
"audio/ogg",
"audio/wav",
"audio/x-m4a",
"video/mp4",
"video/quicktime",
"video/webm",
}
)
@service_api_ns.route("/files/<uuid:file_id>/preview")
class FilePreviewApi(Resource):
"""
Service API File Preview endpoint
Provides secure file preview/download functionality for external API users.
Files can only be accessed if they belong to messages within the requesting app's context.
"""
@error_responses(FileAccessDeniedError, FileNotFoundError)
@service_api_ns.doc(
summary="Download File",
description=(
"Preview or download uploaded files previously uploaded via the [Upload "
"File](/api-reference/files/upload-file) API. Files can only be accessed if they belong to "
"messages within the requesting application."
),
tags=["Files"],
responses={
200: (
"Returns the raw file content. The `Content-Type` header is set to the file's MIME type. If "
"`as_attachment` is `true`, the file is returned as a download with `Content-Disposition: "
"attachment`."
),
403: "`file_access_denied` : Access to the requested file is denied.",
404: "`file_not_found` : The requested file was not found.",
},
)
@service_api_ns.doc(params=query_params_from_model(FilePreviewQuery))
@binary_response(service_api_ns, FILE_PREVIEW_RESPONSE_MEDIA_TYPE)
@service_api_ns.doc("preview_file")
@service_api_ns.doc(description="Preview or download a file uploaded via Service API")
@service_api_ns.doc(
params={
"file_id": (
"The unique identifier of the file to preview, obtained from the "
"[Upload File](/api-reference/files/upload-file) API response."
)
}
)
@service_api_ns.doc(
responses={
200: "File retrieved successfully",
401: "Unauthorized - invalid API token",
403: "Forbidden - file access denied",
404: "File not found",
}
)
@service_api_ns.response(200, "File retrieved successfully")
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY))
@model_validate(FilePreviewQuery)
def get(self, args: FilePreviewQuery, app_model: App, end_user: EndUser, file_id: UUID) -> Response:
"""
Preview/Download a file that was uploaded via Service API.
Provides secure file preview/download functionality.
Files can only be accessed if they belong to messages within the requesting app's context.
"""
try:
preview = application_services().message_file_previews.get_preview(
file_id=str(file_id),
app_id=app_model.id,
tenant_id=app_model.tenant_id,
)
except MessageFilePreviewNotFoundError as error:
raise FileNotFoundError() from error
except MessageFilePreviewAccessDeniedError as error:
raise FileAccessDeniedError() from error
return self._build_file_response(preview=preview, as_attachment=args.as_attachment)
def _build_file_response(self, *, preview: MessageFilePreview, as_attachment: bool = False) -> Response:
"""
Build Flask Response object with appropriate headers for file streaming
Args:
preview: App-scoped file metadata and content stream
as_attachment: Whether to set Content-Disposition as attachment
Returns:
Flask Response object with streaming file content
"""
file = preview.file
response = Response(
preview.content,
mimetype=file.mime_type,
direct_passthrough=True,
headers={},
)
# Add Content-Length if known
if file.size > 0:
response.headers["Content-Length"] = str(file.size)
# Add Accept-Ranges header for audio/video files to support seeking
if file.mime_type in _RANGE_MEDIA_TYPES:
response.headers["Accept-Ranges"] = "bytes"
# Set Content-Disposition for downloads
if as_attachment and file.name:
encoded_filename = quote(file.name)
response.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{encoded_filename}"
# Override content-type for downloads to force download
response.headers["Content-Type"] = "application/octet-stream"
enforce_download_for_html(
response,
mime_type=file.mime_type,
filename=file.name,
extension=file.extension,
)
# Add caching headers for performance
response.headers["Cache-Control"] = "public, max-age=3600" # Cache for 1 hour
return response
@@ -0,0 +1,268 @@
"""
Service API human input form endpoints.
This module exposes app-token authenticated APIs for fetching and submitting
paused human input forms in workflow/chatflow runs.
"""
import json
import logging
from collections.abc import Sequence
from typing import Annotated, NoReturn
from flask import Response, request
from flask_restx import Resource
from pydantic import ConfigDict, WithJsonSchema
from werkzeug.exceptions import BadRequest, NotFound
from controllers.common.human_input import HumanInputFormSubmitPayload, stringify_form_default_values
from controllers.common.schema import register_response_schema_models, register_schema_models
from controllers.console.wraps import model_validate
from controllers.service_api import service_api_ns
from controllers.service_api.schema import expect_with_user
from controllers.service_api.wraps import FetchUserArg, WhereisUserArg, validate_app_token
from core.db.session_factory import session_factory
from core.human_input_v2.shared.values import TenantId
from core.workflow.human_input_policy import HumanInputSurface, is_recipient_type_allowed_for_surface
from core.workflow.nodes.human_input.entities import FormInputConfig, UserActionConfig
from extensions.ext_database import db
from factories.human_input_v2_form_presentation import build_form_presentation
from fields.base import ResponseModel
from libs.external_api import error_responses
from libs.helper import extract_remote_ip, to_timestamp
from models.model import App, EndUser
from repositories.human_input_v2.form_repository import Form as V2Form
from services.human_input_service import (
Form,
FormExpiredError,
FormNotFoundError,
FormSubmittedError,
InvalidFormDataError,
ServiceAPIHumanInputService,
)
from services.human_input_v2.submission_service import (
HumanInputFormError,
HumanInputFormErrorCode,
HumanInputSubmissionService,
ServiceAPIFormActor,
)
logger = logging.getLogger(__name__)
Int64 = Annotated[int, WithJsonSchema({"format": "int64", "type": "integer"})]
class HumanInputFormDefinitionResponse(ResponseModel):
form_content: str
inputs: list[FormInputConfig]
resolved_default_values: dict[str, str]
user_actions: list[UserActionConfig]
expiration_time: Int64 | None = None
class HumanInputFormSubmitResponse(ResponseModel):
model_config = ConfigDict(extra="forbid")
register_schema_models(service_api_ns, HumanInputFormSubmitPayload)
register_response_schema_models(
service_api_ns,
HumanInputFormDefinitionResponse,
HumanInputFormSubmitResponse,
)
def _jsonify_form_definition(form: Form, *, inputs: Sequence[FormInputConfig] = ()) -> Response:
definition_payload = form.get_definition().model_dump(mode="json")
payload = {
"form_content": definition_payload["rendered_content"],
"inputs": [form_input.model_dump(mode="json") for form_input in inputs],
"resolved_default_values": stringify_form_default_values(definition_payload["default_values"]),
"user_actions": definition_payload["user_actions"],
"expiration_time": to_timestamp(form.expiration_time),
}
return Response(json.dumps(payload, ensure_ascii=False), mimetype="application/json")
def _ensure_form_belongs_to_app(form: Form, app_model: App) -> None:
if form.app_id != app_model.id or form.tenant_id != app_model.tenant_id:
raise NotFound("Form not found")
def _ensure_form_is_allowed_for_service_api(form: Form) -> None:
# Keep app-token callers scoped to the public web-form surface; internal HITL
# routes must continue to flow through console-only authentication.
if not is_recipient_type_allowed_for_surface(form.recipient_type, HumanInputSurface.SERVICE_API):
raise NotFound("Form not found")
def _jsonify_v2_form_definition(form: V2Form) -> Response:
presentation = build_form_presentation(form.resolved_form)
response = HumanInputFormDefinitionResponse(
form_content=presentation.form_content,
inputs=presentation.inputs,
resolved_default_values=presentation.resolved_default_values,
user_actions=presentation.user_actions,
expiration_time=to_timestamp(min(form.expiration_time, form.global_timeout_deadline)),
)
return Response(response.model_dump_json(), mimetype="application/json")
def _raise_form_error(error: HumanInputFormError) -> NoReturn:
# Keep the existing Service API errors instead of leaking Web App v2's
# 409/410 statuses or its transport-specific error codes.
match error.code:
case HumanInputFormErrorCode.NOT_FOUND:
raise NotFound("Form not found") from error
case HumanInputFormErrorCode.ALREADY_SUBMITTED:
assert error.form_id is not None
raise FormSubmittedError(error.form_id) from error
case HumanInputFormErrorCode.EXPIRED:
assert error.form_id is not None
raise FormExpiredError(error.form_id) from error
case HumanInputFormErrorCode.INVALID_INPUT:
description = str(error.__cause__) if error.__cause__ is not None else "Invalid form data"
raise InvalidFormDataError(description) from error
case HumanInputFormErrorCode.WORKFLOW_NOT_ACTIVE:
raise BadRequest("The workflow is not paused with an active checkpoint.") from error
@service_api_ns.route("/form/human_input/<string:form_token>")
class WorkflowHumanInputFormApi(Resource):
@error_responses(FormExpiredError, FormSubmittedError)
@service_api_ns.doc(
summary="Get Human Input Form",
description=(
"Retrieve a paused Human Input form's contents using the `form_token` from a "
"`human_input_required` event. Requires **WebApp** delivery."
),
tags=["Human Input"],
responses={
200: "Form contents retrieved successfully.",
404: "`not_found` : Form not found.",
412: (
"- `human_input_form_submitted` : Form already submitted. Forms are one-shot; the first "
"response wins regardless of which user submits it.\n"
"- `human_input_form_expired` : The form's expiration time passed before submission arrived."
),
},
)
@service_api_ns.doc("get_human_input_form")
@service_api_ns.doc(description="Get a paused human input form by token")
@service_api_ns.doc(params={"form_token": "Human input form token"})
@service_api_ns.doc(
responses={
200: "Form retrieved successfully",
401: "Unauthorized - invalid API token",
404: "Form not found",
412: "Form already submitted or expired",
}
)
@service_api_ns.response(
200,
"Form retrieved successfully",
service_api_ns.models[HumanInputFormDefinitionResponse.__name__],
)
@validate_app_token
def get(self, app_model: App, form_token: str):
service = ServiceAPIHumanInputService(db.engine)
form = service.get_form_by_token(form_token)
if form is None:
v2_service = HumanInputSubmissionService(session_factory=session_factory.get_session_maker())
try:
v2_form = v2_service.get_service_api_form(
actor=ServiceAPIFormActor(tenant_id=TenantId(app_model.tenant_id), app_id=app_model.id),
form_token=form_token,
ip_address=extract_remote_ip(request) or None,
)
except HumanInputFormError as error:
_raise_form_error(error)
return _jsonify_v2_form_definition(v2_form)
_ensure_form_belongs_to_app(form, app_model)
_ensure_form_is_allowed_for_service_api(form)
service.ensure_form_active(form)
inputs = service.resolve_form_inputs(form)
return _jsonify_form_definition(form, inputs=inputs)
@error_responses(FormExpiredError, FormSubmittedError, InvalidFormDataError)
@service_api_ns.doc(
summary="Submit Human Input Form",
description=(
"Submit the recipient's response to a paused Human Input form. The workflow resumes on "
"acceptance; use [Stream Workflow Events](/api-reference/chatflows/stream-workflow-events) "
"to follow subsequent events. Requires **WebApp** delivery."
),
tags=["Human Input"],
responses={
200: "Form submitted successfully. The response body is an empty object.",
400: (
"- `bad_request` : Form recipient type is invalid.\n"
"- `invalid_form_data` : Submission failed validation against the form definition."
),
404: "`not_found` : Form not found.",
412: (
"- `human_input_form_submitted` : Form already submitted. Forms are one-shot; the first "
"response wins regardless of which user submits it.\n"
"- `human_input_form_expired` : The form's expiration time passed before submission arrived."
),
},
)
@expect_with_user(service_api_ns, HumanInputFormSubmitPayload)
@service_api_ns.doc("submit_human_input_form")
@service_api_ns.doc(description="Submit a paused human input form by token")
@service_api_ns.doc(params={"form_token": "Human input form token"})
@service_api_ns.doc(
responses={
200: "Form submitted successfully",
400: "Bad request - invalid submission data",
401: "Unauthorized - invalid API token",
404: "Form not found",
412: "Form already submitted or expired",
}
)
@service_api_ns.response(
200,
"Form submitted successfully",
service_api_ns.models[HumanInputFormSubmitResponse.__name__],
)
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON, required=True))
@model_validate(HumanInputFormSubmitPayload)
def post(self, payload: HumanInputFormSubmitPayload, app_model: App, end_user: EndUser, form_token: str):
service = ServiceAPIHumanInputService(db.engine)
form = service.get_form_by_token(form_token)
if form is None:
v2_service = HumanInputSubmissionService(session_factory=session_factory.get_session_maker())
try:
v2_service.submit_service_api_form(
actor=ServiceAPIFormActor(tenant_id=TenantId(app_model.tenant_id), app_id=app_model.id),
end_user_id=end_user.id,
form_token=form_token,
action=payload.action,
inputs=payload.inputs,
)
except HumanInputFormError as error:
_raise_form_error(error)
return {}, 200
_ensure_form_belongs_to_app(form, app_model)
_ensure_form_is_allowed_for_service_api(form)
recipient_type = form.recipient_type
if recipient_type is None:
logger.warning("Recipient type is None for form, form_id=%s", form.id)
raise BadRequest("Form recipient type is invalid")
try:
service.submit_form_by_token(
recipient_type=recipient_type,
form_token=form_token,
selected_action_id=payload.action,
form_data=payload.inputs,
submission_end_user_id=end_user.id,
)
except FormNotFoundError as caught_error:
raise NotFound("Form not found") from caught_error
return {}, 200
@@ -0,0 +1,377 @@
import logging
from http import HTTPStatus
from typing import Annotated
from uuid import UUID
from flask_restx import Resource
from pydantic import BaseModel, Field, WithJsonSchema
from controllers.common.controller_schemas import MessageFeedbackPayload, MessageListQuery
from controllers.common.errors import InternalServerError, MessageFeedbackRatingRequiredError, NotFoundError
from controllers.common.fields import SimpleResultStringListResponse
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
from controllers.console.wraps import model_validate
from controllers.service_api import service_api_ns
from controllers.service_api.app.error import (
AppSuggestedQuestionsAfterAnswerDisabledError,
AppUnavailableError,
CompletionRequestError,
NotChatAppError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
)
from controllers.service_api.flask_admission import service_api_app_admission, service_api_end_user_admission
from controllers.service_api.schema import expect_with_user
from controllers.service_api.wraps import FetchUserArg, WhereisUserArg
from core.errors.error import ModelCurrentlyNotSupportError, ProviderTokenNotInitError, QuotaExceededError
from extensions.ext_application_services import application_services
from fields.base import ResponseModel
from fields.conversation_fields import ResultResponse
from fields.message_fields import MessageInfiniteScrollPagination, MessageListItem
from graphon.model_runtime.errors.invoke import InvokeError
from libs.external_api import error_responses
from libs.helper import dump_response
from machinery.context import AppRequestContext, ServiceApiEndUserContext
from models.enums import FeedbackRating
from models.model import AppMode
from services.agent.errors import AgentVersionNotFoundError
from services.app_definition_query_service import AppDefinitionUnavailableError
from services.entities.message_entities import MessageEndUser
from services.errors.conversation import ConversationNotExistsError
from services.errors.message import (
FeedbackRatingRequiredError,
FirstMessageNotExistsError,
MessageActorNotFoundError,
MessageNotExistsError,
SuggestedQuestionsAfterAnswerDisabledError,
)
logger = logging.getLogger(__name__)
UUIDString = Annotated[str, WithJsonSchema({"format": "uuid", "type": "string"})]
class FeedbackListQuery(BaseModel):
page: int = Field(default=1, ge=1, description="Page number for pagination.")
limit: int = Field(default=20, ge=1, le=101, description="Number of records per page.")
class AppFeedbackResponse(ResponseModel):
id: UUIDString
app_id: UUIDString
conversation_id: UUIDString
message_id: UUIDString
rating: str
content: str | None = None
from_source: str
from_end_user_id: UUIDString | None = None
from_account_id: UUIDString | None = None
created_at: str
updated_at: str
class AppFeedbackListResponse(ResponseModel):
data: list[AppFeedbackResponse]
register_schema_models(service_api_ns, MessageListQuery, MessageFeedbackPayload, FeedbackListQuery)
register_response_schema_models(
service_api_ns,
ResultResponse,
SimpleResultStringListResponse,
MessageInfiniteScrollPagination,
MessageListItem,
AppFeedbackListResponse,
)
@service_api_ns.route("/messages")
class MessageListApi(Resource):
@error_responses(AppUnavailableError, NotChatAppError)
@service_api_ns.doc("list_messages")
@service_api_ns.doc(
summary="List Conversation Messages",
description=(
"Returns historical chat records in a scrolling load format, with the first page returning "
"the latest `limit` messages, i.e., in reverse order."
),
tags=["Conversations"],
responses={
HTTPStatus.OK: "Successfully retrieved conversation history.",
HTTPStatus.BAD_REQUEST: (
"`not_chat_app` : App mode does not match the API route. "
"`app_unavailable` : App is no longer available."
),
HTTPStatus.NOT_FOUND: (
"- `not_found` : Conversation does not exist.\n- `not_found` : First message does not exist."
),
},
)
@service_api_ns.doc(params=query_params_from_model(MessageListQuery))
@service_api_ns.doc(description="List messages in a conversation")
@service_api_ns.doc(
responses={
HTTPStatus.OK: "Messages retrieved successfully",
HTTPStatus.BAD_REQUEST: (
"`not_chat_app` : App mode does not match the API route. "
"`app_unavailable` : App is no longer available."
),
HTTPStatus.UNAUTHORIZED: "Unauthorized - invalid API token",
HTTPStatus.NOT_FOUND: "Conversation or first message not found",
}
)
@service_api_ns.response(
HTTPStatus.OK,
"Messages retrieved successfully",
service_api_ns.models[MessageInfiniteScrollPagination.__name__],
)
@service_api_end_user_admission(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY))
@model_validate(MessageListQuery)
def get(self, query_args: MessageListQuery, context: ServiceApiEndUserContext) -> dict[str, object]:
"""List messages in a conversation.
Retrieves messages with pagination support using first_id.
"""
app_mode = context.app_mode
if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}:
raise NotChatAppError()
try:
pagination = application_services().message_queries.get_page(
app_id=context.app_id,
app_owner_tenant_id=context.tenant_id,
actor=MessageEndUser(end_user_id=context.end_user_id),
conversation_id=query_args.conversation_id,
first_id=query_args.first_id or None,
limit=query_args.limit,
)
return dump_response(MessageInfiniteScrollPagination, pagination)
except AppDefinitionUnavailableError as error:
raise AppUnavailableError() from error
except MessageActorNotFoundError as error:
raise NotFoundError("End user not found") from error
except ConversationNotExistsError as error:
raise NotFoundError("Conversation Not Exists.") from error
except FirstMessageNotExistsError as error:
raise NotFoundError("First Message Not Exists.") from error
@service_api_ns.route("/messages/<uuid:message_id>/feedbacks")
class MessageFeedbackApi(Resource):
@error_responses(AppUnavailableError, MessageFeedbackRatingRequiredError)
@expect_with_user(service_api_ns, MessageFeedbackPayload)
@service_api_ns.response(
HTTPStatus.OK, "Feedback submitted successfully", service_api_ns.models[ResultResponse.__name__]
)
@service_api_ns.doc("create_message_feedback")
@service_api_ns.doc(
summary="Submit Message Feedback",
description=(
"Submit feedback for a message. End users can rate messages as `like` or `dislike`, and "
"optionally provide text feedback. Pass `null` for `rating` to revoke previously submitted feedback."
),
tags=["Feedback"],
responses={
HTTPStatus.NOT_FOUND: "`not_found` : Message does not exist.",
},
)
@service_api_ns.doc(description="Submit feedback for a message")
@service_api_ns.doc(params={"message_id": "Message ID."})
@service_api_ns.doc(
responses={
HTTPStatus.OK: "Feedback submitted successfully",
HTTPStatus.BAD_REQUEST: (
"`message_feedback_rating_required`: Cannot revoke feedback that does not exist. "
"`app_unavailable`: App is no longer available."
),
HTTPStatus.UNAUTHORIZED: "Unauthorized - invalid API token",
HTTPStatus.NOT_FOUND: "Message not found",
}
)
@service_api_end_user_admission(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON, required=True))
@model_validate(MessageFeedbackPayload)
def post(
self,
payload: MessageFeedbackPayload,
context: ServiceApiEndUserContext,
message_id: UUID,
) -> dict[str, object]:
"""Submit feedback for a message.
Allows users to rate messages as like/dislike and provide optional feedback content.
"""
message_id_str = str(message_id)
try:
application_services().message_feedbacks.set_feedback(
app_id=context.app_id,
app_owner_tenant_id=context.tenant_id,
message_id=message_id_str,
actor=MessageEndUser(end_user_id=context.end_user_id),
rating=FeedbackRating(payload.rating) if payload.rating else None,
content=payload.content,
)
except AppDefinitionUnavailableError as error:
raise AppUnavailableError() from error
except MessageActorNotFoundError as error:
raise NotFoundError("End user not found") from error
except MessageNotExistsError as error:
raise NotFoundError("Message Not Exists.") from error
except FeedbackRatingRequiredError as error:
raise MessageFeedbackRatingRequiredError() from error
return dump_response(ResultResponse, {"result": "success"})
@service_api_ns.route("/app/feedbacks")
class AppGetFeedbacksApi(Resource):
@error_responses(AppUnavailableError)
@service_api_ns.doc("get_app_feedbacks")
@service_api_ns.doc(
summary="List App Feedbacks",
description=(
"Retrieve a paginated list of all feedback submitted for messages in this application, including both "
"end-user and admin feedback."
),
tags=["Feedback"],
responses={
HTTPStatus.OK: "A list of application feedbacks.",
},
)
@service_api_ns.doc(params=query_params_from_model(FeedbackListQuery))
@service_api_ns.doc(description="Get all feedbacks for the application")
@service_api_ns.doc(
responses={
HTTPStatus.OK: "Feedbacks retrieved successfully",
HTTPStatus.BAD_REQUEST: "`app_unavailable`: App is no longer available.",
HTTPStatus.UNAUTHORIZED: "Unauthorized - invalid API token",
}
)
@service_api_ns.response(
HTTPStatus.OK,
"Feedbacks retrieved successfully",
service_api_ns.models[AppFeedbackListResponse.__name__],
)
@service_api_app_admission
@model_validate(FeedbackListQuery)
def get(self, query_args: FeedbackListQuery, context: AppRequestContext) -> dict[str, object]:
"""Get all feedbacks for the application.
Returns paginated list of all feedback submitted for messages in this app.
"""
try:
feedbacks = application_services().message_feedbacks.get_feedbacks(
app_id=context.app_id,
app_owner_tenant_id=context.tenant_id,
page=query_args.page,
limit=query_args.limit,
)
except AppDefinitionUnavailableError as error:
raise AppUnavailableError() from error
return dump_response(AppFeedbackListResponse, {"data": feedbacks})
@service_api_ns.route("/messages/<uuid:message_id>/suggested")
class MessageSuggestedApi(Resource):
@error_responses(
AgentVersionNotFoundError,
AppSuggestedQuestionsAfterAnswerDisabledError,
AppUnavailableError,
CompletionRequestError,
NotChatAppError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
)
@service_api_ns.doc("get_suggested_questions")
@service_api_ns.doc(
summary="Get Next Suggested Questions",
description=(
"Get next question suggestions for the current message. "
"If no usable model can be resolved or the model call to generate questions fails, "
"the response is HTTP 200 with an empty data list. "
"Model invocation failures during history token counting instead return "
"HTTP 400 with `completion_request_error`."
),
tags=["Chats", "Chatflows"],
responses={
HTTPStatus.OK: "Suggested questions retrieved successfully",
HTTPStatus.BAD_REQUEST: (
"- `not_chat_app` : App mode does not match the API route.\n"
"- `app_unavailable` : App is no longer available.\n"
"- `completion_request_error` : Model invocation failed while counting history tokens."
),
HTTPStatus.UNAUTHORIZED: "Unauthorized - invalid API token",
HTTPStatus.FORBIDDEN: (
"- `forbidden` : Token scope does not allow access.\n"
"- `app_not_found` : The token's app no longer exists.\n"
"- `app_abnormal_status` : App status does not allow API access.\n"
"- `app_api_disabled` : The app's API service has been disabled.\n"
"- `workspace_not_found` : The app's workspace no longer exists.\n"
"- `workspace_archived` : The app's workspace is archived.\n"
"- `app_suggested_questions_after_answer_disabled` : Suggested questions feature is disabled."
),
HTTPStatus.NOT_FOUND: (
"- `not_found` : End user, message, or conversation does not exist.\n"
"- `agent_version_not_found_error` : Agent config version does not exist."
),
HTTPStatus.INTERNAL_SERVER_ERROR: "`internal_server_error` : Internal server error.",
},
)
@service_api_ns.response(
HTTPStatus.OK,
"Suggested questions retrieved successfully",
service_api_ns.models[SimpleResultStringListResponse.__name__],
)
@service_api_ns.doc(params={"message_id": "Message ID"})
@service_api_end_user_admission(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY, required=True))
def get(self, context: ServiceApiEndUserContext, message_id: UUID) -> dict[str, object]:
"""Get suggested follow-up questions for a message.
Returns an empty list when model resolution or the question-generation
model call fails. History token-counting invocation failures return
HTTP 400 with completion_request_error.
"""
message_id_str = str(message_id)
app_mode = AppMode.value_of(context.app_mode)
if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT, AppMode.AGENT}:
raise NotChatAppError()
try:
questions = application_services().message_suggested_questions.get_suggested_questions(
app_id=context.app_id,
app_owner_tenant_id=context.tenant_id,
expected_app_mode=context.app_mode,
actor=MessageEndUser(end_user_id=context.end_user_id),
invoke_from="service-api",
message_id=message_id_str,
)
except AppDefinitionUnavailableError:
raise AppUnavailableError() from None
except MessageActorNotFoundError:
raise NotFoundError("End user not found") from None
except MessageNotExistsError as caught_error:
raise NotFoundError("Message Not Exists.") from caught_error
except ConversationNotExistsError:
raise NotFoundError("Conversation not found") from None
except SuggestedQuestionsAfterAnswerDisabledError:
raise AppSuggestedQuestionsAfterAnswerDisabledError() from None
except ProviderTokenNotInitError as error:
raise ProviderNotInitializeError(error.description) from error
except QuotaExceededError:
raise ProviderQuotaExceededError() from None
except ModelCurrentlyNotSupportError:
raise ProviderModelCurrentlyNotSupportError() from None
except InvokeError as error:
raise CompletionRequestError(error.description) from error
except AgentVersionNotFoundError:
# The legacy Agent config reader still owns this HTTP error.
# Remove this compatibility case when it exposes a domain error.
raise
except Exception as caught_error:
logger.exception("internal server error.")
raise InternalServerError() from caught_error
return dump_response(SimpleResultStringListResponse, {"result": "success", "data": questions})
@@ -0,0 +1,57 @@
from flask_restx import Resource
from werkzeug.exceptions import Forbidden
from controllers.common.fields import Site as SiteResponse
from controllers.common.schema import register_response_schema_models
from controllers.service_api import service_api_ns
from controllers.service_api.wraps import validate_app_token
from extensions.ext_application_services import application_services
from libs.helper import dump_response
from models.model import App
from services.app_definition_query_service import AppDefinitionUnavailableError
register_response_schema_models(service_api_ns, SiteResponse)
@service_api_ns.route("/site")
class AppSiteApi(Resource):
"""Resource for app sites."""
@service_api_ns.doc(
summary="Get App WebApp Settings",
description=(
"Retrieve the WebApp settings of this application, including site configuration, theme, and "
"customization options."
),
tags=["Applications"],
responses={
200: "WebApp settings of the application.",
403: "`forbidden` : Site not found for this application or the workspace has been archived.",
},
)
@service_api_ns.doc("get_app_site")
@service_api_ns.doc(description="Get application site configuration")
@service_api_ns.doc(
responses={
200: "Site configuration retrieved successfully",
401: "Unauthorized - invalid API token",
403: "Forbidden - site not found or tenant archived",
}
)
@service_api_ns.response(
200,
"Site configuration retrieved successfully",
service_api_ns.models[SiteResponse.__name__],
)
@validate_app_token
def get(self, app_model: App):
"""Retrieve app site info.
Returns the site configuration for the application including theme, icons, and text.
"""
try:
configuration = application_services().app_definitions.get_site_configuration(app_model.id)
except AppDefinitionUnavailableError:
raise Forbidden() from None
return dump_response(SiteResponse, configuration)
@@ -0,0 +1,649 @@
import logging
from collections.abc import Mapping
from datetime import datetime
from typing import Annotated, Literal
from dateutil.parser import isoparse
from flask import request
from flask_restx import Resource
from pydantic import BaseModel, Field, WithJsonSchema, field_validator, model_validator
from pydantic.json_schema import SkipJsonSchema
from sqlalchemy.orm import Session, sessionmaker
from werkzeug.exceptions import BadRequest, InternalServerError, NotFound
from configs import dify_config
from controllers.common.controller_schemas import WorkflowRunPayload as WorkflowRunPayloadBase
from controllers.common.fields import SimpleResultResponse, WorkflowBlockingResponse
from controllers.common.schema import (
query_params_from_model,
query_params_from_request,
register_response_schema_models,
register_schema_models,
)
from controllers.console.app.wraps import with_session
from controllers.service_api import service_api_ns
from controllers.service_api.app.error import (
CompletionRequestError,
NotWorkflowAppError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
TriggerWorkflowServiceModeUnavailableError,
WorkflowVersionExecutionNotAllowedError,
)
from controllers.service_api.schema import (
WORKFLOW_TASK_STOP_USER_DESCRIPTION,
expect_user_json,
expect_with_user,
json_or_event_stream_response,
)
from controllers.service_api.wraps import FetchUserArg, WhereisUserArg, validate_app_token
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 core.helper.trace_id_helper import get_external_trace_id, get_trace_session_id, omit_trace_session_id_from_payload
from enums import CloudPlan, DeploymentEdition
from extensions.ext_application_services import application_services
from extensions.ext_database import db
from fields.base import ResponseModel
from fields.end_user_fields import SimpleEndUser
from fields.member_fields import SimpleAccountResponse
from graphon.enums import WorkflowExecutionStatus
from graphon.model_runtime.errors.invoke import InvokeError
from libs import helper
from libs.external_api import error_responses
from libs.helper import dump_response, to_timestamp
from models.model import App, AppMode, EndUser
from repositories.factory import DifyAPIRepositoryFactory
from services.app_generate_service import AppGenerateService
from services.app_task_service import AppTaskService
from services.billing_service import BillingService
from services.errors.app import (
IsDraftWorkflowError,
WorkflowIdFormatError,
WorkflowNotFoundError,
)
from services.errors.app import (
TriggerWorkflowServiceModeUnavailableError as TriggerWorkflowServiceModeUnavailableServiceError,
)
from services.errors.llm import InvokeRateLimitError
logger = logging.getLogger(__name__)
UUIDString = Annotated[str, WithJsonSchema({"format": "uuid", "type": "string"})]
Int64 = Annotated[int, WithJsonSchema({"format": "int64", "type": "integer"})]
FloatNumber = Annotated[float, WithJsonSchema({"format": "float", "type": "number"})]
class WorkflowRunPayload(WorkflowRunPayloadBase):
response_mode: Literal["blocking", "streaming"] | None = Field(
default=None,
description=(
"Response mode. Use `blocking` for synchronous responses or `streaming` for Server-Sent Events. "
"When omitted, the request runs in blocking mode."
),
)
trace_session_id: SkipJsonSchema[str | None] = Field(
default=None, description="Trace session ID for observability grouping"
)
class WorkflowLogQuery(BaseModel):
keyword: str | None = Field(default=None, description="Keyword to search in logs.")
status: Literal["succeeded", "failed", "stopped"] | None = Field(
default=None,
description="Filter by execution status.",
)
created_at__before: str | None = Field(
default=None,
description="Filter logs created before this ISO 8601 timestamp.",
json_schema_extra={"format": "date-time"},
)
created_at__after: str | None = Field(
default=None,
description="Filter logs created after this ISO 8601 timestamp.",
json_schema_extra={"format": "date-time"},
)
created_by_end_user_session_id: str | None = Field(
default=None,
description="Filter by end user session ID.",
)
created_by_account: str | None = Field(default=None, description="Filter by account ID.")
page: int = Field(default=1, ge=1, le=99999, description="Page number for pagination.")
limit: int = Field(default=20, ge=1, le=100, description="Number of items per page.")
register_schema_models(service_api_ns, WorkflowRunPayload, WorkflowLogQuery)
register_response_schema_models(service_api_ns, WorkflowBlockingResponse, SimpleResultResponse)
def _enum_value(value):
return getattr(value, "value", value)
class WorkflowRunResponse(ResponseModel):
id: UUIDString
workflow_id: UUIDString
status: str
inputs: dict | list | str | int | float | bool | None = Field(default=None)
outputs: dict = Field(default_factory=dict, validation_alias="outputs_dict")
error: str | None = None
total_steps: int | None = None
total_tokens: int | None = None
created_at: Int64 | None = None
finished_at: Int64 | None = None
elapsed_time: FloatNumber | int | None = None
@field_validator("status", mode="before")
@classmethod
def _normalize_enum(cls, value):
return _enum_value(value)
@field_validator("outputs", mode="before")
@classmethod
def _normalize_outputs(cls, value):
if value is None:
return {}
if isinstance(value, dict):
return value
if isinstance(value, Mapping):
return dict(value)
return {}
@field_validator("created_at", "finished_at", mode="before")
@classmethod
def _normalize_timestamp(cls, value: datetime | int | None) -> int | None:
return to_timestamp(value)
@model_validator(mode="after")
def _clear_paused_outputs(self):
if self.status == WorkflowExecutionStatus.PAUSED.value:
self.outputs = {}
return self
class WorkflowRunForLogResponse(ResponseModel):
id: UUIDString
version: str | None = None
status: str | None = None
triggered_from: str | None = None
error: str | None = None
elapsed_time: FloatNumber | int | None = None
total_tokens: int | None = None
total_steps: int | None = None
created_at: Int64 | None = None
finished_at: Int64 | None = None
exceptions_count: int | None = None
@field_validator("status", "triggered_from", mode="before")
@classmethod
def _normalize_enum(cls, value):
return _enum_value(value)
@field_validator("created_at", "finished_at", mode="before")
@classmethod
def _normalize_timestamp(cls, value: datetime | int | None) -> int | None:
return to_timestamp(value)
class WorkflowAppLogPartialResponse(ResponseModel):
id: UUIDString
workflow_run: WorkflowRunForLogResponse | None = None
details: dict | list | str | int | float | bool | None = Field(default=None)
created_from: str | None = None
created_by_role: str | None = None
created_by_account: SimpleAccountResponse | None = None
created_by_end_user: SimpleEndUser | None = None
created_at: Int64 | None = None
@field_validator("created_from", "created_by_role", mode="before")
@classmethod
def _normalize_enum(cls, value):
return _enum_value(value)
@field_validator("created_at", mode="before")
@classmethod
def _normalize_timestamp(cls, value: datetime | int | None) -> int | None:
return to_timestamp(value)
class WorkflowAppLogPaginationResponse(ResponseModel):
page: int
limit: int
total: int
has_more: bool
data: list[WorkflowAppLogPartialResponse]
register_response_schema_models(
service_api_ns,
WorkflowRunResponse,
WorkflowRunForLogResponse,
WorkflowAppLogPartialResponse,
WorkflowAppLogPaginationResponse,
)
@service_api_ns.route("/workflows/run/<string:workflow_run_id>")
class WorkflowRunDetailApi(Resource):
@error_responses(NotWorkflowAppError)
@service_api_ns.doc(
summary="Get Workflow Run Detail",
description="Retrieve the current execution results of a workflow task based on the workflow execution ID.",
tags=["Chatflows", "Workflows"],
responses={
200: "Successfully retrieved workflow run details.",
400: "`not_workflow_app` : App mode does not match the API route.",
404: "`not_found` : Workflow run not found.",
},
)
@service_api_ns.doc("get_workflow_run_detail")
@service_api_ns.doc(description="Get workflow run details")
@service_api_ns.doc(
params={
"workflow_run_id": "Workflow run ID, obtained from the workflow execution response or streaming events."
}
)
@service_api_ns.doc(
responses={
200: "Workflow run details retrieved successfully",
401: "Unauthorized - invalid API token",
404: "Workflow run not found",
}
)
@validate_app_token
@service_api_ns.response(
200,
"Workflow run details retrieved successfully",
service_api_ns.models[WorkflowRunResponse.__name__],
)
def get(self, app_model: App, workflow_run_id: str):
"""Get a workflow task running detail.
Returns detailed information about a specific workflow run.
"""
app_mode = AppMode.value_of(app_model.mode)
if app_mode not in [AppMode.WORKFLOW, AppMode.ADVANCED_CHAT]:
raise NotWorkflowAppError()
# Use repository to get workflow run
session_maker = sessionmaker(bind=db.engine, expire_on_commit=False)
workflow_run_repo = DifyAPIRepositoryFactory.create_api_workflow_run_repository(session_maker)
workflow_run = workflow_run_repo.get_workflow_run_by_id(
tenant_id=app_model.tenant_id,
app_id=app_model.id,
run_id=workflow_run_id,
)
if not workflow_run:
raise NotFound("Workflow run not found.")
return dump_response(WorkflowRunResponse, workflow_run)
@service_api_ns.route("/workflows/run")
class WorkflowRunApi(Resource):
@error_responses(
CompletionRequestError,
InvokeRateLimitHttpError,
NotWorkflowAppError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
TriggerWorkflowServiceModeUnavailableError,
)
@service_api_ns.doc(
summary="Run Workflow",
description="Execute a workflow. Cannot be executed without a published workflow.",
tags=["Workflows"],
responses={
200: (
"Successful response. The content type and structure depend on the `response_mode` parameter "
"in the request.\n"
"\n"
"- If `response_mode` is `blocking`, returns `application/json` with a "
"`WorkflowBlockingResponse` object.\n"
"- If `response_mode` is `streaming`, returns `text/event-stream` with a stream of "
"`ChunkWorkflowEvent` objects."
),
400: (
"- `not_workflow_app` : App mode does not match the API route.\n"
"- `provider_not_initialize` : No valid model provider credentials found.\n"
"- `provider_quota_exceeded` : Model provider quota exhausted.\n"
"- `model_currently_not_support` : Current model unavailable.\n"
"- `completion_request_error` : Workflow execution request failed.\n"
"- `invalid_param` : Invalid parameter value."
),
403: (
"- `forbidden` : Token scope, app, or workspace access denied.\n"
"- `trigger_workflow_service_mode_unavailable` : Trigger-entry workflows cannot be invoked through "
"Web App, Service API, OpenAPI, or MCP."
),
429: (
"- `too_many_requests` : Too many concurrent requests for this app.\n"
"- `rate_limit_error` : The Dify Cloud workflow execution quota for this workspace has been reached."
),
500: "`internal_server_error` : Internal server error.",
},
)
@expect_with_user(service_api_ns, WorkflowRunPayload)
@json_or_event_stream_response(service_api_ns)
@service_api_ns.doc("run_workflow")
@service_api_ns.doc(description="Execute a workflow")
@service_api_ns.doc(
responses={
200: "Workflow executed successfully",
400: "Bad request - invalid parameters or workflow issues",
401: "Unauthorized - invalid API token",
429: "Rate limit exceeded",
500: "Internal server error",
}
)
@service_api_ns.response(
200,
"Workflow executed successfully",
service_api_ns.models[WorkflowBlockingResponse.__name__],
)
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON, required=True))
@with_session
def post(self, session: Session, app_model: App, end_user: EndUser):
"""Execute a workflow.
Runs a workflow with the provided inputs and returns the results.
Supports both blocking and streaming response modes.
"""
app_mode = AppMode.value_of(app_model.mode)
if app_mode != AppMode.WORKFLOW:
raise NotWorkflowAppError()
payload = WorkflowRunPayload.model_validate(omit_trace_session_id_from_payload(service_api_ns.payload) or {})
args = payload.model_dump(exclude_none=True)
trace_session_id = get_trace_session_id(request)
if trace_session_id:
args["trace_session_id"] = trace_session_id
external_trace_id = get_external_trace_id(request)
if external_trace_id:
args["external_trace_id"] = external_trace_id
streaming = payload.response_mode == "streaming"
try:
response = AppGenerateService.generate(
session=session,
app_model=app_model,
user=end_user,
args=args,
invoke_from=InvokeFrom.SERVICE_API,
streaming=streaming,
)
# response-contract:ignore compact_generate_response
return helper.compact_generate_response(response)
except TriggerWorkflowServiceModeUnavailableServiceError as caught_error:
raise TriggerWorkflowServiceModeUnavailableError() 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 InvokeRateLimitError as ex:
raise InvokeRateLimitHttpError(ex.description) from ex
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
@service_api_ns.route("/workflows/<string:workflow_id>/run")
class WorkflowRunByIdApi(Resource):
@error_responses(
CompletionRequestError,
InvokeRateLimitHttpError,
NotWorkflowAppError,
ProviderModelCurrentlyNotSupportError,
ProviderNotInitializeError,
ProviderQuotaExceededError,
TriggerWorkflowServiceModeUnavailableError,
WorkflowVersionExecutionNotAllowedError,
)
@service_api_ns.doc(
summary="Run Workflow by ID",
description=(
"Execute a specific workflow version identified by its ID. Useful for running a particular "
"published version of the workflow."
),
tags=["Workflows"],
responses={
200: (
"Successful response. The content type and structure depend on the `response_mode` parameter "
"in the request.\n"
"\n"
"- If `response_mode` is `blocking`, returns `application/json` with a "
"`WorkflowBlockingResponse` object.\n"
"- If `response_mode` is `streaming`, returns `text/event-stream` with a stream of "
"`ChunkWorkflowEvent` objects."
),
400: (
"- `not_workflow_app` : App mode does not match the API route.\n"
"- `bad_request` : Workflow is a draft or has an invalid ID format.\n"
"- `provider_not_initialize` : No valid model provider credentials found.\n"
"- `provider_quota_exceeded` : Model provider quota exhausted.\n"
"- `model_currently_not_support` : Current model unavailable.\n"
"- `completion_request_error` : Workflow execution request failed.\n"
"- `invalid_param` : Required parameter missing or invalid."
),
403: (
"- `forbidden` : Token scope, app, or workspace access denied.\n"
"- `workflow_version_execution_not_allowed` : Workflow version execution is unavailable on the "
"current plan. Upgrade to a paid plan.\n"
"- `trigger_workflow_service_mode_unavailable` : The selected workflow version uses a trigger entry "
"and cannot be invoked through Web App, Service API, OpenAPI, or MCP."
),
404: "`not_found` : Workflow not found.",
429: (
"- `too_many_requests` : Too many concurrent requests for this app.\n"
"- `rate_limit_error` : The Dify Cloud workflow execution quota for this workspace has been reached."
),
500: "`internal_server_error` : Internal server error.",
},
)
@expect_with_user(service_api_ns, WorkflowRunPayload)
@json_or_event_stream_response(service_api_ns)
@service_api_ns.doc("run_workflow_by_id")
@service_api_ns.doc(description="Execute a specific workflow by ID")
@service_api_ns.doc(
params={
"workflow_id": (
"Workflow ID of the specific version to execute. This value is returned in the `workflow_id` field "
"of workflow run responses."
)
}
)
@service_api_ns.doc(
responses={
200: "Workflow executed successfully",
400: "Bad request - invalid parameters or workflow issues",
401: "Unauthorized - invalid API token",
403: "Forbidden - upgrade to a paid plan to execute a specific workflow version",
404: "Workflow not found",
429: "Rate limit exceeded",
500: "Internal server error",
}
)
@service_api_ns.response(
200,
"Workflow executed successfully",
service_api_ns.models[WorkflowBlockingResponse.__name__],
)
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON, required=True))
@with_session
def post(self, session: Session, app_model: App, end_user: EndUser, workflow_id: str):
"""Run specific workflow by ID.
Executes a specific workflow version identified by its ID.
"""
app_mode = AppMode.value_of(app_model.mode)
if app_mode != AppMode.WORKFLOW:
raise NotWorkflowAppError()
if dify_config.DEPLOYMENT_EDITION == DeploymentEdition.CLOUD:
billing_info = BillingService.get_info(app_model.tenant_id, exclude_vector_space=True)
if billing_info.subscription.plan == CloudPlan.SANDBOX:
raise WorkflowVersionExecutionNotAllowedError()
payload = WorkflowRunPayload.model_validate(omit_trace_session_id_from_payload(service_api_ns.payload) or {})
args = payload.model_dump(exclude_none=True)
trace_session_id = get_trace_session_id(request)
if trace_session_id:
args["trace_session_id"] = trace_session_id
# Add workflow_id to args for AppGenerateService
args["workflow_id"] = workflow_id
external_trace_id = get_external_trace_id(request)
if external_trace_id:
args["external_trace_id"] = external_trace_id
streaming = payload.response_mode == "streaming"
try:
response = AppGenerateService.generate(
session=session,
app_model=app_model,
user=end_user,
args=args,
invoke_from=InvokeFrom.SERVICE_API,
streaming=streaming,
)
# response-contract:ignore compact_generate_response
return helper.compact_generate_response(response)
except TriggerWorkflowServiceModeUnavailableServiceError as caught_error:
raise TriggerWorkflowServiceModeUnavailableError() from caught_error
except WorkflowNotFoundError as ex:
raise NotFound(str(ex)) from ex
except IsDraftWorkflowError as ex:
raise BadRequest(str(ex)) from ex
except WorkflowIdFormatError as ex:
raise BadRequest(str(ex)) from ex
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 InvokeRateLimitError as ex:
raise InvokeRateLimitHttpError(ex.description) from ex
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
@service_api_ns.route("/workflows/tasks/<string:task_id>/stop")
class WorkflowTaskStopApi(Resource):
@error_responses(NotWorkflowAppError)
@service_api_ns.doc(
summary="Stop Workflow Task",
description="Stop a running workflow task. Only supported in `streaming` mode.",
tags=["Workflows"],
responses={
400: (
"- `not_workflow_app` : App mode does not match the API route.\n"
"- `invalid_param` : Required parameter missing or invalid."
),
},
)
@expect_user_json(
service_api_ns,
model_name="WorkflowTaskStopPayload",
user_description=WORKFLOW_TASK_STOP_USER_DESCRIPTION,
)
@service_api_ns.doc("stop_workflow_task")
@service_api_ns.doc(description="Stop a running workflow task")
@service_api_ns.doc(
params={"task_id": "Task ID, obtained from the streaming chunk returned by the Run Workflow API."}
)
@service_api_ns.doc(
responses={
200: "Task stopped successfully",
401: "Unauthorized - invalid API token",
}
)
@service_api_ns.response(200, "Task stopped successfully", service_api_ns.models[SimpleResultResponse.__name__])
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.JSON, required=True))
def post(self, app_model: App, end_user: EndUser, task_id: str):
"""Stop a running workflow task."""
app_mode = AppMode.value_of(app_model.mode)
if app_mode != AppMode.WORKFLOW:
raise NotWorkflowAppError()
AppTaskService.stop_workflow_task(
tenant_id=app_model.tenant_id,
app_id=app_model.id,
task_id=task_id,
app_mode=app_mode,
owner=None,
)
return SimpleResultResponse(result="success").model_dump()
@service_api_ns.route("/workflows/logs")
class WorkflowAppLogApi(Resource):
@service_api_ns.doc(
summary="List Workflow Logs",
description="Retrieve paginated workflow execution logs with filtering options.",
tags=["Chatflows", "Workflows"],
responses={
200: "Successfully retrieved workflow logs.",
},
)
@service_api_ns.doc(params=query_params_from_model(WorkflowLogQuery))
@service_api_ns.doc("get_workflow_logs")
@service_api_ns.doc(description="Get workflow execution logs")
@service_api_ns.doc(
responses={
200: "Logs retrieved successfully",
400: "Bad request - invalid query parameters",
401: "Unauthorized - invalid API token",
}
)
@validate_app_token
@service_api_ns.response(
200,
"Logs retrieved successfully",
service_api_ns.models[WorkflowAppLogPaginationResponse.__name__],
)
def get(self, app_model: App):
"""Get workflow app logs.
Returns paginated workflow execution logs with filtering options.
"""
args = query_params_from_request(WorkflowLogQuery)
status = WorkflowExecutionStatus(args.status) if args.status else None
created_at_before = isoparse(args.created_at__before) if args.created_at__before else None
created_at_after = isoparse(args.created_at__after) if args.created_at__after else None
result = application_services().workflow_app_logs.list_logs(
tenant_id=app_model.tenant_id,
app_id=app_model.id,
keyword=args.keyword,
status=status,
created_at_before=created_at_before,
created_at_after=created_at_after,
page=args.page,
limit=args.limit,
created_by_end_user_session_id=args.created_by_end_user_session_id,
created_by_account=args.created_by_account,
)
return dump_response(WorkflowAppLogPaginationResponse, result)
@@ -0,0 +1,181 @@
"""
Service API workflow resume event stream endpoints.
"""
import json
from collections.abc import Generator
from flask import Response, request
from flask_restx import Resource
from pydantic import BaseModel, Field
from sqlalchemy.orm import sessionmaker
from werkzeug.exceptions import NotFound
from controllers.common.fields import EventStreamResponse
from controllers.common.schema import query_params_from_model, register_response_schema_model, register_schema_models
from controllers.service_api import service_api_ns
from controllers.service_api.app.error import NotWorkflowAppError
from controllers.service_api.schema import event_stream_response
from controllers.service_api.wraps import FetchUserArg, WhereisUserArg, validate_app_token
from core.app.apps.advanced_chat.app_generator import AdvancedChatAppGenerator
from core.app.apps.base_app_generator import BaseAppGenerator
from core.app.apps.common.workflow_response_converter import WorkflowResponseConverter
from core.app.apps.message_generator import MessageGenerator
from core.app.apps.workflow.app_generator import WorkflowAppGenerator
from core.app.entities.task_entities import StreamEvent
from core.workflow.human_input_policy import HumanInputSurface
from extensions.ext_database import db
from libs.external_api import error_responses
from models.enums import CreatorUserRole
from models.model import App, AppMode, EndUser
from repositories.factory import DifyAPIRepositoryFactory
from services.workflow_event_snapshot_service import build_workflow_event_stream
class WorkflowEventsQuery(BaseModel):
user: str = Field(
...,
description="End-user identifier that originally triggered the run. Must match the creator of the run.",
)
include_state_snapshot: bool = Field(
default=False,
description=(
"When `true`, replay from the persisted state snapshot to include a status summary of already-executed "
"nodes before streaming new events."
),
)
continue_on_pause: bool = Field(
default=False,
description=(
"Set to `true` to keep the stream open across multiple `workflow_paused` events, which is useful when "
"the workflow has more than one Human Input node in sequence. By default, the stream closes after the "
"first pause."
),
)
register_schema_models(service_api_ns, WorkflowEventsQuery)
register_response_schema_model(service_api_ns, EventStreamResponse)
@service_api_ns.route("/workflow/<string:workflow_run_id>/events")
class WorkflowEventsApi(Resource):
"""Service API for getting workflow execution events after resume."""
@error_responses(NotWorkflowAppError)
@service_api_ns.doc(
summary="Stream Workflow Events",
description=(
"Resume the Server-Sent Events stream for a workflow run after a pause or a dropped SSE "
"connection. For runs that have already finished, the stream emits a single "
"`workflow_finished` event and closes."
),
tags=["Chatflows", "Workflows"],
responses={
200: (
"Server-Sent Events stream. Each event is delivered as `data: {JSON}\\n\\n`. Event payloads "
"follow the same schemas as the original streaming response."
),
400: "`not_workflow_app` : Please check if your app mode matches the right API route.",
404: "`not_found` : Workflow run not found.",
},
)
@event_stream_response(service_api_ns)
@service_api_ns.doc("get_workflow_events")
@service_api_ns.doc(description="Get workflow execution events stream after resume")
@service_api_ns.doc(params={"workflow_run_id": "Workflow run ID returned by the original workflow run request."})
@service_api_ns.doc(params=query_params_from_model(WorkflowEventsQuery))
@service_api_ns.doc(
responses={
200: "SSE event stream",
401: "Unauthorized - invalid API token",
404: "Workflow run not found",
}
)
@service_api_ns.response(200, "SSE event stream", service_api_ns.models[EventStreamResponse.__name__])
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY, required=True))
def get(self, app_model: App, end_user: EndUser, workflow_run_id: str):
app_mode = AppMode.value_of(app_model.mode)
if app_mode not in {AppMode.WORKFLOW, AppMode.ADVANCED_CHAT}:
raise NotWorkflowAppError()
session_maker = sessionmaker(db.engine)
repo = DifyAPIRepositoryFactory.create_api_workflow_run_repository(session_maker)
workflow_run = repo.get_workflow_run_by_id_and_tenant_id(
tenant_id=app_model.tenant_id,
run_id=workflow_run_id,
)
if workflow_run is None:
raise NotFound("Workflow run not found")
if workflow_run.app_id != app_model.id:
raise NotFound("Workflow run not found")
if workflow_run.created_by_role != CreatorUserRole.END_USER:
raise NotFound("Workflow run not found")
if workflow_run.created_by != end_user.id:
raise NotFound("Workflow run not found")
workflow_run_entity = workflow_run
if workflow_run_entity.finished_at is not None:
response = WorkflowResponseConverter.workflow_run_result_to_finish_response(
task_id=workflow_run_entity.id,
workflow_run=workflow_run_entity,
creator_user=end_user,
)
payload = response.model_dump(mode="json")
payload["event"] = response.event.value
def _generate_finished_events() -> Generator[str]:
yield f"data: {json.dumps(payload)}\n\n"
event_generator = _generate_finished_events
else:
msg_generator = MessageGenerator()
generator: type[BaseAppGenerator]
if app_mode == AppMode.ADVANCED_CHAT:
generator = AdvancedChatAppGenerator
elif app_mode == AppMode.WORKFLOW:
generator = WorkflowAppGenerator
else:
raise NotWorkflowAppError()
include_state_snapshot = request.args.get("include_state_snapshot", "false").lower() == "true"
continue_on_pause = request.args.get("continue_on_pause", "false").lower() == "true"
terminal_events: list[StreamEvent] | None = [] if continue_on_pause else None
def _generate_stream_events():
if include_state_snapshot:
return generator.convert_to_event_stream(
build_workflow_event_stream(
app_mode=app_mode,
workflow_run=workflow_run_entity,
tenant_id=app_model.tenant_id,
app_id=app_model.id,
session_maker=session_maker,
human_input_surface=HumanInputSurface.SERVICE_API,
close_on_pause=not continue_on_pause,
)
)
return generator.convert_to_event_stream(
msg_generator.retrieve_events(
app_mode,
workflow_run_entity.id,
terminal_events=terminal_events,
),
)
event_generator = _generate_stream_events
return Response(
event_generator(),
mimetype="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
},
)