Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

6.9 KB
Raw Blame
"""Client-safe DTOs for Dify plugin-backed business layers.

This module intentionally contains only public config schemas and scalar type
aliases plus stable plugin business-layer type identifiers. Runtime objects
such as HTTP clients, server settings, and adapter implementations live in
sibling implementation modules so clients can build run requests without
importing server-only dependencies.

Shared tenant/user/run context now lives in the sibling
``dify_agent.layers.execution_context`` package. This module only covers the
plugin-backed LLM and tools layers that invoke daemon features with concrete
``plugin_id`` values. Tool configs also carry the API-side prepared parameter
declarations and model-visible JSON schema so the agent runtime does not have to
re-fetch and re-merge tool declarations at execution time.
"""

from enum import StrEnum
from typing import ClassVar, Literal, TypeAlias

from pydantic import BaseModel, ConfigDict, Field, JsonValue, field_validator, model_validator
from pydantic_ai.settings import ModelSettings


DifyPluginCredentialValue: TypeAlias = str | int | float | bool | None
DifyPluginToolCredentialType: TypeAlias = Literal["api-key", "oauth2", "unauthorized"]
DifyPluginToolValue: TypeAlias = JsonValue


def _default_parameters_json_schema() -> dict[str, JsonValue]:
    return {"type": "object", "properties": {}, "required": []}


class DifyPluginToolOption(BaseModel):
    """Selectable tool option value exposed to the model.

    The DTO also accepts API-side option dumps and attribute objects. Fields
    such as ``label`` or ``icon`` are intentionally ignored because Dify Agent
    only preserves the normalized option ``value`` for tool invocation and
    model-visible schema generation.
    """

    value: str

    model_config: ClassVar[ConfigDict] = ConfigDict(extra="ignore", from_attributes=True)

    @field_validator("value", mode="before")
    @classmethod
    def stringify_value(cls, value: object) -> str:
        return value if isinstance(value, str) else str(value)


class DifyPluginToolParameterType(StrEnum):
    STRING = "string"
    NUMBER = "number"
    BOOLEAN = "boolean"
    SELECT = "select"
    SECRET_INPUT = "secret-input"
    FILE = "file"
    FILES = "files"
    APP_SELECTOR = "app-selector"
    MODEL_SELECTOR = "model-selector"
    ANY = "any"
    DYNAMIC_SELECT = "dynamic-select"
    CHECKBOX = "checkbox"
    SYSTEM_FILES = "system-files"
    ARRAY = "array"
    OBJECT = "object"

    def as_normal_type(self) -> str:
        if self in {
            DifyPluginToolParameterType.SECRET_INPUT,
            DifyPluginToolParameterType.SELECT,
            DifyPluginToolParameterType.CHECKBOX,
        }:
            return "string"
        return self.value


class DifyPluginToolParameterForm(StrEnum):
    SCHEMA = "schema"
    FORM = "form"
    LLM = "llm"


class DifyPluginToolParameter(BaseModel):
    """Prepared tool parameter declaration supplied by the API side.

    The DTO intentionally accepts both API-side ``ToolParameter`` dumps and
    attribute objects so callers can adapt existing tool runtime declarations
    without coupling Dify Agent to API-internal model classes.
    """

    name: str
    type: DifyPluginToolParameterType
    form: DifyPluginToolParameterForm
    required: bool = False
    default: DifyPluginToolValue = None
    llm_description: str | None = None
    input_schema: dict[str, JsonValue] | None = None
    options: list[DifyPluginToolOption] = Field(default_factory=list)

    model_config: ClassVar[ConfigDict] = ConfigDict(extra="ignore", from_attributes=True)


class DifyPluginLLMLayerConfig(BaseModel):
    """Public config for selecting a plugin-backed business provider/model."""

    execution_context: str = "execution_context"

    plugin_id: str
    model_provider: str
    model: str
    model_settings: ModelSettings | None = None
    context_window_tokens: int | None = Field(default=None, gt=0)

    model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid", arbitrary_types_allowed=True)

    @model_validator(mode="before")
    @classmethod
    def discard_legacy_credentials(cls, value: object) -> object:
        """Accept old clients without retaining or forwarding their LLM credentials."""
        if isinstance(value, dict) and "credentials" in value:
            value = dict(value)
            value.pop("credentials", None)
        return value


class DifyPluginToolConfig(BaseModel):
    """Public config for exposing one plugin tool to the agent model.

    ``credential_type`` is an explicit caller-supplied daemon transport choice,
    not an auto-discovered property. It must match the actual credential mode of
    ``credentials`` for the configured plugin tool, for example ``"api-key"``
    versus ``"oauth2"``. A wrong value can make invocation fail at runtime even
    when the config itself validates successfully.

    ``runtime_parameters`` mirrors Dify's agent-node hidden/manual tool inputs:
    those values are merged into the actual daemon invocation but omitted from
    the tool schema shown to the model.

    ``parameters`` and ``parameters_json_schema`` are API-side prepared tool
    declaration artifacts. They let the agent runtime validate hidden/default
    inputs and expose the correct LLM-facing schema without re-fetching or
    re-merging daemon declarations at run time.

    ``plugin_unique_identifier`` pins newly prepared tools to their package.
    ``None`` preserves plugin-ID dispatch for configurations from older APIs.
    """

    plugin_id: str
    plugin_unique_identifier: str | None = Field(default=None, min_length=1)
    provider: str
    tool_name: str
    credential_type: DifyPluginToolCredentialType
    name: str | None = None
    description: str | None = None
    credentials: dict[str, DifyPluginCredentialValue] = Field(default_factory=dict)
    runtime_parameters: dict[str, DifyPluginToolValue] = Field(default_factory=dict)
    parameters: list[DifyPluginToolParameter] = Field(default_factory=list)
    parameters_json_schema: dict[str, JsonValue] = Field(default_factory=_default_parameters_json_schema)

    model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid", arbitrary_types_allowed=True)


class DifyPluginToolsLayerConfig(BaseModel):
    """Public config for the Dify plugin tools layer.

    Callers configure the tools layer with this wrapper object and supply one
    or more prepared ``DifyPluginToolConfig`` entries in ``tools``.
    """

    execution_context: str = "execution_context"
    shell: str | None = None

    tools: list[DifyPluginToolConfig] = Field(default_factory=list)

    model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid", arbitrary_types_allowed=True)


__all__ = [
    "DifyPluginCredentialValue",
    "DifyPluginLLMLayerConfig",
    "DifyPluginToolCredentialType",
    "DifyPluginToolConfig",
    "DifyPluginToolOption",
    "DifyPluginToolParameter",
    "DifyPluginToolParameterForm",
    "DifyPluginToolParameterType",
    "DifyPluginToolsLayerConfig",
    "DifyPluginToolValue",
]