workflow.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. import json
  2. import logging
  3. from typing import cast
  4. from flask import abort, request
  5. from flask_restful import Resource, inputs, marshal_with, reqparse # type: ignore
  6. from sqlalchemy.orm import Session
  7. from werkzeug.exceptions import Forbidden, InternalServerError, NotFound
  8. import services
  9. from configs import dify_config
  10. from controllers.console import api
  11. from controllers.console.app.error import (
  12. ConversationCompletedError,
  13. DraftWorkflowNotExist,
  14. DraftWorkflowNotSync,
  15. )
  16. from controllers.console.app.wraps import get_app_model
  17. from controllers.console.wraps import account_initialization_required, setup_required
  18. from controllers.web.error import InvokeRateLimitError as InvokeRateLimitHttpError
  19. from core.app.apps.base_app_queue_manager import AppQueueManager
  20. from core.app.entities.app_invoke_entities import InvokeFrom
  21. from extensions.ext_database import db
  22. from factories import variable_factory
  23. from fields.workflow_fields import workflow_fields, workflow_pagination_fields
  24. from fields.workflow_run_fields import workflow_run_node_execution_fields
  25. from libs import helper
  26. from libs.helper import TimestampField, uuid_value
  27. from libs.login import current_user, login_required
  28. from models import App
  29. from models.account import Account
  30. from models.model import AppMode
  31. from services.app_generate_service import AppGenerateService
  32. from services.errors.app import WorkflowHashNotEqualError
  33. from services.errors.llm import InvokeRateLimitError
  34. from services.workflow_service import DraftWorkflowDeletionError, WorkflowInUseError, WorkflowService
  35. logger = logging.getLogger(__name__)
  36. class DraftWorkflowApi(Resource):
  37. @setup_required
  38. @login_required
  39. @account_initialization_required
  40. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  41. @marshal_with(workflow_fields)
  42. def get(self, app_model: App):
  43. """
  44. Get draft workflow
  45. """
  46. # The role of the current user in the ta table must be admin, owner, or editor
  47. if not current_user.is_editor:
  48. raise Forbidden()
  49. # fetch draft workflow by app_model
  50. workflow_service = WorkflowService()
  51. workflow = workflow_service.get_draft_workflow(app_model=app_model)
  52. if not workflow:
  53. raise DraftWorkflowNotExist()
  54. # return workflow, if not found, return None (initiate graph by frontend)
  55. return workflow
  56. @setup_required
  57. @login_required
  58. @account_initialization_required
  59. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  60. def post(self, app_model: App):
  61. """
  62. Sync draft workflow
  63. """
  64. # The role of the current user in the ta table must be admin, owner, or editor
  65. if not current_user.is_editor:
  66. raise Forbidden()
  67. content_type = request.headers.get("Content-Type", "")
  68. if "application/json" in content_type:
  69. parser = reqparse.RequestParser()
  70. parser.add_argument("graph", type=dict, required=True, nullable=False, location="json")
  71. parser.add_argument("features", type=dict, required=True, nullable=False, location="json")
  72. parser.add_argument("hash", type=str, required=False, location="json")
  73. # TODO: set this to required=True after frontend is updated
  74. parser.add_argument("environment_variables", type=list, required=False, location="json")
  75. parser.add_argument("conversation_variables", type=list, required=False, location="json")
  76. args = parser.parse_args()
  77. elif "text/plain" in content_type:
  78. try:
  79. data = json.loads(request.data.decode("utf-8"))
  80. if "graph" not in data or "features" not in data:
  81. raise ValueError("graph or features not found in data")
  82. if not isinstance(data.get("graph"), dict) or not isinstance(data.get("features"), dict):
  83. raise ValueError("graph or features is not a dict")
  84. args = {
  85. "graph": data.get("graph"),
  86. "features": data.get("features"),
  87. "hash": data.get("hash"),
  88. "environment_variables": data.get("environment_variables"),
  89. "conversation_variables": data.get("conversation_variables"),
  90. }
  91. except json.JSONDecodeError:
  92. return {"message": "Invalid JSON data"}, 400
  93. else:
  94. abort(415)
  95. if not isinstance(current_user, Account):
  96. raise Forbidden()
  97. workflow_service = WorkflowService()
  98. try:
  99. environment_variables_list = args.get("environment_variables") or []
  100. environment_variables = [
  101. variable_factory.build_environment_variable_from_mapping(obj) for obj in environment_variables_list
  102. ]
  103. conversation_variables_list = args.get("conversation_variables") or []
  104. conversation_variables = [
  105. variable_factory.build_conversation_variable_from_mapping(obj) for obj in conversation_variables_list
  106. ]
  107. workflow = workflow_service.sync_draft_workflow(
  108. app_model=app_model,
  109. graph=args["graph"],
  110. features=args["features"],
  111. unique_hash=args.get("hash"),
  112. account=current_user,
  113. environment_variables=environment_variables,
  114. conversation_variables=conversation_variables,
  115. )
  116. except WorkflowHashNotEqualError:
  117. raise DraftWorkflowNotSync()
  118. return {
  119. "result": "success",
  120. "hash": workflow.unique_hash,
  121. "updated_at": TimestampField().format(workflow.updated_at or workflow.created_at),
  122. }
  123. class AdvancedChatDraftWorkflowRunApi(Resource):
  124. @setup_required
  125. @login_required
  126. @account_initialization_required
  127. @get_app_model(mode=[AppMode.ADVANCED_CHAT])
  128. def post(self, app_model: App):
  129. """
  130. Run draft workflow
  131. """
  132. # The role of the current user in the ta table must be admin, owner, or editor
  133. if not current_user.is_editor:
  134. raise Forbidden()
  135. if not isinstance(current_user, Account):
  136. raise Forbidden()
  137. parser = reqparse.RequestParser()
  138. parser.add_argument("inputs", type=dict, location="json")
  139. parser.add_argument("query", type=str, required=True, location="json", default="")
  140. parser.add_argument("files", type=list, location="json")
  141. parser.add_argument("conversation_id", type=uuid_value, location="json")
  142. parser.add_argument("parent_message_id", type=uuid_value, required=False, location="json")
  143. args = parser.parse_args()
  144. try:
  145. response = AppGenerateService.generate(
  146. app_model=app_model, user=current_user, args=args, invoke_from=InvokeFrom.DEBUGGER, streaming=True
  147. )
  148. return helper.compact_generate_response(response)
  149. except services.errors.conversation.ConversationNotExistsError:
  150. raise NotFound("Conversation Not Exists.")
  151. except services.errors.conversation.ConversationCompletedError:
  152. raise ConversationCompletedError()
  153. except InvokeRateLimitError as ex:
  154. raise InvokeRateLimitHttpError(ex.description)
  155. except ValueError as e:
  156. raise e
  157. except Exception:
  158. logging.exception("internal server error.")
  159. raise InternalServerError()
  160. class AdvancedChatDraftRunIterationNodeApi(Resource):
  161. @setup_required
  162. @login_required
  163. @account_initialization_required
  164. @get_app_model(mode=[AppMode.ADVANCED_CHAT])
  165. def post(self, app_model: App, node_id: str):
  166. """
  167. Run draft workflow iteration node
  168. """
  169. # The role of the current user in the ta table must be admin, owner, or editor
  170. if not current_user.is_editor:
  171. raise Forbidden()
  172. if not isinstance(current_user, Account):
  173. raise Forbidden()
  174. parser = reqparse.RequestParser()
  175. parser.add_argument("inputs", type=dict, location="json")
  176. args = parser.parse_args()
  177. try:
  178. response = AppGenerateService.generate_single_iteration(
  179. app_model=app_model, user=current_user, node_id=node_id, args=args, streaming=True
  180. )
  181. return helper.compact_generate_response(response)
  182. except services.errors.conversation.ConversationNotExistsError:
  183. raise NotFound("Conversation Not Exists.")
  184. except services.errors.conversation.ConversationCompletedError:
  185. raise ConversationCompletedError()
  186. except ValueError as e:
  187. raise e
  188. except Exception:
  189. logging.exception("internal server error.")
  190. raise InternalServerError()
  191. class WorkflowDraftRunIterationNodeApi(Resource):
  192. @setup_required
  193. @login_required
  194. @account_initialization_required
  195. @get_app_model(mode=[AppMode.WORKFLOW])
  196. def post(self, app_model: App, node_id: str):
  197. """
  198. Run draft workflow iteration node
  199. """
  200. # The role of the current user in the ta table must be admin, owner, or editor
  201. if not current_user.is_editor:
  202. raise Forbidden()
  203. if not isinstance(current_user, Account):
  204. raise Forbidden()
  205. parser = reqparse.RequestParser()
  206. parser.add_argument("inputs", type=dict, location="json")
  207. args = parser.parse_args()
  208. try:
  209. response = AppGenerateService.generate_single_iteration(
  210. app_model=app_model, user=current_user, node_id=node_id, args=args, streaming=True
  211. )
  212. return helper.compact_generate_response(response)
  213. except services.errors.conversation.ConversationNotExistsError:
  214. raise NotFound("Conversation Not Exists.")
  215. except services.errors.conversation.ConversationCompletedError:
  216. raise ConversationCompletedError()
  217. except ValueError as e:
  218. raise e
  219. except Exception:
  220. logging.exception("internal server error.")
  221. raise InternalServerError()
  222. class AdvancedChatDraftRunLoopNodeApi(Resource):
  223. @setup_required
  224. @login_required
  225. @account_initialization_required
  226. @get_app_model(mode=[AppMode.ADVANCED_CHAT])
  227. def post(self, app_model: App, node_id: str):
  228. """
  229. Run draft workflow loop node
  230. """
  231. # The role of the current user in the ta table must be admin, owner, or editor
  232. if not current_user.is_editor:
  233. raise Forbidden()
  234. if not isinstance(current_user, Account):
  235. raise Forbidden()
  236. parser = reqparse.RequestParser()
  237. parser.add_argument("inputs", type=dict, location="json")
  238. args = parser.parse_args()
  239. try:
  240. response = AppGenerateService.generate_single_loop(
  241. app_model=app_model, user=current_user, node_id=node_id, args=args, streaming=True
  242. )
  243. return helper.compact_generate_response(response)
  244. except services.errors.conversation.ConversationNotExistsError:
  245. raise NotFound("Conversation Not Exists.")
  246. except services.errors.conversation.ConversationCompletedError:
  247. raise ConversationCompletedError()
  248. except ValueError as e:
  249. raise e
  250. except Exception:
  251. logging.exception("internal server error.")
  252. raise InternalServerError()
  253. class WorkflowDraftRunLoopNodeApi(Resource):
  254. @setup_required
  255. @login_required
  256. @account_initialization_required
  257. @get_app_model(mode=[AppMode.WORKFLOW])
  258. def post(self, app_model: App, node_id: str):
  259. """
  260. Run draft workflow loop node
  261. """
  262. # The role of the current user in the ta table must be admin, owner, or editor
  263. if not current_user.is_editor:
  264. raise Forbidden()
  265. if not isinstance(current_user, Account):
  266. raise Forbidden()
  267. parser = reqparse.RequestParser()
  268. parser.add_argument("inputs", type=dict, location="json")
  269. args = parser.parse_args()
  270. try:
  271. response = AppGenerateService.generate_single_loop(
  272. app_model=app_model, user=current_user, node_id=node_id, args=args, streaming=True
  273. )
  274. return helper.compact_generate_response(response)
  275. except services.errors.conversation.ConversationNotExistsError:
  276. raise NotFound("Conversation Not Exists.")
  277. except services.errors.conversation.ConversationCompletedError:
  278. raise ConversationCompletedError()
  279. except ValueError as e:
  280. raise e
  281. except Exception:
  282. logging.exception("internal server error.")
  283. raise InternalServerError()
  284. class DraftWorkflowRunApi(Resource):
  285. @setup_required
  286. @login_required
  287. @account_initialization_required
  288. @get_app_model(mode=[AppMode.WORKFLOW])
  289. def post(self, app_model: App):
  290. """
  291. Run draft workflow
  292. """
  293. # The role of the current user in the ta table must be admin, owner, or editor
  294. if not current_user.is_editor:
  295. raise Forbidden()
  296. if not isinstance(current_user, Account):
  297. raise Forbidden()
  298. parser = reqparse.RequestParser()
  299. parser.add_argument("inputs", type=dict, required=True, nullable=False, location="json")
  300. parser.add_argument("files", type=list, required=False, location="json")
  301. args = parser.parse_args()
  302. try:
  303. response = AppGenerateService.generate(
  304. app_model=app_model,
  305. user=current_user,
  306. args=args,
  307. invoke_from=InvokeFrom.DEBUGGER,
  308. streaming=True,
  309. )
  310. return helper.compact_generate_response(response)
  311. except InvokeRateLimitError as ex:
  312. raise InvokeRateLimitHttpError(ex.description)
  313. class WorkflowTaskStopApi(Resource):
  314. @setup_required
  315. @login_required
  316. @account_initialization_required
  317. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  318. def post(self, app_model: App, task_id: str):
  319. """
  320. Stop workflow task
  321. """
  322. # The role of the current user in the ta table must be admin, owner, or editor
  323. if not current_user.is_editor:
  324. raise Forbidden()
  325. AppQueueManager.set_stop_flag(task_id, InvokeFrom.DEBUGGER, current_user.id)
  326. return {"result": "success"}
  327. class DraftWorkflowNodeRunApi(Resource):
  328. @setup_required
  329. @login_required
  330. @account_initialization_required
  331. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  332. @marshal_with(workflow_run_node_execution_fields)
  333. def post(self, app_model: App, node_id: str):
  334. """
  335. Run draft workflow node
  336. """
  337. # The role of the current user in the ta table must be admin, owner, or editor
  338. if not current_user.is_editor:
  339. raise Forbidden()
  340. if not isinstance(current_user, Account):
  341. raise Forbidden()
  342. parser = reqparse.RequestParser()
  343. parser.add_argument("inputs", type=dict, required=True, nullable=False, location="json")
  344. args = parser.parse_args()
  345. inputs = args.get("inputs")
  346. if inputs == None:
  347. raise ValueError("missing inputs")
  348. workflow_service = WorkflowService()
  349. workflow_node_execution = workflow_service.run_draft_workflow_node(
  350. app_model=app_model, node_id=node_id, user_inputs=inputs, account=current_user
  351. )
  352. return workflow_node_execution
  353. class PublishedWorkflowApi(Resource):
  354. @setup_required
  355. @login_required
  356. @account_initialization_required
  357. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  358. @marshal_with(workflow_fields)
  359. def get(self, app_model: App):
  360. """
  361. Get published workflow
  362. """
  363. # The role of the current user in the ta table must be admin, owner, or editor
  364. if not current_user.is_editor:
  365. raise Forbidden()
  366. # fetch published workflow by app_model
  367. workflow_service = WorkflowService()
  368. workflow = workflow_service.get_published_workflow(app_model=app_model)
  369. # return workflow, if not found, return None
  370. return workflow
  371. @setup_required
  372. @login_required
  373. @account_initialization_required
  374. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  375. def post(self, app_model: App):
  376. """
  377. Publish workflow
  378. """
  379. # The role of the current user in the ta table must be admin, owner, or editor
  380. if not current_user.is_editor:
  381. raise Forbidden()
  382. if not isinstance(current_user, Account):
  383. raise Forbidden()
  384. parser = reqparse.RequestParser()
  385. parser.add_argument("marked_name", type=str, required=False, default="", location="json")
  386. parser.add_argument("marked_comment", type=str, required=False, default="", location="json")
  387. args = parser.parse_args()
  388. # Validate name and comment length
  389. if args.marked_name and len(args.marked_name) > 20:
  390. raise ValueError("Marked name cannot exceed 20 characters")
  391. if args.marked_comment and len(args.marked_comment) > 100:
  392. raise ValueError("Marked comment cannot exceed 100 characters")
  393. workflow_service = WorkflowService()
  394. with Session(db.engine) as session:
  395. workflow = workflow_service.publish_workflow(
  396. session=session,
  397. app_model=app_model,
  398. account=current_user,
  399. marked_name=args.marked_name or "",
  400. marked_comment=args.marked_comment or "",
  401. )
  402. app_model.workflow_id = workflow.id
  403. db.session.commit()
  404. workflow_created_at = TimestampField().format(workflow.created_at)
  405. session.commit()
  406. return {
  407. "result": "success",
  408. "created_at": workflow_created_at,
  409. }
  410. class DefaultBlockConfigsApi(Resource):
  411. @setup_required
  412. @login_required
  413. @account_initialization_required
  414. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  415. def get(self, app_model: App):
  416. """
  417. Get default block config
  418. """
  419. # The role of the current user in the ta table must be admin, owner, or editor
  420. if not current_user.is_editor:
  421. raise Forbidden()
  422. # Get default block configs
  423. workflow_service = WorkflowService()
  424. return workflow_service.get_default_block_configs()
  425. class DefaultBlockConfigApi(Resource):
  426. @setup_required
  427. @login_required
  428. @account_initialization_required
  429. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  430. def get(self, app_model: App, block_type: str):
  431. """
  432. Get default block config
  433. """
  434. # The role of the current user in the ta table must be admin, owner, or editor
  435. if not current_user.is_editor:
  436. raise Forbidden()
  437. if not isinstance(current_user, Account):
  438. raise Forbidden()
  439. parser = reqparse.RequestParser()
  440. parser.add_argument("q", type=str, location="args")
  441. args = parser.parse_args()
  442. q = args.get("q")
  443. filters = None
  444. if q:
  445. try:
  446. filters = json.loads(args.get("q", ""))
  447. except json.JSONDecodeError:
  448. raise ValueError("Invalid filters")
  449. # Get default block configs
  450. workflow_service = WorkflowService()
  451. return workflow_service.get_default_block_config(node_type=block_type, filters=filters)
  452. class ConvertToWorkflowApi(Resource):
  453. @setup_required
  454. @login_required
  455. @account_initialization_required
  456. @get_app_model(mode=[AppMode.CHAT, AppMode.COMPLETION])
  457. def post(self, app_model: App):
  458. """
  459. Convert basic mode of chatbot app to workflow mode
  460. Convert expert mode of chatbot app to workflow mode
  461. Convert Completion App to Workflow App
  462. """
  463. # The role of the current user in the ta table must be admin, owner, or editor
  464. if not current_user.is_editor:
  465. raise Forbidden()
  466. if not isinstance(current_user, Account):
  467. raise Forbidden()
  468. if request.data:
  469. parser = reqparse.RequestParser()
  470. parser.add_argument("name", type=str, required=False, nullable=True, location="json")
  471. parser.add_argument("icon_type", type=str, required=False, nullable=True, location="json")
  472. parser.add_argument("icon", type=str, required=False, nullable=True, location="json")
  473. parser.add_argument("icon_background", type=str, required=False, nullable=True, location="json")
  474. args = parser.parse_args()
  475. else:
  476. args = {}
  477. # convert to workflow mode
  478. workflow_service = WorkflowService()
  479. new_app_model = workflow_service.convert_to_workflow(app_model=app_model, account=current_user, args=args)
  480. # return app id
  481. return {
  482. "new_app_id": new_app_model.id,
  483. }
  484. class WorkflowConfigApi(Resource):
  485. """Resource for workflow configuration."""
  486. @setup_required
  487. @login_required
  488. @account_initialization_required
  489. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  490. def get(self, app_model: App):
  491. return {
  492. "parallel_depth_limit": dify_config.WORKFLOW_PARALLEL_DEPTH_LIMIT,
  493. }
  494. class PublishedAllWorkflowApi(Resource):
  495. @setup_required
  496. @login_required
  497. @account_initialization_required
  498. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  499. @marshal_with(workflow_pagination_fields)
  500. def get(self, app_model: App):
  501. """
  502. Get published workflows
  503. """
  504. if not current_user.is_editor:
  505. raise Forbidden()
  506. parser = reqparse.RequestParser()
  507. parser.add_argument("page", type=inputs.int_range(1, 99999), required=False, default=1, location="args")
  508. parser.add_argument("limit", type=inputs.int_range(1, 100), required=False, default=20, location="args")
  509. parser.add_argument("user_id", type=str, required=False, location="args")
  510. parser.add_argument("named_only", type=inputs.boolean, required=False, default=False, location="args")
  511. args = parser.parse_args()
  512. page = int(args.get("page", 1))
  513. limit = int(args.get("limit", 10))
  514. user_id = args.get("user_id")
  515. named_only = args.get("named_only", False)
  516. if user_id:
  517. if user_id != current_user.id:
  518. raise Forbidden()
  519. user_id = cast(str, user_id)
  520. workflow_service = WorkflowService()
  521. with Session(db.engine) as session:
  522. workflows, has_more = workflow_service.get_all_published_workflow(
  523. session=session,
  524. app_model=app_model,
  525. page=page,
  526. limit=limit,
  527. user_id=user_id,
  528. named_only=named_only,
  529. )
  530. return {
  531. "items": workflows,
  532. "page": page,
  533. "limit": limit,
  534. "has_more": has_more,
  535. }
  536. class WorkflowByIdApi(Resource):
  537. @setup_required
  538. @login_required
  539. @account_initialization_required
  540. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  541. @marshal_with(workflow_fields)
  542. def patch(self, app_model: App, workflow_id: str):
  543. """
  544. Update workflow attributes
  545. """
  546. # Check permission
  547. if not current_user.is_editor:
  548. raise Forbidden()
  549. if not isinstance(current_user, Account):
  550. raise Forbidden()
  551. parser = reqparse.RequestParser()
  552. parser.add_argument("marked_name", type=str, required=False, location="json")
  553. parser.add_argument("marked_comment", type=str, required=False, location="json")
  554. args = parser.parse_args()
  555. # Validate name and comment length
  556. if args.marked_name and len(args.marked_name) > 20:
  557. raise ValueError("Marked name cannot exceed 20 characters")
  558. if args.marked_comment and len(args.marked_comment) > 100:
  559. raise ValueError("Marked comment cannot exceed 100 characters")
  560. args = parser.parse_args()
  561. # Prepare update data
  562. update_data = {}
  563. if args.get("marked_name") is not None:
  564. update_data["marked_name"] = args["marked_name"]
  565. if args.get("marked_comment") is not None:
  566. update_data["marked_comment"] = args["marked_comment"]
  567. if not update_data:
  568. return {"message": "No valid fields to update"}, 400
  569. workflow_service = WorkflowService()
  570. # Create a session and manage the transaction
  571. with Session(db.engine, expire_on_commit=False) as session:
  572. workflow = workflow_service.update_workflow(
  573. session=session,
  574. workflow_id=workflow_id,
  575. tenant_id=app_model.tenant_id,
  576. account_id=current_user.id,
  577. data=update_data,
  578. )
  579. if not workflow:
  580. raise NotFound("Workflow not found")
  581. # Commit the transaction in the controller
  582. session.commit()
  583. return workflow
  584. @setup_required
  585. @login_required
  586. @account_initialization_required
  587. @get_app_model(mode=[AppMode.ADVANCED_CHAT, AppMode.WORKFLOW])
  588. def delete(self, app_model: App, workflow_id: str):
  589. """
  590. Delete workflow
  591. """
  592. # Check permission
  593. if not current_user.is_editor:
  594. raise Forbidden()
  595. if not isinstance(current_user, Account):
  596. raise Forbidden()
  597. workflow_service = WorkflowService()
  598. # Create a session and manage the transaction
  599. with Session(db.engine) as session:
  600. try:
  601. workflow_service.delete_workflow(
  602. session=session, workflow_id=workflow_id, tenant_id=app_model.tenant_id
  603. )
  604. # Commit the transaction in the controller
  605. session.commit()
  606. except WorkflowInUseError as e:
  607. abort(400, description=str(e))
  608. except DraftWorkflowDeletionError as e:
  609. abort(400, description=str(e))
  610. except ValueError as e:
  611. raise NotFound(str(e))
  612. return None, 204
  613. api.add_resource(
  614. DraftWorkflowApi,
  615. "/apps/<uuid:app_id>/workflows/draft",
  616. )
  617. api.add_resource(
  618. WorkflowConfigApi,
  619. "/apps/<uuid:app_id>/workflows/draft/config",
  620. )
  621. api.add_resource(
  622. AdvancedChatDraftWorkflowRunApi,
  623. "/apps/<uuid:app_id>/advanced-chat/workflows/draft/run",
  624. )
  625. api.add_resource(
  626. DraftWorkflowRunApi,
  627. "/apps/<uuid:app_id>/workflows/draft/run",
  628. )
  629. api.add_resource(
  630. WorkflowTaskStopApi,
  631. "/apps/<uuid:app_id>/workflow-runs/tasks/<string:task_id>/stop",
  632. )
  633. api.add_resource(
  634. DraftWorkflowNodeRunApi,
  635. "/apps/<uuid:app_id>/workflows/draft/nodes/<string:node_id>/run",
  636. )
  637. api.add_resource(
  638. AdvancedChatDraftRunIterationNodeApi,
  639. "/apps/<uuid:app_id>/advanced-chat/workflows/draft/iteration/nodes/<string:node_id>/run",
  640. )
  641. api.add_resource(
  642. WorkflowDraftRunIterationNodeApi,
  643. "/apps/<uuid:app_id>/workflows/draft/iteration/nodes/<string:node_id>/run",
  644. )
  645. api.add_resource(
  646. AdvancedChatDraftRunLoopNodeApi,
  647. "/apps/<uuid:app_id>/advanced-chat/workflows/draft/loop/nodes/<string:node_id>/run",
  648. )
  649. api.add_resource(
  650. WorkflowDraftRunLoopNodeApi,
  651. "/apps/<uuid:app_id>/workflows/draft/loop/nodes/<string:node_id>/run",
  652. )
  653. api.add_resource(
  654. PublishedWorkflowApi,
  655. "/apps/<uuid:app_id>/workflows/publish",
  656. )
  657. api.add_resource(
  658. PublishedAllWorkflowApi,
  659. "/apps/<uuid:app_id>/workflows",
  660. )
  661. api.add_resource(
  662. DefaultBlockConfigsApi,
  663. "/apps/<uuid:app_id>/workflows/default-workflow-block-configs",
  664. )
  665. api.add_resource(
  666. DefaultBlockConfigApi,
  667. "/apps/<uuid:app_id>/workflows/default-workflow-block-configs/<string:block_type>",
  668. )
  669. api.add_resource(
  670. ConvertToWorkflowApi,
  671. "/apps/<uuid:app_id>/convert-to-workflow",
  672. )
  673. api.add_resource(
  674. WorkflowByIdApi,
  675. "/apps/<uuid:app_id>/workflows/<string:workflow_id>",
  676. )