mirror of
https://github.com/langgenius/dify.git
synced 2026-11-24 20:59:04 +08:00
# Conflicts: # api/.importlinter # api/controllers/console/app/workflow.py # api/controllers/console/explore/trial.py # api/controllers/openapi/app_workflow.py # api/extensions/application_services/installed_app.py # api/extensions/ext_application_services.py # api/repositories/sqlalchemy_execution_extra_content_repository.py # api/services/agent/composer_service.py # api/services/annotation_service.py # api/services/app/console_gateway.py # api/services/app_dsl_service.py # api/services/app_generate_service.py # api/services/app_package_service.py # api/services/snippet_generate_service.py # api/services/snippet_service.py # api/services/workflow_run_service.py # api/services/workflow_service.py # api/services/workflow_tool_source_service.py # api/tasks/app_generate/workflow_execute_task.py # api/tasks/async_workflow_tasks.py # api/tasks/human_input_timeout_tasks.py # api/tests/e2e_tests/containers/core/workflow/test_human_input_resume_node_execution.py # api/tests/e2e_tests/containers/services/test_annotation_service.py # api/tests/unit_tests/controllers/console/app/test_workflow.py # api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow.py # api/tests/unit_tests/controllers/inner_api/agent/test_tools.py # api/tests/unit_tests/controllers/openapi/auth/test_resource_access.py # api/tests/unit_tests/controllers/service_api/app/test_completion.py # api/tests/unit_tests/controllers/service_api/app/test_workflow.py # api/tests/unit_tests/controllers/service_api/app/test_workflow_events.py # api/tests/unit_tests/controllers/service_api/dataset/rag_pipeline/test_rag_pipeline_workflow.py # api/tests/unit_tests/core/tools/__base/test_tool.py # api/tests/unit_tests/dev/test_check_knowledge_fs_coverage.py # api/tests/unit_tests/pyrefly.toml # api/tests/unit_tests/services/agent/test_home_snapshot_service.py # api/tests/unit_tests/services/app/test_console_service.py # api/tests/unit_tests/services/rag_pipeline/test_rag_pipeline.py # api/tests/unit_tests/services/test_agent_service.py # api/tests/unit_tests/services/test_annotation_service.py # api/tests/unit_tests/services/test_app_definition_query_service.py # api/tests/unit_tests/services/test_app_dsl_service.py # api/tests/unit_tests/services/test_app_generate_service.py # api/tests/unit_tests/services/test_app_package_service.py # api/tests/unit_tests/services/test_snippet_service.py # api/tests/unit_tests/services/test_workflow_run_service.py # api/tests/unit_tests/services/test_workflow_service.py # api/tests/unit_tests/services/trigger/test_webhook_service.py # api/tests/unit_tests/tasks/app_generate/test_workflow_execute_task.py # packages/contracts/generated/api/console/apps/errors.gen.ts # packages/contracts/generated/api/console/apps/orpc.gen.ts # packages/contracts/generated/api/console/errors.gen.ts
162 lines
6.9 KiB
Python
162 lines
6.9 KiB
Python
"""Materialize pinned Workflow Tool definitions before execution begins."""
|
|
|
|
from collections.abc import Callable, Mapping, Sequence
|
|
from dataclasses import dataclass
|
|
from typing import Any
|
|
|
|
from pydantic import BaseModel, ConfigDict
|
|
|
|
from core.app.apps.draft_variable_saver import DraftVariableSaverFactory
|
|
from core.tools.__base.tool_runtime import ToolRuntime
|
|
from core.tools.entities.tool_entities import ToolEntity
|
|
from core.tools.workflow_as_tool.repository import WorkflowToolSource
|
|
from core.workflow.workflow_tool_container_types import WorkflowToolContainerPayload
|
|
from graphon.nodes.tool.exc import ToolRuntimeResolutionError
|
|
from models import Account
|
|
from repositories.workflow_tool_source_repository import SQLAlchemyWorkflowToolSourceRepository
|
|
from services.tools.workflow.tool import WorkflowTool
|
|
from services.workflow.execution.ports import WorkflowRuntime
|
|
|
|
|
|
class WorkflowToolDefinition(BaseModel):
|
|
"""Serializable tool definition, without invocation state or credentials."""
|
|
|
|
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
|
|
app_id: str
|
|
workflow_id: str
|
|
version: str
|
|
entity: ToolEntity
|
|
label: str
|
|
|
|
|
|
class WorkflowToolSnapshot(BaseModel):
|
|
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
|
|
tools: dict[str, WorkflowToolDefinition]
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class MaterializedWorkflowTools:
|
|
sources: dict[str, WorkflowToolSource]
|
|
# Multiple providers may refer to the same workflow with different definitions.
|
|
tools: dict[str, WorkflowTool]
|
|
|
|
def snapshot(self) -> WorkflowToolSnapshot:
|
|
return WorkflowToolSnapshot(
|
|
tools={
|
|
provider_id: WorkflowToolDefinition(
|
|
app_id=tool.workflow_app_id,
|
|
workflow_id=tool.workflow_id,
|
|
version=tool.version,
|
|
entity=tool.entity.model_copy(deep=True),
|
|
label=tool.label,
|
|
)
|
|
for provider_id, tool in self.tools.items()
|
|
}
|
|
)
|
|
|
|
|
|
class WorkflowToolSourceService:
|
|
def __init__(
|
|
self,
|
|
repository: SQLAlchemyWorkflowToolSourceRepository,
|
|
*,
|
|
workflow_runtime: WorkflowRuntime | None,
|
|
draft_variable_saver: Callable[[str, Account], DraftVariableSaverFactory] | None,
|
|
) -> None:
|
|
self._repository = repository
|
|
self._workflow_runtime = workflow_runtime
|
|
self._draft_variable_saver = draft_variable_saver
|
|
|
|
def load(
|
|
self,
|
|
*,
|
|
tenant_id: str,
|
|
graph_config: Mapping[str, Any],
|
|
allow_human_input: bool = True,
|
|
suspended_tools: Sequence[WorkflowToolContainerPayload] = (),
|
|
snapshot: WorkflowToolSnapshot | None = None,
|
|
) -> MaterializedWorkflowTools:
|
|
"""Restore saved definitions, or materialize current providers for new/legacy runs."""
|
|
sources: dict[str, WorkflowToolSource] = {}
|
|
tools: dict[str, WorkflowTool] = {}
|
|
pending = [graph_config]
|
|
for tool in suspended_tools:
|
|
source = self._repository.get_source(
|
|
tenant_id=tenant_id,
|
|
app_id=tool.source_app_id,
|
|
workflow_id=tool.source_workflow_id,
|
|
version=tool.source_workflow_version,
|
|
)
|
|
if source is None:
|
|
raise ValueError("Workflow Tool source was not found")
|
|
sources[source.workflow_id] = source
|
|
pending.append(source.graph_config)
|
|
|
|
if snapshot is not None:
|
|
for provider_id, definition in snapshot.tools.items():
|
|
source = self._repository.get_source(
|
|
tenant_id=tenant_id,
|
|
app_id=definition.app_id,
|
|
workflow_id=definition.workflow_id,
|
|
version=definition.version,
|
|
)
|
|
if source is None:
|
|
raise ValueError("Workflow Tool source was not found")
|
|
sources[source.workflow_id] = source
|
|
pending.append(source.graph_config)
|
|
runtime = self._require_runtime()
|
|
tools[provider_id] = WorkflowTool(
|
|
workflow_app_id=source.app_id,
|
|
workflow_id=source.workflow_id,
|
|
workflow_as_tool_id=provider_id,
|
|
version=definition.version,
|
|
workflow_call_depth=0,
|
|
entity=definition.entity.model_copy(deep=True),
|
|
runtime=ToolRuntime(tenant_id=tenant_id),
|
|
label=definition.label,
|
|
queries=runtime.tools,
|
|
draft_variable_saver=self._draft_variable_saver,
|
|
workflow_runtime=runtime,
|
|
)
|
|
|
|
visited: set[str] = set()
|
|
while pending:
|
|
provider_ids: set[str] = set()
|
|
for graph in pending:
|
|
for node in graph.get("nodes", []):
|
|
data = node.get("data", {})
|
|
if not allow_human_input and data.get("type") == "human-input":
|
|
raise ValueError("Human Input nodes are not supported in this execution context.")
|
|
if data.get("type") == "tool" and data.get("provider_type") == "workflow":
|
|
provider_id = data.get("provider_id")
|
|
if isinstance(provider_id, str) and provider_id not in visited:
|
|
provider_ids.add(provider_id)
|
|
# A present snapshot is authoritative, including an empty registry.
|
|
# Never resolve mutable provider records after a durable pause.
|
|
if snapshot is not None or not provider_ids:
|
|
break
|
|
visited.update(provider_ids)
|
|
pending = []
|
|
for source in self._repository.get_by_provider_ids(tenant_id=tenant_id, provider_ids=tuple(provider_ids)):
|
|
if source.tool is not None:
|
|
if not isinstance(source.tool, WorkflowTool):
|
|
raise TypeError("Workflow Tool source returned an unsupported tool implementation")
|
|
tools[source.tool.workflow_as_tool_id] = source.tool
|
|
if source.workflow_id not in sources:
|
|
pending.append(source.graph_config)
|
|
sources[source.workflow_id] = source
|
|
for source in sources.values():
|
|
if any(
|
|
node.get("data", {}).get("type") == "human-input" and node.get("data", {}).get("version") == "2"
|
|
for node in source.graph_config.get("nodes", [])
|
|
):
|
|
raise ToolRuntimeResolutionError("Human Input V2 nodes are not supported in nested Workflow Tools.")
|
|
return MaterializedWorkflowTools(sources=sources, tools=tools)
|
|
|
|
def _require_runtime(self) -> WorkflowRuntime:
|
|
if self._workflow_runtime is None:
|
|
raise ValueError("Workflow execution dependencies are required to materialize Workflow Tools")
|
|
return self._workflow_runtime
|