workflow_entry.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import logging
  2. import time
  3. import uuid
  4. from collections.abc import Generator, Mapping, Sequence
  5. from typing import Any, Optional, cast
  6. from configs import dify_config
  7. from core.app.app_config.entities import FileExtraConfig
  8. from core.app.apps.base_app_queue_manager import GenerateTaskStoppedError
  9. from core.app.entities.app_invoke_entities import InvokeFrom
  10. from core.file.models import File, FileTransferMethod, FileType, ImageConfig
  11. from core.workflow.callbacks import WorkflowCallback
  12. from core.workflow.entities.variable_pool import VariablePool
  13. from core.workflow.errors import WorkflowNodeRunFailedError
  14. from core.workflow.graph_engine.entities.event import GraphEngineEvent, GraphRunFailedEvent, InNodeEvent
  15. from core.workflow.graph_engine.entities.graph import Graph
  16. from core.workflow.graph_engine.entities.graph_init_params import GraphInitParams
  17. from core.workflow.graph_engine.entities.graph_runtime_state import GraphRuntimeState
  18. from core.workflow.graph_engine.graph_engine import GraphEngine
  19. from core.workflow.nodes import NodeType
  20. from core.workflow.nodes.base import BaseNode, BaseNodeData
  21. from core.workflow.nodes.event import NodeEvent
  22. from core.workflow.nodes.llm import LLMNodeData
  23. from core.workflow.nodes.node_mapping import node_type_classes_mapping
  24. from models.enums import UserFrom
  25. from models.workflow import (
  26. Workflow,
  27. WorkflowType,
  28. )
  29. logger = logging.getLogger(__name__)
  30. class WorkflowEntry:
  31. def __init__(
  32. self,
  33. tenant_id: str,
  34. app_id: str,
  35. workflow_id: str,
  36. workflow_type: WorkflowType,
  37. graph_config: Mapping[str, Any],
  38. graph: Graph,
  39. user_id: str,
  40. user_from: UserFrom,
  41. invoke_from: InvokeFrom,
  42. call_depth: int,
  43. variable_pool: VariablePool,
  44. thread_pool_id: Optional[str] = None,
  45. ) -> None:
  46. """
  47. Init workflow entry
  48. :param tenant_id: tenant id
  49. :param app_id: app id
  50. :param workflow_id: workflow id
  51. :param workflow_type: workflow type
  52. :param graph_config: workflow graph config
  53. :param graph: workflow graph
  54. :param user_id: user id
  55. :param user_from: user from
  56. :param invoke_from: invoke from
  57. :param call_depth: call depth
  58. :param variable_pool: variable pool
  59. :param thread_pool_id: thread pool id
  60. """
  61. # check call depth
  62. workflow_call_max_depth = dify_config.WORKFLOW_CALL_MAX_DEPTH
  63. if call_depth > workflow_call_max_depth:
  64. raise ValueError("Max workflow call depth {} reached.".format(workflow_call_max_depth))
  65. # init workflow run state
  66. self.graph_engine = GraphEngine(
  67. tenant_id=tenant_id,
  68. app_id=app_id,
  69. workflow_type=workflow_type,
  70. workflow_id=workflow_id,
  71. user_id=user_id,
  72. user_from=user_from,
  73. invoke_from=invoke_from,
  74. call_depth=call_depth,
  75. graph=graph,
  76. graph_config=graph_config,
  77. variable_pool=variable_pool,
  78. max_execution_steps=dify_config.WORKFLOW_MAX_EXECUTION_STEPS,
  79. max_execution_time=dify_config.WORKFLOW_MAX_EXECUTION_TIME,
  80. thread_pool_id=thread_pool_id,
  81. )
  82. def run(
  83. self,
  84. *,
  85. callbacks: Sequence[WorkflowCallback],
  86. ) -> Generator[GraphEngineEvent, None, None]:
  87. """
  88. :param callbacks: workflow callbacks
  89. """
  90. graph_engine = self.graph_engine
  91. try:
  92. # run workflow
  93. generator = graph_engine.run()
  94. for event in generator:
  95. if callbacks:
  96. for callback in callbacks:
  97. callback.on_event(event=event)
  98. yield event
  99. except GenerateTaskStoppedError:
  100. pass
  101. except Exception as e:
  102. logger.exception("Unknown Error when workflow entry running")
  103. if callbacks:
  104. for callback in callbacks:
  105. callback.on_event(event=GraphRunFailedEvent(error=str(e)))
  106. return
  107. @classmethod
  108. def single_step_run(
  109. cls, workflow: Workflow, node_id: str, user_id: str, user_inputs: dict
  110. ) -> tuple[BaseNode, Generator[NodeEvent | InNodeEvent, None, None]]:
  111. """
  112. Single step run workflow node
  113. :param workflow: Workflow instance
  114. :param node_id: node id
  115. :param user_id: user id
  116. :param user_inputs: user inputs
  117. :return:
  118. """
  119. # fetch node info from workflow graph
  120. graph = workflow.graph_dict
  121. if not graph:
  122. raise ValueError("workflow graph not found")
  123. nodes = graph.get("nodes")
  124. if not nodes:
  125. raise ValueError("nodes not found in workflow graph")
  126. # fetch node config from node id
  127. node_config = None
  128. for node in nodes:
  129. if node.get("id") == node_id:
  130. node_config = node
  131. break
  132. if not node_config:
  133. raise ValueError("node id not found in workflow graph")
  134. # Get node class
  135. node_type = NodeType(node_config.get("data", {}).get("type"))
  136. node_cls = node_type_classes_mapping.get(node_type)
  137. node_cls = cast(type[BaseNode], node_cls)
  138. if not node_cls:
  139. raise ValueError(f"Node class not found for node type {node_type}")
  140. # init variable pool
  141. variable_pool = VariablePool(
  142. system_variables={},
  143. user_inputs={},
  144. environment_variables=workflow.environment_variables,
  145. )
  146. # init graph
  147. graph = Graph.init(graph_config=workflow.graph_dict)
  148. # init workflow run state
  149. node_instance = node_cls(
  150. id=str(uuid.uuid4()),
  151. config=node_config,
  152. graph_init_params=GraphInitParams(
  153. tenant_id=workflow.tenant_id,
  154. app_id=workflow.app_id,
  155. workflow_type=WorkflowType.value_of(workflow.type),
  156. workflow_id=workflow.id,
  157. graph_config=workflow.graph_dict,
  158. user_id=user_id,
  159. user_from=UserFrom.ACCOUNT,
  160. invoke_from=InvokeFrom.DEBUGGER,
  161. call_depth=0,
  162. ),
  163. graph=graph,
  164. graph_runtime_state=GraphRuntimeState(variable_pool=variable_pool, start_at=time.perf_counter()),
  165. )
  166. try:
  167. # variable selector to variable mapping
  168. try:
  169. variable_mapping = node_cls.extract_variable_selector_to_variable_mapping(
  170. graph_config=workflow.graph_dict, config=node_config
  171. )
  172. except NotImplementedError:
  173. variable_mapping = {}
  174. cls.mapping_user_inputs_to_variable_pool(
  175. variable_mapping=variable_mapping,
  176. user_inputs=user_inputs,
  177. variable_pool=variable_pool,
  178. tenant_id=workflow.tenant_id,
  179. node_type=node_type,
  180. node_data=node_instance.node_data,
  181. )
  182. # run node
  183. generator = node_instance.run()
  184. return node_instance, generator
  185. except Exception as e:
  186. raise WorkflowNodeRunFailedError(node_instance=node_instance, error=str(e))
  187. @staticmethod
  188. def handle_special_values(value: Optional[Mapping[str, Any]]) -> Mapping[str, Any] | None:
  189. return WorkflowEntry._handle_special_values(value)
  190. @staticmethod
  191. def _handle_special_values(value: Any) -> Any:
  192. if value is None:
  193. return value
  194. if isinstance(value, dict):
  195. res = {}
  196. for k, v in value.items():
  197. res[k] = WorkflowEntry._handle_special_values(v)
  198. return res
  199. if isinstance(value, list):
  200. res = []
  201. for item in value:
  202. res.append(WorkflowEntry._handle_special_values(item))
  203. return res
  204. if isinstance(value, File):
  205. return value.to_dict()
  206. return value
  207. @classmethod
  208. def mapping_user_inputs_to_variable_pool(
  209. cls,
  210. variable_mapping: Mapping[str, Sequence[str]],
  211. user_inputs: dict,
  212. variable_pool: VariablePool,
  213. tenant_id: str,
  214. node_type: NodeType,
  215. node_data: BaseNodeData,
  216. ) -> None:
  217. for node_variable, variable_selector in variable_mapping.items():
  218. # fetch node id and variable key from node_variable
  219. node_variable_list = node_variable.split(".")
  220. if len(node_variable_list) < 1:
  221. raise ValueError(f"Invalid node variable {node_variable}")
  222. node_variable_key = ".".join(node_variable_list[1:])
  223. if (node_variable_key not in user_inputs and node_variable not in user_inputs) and not variable_pool.get(
  224. variable_selector
  225. ):
  226. raise ValueError(f"Variable key {node_variable} not found in user inputs.")
  227. # fetch variable node id from variable selector
  228. variable_node_id = variable_selector[0]
  229. variable_key_list = variable_selector[1:]
  230. variable_key_list = cast(list[str], variable_key_list)
  231. # get input value
  232. input_value = user_inputs.get(node_variable)
  233. if not input_value:
  234. input_value = user_inputs.get(node_variable_key)
  235. # FIXME: temp fix for image type
  236. if node_type == NodeType.LLM:
  237. new_value = []
  238. if isinstance(input_value, list):
  239. node_data = cast(LLMNodeData, node_data)
  240. detail = node_data.vision.configs.detail if node_data.vision.configs else None
  241. for item in input_value:
  242. if isinstance(item, dict) and "type" in item and item["type"] == "image":
  243. transfer_method = FileTransferMethod.value_of(item.get("transfer_method"))
  244. file = File(
  245. tenant_id=tenant_id,
  246. type=FileType.IMAGE,
  247. transfer_method=transfer_method,
  248. remote_url=item.get("url")
  249. if transfer_method == FileTransferMethod.REMOTE_URL
  250. else None,
  251. related_id=item.get("upload_file_id")
  252. if transfer_method == FileTransferMethod.LOCAL_FILE
  253. else None,
  254. _extra_config=FileExtraConfig(
  255. image_config=ImageConfig(detail=detail) if detail else None
  256. ),
  257. )
  258. new_value.append(file)
  259. if new_value:
  260. input_value = new_value
  261. # append variable and value to variable pool
  262. variable_pool.add([variable_node_id] + variable_key_list, input_value)